#@gmic pack_sprites : _spacing,_precision>0
#@gmic : Try to randomly pack as much sprites as possible onto the 'empty' areas of an image.
#@gmic : First selected image is the one that will be filled with the sprites. Its last channel must be
#@gmic : a binary mask whose zero values represent potential locations for drawing the sprites.
#@gmic : Second selected image represents the sprite. Its last channel must be a binary mask that
#@gmic : represents the sprite shape.
#@gmic : 'precision' tells about the desired number of failed trials before ending the filling process.
#@gmic : Default value: 'precision=5'.
#@gmic : $ 512,512,1,3,"min(255,y*c/2)" 100%,100% -circle 50%,50%,100,1,255 -append c image.jpg -resize2dy[-1] 24 -to_rgba -pack_sprites ,
pack_sprites : -check "isint(${1=1}) && isint(${2=5}) && $2>0"
  -e[^-1] "Randomly pack image$? two-by-two, with spacing $1 and precision $2."
  -v - -repeat {int(@#/2)} -l[{2*$<},{2*$<+1}]
    -sh 100%,100% -neq[-2,-1] 0 area=@{-1,+} -rm[-2,-1]
    is_first_time=1 nb_attempts=0

    -repeat 256  # Max number of iterations.

      # Get binary map of possible locations.
      --channels[0] 100% -eq[-1] 0
      -if {$1>1} -erode[-1] {2*$1-1}
      -elif {$1<1} -dilate[-1] {-2*$1+3}
      -endif

      # Generate 'random' skeleton-oriented point cloud.
      --rectangle[-1] 0,0,100%,100%,1,0xFFFFFFFF,0
      -if $is_first_time -noise[-1] 0.1,2 -endif
      -distance[-1] 0 -noise[-1] 1,1
      -max_patch[-1] {round(1.5*@{1,max(w,h)})}
      -*[-1] [-2]
      -pointcloud3d[-1]

      # Create 3d cloud of sprites.
      N=@{-1,7}
      -if $N
        -s3d[-1] -rm[-2,-1]
        (-128,@{1,w},@{1,h},@{1,s}) [1]
        -if {$N>1} 4,{$N-1},1,1,-128,0,0,0 -endif
        (-128,@{1,w},@{1,h},1) --channels[1] 100% -neq[-1] 0
        -if {$N>1} 4,{$N-1},1,1,-128,0,0,0 -endif
        -y[3--1] y -a[3--1] y
      -endif

      # Draw cloud and detect non-intersecting sprites.
      [0] -sh[-1] 100%,100% -f[-1] 1 --[-1] [-4]
      -object3d[-2] [-3],0,0,0,1,2,0,0 -rm[-3,-1]
      -sh[-1] 100%,100% -area_fg[-1] 0,1 -eq[-1] $area
      -*[-1] [-3] -rm[-3] -sh[-2] 0,@{-2,s-2} -*[-1] [-2] -rm[-1]

      # Draw selected sprites on rendering image.
      -if {iM} -j[0] [-2],0,0,0,0,1,[-1] -rm[-2,-1]
      -else
        -rm[-2,-1]
        nb_attempts={$nb_attempts+1}
        -if {$nb_attempts>$2} -break -else -continue -endif
      -endif
    -done
    -rm[-1]  # Delete sprite.
  -endl -done -v +