-
Notifications
You must be signed in to change notification settings - Fork 0
/
StippleGen_2.pde
1372 lines (972 loc) · 33.4 KB
/
StippleGen_2.pde
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
StippleGen_2
SVG Stipple Generator, v. 2.02
Copyright (C) 2012 by Windell H. Oskay, www.evilmadscientist.com
Full Documentation: http://wiki.evilmadscience.com/StippleGen
Blog post about the release: http://www.evilmadscientist.com/go/stipple2
An implementation of Weighted Voronoi Stippling:
http://mrl.nyu.edu/~ajsecord/stipples.html
*******************************************************************************
Change Log:
v 2.02
* Force files to end in .svg
* Fix bug that gave wrong size to stipple files saved white stipples on black background
v 2.01:
* Improved handling of Save process, to prevent accidental "not saving" by users.
v 2.0:
* Add tone reversal option (white on black / black on white)
* Reduce vertical extent of GUI, to reduce likelihood of cropping on small screens
* Speling corections
* Fixed a bug that caused unintended cropping of long, wide images
* Reorganized GUI controls
* Fail less disgracefully when a bad image type is selected.
*******************************************************************************
Program is based on the Toxic Libs Library ( http://toxiclibs.org/ )
& example code:
http://forum.processing.org/topic/toxiclib-voronoi-example-sketch
Additional inspiration:
Stipple Cam from Jim Bumgardner
http://joyofprocessing.com/blog/2011/11/stipple-cam/
and
MeshLibDemo.pde - Demo of Lee Byron's Mesh library, by
Marius Watz - http://workshop.evolutionzone.com/
Requires ControlP5 library and Toxic Libs library:
http://www.sojamo.de/libraries/controlP5/
http://hg.postspectacular.com/toxiclibs/downloads
*/
/*
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* http://creativecommons.org/licenses/LGPL/2.1/
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// You need the controlP5 library from http://www.sojamo.de/libraries/controlP5/
import controlP5.*;
//You need the Toxic Libs library: http://hg.postspectacular.com/toxiclibs/downloads
import toxi.geom.*;
import toxi.geom.mesh2d.*;
import toxi.util.datatypes.*;
import toxi.processing.*;
// helper class for rendering
ToxiclibsSupport gfx;
import javax.swing.UIManager;
import javax.swing.JFileChooser;
import java.util.List;
// Feel free to play with these three default settings:
int maxParticles = 2000; // Max value is normally 10000. Press 'x' key to allow 50000 stipples. (SLOW)
float MinDotSize = 1.75; //2;
float DotSizeFactor = 4; //5;
float cutoff = 0; // White cutoff value
int cellBuffer = 100; //Scale each cell to fit in a cellBuffer-sized square window for computing the centroid.
// Display window and GUI area sizes:
int mainwidth;
int mainheight;
int borderWidth;
int ctrlheight;
int TextColumnStart;
float lowBorderX;
float hiBorderX;
float lowBorderY;
float hiBorderY;
float MaxDotSize;
boolean ReInitiallizeArray;
boolean pausemode;
boolean fileLoaded;
int SaveNow;
String savePath;
String[] FileOutput;
String StatusDisplay = "Initializing, please wait. :)";
float millisLastFrame = 0;
float frameTime = 0;
String ErrorDisplay = "";
float ErrorTime;
Boolean ErrorDisp = false;
int Generation;
int particleRouteLength;
int RouteStep;
boolean showBG;
boolean showPath;
boolean showCells;
boolean invertImg;
boolean TempShowCells;
boolean FileModeTSP;
int vorPointsAdded;
boolean VoronoiCalculated;
// Toxic libs library setup:
Voronoi voronoi;
List<Polygon2D> RegionList;
PolygonClipper2D clip; // polygon clipper
int cellsTotal, cellsCalculated, cellsCalculatedLast;
// ControlP5 GUI library variables setup
Textlabel ProgName;
Button OrderOnOff, ImgOnOff, CellOnOff, InvertOnOff, PauseButton;
ControlP5 cp5;
PImage img, imgload, imgblur;
Vec2D[] particles;
int[] particleRoute;
void LoadImageAndScale() {
int tempx = 0;
int tempy = 0;
img = createImage(mainwidth, mainheight, RGB);
imgblur = createImage(mainwidth, mainheight, RGB);
img.loadPixels();
if (invertImg)
for (int i = 0; i < img.pixels.length; i++) {
img.pixels[i] = color(0);
}
else
for (int i = 0; i < img.pixels.length; i++) {
img.pixels[i] = color(255);
}
img.updatePixels();
if ( fileLoaded == false) {
// Load a demo image, at least until we have a "real" image to work with.
imgload = loadImage("grace.jpg"); // Load demo image
// Image source: http://commons.wikimedia.org/wiki/File:Kelly,_Grace_(Rear_Window).jpg
}
if ((imgload.width > mainwidth) || (imgload.height > mainheight)) {
if (((float) imgload.width / (float)imgload.height) > ((float) mainwidth / (float) mainheight))
{
imgload.resize(mainwidth, 0);
}
else
{
imgload.resize(0, mainheight);
}
}
if (imgload.height < (mainheight - 2) ) {
tempy = (int) (( mainheight - imgload.height ) / 2) ;
}
if (imgload.width < (mainwidth - 2)) {
tempx = (int) (( mainwidth - imgload.width ) / 2) ;
}
img.copy(imgload, 0, 0, imgload.width, imgload.height, tempx, tempy, imgload.width, imgload.height);
// For background image!
/*
// Optional gamma correction for background image.
img.loadPixels();
float tempFloat;
float GammaValue = 1.0; // Normally in the range 0.25 - 4.0
for (int i = 0; i < img.pixels.length; i++) {
tempFloat = brightness(img.pixels[i])/255;
img.pixels[i] = color(floor(255 * pow(tempFloat,GammaValue)));
}
img.updatePixels();
*/
imgblur.copy(img, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
// This is a duplicate of the background image, that we will apply a blur to,
// to reduce "high frequency" noise artifacts.
imgblur.filter(BLUR, 1); // Low-level blur filter to elminate pixel-to-pixel noise artifacts.
imgblur.loadPixels();
}
void MainArraysetup() {
// Main particle array initialization (to be called whenever necessary):
LoadImageAndScale();
// image(img, 0, 0); // SHOW BG IMG
particles = new Vec2D[maxParticles];
// Fill array by "rejection sampling"
int i = 0;
while (i < maxParticles)
{
float fx = lowBorderX + random(hiBorderX - lowBorderX);
float fy = lowBorderY + random(hiBorderY - lowBorderY);
float p = brightness(imgblur.pixels[ floor(fy)*imgblur.width + floor(fx) ])/255;
// OK to use simple floor_ rounding here, because this is a one-time operation,
// creating the initial distribution that will be iterated.
if (invertImg)
{
p = 1 - p;
}
// if (random(.5) >= p ) {
if (.5 >= p ) {
Vec2D p1 = new Vec2D(fx, fy);
particles[i] = p1;
i++;
}
}
particleRouteLength = 0;
Generation = 0;
millisLastFrame = millis();
RouteStep = 0;
VoronoiCalculated = false;
cellsCalculated = 0;
vorPointsAdded = 0;
voronoi = new Voronoi(); // Erase mesh
TempShowCells = true;
FileModeTSP = false;
}
boolean sketchFullScreen() {
return false;
}
void setup()
{
borderWidth = 6;
mainwidth = displayWidth/2;
mainheight = displayHeight/2-110;
ctrlheight = 110;
size(mainwidth, mainheight + ctrlheight, JAVA2D);
gfx = new ToxiclibsSupport(this);
lowBorderX = borderWidth; //mainwidth*0.01;
hiBorderX = mainwidth - borderWidth; //mainwidth*0.98;
lowBorderY = borderWidth; // mainheight*0.01;
hiBorderY = mainheight - borderWidth; //mainheight*0.98;
int innerWidth = mainwidth - 2 * borderWidth;
int innerHeight = mainheight - 2 * borderWidth;
clip=new SutherlandHodgemanClipper(new Rect(lowBorderX, lowBorderY, innerWidth, innerHeight));
MainArraysetup(); // Main particle array setup
frameRate(24);
smooth();
noStroke();
fill(153); // Background fill color, for control section
textFont(createFont("SansSerif", 10));
cp5 = new ControlP5(this);
int leftcolumwidth = 225;
int GUItop = mainheight + 15;
int GUI2ndRow = 4; // Spacing for firt row after group heading
int GuiRowSpacing = 14; // Spacing for subsequent rows
int GUIFudge = mainheight + 19; // I wish that we didn't need ONE MORE of these stupid spacings.
ControlGroup l3 = cp5.addGroup("Primary controls (Changing will restart)", 10, GUItop, 225);
cp5.addSlider("Stipples", 10, 10000, maxParticles, 10, GUI2ndRow, 150, 10).setGroup(l3);
InvertOnOff = cp5.addButton("INVERT_IMG", 10, 10, GUI2ndRow + GuiRowSpacing, 190, 10).setGroup(l3);
InvertOnOff.setCaptionLabel("Black stipples, White Background");
Button LoadButton = cp5.addButton("LOAD_FILE", 10, 10, GUIFudge + 3*GuiRowSpacing, 175, 10);
LoadButton.setCaptionLabel("LOAD IMAGE FILE (.PNG, .JPG, or .GIF)");
cp5.addButton("QUIT", 10, 205, GUIFudge + 3*GuiRowSpacing, 30, 10);
cp5.addButton("SAVE_STIPPLES", 10, 25, GUIFudge + 4*GuiRowSpacing, 160, 10);
cp5.controller("SAVE_STIPPLES").setCaptionLabel("Save Stipple File (.SVG format)");
cp5.addButton("SAVE_PATH", 10, 25, GUIFudge + 5*GuiRowSpacing, 160, 10);
cp5.controller("SAVE_PATH").setCaptionLabel("Save \"TSP\" Path (.SVG format)");
ControlGroup l5 = cp5.addGroup("Display Options - Updated on next generation", leftcolumwidth+50, GUItop, 225);
cp5.addSlider("Min_Dot_Size", .5, 8, 2, 10, 4, 140, 10).setGroup(l5);
cp5.controller("Min_Dot_Size").setValue(MinDotSize);
cp5.controller("Min_Dot_Size").setCaptionLabel("Min. Dot Size");
cp5.addSlider("Dot_Size_Range", 0, 20, 5, 10, 18, 140, 10).setGroup(l5);
cp5.controller("Dot_Size_Range").setValue(DotSizeFactor);
cp5.controller("Dot_Size_Range").setCaptionLabel("Dot Size Range");
cp5.addSlider("White_Cutoff", 0, 1, 0, 10, 32, 140, 10).setGroup(l5);
cp5.controller("White_Cutoff").setValue(cutoff);
cp5.controller("White_Cutoff").setCaptionLabel("White Cutoff");
ImgOnOff = cp5.addButton("IMG_ON_OFF", 10, 10, 46, 90, 10);
ImgOnOff.setGroup(l5);
ImgOnOff.setCaptionLabel("Image BG >> Hide");
CellOnOff = cp5.addButton("CELLS_ON_OFF", 10, 110, 46, 90, 10);
CellOnOff.setGroup(l5);
CellOnOff.setCaptionLabel("Cells >> Hide");
PauseButton = cp5.addButton("Pause", 10, 10, 60, 190, 10);
PauseButton.setGroup(l5);
PauseButton.setCaptionLabel("Pause (to calculate TSP path)");
OrderOnOff = cp5.addButton("ORDER_ON_OFF", 10, 10, 74, 190, 10);
OrderOnOff.setGroup(l5);
OrderOnOff.setCaptionLabel("Plotting path >> shown while paused");
TextColumnStart = 2 * leftcolumwidth + 100;
MaxDotSize = MinDotSize * (1 + DotSizeFactor);
ReInitiallizeArray = false;
pausemode = true;
showBG = false;
invertImg = false;
showPath = false;
showCells = false;
fileLoaded = false;
SaveNow = 0;
}
void LOAD_FILE(float theValue) {
println(":::LOAD JPG, GIF or PNG FILE:::");
selectInput("Select a file to process:", "fileSelected");
} //End Load File
void fileSelected(File selection) {
if (selection == null) {
// If a file was not selected
println("No file was selected...");
}
else {
// If a file was selected, print path to file
println("Loaded file: " + selection.getPath());
String[] p = splitTokens(selection.getPath(), ".");
boolean fileOK = false;
if ( p[p.length - 1].equals("GIF"))
fileOK = true;
if ( p[p.length - 1].equals("gif"))
fileOK = true;
if ( p[p.length - 1].equals("JPG"))
fileOK = true;
if ( p[p.length - 1].equals("jpg"))
fileOK = true;
if ( p[p.length - 1].equals("TGA"))
fileOK = true;
if ( p[p.length - 1].equals("tga"))
fileOK = true;
if ( p[p.length - 1].equals("PNG"))
fileOK = true;
if ( p[p.length - 1].equals("png"))
fileOK = true;
println("File OK: " + fileOK);
if (fileOK) {
imgload = loadImage( selection.getAbsolutePath());
fileLoaded = true;
// MainArraysetup();
ReInitiallizeArray = true;
}
else {
// Can't load file
ErrorDisplay = "ERROR: BAD FILE TYPE";
ErrorTime = millis();
ErrorDisp = true;
}
}
} //End Load File
void SAVE_PATH(float theValue) {
FileModeTSP = true;
SAVE_SVG(0);
}
void SAVE_STIPPLES(float theValue) {
FileModeTSP = false;
SAVE_SVG(0);
}
void SAVE_SVG(float theValue) {
if (pausemode != true) {
Pause(0.0);
ErrorDisplay = "Error: PAUSE before saving.";
ErrorTime = millis();
ErrorDisp = true;
}
else {
// savePath = selectOutput("Output .svg file name:"); // Opens file chooser
if (savePath == null) {
// If a file was not selected
println("No output file was selected...");
ErrorDisplay = "ERROR: NO FILE NAME CHOSEN.";
ErrorTime = millis();
ErrorDisp = true;
}
else {
String[] p = splitTokens(savePath, ".");
boolean fileOK = false;
if ( p[p.length - 1].equals("SVG"))
fileOK = true;
if ( p[p.length - 1].equals("svg"))
fileOK = true;
if (fileOK == false)
savePath = savePath + ".svg";
// If a file was selected, print path to folder
println("Save file: " + savePath);
SaveNow = 1;
showPath = true;
ErrorDisplay = "SAVING FILE...";
ErrorTime = millis();
ErrorDisp = true;
}
}
}
void QUIT(float theValue) {
exit();
}
void ORDER_ON_OFF(float theValue) {
if (showPath) {
showPath = false;
OrderOnOff.setCaptionLabel("Plotting path >> Hide");
}
else {
showPath = true;
OrderOnOff.setCaptionLabel("Plotting path >> Shown while paused");
}
}
void CELLS_ON_OFF(float theValue) {
if (showCells) {
showCells = false;
CellOnOff.setCaptionLabel("Cells >> Hide");
}
else {
showCells = true;
CellOnOff.setCaptionLabel("Cells >> Show");
}
}
void IMG_ON_OFF(float theValue) {
if (showBG) {
showBG = false;
ImgOnOff.setCaptionLabel("Image BG >> Hide");
}
else {
showBG = true;
ImgOnOff.setCaptionLabel("Image BG >> Show");
}
}
void INVERT_IMG(float theValue) {
if (invertImg) {
invertImg = false;
InvertOnOff.setCaptionLabel("Black stipples, White Background");
cp5.controller("White_Cutoff").setCaptionLabel("White Cutoff");
}
else {
invertImg = true;
InvertOnOff.setCaptionLabel("White stipples, Black Background");
cp5.controller("White_Cutoff").setCaptionLabel("Black Cutoff");
}
ReInitiallizeArray = true;
pausemode = false;
}
void Pause(float theValue) {
// Main particle array setup (to be repeated if necessary):
if (pausemode)
{
pausemode = false;
println("Resuming.");
PauseButton.setCaptionLabel("Pause (to calculate TSP path)");
}
else
{
pausemode = true;
println("Paused. Press PAUSE again to resume.");
PauseButton.setCaptionLabel("Paused (calculating TSP path)");
}
RouteStep = 0;
}
boolean overRect(int x, int y, int width, int height)
{
if (mouseX >= x && mouseX <= x+width &&
mouseY >= y && mouseY <= y+height) {
return true;
}
else {
return false;
}
}
void Stipples(int inValue) {
if (maxParticles != (int) inValue) {
println("Update: Stipple Count -> " + inValue);
ReInitiallizeArray = true;
pausemode = false;
}
}
void Min_Dot_Size(float inValue) {
if (MinDotSize != inValue) {
println("Update: Min_Dot_Size -> "+inValue);
MinDotSize = inValue;
MaxDotSize = MinDotSize* (1 + DotSizeFactor);
}
}
void Dot_Size_Range(float inValue) {
if (DotSizeFactor != inValue) {
println("Update: Dot Size Range -> "+inValue);
DotSizeFactor = inValue;
MaxDotSize = MinDotSize* (1 + DotSizeFactor);
}
}
void White_Cutoff(float inValue) {
if (cutoff != inValue) {
println("Update: White_Cutoff -> "+inValue);
cutoff = inValue;
RouteStep = 0; // Reset TSP path
}
}
void DoBackgrounds() {
if (showBG)
image(imgblur, 0, 0); // Show original (cropped and scaled, but not blurred!) image in background
else {
if (invertImg)
fill(0);
else
fill(255);
rect(0, 0, mainwidth, mainheight);
}
}
void OptimizePlotPath()
{
int temp;
// Calculate and show "optimized" plotting path, beneath points.
StatusDisplay = "Optimizing plotting path";
/*
if (RouteStep % 100 == 0) {
println("RouteStep:" + RouteStep);
println("fps = " + frameRate );
}
*/
Vec2D p1;
if (RouteStep == 0)
{
float cutoffScaled = 1 - cutoff;
// Begin process of optimizing plotting route, by flagging particles that will be shown.
particleRouteLength = 0;
boolean particleRouteTemp[] = new boolean[maxParticles];
for (int i = 0; i < maxParticles; ++i) {
particleRouteTemp[i] = false;
int px = (int) particles[i].x;
int py = (int) particles[i].y;
if ((px >= imgblur.width) || (py >= imgblur.height) || (px < 0) || (py < 0))
continue;
float v = (brightness(imgblur.pixels[ py*imgblur.width + px ]))/255;
if (invertImg)
v = 1 - v;
if (v < cutoffScaled) {
particleRouteTemp[i] = true;
particleRouteLength++;
}
}
particleRoute = new int[particleRouteLength];
int tempCounter = 0;
for (int i = 0; i < maxParticles; ++i) {
if (particleRouteTemp[i])
{
particleRoute[tempCounter] = i;
tempCounter++;
}
}
// These are the ONLY points to be drawn in the tour.
}
if (RouteStep < (particleRouteLength - 2))
{
// Nearest neighbor ("Simple, Greedy") algorithm path optimization:
int StopPoint = RouteStep + 1000; // 1000 steps per frame displayed; you can edit this number!
if (StopPoint > (particleRouteLength - 1))
StopPoint = particleRouteLength - 1;
for (int i = RouteStep; i < StopPoint; ++i) {
p1 = particles[particleRoute[RouteStep]];
int ClosestParticle = 0;
float distMin = Float.MAX_VALUE;
for (int j = RouteStep + 1; j < (particleRouteLength - 1); ++j) {
Vec2D p2 = particles[particleRoute[j]];
float dx = p1.x - p2.x;
float dy = p1.y - p2.y;
float distance = (float) (dx*dx+dy*dy); // Only looking for closest; do not need sqrt factor!
if (distance < distMin) {
ClosestParticle = j;
distMin = distance;
}
}
temp = particleRoute[RouteStep + 1];
// p1 = particles[particleRoute[RouteStep + 1]];
particleRoute[RouteStep + 1] = particleRoute[ClosestParticle];
particleRoute[ClosestParticle] = temp;
if (RouteStep < (particleRouteLength - 1))
RouteStep++;
else
{
println("Now optimizing plot path" );
}
}
}
else
{ // Initial routing is complete
// 2-opt heuristic optimization:
// Identify a pair of edges that would become shorter by reversing part of the tour.
for (int i = 0; i < 9000; ++i) { // 1000 tests per frame; you can edit this number.
int indexA = floor(random(particleRouteLength - 1));
int indexB = floor(random(particleRouteLength - 1));
if (Math.abs(indexA - indexB) < 2)
continue;
if (indexB < indexA)
{ // swap A, B.
temp = indexB;
indexB = indexA;
indexA = temp;
}
Vec2D a0 = particles[particleRoute[indexA]];
Vec2D a1 = particles[particleRoute[indexA + 1]];
Vec2D b0 = particles[particleRoute[indexB]];
Vec2D b1 = particles[particleRoute[indexB + 1]];
// Original distance:
float dx = a0.x - a1.x;
float dy = a0.y - a1.y;
float distance = (float) (dx*dx+dy*dy); // Only a comparison; do not need sqrt factor!
dx = b0.x - b1.x;
dy = b0.y - b1.y;
distance += (float) (dx*dx+dy*dy); // Only a comparison; do not need sqrt factor!
// Possible shorter distance?
dx = a0.x - b0.x;
dy = a0.y - b0.y;
float distance2 = (float) (dx*dx+dy*dy); // Only a comparison; do not need sqrt factor!
dx = a1.x - b1.x;
dy = a1.y - b1.y;
distance2 += (float) (dx*dx+dy*dy); // Only a comparison; do not need sqrt factor!
if (distance2 < distance)
{
// Reverse tour between a1 and b0.
int indexhigh = indexB;
int indexlow = indexA + 1;
// println("Shorten!" + frameRate );
while (indexhigh > indexlow)
{
temp = particleRoute[indexlow];
particleRoute[indexlow] = particleRoute[indexhigh];
particleRoute[indexhigh] = temp;
indexhigh--;
indexlow++;
}
}
}
}
frameTime = (millis() - millisLastFrame)/1000;
millisLastFrame = millis();
}
void doPhysics()
{ // Iterative relaxation via weighted Lloyd's algorithm.
int temp;
int CountTemp;
if (VoronoiCalculated == false)
{ // Part I: Calculate voronoi cell diagram of the points.
StatusDisplay = "Calculating Voronoi diagram ";
// float millisBaseline = millis(); // Baseline for timing studies
// println("Baseline. Time = " + (millis() - millisBaseline) );
if (vorPointsAdded == 0)
voronoi = new Voronoi(); // Erase mesh
temp = vorPointsAdded + maxParticles/5; // This line: VoronoiPointsPerPass (Feel free to edit this number.)
if (temp > maxParticles)
temp = maxParticles;
for (int i = vorPointsAdded; i < temp; ++i) {
voronoi.addPoint(new Vec2D(particles[i].x, particles[i].y ));
vorPointsAdded++;
}
if (vorPointsAdded >= maxParticles)
{
// println("Points added. Time = " + (millis() - millisBaseline) );
RegionList = voronoi.getRegions();
cellsTotal = (RegionList.size());
vorPointsAdded = 0;
cellsCalculated = 0;
cellsCalculatedLast = 0;
// RegionList = new Polygon2D[cellsTotal];
// int i = 0;
// for (Polygon2D poly : voronoi.getRegions()) {
// RegionList[i++] = poly; // Build array of polygons
// }
VoronoiCalculated = true;
}
}
else
{ // Part II: Calculate weighted centroids of cells.
// float millisBaseline = millis();
// println("fps = " + frameRate );
StatusDisplay = "Calculating weighted centroids";
temp = cellsCalculated + cellsTotal/5; // This line: CentroidsPerPass (Feel free to edit this number.)
// Higher values give slightly faster computation, but a less responsive GUI.
if (temp > cellsTotal)
{
temp = cellsTotal;
}
for (int i=cellsCalculated; i< temp; i++) {
float xMax = 0;
float xMin = mainwidth;
float yMax = 0;
float yMin = mainheight;
float xt, yt;
Polygon2D region = clip.clipPolygon(RegionList.get(i));
for (Vec2D v : region.vertices) {
xt = v.x;
yt = v.y;
if (xt < xMin)
xMin = xt;
if (xt > xMax)
xMax = xt;
if (yt < yMin)
yMin = yt;
if (yt > yMax)
yMax = yt;
}
float xDiff = xMax - xMin;
float yDiff = yMax - yMin;
float maxSize = max(xDiff, yDiff);
float minSize = min(xDiff, yDiff);
float scaleFactor = 1.0;
// Maximum voronoi cell extent should be between
// cellBuffer/2 and cellBuffer in size.
while (maxSize > cellBuffer)
{
scaleFactor /= 2;
maxSize /=2 ;
}
while (maxSize < (cellBuffer/2))
{
scaleFactor *= 2;
maxSize *= 2;
}
if ((minSize * scaleFactor) > (cellBuffer/2))
{ // Special correction for objects of near-unity (square-like) aspect ratio,
// which have larger area *and* where it is less essential to find the exact centroid:
scaleFactor *= 0.5;
}
float StepSize = (1/scaleFactor);
float xSum = 0;
float ySum = 0;
float dSum = 0;
float PicDensity = 1.0;
if (invertImg)
for (float x=xMin; x<=xMax; x += StepSize) {
for (float y=yMin; y<=yMax; y += StepSize) {
Vec2D p0 = new Vec2D(x, y);
if (region.containsPoint(p0)) {
// Thanks to polygon clipping, NO vertices will be beyond the sides of imgblur.
PicDensity = 0.001 + (brightness(imgblur.pixels[ round(y)*imgblur.width + round(x) ]));
xSum += PicDensity * x;
ySum += PicDensity * y;