-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplanet-generator.js
4222 lines (3749 loc) · 135 KB
/
planet-generator.js
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
var scene = null;
var camera = null;
var renderer = null;
var projector = null;
var directionalLight = null;
var activeAction = null;
var planet = null;
var tileSelection = null;
var zoom = 1.0;
var zoomAnimationStartTime = null;
var zoomAnimationDuration = null;
var zoomAnimationStartValue = null;
var zoomAnimationEndValue = null;
var cameraLatitude = 0;
var cameraLongitude = 0;
var projectionRenderMode = "globe";
var surfaceRenderMode = "terrain";
var renderSunlight = true;
var renderPlateBoundaries = false;
var renderPlateMovements = false;
var renderAirCurrents = false;
var sunTimeOffset = 0;
var pressedKeys = {};
var disableKeys = false;
var ui = {};
var generationSettings =
{
subdivisions: 20,
distortionLevel: 1,
plateCount: 36,
oceanicRate: 0.7,
heatLevel: 1.0,
moistureLevel: 1.0,
seed: null,
};
var Vector3 = THREE.Vector3;
var KEY_ENTER = 13;
var KEY_SHIFT = 16;
var KEY_ESCAPE = 27;
var KEY_SPACE = 32;
var KEY_LEFTARROW = 37;
var KEY_UPARROW = 38;
var KEY_RIGHTARROW = 39;
var KEY_DOWNARROW = 40;
var KEY_PAGEUP = 33;
var KEY_PAGEDOWN = 34;
var KEY_NUMPAD_PLUS = 107;
var KEY_NUMPAD_MINUS = 109;
var KEY_FORWARD_SLASH = 191;
var KEY = {};
for (var k = 0; k < 10; ++k) KEY[ String.fromCharCode(k + 48) ] = k + 48;
for (var k = 0; k < 26; ++k) KEY[ String.fromCharCode(k + 65) ] = k + 65;
$(document).ready(function onDocumentReady()
{
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, 1, 0.2, 2000);
mapCamera = new THREE.OrthographicCamera(-1, 1, -1, 1, 1, 10);
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
projector = new THREE.Projector();
mapCamera.position.set(0, 0, 8);
mapCamera.up.set(0, 1, 0);
mapCamera.lookAt(new Vector3(0, 0, 0));
mapCamera.updateProjectionMatrix();
renderer.setFaceCulling(THREE.CullFaceFront, THREE.FrontFaceDirectionCW);
var ambientLight = new THREE.AmbientLight(0xFFFFFF);
scene.add(ambientLight);
directionalLight = new THREE.DirectionalLight(0xFFFFFF);
directionalLight.position.set(-3, 3, 7).normalize();
scene.add(directionalLight);
requestAnimationFrame(render);
resetCamera();
updateCamera();
ui.body = $("body");
ui.frame = $("#viewportFrame");
ui.rendererElement = $(renderer.domElement);
ui.frame.append(ui.rendererElement);
ui.rendererElement.on("mousewheel", zoomHandler);
ui.rendererElement.on("click", clickHandler);
ui.body.on("keydown", keyDownHandler);
ui.body.on("keyup", keyUpHandler);
ui.body.focus();
ui.helpPanel = $("#helpPanel");
ui.controlPanel = $("#controlPanel");
ui.projectionDisplayButtons =
{
globe: $("#projectGlobe"),
equalAreaMap: $("#projectEqualAreaMap"),
mercatorMap: $("#projectMercatorMap"),
};
ui.projectionDisplayButtons.globe.click(setProjectionRenderMode.bind(null, "globe"));
ui.projectionDisplayButtons.equalAreaMap.click(setProjectionRenderMode.bind(null, "equalAreaMap"));
ui.projectionDisplayButtons.mercatorMap.click(setProjectionRenderMode.bind(null, "mercatorMap"));
ui.surfaceDisplayButtons =
{
terrain: $("#showTerrainButton"),
plates: $("#showPlatesButton"),
elevation: $("#showElevationButton"),
temperature: $("#showTemperatureButton"),
moisture: $("#showMoistureButton"),
};
ui.surfaceDisplayButtons.terrain.click(setSurfaceRenderMode.bind(null, "terrain"));
ui.surfaceDisplayButtons.plates.click(setSurfaceRenderMode.bind(null, "plates"));
ui.surfaceDisplayButtons.elevation.click(setSurfaceRenderMode.bind(null, "elevation"));
ui.surfaceDisplayButtons.temperature.click(setSurfaceRenderMode.bind(null, "temperature"));
ui.surfaceDisplayButtons.moisture.click(setSurfaceRenderMode.bind(null, "moisture"));
ui.showSunlightButton = $("#showSunlightButton");
ui.showPlateBoundariesButton = $("#showPlateBoundariesButton");
ui.showPlateMovementsButton = $("#showPlateMovementsButton");
ui.showAirCurrentsButton = $("#showAirCurrentsButton");
ui.showSunlightButton.click(showHideSunlight);
ui.showPlateBoundariesButton.click(showHidePlateBoundaries);
ui.showPlateMovementsButton.click(showHidePlateMovements);
ui.showAirCurrentsButton.click(showHideAirCurrents);
ui.lowDetailButton = $("#lowDetailButton");
ui.mediumDetailButton = $("#mediumDetailButton");
ui.highDetailButton = $("#highDetailButton");
ui.generatePlanetButton = $("#generatePlanetButton");
ui.advancedSettingsButton = $("#advancedSettingsButton");
ui.lowDetailButton.click(setSubdivisions.bind(null, 20));
ui.mediumDetailButton.click(setSubdivisions.bind(null, 40));
ui.highDetailButton.click(setSubdivisions.bind(null, 60));
ui.generatePlanetButton.click(generatePlanetAsynchronous);
ui.advancedSettingsButton.click(showAdvancedSettings);
ui.dataPanel = $("#dataPanel");
ui.progressPanel = $("#progressPanel");
ui.progressActionLabel = $("#progressActionLabel");
ui.progressBarFrame = $("#progressBarFrame");
ui.progressBar = $("#progressBar");
ui.progressBarLabel = $("#progressBarLabel");
ui.progressCancelButton = $("#progressCancelButton");
ui.progressCancelButton.click(cancelButtonHandler);
ui.progressPanel.hide();
ui.tileCountLabel = $("#tileCountLabel");
ui.pentagonCountLabel = $("#pentagonCountLabel");
ui.hexagonCountLabel = $("#hexagonCountLabel");
ui.heptagonCountLabel = $("#heptagonCountLabel");
ui.plateCountLabel = $("#plateCountLabel");
ui.waterPercentageLabel = $("#waterPercentageLabel");
ui.rawSeedLabel = $("#rawSeedLabel");
ui.originalSeedLabel = $("#originalSeedLabel");
ui.minAirCurrentSpeedLabel = $("#minAirCurrentSpeedLabel");
ui.avgAirCurrentSpeedLabel = $("#avgAirCurrentSpeedLabel");
ui.maxAirCurrentSpeedLabel = $("#maxAirCurrentSpeedLabel");
ui.minElevationLabel = $("#minElevationLabel");
ui.avgElevationLabel = $("#avgElevationLabel");
ui.maxElevationLabel = $("#maxElevationLabel");
ui.minTemperatureLabel = $("#minTemperatureLabel");
ui.avgTemperatureLabel = $("#avgTemperatureLabel");
ui.maxTemperatureLabel = $("#maxTemperatureLabel");
ui.minMoistureLabel = $("#minMoistureLabel");
ui.avgMoistureLabel = $("#avgMoistureLabel");
ui.maxMoistureLabel = $("#maxMoistureLabel");
ui.minPlateMovementSpeedLabel = $("#minPlateMovementSpeedLabel");
ui.avgPlateMovementSpeedLabel = $("#avgPlateMovementSpeedLabel");
ui.maxPlateMovementSpeedLabel = $("#maxPlateMovementSpeedLabel");
ui.minTileAreaLabel = $("#minTileAreaLabel");
ui.avgTileAreaLabel = $("#avgTileAreaLabel");
ui.maxTileAreaLabel = $("#maxTileAreaLabel");
ui.minPlateAreaLabel = $("#minPlateAreaLabel");
ui.avgPlateAreaLabel = $("#avgPlateAreaLabel");
ui.maxPlateAreaLabel = $("#maxPlateAreaLabel");
ui.minPlateCircumferenceLabel = $("#minPlateCircumferenceLabel");
ui.avgPlateCircumferenceLabel = $("#avgPlateCircumferenceLabel");
ui.maxPlateCircumferenceLabel = $("#maxPlateCircumferenceLabel");
ui.generationSettingsPanel = $("#generationSettingsPanel");
ui.detailLevelLabel = $("#detailLevelLabel");
ui.detailLevelRange = $("#detailLevelRange");
ui.distortionLevelLabel = $("#distortionLevelLabel");
ui.distortionLevelRange = $("#distortionLevelRange");
ui.tectonicPlateCountLabel = $("#tectonicPlateCountLabel");
ui.tectonicPlateCountRange = $("#tectonicPlateCountRange");
ui.oceanicRateLabel = $("#oceanicRateLabel");
ui.oceanicRateRange = $("#oceanicRateRange");
ui.heatLevelLabel = $("#heatLevelLabel");
ui.heatLevelRange = $("#heatLevelRange");
ui.moistureLevelLabel = $("#moistureLevelLabel");
ui.moistureLevelRange = $("#moistureLevelRange");
ui.seedTextBox = $("#seedTextBox");
ui.advancedGeneratePlanetButton = $("#advancedGeneratePlanetButton");
ui.advancedCancelButton = $("#advancedCancelButton");
ui.detailLevelRange.on("input", function() { setSubdivisions(parseInt(ui.detailLevelRange.val())); });
ui.distortionLevelRange.on("input", function() { setDistortionLevel(parseInt(ui.distortionLevelRange.val()) / 100); });
ui.tectonicPlateCountRange.on("input", function() { setPlateCount(Math.floor(Math.pow(2, parseInt(ui.tectonicPlateCountRange.val()) / 300 * (Math.log(1000) / Math.log(2) - 1) + 1))); });
ui.oceanicRateRange.on("input", function() { setOceanicRate(parseInt(ui.oceanicRateRange.val()) / 100); });
ui.heatLevelRange.on("input", function() { setHeatLevel(parseInt(ui.heatLevelRange.val()) / 100 + 1); });
ui.moistureLevelRange.on("input", function() { setMoistureLevel(parseInt(ui.moistureLevelRange.val()) / 100 + 1); });
ui.seedTextBox.on("input", function() { setSeed(ui.seedTextBox.val()); });
ui.advancedGeneratePlanetButton.click(function() { hideAdvancedSettings(); generatePlanetAsynchronous(); });
ui.advancedCancelButton.click(hideAdvancedSettings);
$("button").on("click", function(b) { $(this).blur(); });
$("button").on("focus", function() { disableKeys = true; });
$("input").on("focus", function() { disableKeys = true; });
$("button").on("blur", function() { disableKeys = false; });
$("input").on("blur", function() { disableKeys = false; });
hideAdvancedSettings();
setPlateCount(50);
setProjectionRenderMode(projectionRenderMode, true);
setSurfaceRenderMode(surfaceRenderMode, true);
showHideSunlight(renderSunlight);
showHidePlateBoundaries(renderPlateBoundaries);
showHidePlateMovements(renderPlateMovements);
showHideAirCurrents(renderAirCurrents);
ui.lowDetailButton.click();
//saveToFileSystem(serializePlanetMesh(planet.mesh, "function getPregeneratedPlanetMesh() { return ", "; }\n"));
window.addEventListener("resize", resizeHandler);
resizeHandler();
ui.generatePlanetButton.click();
});
function setSubdivisions(subdivisions)
{
if (typeof(subdivisions) === "number" && subdivisions >= 4)
{
generationSettings.subdivisions = subdivisions;
$("#detailDisplaylist>button.toggled").removeClass("toggled");
if (subdivisions === 20) ui.lowDetailButton.addClass("toggled");
else if (subdivisions === 40) ui.mediumDetailButton.addClass("toggled");
else if (subdivisions === 60) ui.highDetailButton.addClass("toggled");
subdivisions = subdivisions.toFixed(0);
if (ui.detailLevelRange.val() !== subdivisions) ui.detailLevelRange.val(subdivisions);
ui.detailLevelLabel.text("Detail Level (" + subdivisions + ")");
}
}
function setDistortionLevel(distortionLevel)
{
if (typeof(distortionLevel) === "number" && distortionLevel >= 0 && distortionLevel <= 1)
{
generationSettings.distortionLevel = distortionLevel;
distortionLevel = Math.floor(distortionLevel * 100 + 0.5).toFixed(0);
if (ui.distortionLevelRange.val() !== distortionLevel) ui.distortionLevelRange.val(distortionLevel);
ui.distortionLevelLabel.text("Distortion Level (" + distortionLevel + "%)");
}
}
function setPlateCount(plateCount)
{
if (typeof(plateCount) === "number" && plateCount >= 0)
{
generationSettings.plateCount = plateCount;
var sliderVal = Math.ceil((Math.log(plateCount) / Math.log(2) - 1) / (Math.log(1000) / Math.log(2) - 1) * 300).toFixed(0);
if (ui.tectonicPlateCountRange.val() !== sliderVal) ui.tectonicPlateCountRange.val(sliderVal);
ui.tectonicPlateCountLabel.text(plateCount.toFixed(0));
}
}
function setOceanicRate(oceanicRate)
{
if (typeof(oceanicRate) === "number" && oceanicRate >= 0 && oceanicRate <= 1)
{
generationSettings.oceanicRate = oceanicRate;
oceanicRate = Math.floor(oceanicRate * 100 + 0.5).toFixed(0);
if (ui.oceanicRateRange.val() !== oceanicRate) ui.oceanicRateRange.val(oceanicRate);
ui.oceanicRateLabel.text(oceanicRate);
}
}
function setHeatLevel(heatLevel)
{
if (typeof(heatLevel) === "number" && heatLevel >= 0)
{
generationSettings.heatLevel = heatLevel;
heatLevel = Math.floor(heatLevel * 100 - 100).toFixed(0);
if (ui.heatLevelRange.val() !== heatLevel) ui.heatLevelRange.val(heatLevel);
if (generationSettings.heatLevel > 1) heatLevel = "+" + heatLevel;
else if (generationSettings.heatLevel < 1) heatLevel = "-" + heatLevel;
ui.heatLevelLabel.text(heatLevel);
}
}
function setMoistureLevel(moistureLevel)
{
if (typeof(moistureLevel) === "number" && moistureLevel >= 0)
{
generationSettings.moistureLevel = moistureLevel;
moistureLevel = Math.floor(moistureLevel * 100 - 100).toFixed(0);
if (ui.moistureLevelRange.val() !== moistureLevel) ui.moistureLevelRange.val(moistureLevel);
if (generationSettings.moistureLevel > 1) moistureLevel = "+" + moistureLevel;
else if (generationSettings.moistureLevel < 1) moistureLevel = "-" + moistureLevel;
ui.moistureLevelLabel.text(moistureLevel);
}
}
function setSeed(seed)
{
if (!seed) generationSettings.seed = null;
if (typeof(seed) === "number")
{
generationSettings.seed = Math.floor(seed);
ui.seedTextBox.val(generationSettings.seed.toFixed(0));
}
else if (typeof(seed) === "string")
{
var asInt = parseInt(seed);
if (isNaN(asInt) || asInt.toFixed(0) !== seed)
{
generationSettings.seed = seed;
}
else
{
generationSettings.seed = asInt;
ui.seedTextBox.val(generationSettings.seed.toFixed(0));
}
}
else
{
generationSettings.seed = null;
ui.seedTextBox.val("");
}
}
function generatePlanetAsynchronous()
{
var planet;
var subdivisions = generationSettings.subdivisions;
var distortionRate;
if (generationSettings.distortionLevel < 0.25) distortionRate = adjustRange(generationSettings.distortionLevel, 0.00, 0.25, 0.000, 0.040);
else if (generationSettings.distortionLevel < 0.50) distortionRate = adjustRange(generationSettings.distortionLevel, 0.25, 0.50, 0.040, 0.050);
else if (generationSettings.distortionLevel < 0.75) distortionRate = adjustRange(generationSettings.distortionLevel, 0.50, 0.75, 0.050, 0.075);
else distortionRate = adjustRange(generationSettings.distortionLevel, 0.75, 1.00, 0.075, 0.150);
var originalSeed = generationSettings.seed;
var seed;
if (typeof(originalSeed) === "number") seed = originalSeed;
else if (typeof(originalSeed) === "string") seed = hashString(originalSeed);
else seed = Date.now();
var random = new XorShift128(seed);
var plateCount = generationSettings.plateCount;
var oceanicRate = generationSettings.oceanicRate;
var heatLevel = generationSettings.heatLevel;
var moistureLevel = generationSettings.moistureLevel;
activeAction = new SteppedAction(updateProgressUI)
.executeSubaction(function(action) { ui.progressPanel.show(); }, 0)
.executeSubaction(function(action) { generatePlanet(subdivisions, distortionRate, plateCount, oceanicRate, heatLevel, moistureLevel, random, action); }, 1, "Generating Planet")
.getResult(function(result) { planet = result; planet.seed = seed; planet.originalSeed = originalSeed; })
.executeSubaction(function(action) { displayPlanet(planet); setSeed(null); }, 0)
.finalize(function(action) { activeAction = null; ui.progressPanel.hide(); }, 0)
.execute();
}
function showAdvancedSettings()
{
ui.generationSettingsPanel.show();
}
function hideAdvancedSettings()
{
ui.generationSettingsPanel.hide();
}
function Planet()
{
}
function generatePlanet(icosahedronSubdivision, topologyDistortionRate, plateCount, oceanicRate, heatLevel, moistureLevel, random, action)
{
var planet = new Planet();
var mesh;
action
.executeSubaction(function(action) { generatePlanetMesh(icosahedronSubdivision, topologyDistortionRate, random, action); }, 6, "Generating Mesh")
.getResult(function(result) { mesh = result; })
.executeSubaction(function(action) { generatePlanetTopology(mesh, action); }, 1, "Generating Topology")
.getResult(function(result) { planet.topology = result; })
.executeSubaction(function(action) { generatePlanetPartition(planet.topology.tiles, action); }, 1, "Generating Spatial Partitions")
.getResult(function(result) { planet.partition = result; })
.executeSubaction(function(action) { generatePlanetTerrain(planet, plateCount, oceanicRate, heatLevel, moistureLevel, random, action); }, 8, "Generating Terrain")
.executeSubaction(function(action) { generatePlanetRenderData(planet.topology, random, action); }, 1, "Building Visuals")
.getResult(function(result) { planet.renderData = result; })
.executeSubaction(function(action) { generatePlanetStatistics(planet.topology, planet.plates, action); }, 1, "Compiling Statistics")
.getResult(function(result) { planet.statistics = result; })
.provideResult(planet);
}
function generatePlanetMesh(icosahedronSubdivision, topologyDistortionRate, random, action)
{
var mesh;
action.executeSubaction(function(action)
{
mesh = generateSubdividedIcosahedron(icosahedronSubdivision);
}, 1, "Generating Subdivided Icosahedron");
action.executeSubaction(function(action)
{
var totalDistortion = Math.ceil(mesh.edges.length * topologyDistortionRate);
var remainingIterations = 6;
action.executeSubaction(function(action)
{
var iterationDistortion = Math.floor(totalDistortion / remainingIterations);
totalDistortion -= iterationDistortion;
action.executeSubaction(function(action) { distortMesh(mesh, iterationDistortion, random, action); });
action.executeSubaction(function(action) { relaxMesh(mesh, 0.5, action); });
--remainingIterations;
if (remainingIterations > 0) action.loop(1 - remainingIterations / 6);
});
}, 15, "Distorting Triangle Mesh");
action.executeSubaction(function(action)
{
var initialIntervalIteration = action.intervalIteration;
var averageNodeRadius = Math.sqrt(4 * Math.PI / mesh.nodes.length);
var minShiftDelta = averageNodeRadius / 50000 * mesh.nodes.length;
var maxShiftDelta = averageNodeRadius / 50 * mesh.nodes.length;
var priorShift;
var currentShift = relaxMesh(mesh, 0.5, action);
action.executeSubaction(function(action)
{
priorShift = currentShift;
currentShift = relaxMesh(mesh, 0.5, action);
var shiftDelta = Math.abs(currentShift - priorShift);
if (shiftDelta >= minShiftDelta && action.intervalIteration - initialIntervalIteration < 300)
{
action.loop(Math.pow(Math.max(0, (maxShiftDelta - shiftDelta) / (maxShiftDelta - minShiftDelta)), 4));
}
});
}, 25, "Relaxing Triangle Mesh");
action.executeSubaction(function(action)
{
for (var i = 0; i < mesh.faces.length; ++i)
{
var face = mesh.faces[i];
var p0 = mesh.nodes[face.n[0]].p;
var p1 = mesh.nodes[face.n[1]].p;
var p2 = mesh.nodes[face.n[2]].p;
face.centroid = calculateFaceCentroid(p0, p1, p2).normalize();
}
}, 1, "Calculating Triangle Centroids");
action.executeSubaction(function(action)
{
for (var i = 0; i < mesh.nodes.length; ++i)
{
var node = mesh.nodes[i];
var faceIndex = node.f[0];
for (var j = 1; j < node.f.length - 1; ++j)
{
faceIndex = findNextFaceIndex(mesh, i, faceIndex);
var k = node.f.indexOf(faceIndex);
node.f[k] = node.f[j];
node.f[j] = faceIndex;
}
}
}, 1, "Reordering Triangle Nodes");
action.provideResult(function() { return mesh; });
}
function generateIcosahedron()
{
var phi = (1.0 + Math.sqrt(5.0)) / 2.0;
var du = 1.0 / Math.sqrt(phi * phi + 1.0);
var dv = phi * du;
nodes =
[
{ p: new Vector3(0, +dv, +du), e: [], f: [] },
{ p: new Vector3(0, +dv, -du), e: [], f: [] },
{ p: new Vector3(0, -dv, +du), e: [], f: [] },
{ p: new Vector3(0, -dv, -du), e: [], f: [] },
{ p: new Vector3(+du, 0, +dv), e: [], f: [] },
{ p: new Vector3(-du, 0, +dv), e: [], f: [] },
{ p: new Vector3(+du, 0, -dv), e: [], f: [] },
{ p: new Vector3(-du, 0, -dv), e: [], f: [] },
{ p: new Vector3(+dv, +du, 0), e: [], f: [] },
{ p: new Vector3(+dv, -du, 0), e: [], f: [] },
{ p: new Vector3(-dv, +du, 0), e: [], f: [] },
{ p: new Vector3(-dv, -du, 0), e: [], f: [] },
];
edges =
[
{ n: [ 0, 1, ], f: [], },
{ n: [ 0, 4, ], f: [], },
{ n: [ 0, 5, ], f: [], },
{ n: [ 0, 8, ], f: [], },
{ n: [ 0, 10, ], f: [], },
{ n: [ 1, 6, ], f: [], },
{ n: [ 1, 7, ], f: [], },
{ n: [ 1, 8, ], f: [], },
{ n: [ 1, 10, ], f: [], },
{ n: [ 2, 3, ], f: [], },
{ n: [ 2, 4, ], f: [], },
{ n: [ 2, 5, ], f: [], },
{ n: [ 2, 9, ], f: [], },
{ n: [ 2, 11, ], f: [], },
{ n: [ 3, 6, ], f: [], },
{ n: [ 3, 7, ], f: [], },
{ n: [ 3, 9, ], f: [], },
{ n: [ 3, 11, ], f: [], },
{ n: [ 4, 5, ], f: [], },
{ n: [ 4, 8, ], f: [], },
{ n: [ 4, 9, ], f: [], },
{ n: [ 5, 10, ], f: [], },
{ n: [ 5, 11, ], f: [], },
{ n: [ 6, 7, ], f: [], },
{ n: [ 6, 8, ], f: [], },
{ n: [ 6, 9, ], f: [], },
{ n: [ 7, 10, ], f: [], },
{ n: [ 7, 11, ], f: [], },
{ n: [ 8, 9, ], f: [], },
{ n: [ 10, 11, ], f: [], },
];
faces =
[
{ n: [ 0, 1, 8 ], e: [ 0, 7, 3 ], },
{ n: [ 0, 4, 5 ], e: [ 1, 18, 2 ], },
{ n: [ 0, 5, 10 ], e: [ 2, 21, 4 ], },
{ n: [ 0, 8, 4 ], e: [ 3, 19, 1 ], },
{ n: [ 0, 10, 1 ], e: [ 4, 8, 0 ], },
{ n: [ 1, 6, 8 ], e: [ 5, 24, 7 ], },
{ n: [ 1, 7, 6 ], e: [ 6, 23, 5 ], },
{ n: [ 1, 10, 7 ], e: [ 8, 26, 6 ], },
{ n: [ 2, 3, 11 ], e: [ 9, 17, 13 ], },
{ n: [ 2, 4, 9 ], e: [ 10, 20, 12 ], },
{ n: [ 2, 5, 4 ], e: [ 11, 18, 10 ], },
{ n: [ 2, 9, 3 ], e: [ 12, 16, 9 ], },
{ n: [ 2, 11, 5 ], e: [ 13, 22, 11 ], },
{ n: [ 3, 6, 7 ], e: [ 14, 23, 15 ], },
{ n: [ 3, 7, 11 ], e: [ 15, 27, 17 ], },
{ n: [ 3, 9, 6 ], e: [ 16, 25, 14 ], },
{ n: [ 4, 8, 9 ], e: [ 19, 28, 20 ], },
{ n: [ 5, 11, 10 ], e: [ 22, 29, 21 ], },
{ n: [ 6, 9, 8 ], e: [ 25, 28, 24 ], },
{ n: [ 7, 10, 11 ], e: [ 26, 29, 27 ], },
];
for (var i = 0; i < edges.length; ++i)
for (var j = 0; j < edges[i].n.length; ++j)
nodes[j].e.push(i);
for (var i = 0; i < faces.length; ++i)
for (var j = 0; j < faces[i].n.length; ++j)
nodes[j].f.push(i);
for (var i = 0; i < faces.length; ++i)
for (var j = 0; j < faces[i].e.length; ++j)
edges[j].f.push(i);
return { nodes: nodes, edges: edges, faces: faces };
}
function generateSubdividedIcosahedron(degree)
{
var icosahedron = generateIcosahedron();
var nodes = [];
for (var i = 0; i < icosahedron.nodes.length; ++i)
{
nodes.push({ p: icosahedron.nodes[i].p, e: [], f: [] });
}
var edges = [];
for (var i = 0; i < icosahedron.edges.length; ++i)
{
var edge = icosahedron.edges[i];
edge.subdivided_n = [];
edge.subdivided_e = [];
var n0 = icosahedron.nodes[edge.n[0]];
var n1 = icosahedron.nodes[edge.n[1]];
var p0 = n0.p;
var p1 = n1.p;
var delta = p1.clone().sub(p0);
nodes[edge.n[0]].e.push(edges.length);
var priorNodeIndex = edge.n[0];
for (var s = 1; s < degree; ++s)
{
var edgeIndex = edges.length;
var nodeIndex = nodes.length;
edge.subdivided_e.push(edgeIndex);
edge.subdivided_n.push(nodeIndex);
edges.push({ n: [ priorNodeIndex, nodeIndex ], f: [] });
priorNodeIndex = nodeIndex;
nodes.push({ p: slerp(p0, p1, s / degree), e: [ edgeIndex, edgeIndex + 1 ], f: [] });
}
edge.subdivided_e.push(edges.length);
nodes[edge.n[1]].e.push(edges.length);
edges.push({ n: [ priorNodeIndex, edge.n[1] ], f: [] });
}
var faces = [];
for (var i = 0; i < icosahedron.faces.length; ++i)
{
var face = icosahedron.faces[i];
var edge0 = icosahedron.edges[face.e[0]];
var edge1 = icosahedron.edges[face.e[1]];
var edge2 = icosahedron.edges[face.e[2]];
var point0 = icosahedron.nodes[face.n[0]].p;
var point1 = icosahedron.nodes[face.n[1]].p;
var point2 = icosahedron.nodes[face.n[2]].p;
var delta = point1.clone().sub(point0);
var getEdgeNode0 = (face.n[0] === edge0.n[0])
? function(k) { return edge0.subdivided_n[k]; }
: function(k) { return edge0.subdivided_n[degree - 2 - k]; };
var getEdgeNode1 = (face.n[1] === edge1.n[0])
? function(k) { return edge1.subdivided_n[k]; }
: function(k) { return edge1.subdivided_n[degree - 2 - k]; };
var getEdgeNode2 = (face.n[0] === edge2.n[0])
? function(k) { return edge2.subdivided_n[k]; }
: function(k) { return edge2.subdivided_n[degree - 2 - k]; };
var faceNodes = [];
faceNodes.push(face.n[0]);
for (var j = 0; j < edge0.subdivided_n.length; ++j)
faceNodes.push(getEdgeNode0(j));
faceNodes.push(face.n[1]);
for (var s = 1; s < degree; ++s)
{
faceNodes.push(getEdgeNode2(s - 1));
var p0 = nodes[getEdgeNode2(s - 1)].p;
var p1 = nodes[getEdgeNode1(s - 1)].p;
for (var t = 1; t < degree - s; ++t)
{
faceNodes.push(nodes.length);
nodes.push({ p: slerp(p0, p1, t / (degree - s)), e: [], f: [], });
}
faceNodes.push(getEdgeNode1(s - 1));
}
faceNodes.push(face.n[2]);
var getEdgeEdge0 = (face.n[0] === edge0.n[0])
? function(k) { return edge0.subdivided_e[k]; }
: function(k) { return edge0.subdivided_e[degree - 1 - k]; };
var getEdgeEdge1 = (face.n[1] === edge1.n[0])
? function(k) { return edge1.subdivided_e[k]; }
: function(k) { return edge1.subdivided_e[degree - 1 - k]; };
var getEdgeEdge2 = (face.n[0] === edge2.n[0])
? function(k) { return edge2.subdivided_e[k]; }
: function(k) { return edge2.subdivided_e[degree - 1 - k]; };
var faceEdges0 = [];
for (var j = 0; j < degree; ++j)
faceEdges0.push(getEdgeEdge0(j));
var nodeIndex = degree + 1;
for (var s = 1; s < degree; ++s)
{
for (var t = 0; t < degree - s; ++t)
{
faceEdges0.push(edges.length);
var edge = { n: [ faceNodes[nodeIndex], faceNodes[nodeIndex + 1], ], f: [], };
nodes[edge.n[0]].e.push(edges.length);
nodes[edge.n[1]].e.push(edges.length);
edges.push(edge);
++nodeIndex;
}
++nodeIndex;
}
var faceEdges1 = [];
nodeIndex = 1;
for (var s = 0; s < degree; ++s)
{
for (var t = 1; t < degree - s; ++t)
{
faceEdges1.push(edges.length);
var edge = { n: [ faceNodes[nodeIndex], faceNodes[nodeIndex + degree - s], ], f: [], };
nodes[edge.n[0]].e.push(edges.length);
nodes[edge.n[1]].e.push(edges.length);
edges.push(edge);
++nodeIndex;
}
faceEdges1.push(getEdgeEdge1(s));
nodeIndex += 2;
}
var faceEdges2 = [];
nodeIndex = 1;
for (var s = 0; s < degree; ++s)
{
faceEdges2.push(getEdgeEdge2(s));
for (var t = 1; t < degree - s; ++t)
{
faceEdges2.push(edges.length);
var edge = { n: [ faceNodes[nodeIndex], faceNodes[nodeIndex + degree - s + 1], ], f: [], };
nodes[edge.n[0]].e.push(edges.length);
nodes[edge.n[1]].e.push(edges.length);
edges.push(edge);
++nodeIndex;
}
nodeIndex += 2;
}
nodeIndex = 0;
edgeIndex = 0;
for (var s = 0; s < degree; ++s)
{
for (t = 1; t < degree - s + 1; ++t)
{
var subFace = {
n: [ faceNodes[nodeIndex], faceNodes[nodeIndex + 1], faceNodes[nodeIndex + degree - s + 1], ],
e: [ faceEdges0[edgeIndex], faceEdges1[edgeIndex], faceEdges2[edgeIndex], ], };
nodes[subFace.n[0]].f.push(faces.length);
nodes[subFace.n[1]].f.push(faces.length);
nodes[subFace.n[2]].f.push(faces.length);
edges[subFace.e[0]].f.push(faces.length);
edges[subFace.e[1]].f.push(faces.length);
edges[subFace.e[2]].f.push(faces.length);
faces.push(subFace);
++nodeIndex;
++edgeIndex;
}
++nodeIndex;
}
nodeIndex = 1;
edgeIndex = 0;
for (var s = 1; s < degree; ++s)
{
for (t = 1; t < degree - s + 1; ++t)
{
var subFace = {
n: [ faceNodes[nodeIndex], faceNodes[nodeIndex + degree - s + 2], faceNodes[nodeIndex + degree - s + 1], ],
e: [ faceEdges2[edgeIndex + 1], faceEdges0[edgeIndex + degree - s + 1], faceEdges1[edgeIndex], ], };
nodes[subFace.n[0]].f.push(faces.length);
nodes[subFace.n[1]].f.push(faces.length);
nodes[subFace.n[2]].f.push(faces.length);
edges[subFace.e[0]].f.push(faces.length);
edges[subFace.e[1]].f.push(faces.length);
edges[subFace.e[2]].f.push(faces.length);
faces.push(subFace);
++nodeIndex;
++edgeIndex;
}
nodeIndex += 2;
edgeIndex += 1;
}
}
return { nodes: nodes, edges: edges, faces: faces };
}
function getEdgeOppositeFaceIndex(edge, faceIndex)
{
if (edge.f[0] === faceIndex) return edge.f[1];
if (edge.f[1] === faceIndex) return edge.f[0];
throw "Given face is not part of given edge.";
}
function getFaceOppositeNodeIndex(face, edge)
{
if (face.n[0] !== edge.n[0] && face.n[0] !== edge.n[1]) return 0;
if (face.n[1] !== edge.n[0] && face.n[1] !== edge.n[1]) return 1;
if (face.n[2] !== edge.n[0] && face.n[2] !== edge.n[1]) return 2;
throw "Cannot find node of given face that is not also a node of given edge.";
}
function findNextFaceIndex(mesh, nodeIndex, faceIndex)
{
var node = mesh.nodes[nodeIndex];
var face = mesh.faces[faceIndex];
var nodeFaceIndex = face.n.indexOf(nodeIndex);
var edge = mesh.edges[face.e[(nodeFaceIndex + 2) % 3]];
return getEdgeOppositeFaceIndex(edge, faceIndex);
}
function conditionalRotateEdge(mesh, edgeIndex, predicate)
{
var edge = mesh.edges[edgeIndex];
var face0 = mesh.faces[edge.f[0]];
var face1 = mesh.faces[edge.f[1]];
var farNodeFaceIndex0 = getFaceOppositeNodeIndex(face0, edge);
var farNodeFaceIndex1 = getFaceOppositeNodeIndex(face1, edge);
var newNodeIndex0 = face0.n[farNodeFaceIndex0];
var oldNodeIndex0 = face0.n[(farNodeFaceIndex0 + 1) % 3];
var newNodeIndex1 = face1.n[farNodeFaceIndex1];
var oldNodeIndex1 = face1.n[(farNodeFaceIndex1 + 1) % 3];
var oldNode0 = mesh.nodes[oldNodeIndex0];
var oldNode1 = mesh.nodes[oldNodeIndex1];
var newNode0 = mesh.nodes[newNodeIndex0];
var newNode1 = mesh.nodes[newNodeIndex1];
var newEdgeIndex0 = face1.e[(farNodeFaceIndex1 + 2) % 3];
var newEdgeIndex1 = face0.e[(farNodeFaceIndex0 + 2) % 3];
var newEdge0 = mesh.edges[newEdgeIndex0];
var newEdge1 = mesh.edges[newEdgeIndex1];
if (!predicate(oldNode0, oldNode1, newNode0, newNode1)) return false;
oldNode0.e.splice(oldNode0.e.indexOf(edgeIndex), 1);
oldNode1.e.splice(oldNode1.e.indexOf(edgeIndex), 1);
newNode0.e.push(edgeIndex);
newNode1.e.push(edgeIndex);
edge.n[0] = newNodeIndex0;
edge.n[1] = newNodeIndex1;
newEdge0.f.splice(newEdge0.f.indexOf(edge.f[1]), 1);
newEdge1.f.splice(newEdge1.f.indexOf(edge.f[0]), 1);
newEdge0.f.push(edge.f[0]);
newEdge1.f.push(edge.f[1]);
oldNode0.f.splice(oldNode0.f.indexOf(edge.f[1]), 1);
oldNode1.f.splice(oldNode1.f.indexOf(edge.f[0]), 1);
newNode0.f.push(edge.f[1]);
newNode1.f.push(edge.f[0]);
face0.n[(farNodeFaceIndex0 + 2) % 3] = newNodeIndex1;
face1.n[(farNodeFaceIndex1 + 2) % 3] = newNodeIndex0;
face0.e[(farNodeFaceIndex0 + 1) % 3] = newEdgeIndex0;
face1.e[(farNodeFaceIndex1 + 1) % 3] = newEdgeIndex1;
face0.e[(farNodeFaceIndex0 + 2) % 3] = edgeIndex;
face1.e[(farNodeFaceIndex1 + 2) % 3] = edgeIndex;
return true;
}
function calculateFaceCentroid(pa, pb, pc)
{
var vabHalf = pb.clone().sub(pa).divideScalar(2);
var pabHalf = pa.clone().add(vabHalf);
var centroid = pc.clone().sub(pabHalf).multiplyScalar(1/3).add(pabHalf);
return centroid;
}
function distortMesh(mesh, degree, random, action)
{
var totalSurfaceArea = 4 * Math.PI;
var idealFaceArea = totalSurfaceArea / mesh.faces.length;
var idealEdgeLength = Math.sqrt(idealFaceArea * 4 / Math.sqrt(3));
var idealFaceHeight = idealEdgeLength * Math.sqrt(3) / 2;
var rotationPredicate = function(oldNode0, oldNode1, newNode0, newNode1)
{
if (newNode0.f.length >= 7 ||
newNode1.f.length >= 7 ||
oldNode0.f.length <= 5 ||
oldNode1.f.length <= 5) return false;
var oldEdgeLength = oldNode0.p.distanceTo(oldNode1.p);
var newEdgeLength = newNode0.p.distanceTo(newNode1.p);
var ratio = oldEdgeLength / newEdgeLength;
if (ratio >= 2 || ratio <= 0.5) return false;
var v0 = oldNode1.p.clone().sub(oldNode0.p).divideScalar(oldEdgeLength);
var v1 = newNode0.p.clone().sub(oldNode0.p).normalize();
var v2 = newNode1.p.clone().sub(oldNode0.p).normalize();
if (v0.dot(v1) < 0.2 || v0.dot(v2) < 0.2) return false;
v0.negate();
var v3 = newNode0.p.clone().sub(oldNode1.p).normalize();
var v4 = newNode1.p.clone().sub(oldNode1.p).normalize();
if (v0.dot(v3) < 0.2 || v0.dot(v4) < 0.2) return false;
return true;
};
var i = 0;
action.executeSubaction(function(action)
{
if (i >= degree) return;
var consecutiveFailedAttempts = 0;
var edgeIndex = random.integerExclusive(0, mesh.edges.length);
while (!conditionalRotateEdge(mesh, edgeIndex, rotationPredicate))
{
if (++consecutiveFailedAttempts >= mesh.edges.length) return false;
edgeIndex = (edgeIndex + 1) % mesh.edges.length;
}
++i;
action.loop(i / degree);
});
return true;
}
function relaxMesh(mesh, multiplier, action)
{
var totalSurfaceArea = 4 * Math.PI;
var idealFaceArea = totalSurfaceArea / mesh.faces.length;
var idealEdgeLength = Math.sqrt(idealFaceArea * 4 / Math.sqrt(3));
var idealDistanceToCentroid = idealEdgeLength * Math.sqrt(3) / 3 * 0.9;
var pointShifts = new Array(mesh.nodes.length);
action.executeSubaction(function(action)
{
for (var i = 0; i < mesh.nodes.length; ++i)
pointShifts[i] = new Vector3(0, 0, 0);
}, 1);
var i = 0;
action.executeSubaction(function(action)
{
if (i >= mesh.faces.length) return;
var face = mesh.faces[i];
var n0 = mesh.nodes[face.n[0]];
var n1 = mesh.nodes[face.n[1]];
var n2 = mesh.nodes[face.n[2]];
var p0 = n0.p;
var p1 = n1.p;
var p2 = n2.p;
var e0 = p1.distanceTo(p0) / idealEdgeLength;
var e1 = p2.distanceTo(p1) / idealEdgeLength;
var e2 = p0.distanceTo(p2) / idealEdgeLength;
var centroid = calculateFaceCentroid(p0, p1, p2).normalize();
var v0 = centroid.clone().sub(p0);
var v1 = centroid.clone().sub(p1);
var v2 = centroid.clone().sub(p2);
var length0 = v0.length();
var length1 = v1.length();
var length2 = v2.length();
v0.multiplyScalar(multiplier * (length0 - idealDistanceToCentroid) / length0);
v1.multiplyScalar(multiplier * (length1 - idealDistanceToCentroid) / length1);
v2.multiplyScalar(multiplier * (length2 - idealDistanceToCentroid) / length2);
pointShifts[face.n[0]].add(v0);
pointShifts[face.n[1]].add(v1);
pointShifts[face.n[2]].add(v2);
++i;
action.loop(i / mesh.faces.length);
}, mesh.faces.length);
var origin = new Vector3(0, 0, 0);
var plane = new THREE.Plane();
action.executeSubaction(function(action)
{
for (var i = 0; i < mesh.nodes.length; ++i)
{
plane.setFromNormalAndCoplanarPoint(mesh.nodes[i].p, origin);
pointShifts[i] = mesh.nodes[i].p.clone().add(plane.projectPoint(pointShifts[i])).normalize();
}
}, mesh.nodes.length / 10);
var rotationSupressions = new Array(mesh.nodes.length);
for (var i = 0; i < mesh.nodes.length; ++i)
rotationSupressions[i] = 0;
var i = 0;
action.executeSubaction(function(action)
{
if (i >= mesh.edges.length) return;
var edge = mesh.edges[i];
var oldPoint0 = mesh.nodes[edge.n[0]].p;
var oldPoint1 = mesh.nodes[edge.n[1]].p;
var newPoint0 = pointShifts[edge.n[0]];
var newPoint1 = pointShifts[edge.n[1]];
var oldVector = oldPoint1.clone().sub(oldPoint0).normalize();
var newVector = newPoint1.clone().sub(newPoint0).normalize();
var suppression = (1 - oldVector.dot(newVector)) * 0.5;
rotationSupressions[edge.n[0]] = Math.max(rotationSupressions[edge.n[0]], suppression);
rotationSupressions[edge.n[1]] = Math.max(rotationSupressions[edge.n[1]], suppression);
++i;