-
Notifications
You must be signed in to change notification settings - Fork 112
/
THREE.Terrain.js
2065 lines (1962 loc) · 85.1 KB
/
THREE.Terrain.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
/**
* THREE.Terrain.js 2.0.0-20220705
*
* @author Isaac Sukin (http://www.isaacsukin.com/)
* @license MIT
*/
/**
* Simplex and Perlin noise.
*
* Copied with small edits from https://github.com/josephg/noisejs which is
* public domain. Originally by Stefan Gustavson (stegu@itn.liu.se) with
* optimizations by Peter Eastman (peastman@drizzle.stanford.edu) and converted
* to JavaScript by Joseph Gentle.
*/
(function(global) {
var module = global.noise = {};
function Grad(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
Grad.prototype.dot2 = function(x, y) {
return this.x*x + this.y*y;
};
Grad.prototype.dot3 = function(x, y, z) {
return this.x*x + this.y*y + this.z*z;
};
var grad3 = [
new Grad(1,1,0),new Grad(-1,1,0),new Grad(1,-1,0),new Grad(-1,-1,0),
new Grad(1,0,1),new Grad(-1,0,1),new Grad(1,0,-1),new Grad(-1,0,-1),
new Grad(0,1,1),new Grad(0,-1,1),new Grad(0,1,-1),new Grad(0,-1,-1),
];
var p = [151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,
30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,
252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,
168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,
60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,
1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,
86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,
118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,
170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,
22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,
107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,
150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,
61,156,180];
// To avoid the need for index wrapping, double the permutation table length
var perm = new Array(512),
gradP = new Array(512);
// This isn't a very good seeding function, but it works okay. It supports
// 2^16 different seed values. Write your own if you need more seeds.
module.seed = function(seed) {
if (seed > 0 && seed < 1) {
// Scale the seed out
seed *= 65536;
}
seed = Math.floor(seed);
if (seed < 256) {
seed |= seed << 8;
}
for (var i = 0; i < 256; i++) {
var v;
if (i & 1) {
v = p[i] ^ (seed & 255);
}
else {
v = p[i] ^ ((seed>>8) & 255);
}
perm[i] = perm[i + 256] = v;
gradP[i] = gradP[i + 256] = grad3[v % 12];
}
};
module.seed(Math.random());
// Skewing and unskewing factors for 2 and 3 dimensions
var F2 = 0.5*(Math.sqrt(3)-1),
G2 = (3-Math.sqrt(3))/6,
F3 = 1/3,
G3 = 1/6;
// 2D simplex noise
module.simplex = function(xin, yin) {
var n0, n1, n2; // Noise contributions from the three corners
// Skew the input space to determine which simplex cell we're in
var s = (xin+yin)*F2; // Hairy factor for 2D
var i = Math.floor(xin+s);
var j = Math.floor(yin+s);
var t = (i+j)*G2;
var x0 = xin-i+t; // The x,y distances from the cell origin, unskewed
var y0 = yin-j+t;
// For the 2D case, the simplex shape is an equilateral triangle.
// Determine which simplex we are in.
var i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords
if (x0 > y0) { // Lower triangle, XY order: (0,0)->(1,0)->(1,1)
i1 = 1; j1 = 0;
}
else { // Upper triangle, YX order: (0,0)->(0,1)->(1,1)
i1 = 0; j1 = 1;
}
// A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
// a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
// c = (3-sqrt(3))/6
var x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords
var y1 = y0 - j1 + G2;
var x2 = x0 - 1 + 2 * G2; // Offsets for last corner in (x,y) unskewed coords
var y2 = y0 - 1 + 2 * G2;
// Work out the hashed gradient indices of the three simplex corners
i &= 255;
j &= 255;
var gi0 = gradP[i+perm[j]];
var gi1 = gradP[i+i1+perm[j+j1]];
var gi2 = gradP[i+1+perm[j+1]];
// Calculate the contribution from the three corners
var t0 = 0.5 - x0*x0-y0*y0;
if (t0 < 0) {
n0 = 0;
}
else {
t0 *= t0;
n0 = t0 * t0 * gi0.dot2(x0, y0); // (x,y) of grad3 used for 2D gradient
}
var t1 = 0.5 - x1*x1-y1*y1;
if (t1 < 0) {
n1 = 0;
}
else {
t1 *= t1;
n1 = t1 * t1 * gi1.dot2(x1, y1);
}
var t2 = 0.5 - x2*x2-y2*y2;
if (t2 < 0) {
n2 = 0;
}
else {
t2 *= t2;
n2 = t2 * t2 * gi2.dot2(x2, y2);
}
// Add contributions from each corner to get the final noise value.
// The result is scaled to return values in the interval [-1,1].
return 70 * (n0 + n1 + n2);
};
// ##### Perlin noise stuff
function fade(t) {
return t*t*t*(t*(t*6-15)+10);
}
function lerp(a, b, t) {
return (1-t)*a + t*b;
}
// 2D Perlin Noise
module.perlin = function(x, y) {
// Find unit grid cell containing point
var X = Math.floor(x),
Y = Math.floor(y);
// Get relative xy coordinates of point within that cell
x = x - X;
y = y - Y;
// Wrap the integer cells at 255 (smaller integer period can be introduced here)
X = X & 255;
Y = Y & 255;
// Calculate noise contributions from each of the four corners
var n00 = gradP[X+perm[Y]].dot2(x, y);
var n01 = gradP[X+perm[Y+1]].dot2(x, y-1);
var n10 = gradP[X+1+perm[Y]].dot2(x-1, y);
var n11 = gradP[X+1+perm[Y+1]].dot2(x-1, y-1);
// Compute the fade curve value for x
var u = fade(x);
// Interpolate the four results
return lerp(
lerp(n00, n10, u),
lerp(n01, n11, u),
fade(y)
);
};
})(this);
/**
* A terrain object for use with the Three.js library.
*
* Usage: `var terrainScene = THREE.Terrain();`
*
* @param {Object} [options]
* An optional map of settings that control how the terrain is constructed
* and displayed. Options include:
*
* - `after`: A function to run after other transformations on the terrain
* produce the highest-detail heightmap, but before optimizations and
* visual properties are applied. Takes two parameters, which are the same
* as those for {@link THREE.Terrain.DiamondSquare}: an array of
* `THREE.Vector3` objects representing the vertices of the terrain, and a
* map of options with the same available properties as the `options`
* parameter for the `THREE.Terrain` function.
* - `easing`: A function that affects the distribution of slopes by
* interpolating the height of each vertex along a curve. Valid values
* include `THREE.Terrain.Linear` (the default), `THREE.Terrain.EaseIn`,
* `THREE.Terrain.EaseOut`, `THREE.Terrain.EaseInOut`,
* `THREE.Terrain.InEaseOut`, and any custom function that accepts a float
* between 0 and 1 and returns a float between 0 and 1.
* - `frequency`: For terrain generation methods that support it (Perlin,
* Simplex, and Worley) the octave of randomness. This basically controls
* how big features of the terrain will be (higher frequencies result in
* smaller features). Often running multiple generation functions with
* different frequencies and heights results in nice detail, as
* the PerlinLayers and SimplexLayers methods demonstrate. (The counterpart
* to frequency, amplitude, is represented by the difference between the
* `maxHeight` and `minHeight` parameters.) Defaults to 2.5.
* - `heightmap`: Either a canvas or pre-loaded image (from the same domain
* as the webpage or served with a CORS-friendly header) representing
* terrain height data (lighter pixels are higher); or a function used to
* generate random height data for the terrain. Valid random functions are
* specified in `generators.js` (or custom functions with the same
* signature). Ideally heightmap images have the same number of pixels as
* the terrain has vertices, as determined by the `xSegments` and
* `ySegments` options, but this is not required. If the heightmap is a
* different size, vertex height values will be interpolated.) Defaults to
* `THREE.Terrain.DiamondSquare`.
* - `material`: a THREE.Material instance used to display the terrain.
* Defaults to `new THREE.MeshBasicMaterial({color: 0xee6633})`.
* - `maxHeight`: the highest point, in Three.js units, that a peak should
* reach. Defaults to 100. Setting to `undefined`, `null`, or `Infinity`
* removes the cap, but this is generally not recommended because many
* generators and filters require a vertical range. Instead, consider
* setting the `stretch` option to `false`.
* - `minHeight`: the lowest point, in Three.js units, that a valley should
* reach. Defaults to -100. Setting to `undefined`, `null`, or `-Infinity`
* removes the cap, but this is generally not recommended because many
* generators and filters require a vertical range. Instead, consider
* setting the `stretch` option to `false`.
* - `steps`: If this is a number above 1, the terrain will be paritioned
* into that many flat "steps," resulting in a blocky appearance. Defaults
* to 1.
* - `stretch`: Determines whether to stretch the heightmap across the
* maximum and minimum height range if the height range produced by the
* `heightmap` property is smaller. Defaults to true.
* - `turbulent`: Whether to perform a turbulence transformation. Defaults to
* false.
* - `xSegments`: The number of segments (rows) to divide the terrain plane
* into. (This basically determines how detailed the terrain is.) Defaults
* to 63.
* - `xSize`: The width of the terrain in Three.js units. Defaults to 1024.
* Rendering might be slightly faster if this is a multiple of
* `options.xSegments + 1`.
* - `ySegments`: The number of segments (columns) to divide the terrain
* plane into. (This basically determines how detailed the terrain is.)
* Defaults to 63.
* - `ySize`: The length of the terrain in Three.js units. Defaults to 1024.
* Rendering might be slightly faster if this is a multiple of
* `options.ySegments + 1`.
*/
THREE.Terrain = function(options) {
var defaultOptions = {
after: null,
easing: THREE.Terrain.Linear,
heightmap: THREE.Terrain.DiamondSquare,
material: null,
maxHeight: 100,
minHeight: -100,
optimization: THREE.Terrain.NONE,
frequency: 2.5,
steps: 1,
stretch: true,
turbulent: false,
xSegments: 63,
xSize: 1024,
ySegments: 63,
ySize: 1024,
};
options = options || {};
for (var opt in defaultOptions) {
if (defaultOptions.hasOwnProperty(opt)) {
options[opt] = typeof options[opt] === 'undefined' ? defaultOptions[opt] : options[opt];
}
}
options.material = options.material || new THREE.MeshBasicMaterial({ color: 0xee6633 });
// Encapsulating the terrain in a parent object allows us the flexibility
// to more easily have multiple meshes for optimization purposes.
var scene = new THREE.Object3D();
// Planes are initialized on the XY plane, so rotate the plane to make it lie flat.
scene.rotation.x = -0.5 * Math.PI;
// Create the terrain mesh.
var mesh = new THREE.Mesh(
new THREE.PlaneGeometry(options.xSize, options.ySize, options.xSegments, options.ySegments),
options.material
);
// Assign elevation data to the terrain plane from a heightmap or function.
var zs = THREE.Terrain.toArray1D(mesh.geometry.attributes.position.array);
if (options.heightmap instanceof HTMLCanvasElement || options.heightmap instanceof Image) {
THREE.Terrain.fromHeightmap(zs, options);
}
else if (typeof options.heightmap === 'function') {
options.heightmap(zs, options);
}
else {
console.warn('An invalid value was passed for `options.heightmap`: ' + options.heightmap);
}
THREE.Terrain.fromArray1D(mesh.geometry.attributes.position.array, zs);
THREE.Terrain.Normalize(mesh, options);
// lod.addLevel(mesh, options.unit * 10 * Math.pow(2, lodLevel));
scene.add(mesh);
return scene;
};
/**
* Normalize the terrain after applying a heightmap or filter.
*
* This applies turbulence, steps, and height clamping; calls the `after`
* callback; updates normals and the bounding sphere; and marks vertices as
* dirty.
*
* @param {THREE.Mesh} mesh
* The terrain mesh.
* @param {Object} options
* A map of settings that control how the terrain is constructed and
* displayed. Valid options are the same as for {@link THREE.Terrain}().
*/
THREE.Terrain.Normalize = function(mesh, options) {
var zs = THREE.Terrain.toArray1D(mesh.geometry.attributes.position.array);
if (options.turbulent) {
THREE.Terrain.Turbulence(zs, options);
}
if (options.steps > 1) {
THREE.Terrain.Step(zs, options.steps);
THREE.Terrain.Smooth(zs, options);
}
// Keep the terrain within the allotted height range if necessary, and do easing.
THREE.Terrain.Clamp(zs, options);
// Call the "after" callback
if (typeof options.after === 'function') {
options.after(zs, options);
}
THREE.Terrain.fromArray1D(mesh.geometry.attributes.position.array, zs);
// Mark the geometry as having changed and needing updates.
mesh.geometry.computeBoundingSphere();
mesh.geometry.computeFaceNormals();
mesh.geometry.computeVertexNormals();
};
/**
* Optimization types.
*
* Note that none of these are implemented right now. They should be done as
* shaders so that they execute on the GPU, and the resulting scene would need
* to be updated every frame to adjust to the camera's position.
*
* Further reading:
* - http://vterrain.org/LOD/Papers/
* - http://vterrain.org/LOD/Implementations/
*
* GEOMIPMAP: The terrain plane should be split into sections, each with their
* own LODs, for screen-space occlusion and detail reduction. Intermediate
* vertices on higher-detail neighboring sections should be interpolated
* between neighbor edge vertices in order to match with the edge of the
* lower-detail section. The number of sections should be around sqrt(segments)
* along each axis. It's unclear how to make materials stretch across segments.
* Possible example (I haven't looked too much into it) at
* https://github.com/felixpalmer/lod-terrain/tree/master/js/shaders
*
* GEOCLIPMAP: The terrain should be composed of multiple donut-shaped sections
* at decreasing resolution as the radius gets bigger. When the player moves,
* the sections should morph so that the detail "follows" the player around.
* There is an implementation of geoclipmapping at
* https://github.com/CodeArtemis/TriggerRally/blob/unified/server/public/scripts/client/terrain.coffee
* and a tutorial on morph targets at
* http://nikdudnik.com/making-3d-gfx-for-the-cinema-on-low-budget-and-three-js/
*
* POLYGONREDUCTION: Combine areas that are relatively coplanar into larger
* polygons as described at http://www.shamusyoung.com/twentysidedtale/?p=142.
* This method can be combined with the others if done very carefully, or it
* can be adjusted to be more aggressive at greater distance from the camera
* (similar to combining with geomipmapping).
*
* If these do get implemented, here is the option description to add to the
* `THREE.Terrain` docblock:
*
* - `optimization`: the type of optimization to apply to the terrain. If
* an optimization is applied, the number of segments along each axis that
* the terrain should be divided into at the most detailed level should
* equal (n * 2^(LODs-1))^2 - 1, for arbitrary n, where LODs is the number
* of levels of detail desired. Valid values include:
*
* - `THREE.Terrain.NONE`: Don't apply any optimizations. This is the
* default.
* - `THREE.Terrain.GEOMIPMAP`: Divide the terrain into evenly-sized
* sections with multiple levels of detail. For each section,
* display a level of detail dependent on how close the camera is.
* - `THREE.Terrain.GEOCLIPMAP`: Divide the terrain into donut-shaped
* sections, where detail decreases as the radius increases. The
* rings then morph to "follow" the camera around so that the camera
* is always at the center, surrounded by the most detail.
*/
THREE.Terrain.NONE = 0;
THREE.Terrain.GEOMIPMAP = 1;
THREE.Terrain.GEOCLIPMAP = 2;
THREE.Terrain.POLYGONREDUCTION = 3;
/**
* Get a 2D array of heightmap values from a 1D array of Z-positions.
*
* @param {Float32Array} vertices
* A 1D array containing the vertex Z-positions of the geometry representing
* the terrain.
* @param {Object} options
* A map of settings defining properties of the terrain. The only properties
* that matter here are `xSegments` and `ySegments`, which represent how many
* vertices wide and deep the terrain plane is, respectively (and therefore
* also the dimensions of the returned array).
*
* @return {Float32Array[]}
* A 2D array representing the terrain's heightmap.
*/
THREE.Terrain.toArray2D = function(vertices, options) {
var tgt = new Array(options.xSegments + 1),
xl = options.xSegments + 1,
yl = options.ySegments + 1,
i, j;
for (i = 0; i < xl; i++) {
tgt[i] = new Float32Array(options.ySegments + 1);
for (j = 0; j < yl; j++) {
tgt[i][j] = vertices[j * xl + i];
}
}
return tgt;
};
/**
* Set the height of plane vertices from a 2D array of heightmap values.
*
* @param {Float32Array} vertices
* A 1D array containing the vertex Z-positions of the geometry representing
* the terrain.
* @param {Number[][]} src
* A 2D array representing a heightmap to apply to the terrain.
*/
THREE.Terrain.fromArray2D = function(vertices, src) {
for (var i = 0, xl = src.length; i < xl; i++) {
for (var j = 0, yl = src[i].length; j < yl; j++) {
vertices[j * xl + i] = src[i][j];
}
}
};
/**
* Get a 1D array of heightmap values from a 1D array of plane vertices.
*
* @param {Float32Array} vertices
* A 1D array containing the vertex positions of the geometry representing the
* terrain.
* @param {Object} options
* A map of settings defining properties of the terrain. The only properties
* that matter here are `xSegments` and `ySegments`, which represent how many
* vertices wide and deep the terrain plane is, respectively (and therefore
* also the dimensions of the returned array).
*
* @return {Float32Array}
* A 1D array representing the terrain's heightmap.
*/
THREE.Terrain.toArray1D = function(vertices) {
var tgt = new Float32Array(vertices.length / 3);
for (var i = 0, l = tgt.length; i < l; i++) {
tgt[i] = vertices[i * 3 + 2];
}
return tgt;
};
/**
* Set the height of plane vertices from a 1D array of heightmap values.
*
* @param {Float32Array} vertices
* A 1D array containing the vertex positions of the geometry representing the
* terrain.
* @param {Number[]} src
* A 1D array representing a heightmap to apply to the terrain.
*/
THREE.Terrain.fromArray1D = function(vertices, src) {
for (var i = 0, l = Math.min(vertices.length / 3, src.length); i < l; i++) {
vertices[i * 3 + 2] = src[i];
}
};
/**
* Generate a 1D array containing random heightmap data.
*
* This is like {@link THREE.Terrain.toHeightmap} except that instead of
* generating the Three.js mesh and material information you can just get the
* height data.
*
* @param {Function} method
* The method to use to generate the heightmap data. Works with function that
* would be an acceptable value for the `heightmap` option for the
* {@link THREE.Terrain} function.
* @param {Number} options
* The same as the options parameter for the {@link THREE.Terrain} function.
*/
THREE.Terrain.heightmapArray = function(method, options) {
var arr = new Array((options.xSegments+1) * (options.ySegments+1)),
l = arr.length,
i;
arr.fill(0);
options.minHeight = options.minHeight || 0;
options.maxHeight = typeof options.maxHeight === 'undefined' ? 1 : options.maxHeight;
options.stretch = options.stretch || false;
method(arr, options);
THREE.Terrain.Clamp(arr, options);
return arr;
};
/**
* Randomness interpolation functions.
*/
THREE.Terrain.Linear = function(x) {
return x;
};
// x = [0, 1], x^2
THREE.Terrain.EaseIn = function(x) {
return x*x;
};
// x = [0, 1], -x(x-2)
THREE.Terrain.EaseOut = function(x) {
return -x * (x - 2);
};
// x = [0, 1], x^2(3-2x)
// Nearly identical alternatives: 0.5+0.5*cos(x*pi-pi), x^a/(x^a+(1-x)^a) (where a=1.6 seems nice)
// For comparison: http://www.wolframalpha.com/input/?i=x^1.6%2F%28x^1.6%2B%281-x%29^1.6%29%2C+x^2%283-2x%29%2C+0.5%2B0.5*cos%28x*pi-pi%29+from+0+to+1
THREE.Terrain.EaseInOut = function(x) {
return x*x*(3-2*x);
};
// x = [0, 1], 0.5*(2x-1)^3+0.5
THREE.Terrain.InEaseOut = function(x) {
var y = 2*x-1;
return 0.5 * y*y*y + 0.5;
};
// x = [0, 1], x^1.55
THREE.Terrain.EaseInWeak = function(x) {
return Math.pow(x, 1.55);
};
// x = [0, 1], x^7
THREE.Terrain.EaseInStrong = function(x) {
return x*x*x*x*x*x*x;
};
/**
* Convert an image-based heightmap into vertex-based height data.
*
* @param {Float32Array} g
* The geometry's z-positions to modify with heightmap data.
* @param {Object} options
* A map of settings that control how the terrain is constructed and
* displayed. Valid values are the same as those for the `options` parameter
* of {@link THREE.Terrain}().
*/
THREE.Terrain.fromHeightmap = function(g, options) {
var canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
rows = options.ySegments + 1,
cols = options.xSegments + 1,
spread = options.maxHeight - options.minHeight;
canvas.width = cols;
canvas.height = rows;
context.drawImage(options.heightmap, 0, 0, canvas.width, canvas.height);
var data = context.getImageData(0, 0, canvas.width, canvas.height).data;
for (var row = 0; row < rows; row++) {
for (var col = 0; col < cols; col++) {
var i = row * cols + col,
idx = i * 4;
g[i] = (data[idx] + data[idx+1] + data[idx+2]) / 765 * spread + options.minHeight;
}
}
};
/**
* Convert a terrain plane into an image-based heightmap.
*
* Parameters are the same as for {@link THREE.Terrain.fromHeightmap} except
* that if `options.heightmap` is a canvas element then the image will be
* painted onto that canvas; otherwise a new canvas will be created.
*
* @param {Float32Array} g
* The vertex position array for the geometry to paint to a heightmap.
* @param {Object} options
* A map of settings that control how the terrain is constructed and
* displayed. Valid values are the same as those for the `options` parameter
* of {@link THREE.Terrain}().
*
* @return {HTMLCanvasElement}
* A canvas with the relevant heightmap painted on it.
*/
THREE.Terrain.toHeightmap = function(g, options) {
var hasMax = typeof options.maxHeight !== 'undefined',
hasMin = typeof options.minHeight !== 'undefined',
max = hasMax ? options.maxHeight : -Infinity,
min = hasMin ? options.minHeight : Infinity;
if (!hasMax || !hasMin) {
var max2 = max,
min2 = min;
for (var k = 2, l = g.length; k < l; k += 3) {
if (g[k] > max2) max2 = g[k];
if (g[k] < min2) min2 = g[k];
}
if (!hasMax) max = max2;
if (!hasMin) min = min2;
}
var canvas = options.heightmap instanceof HTMLCanvasElement ? options.heightmap : document.createElement('canvas'),
context = canvas.getContext('2d'),
rows = options.ySegments + 1,
cols = options.xSegments + 1,
spread = max - min;
canvas.width = cols;
canvas.height = rows;
var d = context.createImageData(canvas.width, canvas.height),
data = d.data;
for (var row = 0; row < rows; row++) {
for (var col = 0; col < cols; col++) {
var i = row * cols + col,
idx = i * 4;
data[idx] = data[idx+1] = data[idx+2] = Math.round(((g[i * 3 + 2] - min) / spread) * 255);
data[idx+3] = 255;
}
}
context.putImageData(d, 0, 0);
return canvas;
};
/**
* Rescale the heightmap of a terrain to keep it within the maximum range.
*
* @param {Float32Array} g
* The geometry's z-positions to modify with heightmap data.
* @param {Object} options
* A map of settings that control how the terrain is constructed and
* displayed. Valid values are the same as those for the `options` parameter
* of {@link THREE.Terrain}() but only `maxHeight`, `minHeight`, and `easing`
* are used.
*/
THREE.Terrain.Clamp = function(g, options) {
var min = Infinity,
max = -Infinity,
l = g.length,
i;
options.easing = options.easing || THREE.Terrain.Linear;
for (i = 0; i < l; i++) {
if (g[i] < min) min = g[i];
if (g[i] > max) max = g[i];
}
var actualRange = max - min,
optMax = typeof options.maxHeight !== 'number' ? max : options.maxHeight,
optMin = typeof options.minHeight !== 'number' ? min : options.minHeight,
targetMax = options.stretch ? optMax : (max < optMax ? max : optMax),
targetMin = options.stretch ? optMin : (min > optMin ? min : optMin),
range = targetMax - targetMin;
if (targetMax < targetMin) {
targetMax = optMax;
range = targetMax - targetMin;
}
for (i = 0; i < l; i++) {
g[i] = options.easing((g[i] - min) / actualRange) * range + optMin;
}
};
/**
* Move the edges of the terrain up or down based on distance from the edge.
*
* Useful to make islands or enclosing walls/cliffs.
*
* @param {Float32Array} g
* The geometry's z-positions to modify with heightmap data.
* @param {Object} options
* A map of settings that control how the terrain is constructed and
* displayed. Valid values are the same as those for the `options` parameter
* of {@link THREE.Terrain}().
* @param {Boolean} direction
* `true` if the edges should be turned up; `false` if they should be turned
* down.
* @param {Number} distance
* The distance from the edge at which the edges should begin to be affected
* by this operation.
* @param {Number/Function} [e=THREE.Terrain.EaseInOut]
* A function that determines how quickly the terrain will transition between
* its current height and the edge shape as distance to the edge decreases.
* It does this by interpolating the height of each vertex along a curve.
* Valid values include `THREE.Terrain.Linear`, `THREE.Terrain.EaseIn`,
* `THREE.Terrain.EaseOut`, `THREE.Terrain.EaseInOut`,
* `THREE.Terrain.InEaseOut`, and any custom function that accepts a float
* between 0 and 1 and returns a float between 0 and 1.
* @param {Object} [edges={top: true, bottom: true, left: true, right: true}]
* Determines which edges should be affected by this function. Defaults to
* all edges. If passed, should be an object with `top`, `bottom`, `left`,
* and `right` Boolean properties specifying which edges to affect.
*/
THREE.Terrain.Edges = function(g, options, direction, distance, easing, edges) {
var numXSegments = Math.floor(distance / (options.xSize / options.xSegments)) || 1,
numYSegments = Math.floor(distance / (options.ySize / options.ySegments)) || 1,
peak = direction ? options.maxHeight : options.minHeight,
max = direction ? Math.max : Math.min,
xl = options.xSegments + 1,
yl = options.ySegments + 1,
i, j, multiplier, k1, k2;
easing = easing || THREE.Terrain.EaseInOut;
if (typeof edges !== 'object') {
edges = {top: true, bottom: true, left: true, right: true};
}
for (i = 0; i < xl; i++) {
for (j = 0; j < numYSegments; j++) {
multiplier = easing(1 - j / numYSegments);
k1 = j*xl + i;
k2 = (options.ySegments-j)*xl + i;
if (edges.top) {
g[k1] = max(g[k1], (peak - g[k1]) * multiplier + g[k1]);
}
if (edges.bottom) {
g[k2] = max(g[k2], (peak - g[k2]) * multiplier + g[k2]);
}
}
}
for (i = 0; i < yl; i++) {
for (j = 0; j < numXSegments; j++) {
multiplier = easing(1 - j / numXSegments);
k1 = i*xl+j;
k2 = (options.ySegments-i)*xl + (options.xSegments-j);
if (edges.left) {
g[k1] = max(g[k1], (peak - g[k1]) * multiplier + g[k1]);
}
if (edges.right) {
g[k2] = max(g[k2], (peak - g[k2]) * multiplier + g[k2]);
}
}
}
THREE.Terrain.Clamp(g, {
maxHeight: options.maxHeight,
minHeight: options.minHeight,
stretch: true,
});
};
/**
* Move the edges of the terrain up or down based on distance from the center.
*
* Useful to make islands or enclosing walls/cliffs.
*
* @param {Float32Array} g
* The geometry's z-positions to modify with heightmap data.
* @param {Object} options
* A map of settings that control how the terrain is constructed and
* displayed. Valid values are the same as those for the `options` parameter
* of {@link THREE.Terrain}().
* @param {Boolean} direction
* `true` if the edges should be turned up; `false` if they should be turned
* down.
* @param {Number} distance
* The distance from the center at which the edges should begin to be
* affected by this operation.
* @param {Number/Function} [e=THREE.Terrain.EaseInOut]
* A function that determines how quickly the terrain will transition between
* its current height and the edge shape as distance to the edge decreases.
* It does this by interpolating the height of each vertex along a curve.
* Valid values include `THREE.Terrain.Linear`, `THREE.Terrain.EaseIn`,
* `THREE.Terrain.EaseOut`, `THREE.Terrain.EaseInOut`,
* `THREE.Terrain.InEaseOut`, and any custom function that accepts a float
* between 0 and 1 and returns a float between 0 and 1.
*/
THREE.Terrain.RadialEdges = function(g, options, direction, distance, easing) {
var peak = direction ? options.maxHeight : options.minHeight,
max = direction ? Math.max : Math.min,
xl = (options.xSegments + 1),
yl = (options.ySegments + 1),
xl2 = xl * 0.5,
yl2 = yl * 0.5,
xSegmentSize = options.xSize / options.xSegments,
ySegmentSize = options.ySize / options.ySegments,
edgeRadius = Math.min(options.xSize, options.ySize) * 0.5 - distance,
i, j, multiplier, k, vertexDistance;
for (i = 0; i < xl; i++) {
for (j = 0; j < yl2; j++) {
k = j*xl + i;
vertexDistance = Math.min(edgeRadius, Math.sqrt((xl2-i)*xSegmentSize*(xl2-i)*xSegmentSize + (yl2-j)*ySegmentSize*(yl2-j)*ySegmentSize) - distance);
if (vertexDistance < 0) continue;
multiplier = easing(vertexDistance / edgeRadius);
g[k] = max(g[k], (peak - g[k]) * multiplier + g[k]);
// Use symmetry to reduce the number of iterations.
k = (options.ySegments-j)*xl + i;
g[k] = max(g[k], (peak - g[k]) * multiplier + g[k]);
}
}
};
/**
* Smooth the terrain by setting each point to the mean of its neighborhood.
*
* @param {Float32Array} g
* The geometry's z-positions to modify with heightmap data.
* @param {Object} options
* A map of settings that control how the terrain is constructed and
* displayed. Valid values are the same as those for the `options` parameter
* of {@link THREE.Terrain}().
* @param {Number} [weight=0]
* How much to weight the original vertex height against the average of its
* neighbors.
*/
THREE.Terrain.Smooth = function(g, options, weight) {
var heightmap = new Float32Array(g.length);
for (var i = 0, xl = options.xSegments + 1, yl = options.ySegments + 1; i < xl; i++) {
for (var j = 0; j < yl; j++) {
var sum = 0,
c = 0;
for (var n = -1; n <= 1; n++) {
for (var m = -1; m <= 1; m++) {
var key = (j+n)*xl + i + m;
if (typeof g[key] !== 'undefined' && i+m >= 0 && j+n >= 0 && i+m < xl && j+n < yl) {
sum += g[key];
c++;
}
}
}
heightmap[j*xl + i] = sum / c;
}
}
weight = weight || 0;
var w = 1 / (1 + weight);
for (var k = 0, l = g.length; k < l; k++) {
g[k] = (heightmap[k] + g[k] * weight) * w;
}
};
/**
* Smooth the terrain by setting each point to the median of its neighborhood.
*
* @param {Float32Array} g
* The geometry's z-positions to modify with heightmap data.
* @param {Object} options
* A map of settings that control how the terrain is constructed and
* displayed. Valid values are the same as those for the `options` parameter
* of {@link THREE.Terrain}().
*/
THREE.Terrain.SmoothMedian = function(g, options) {
var heightmap = new Float32Array(g.length),
neighborValues = [],
neighborKeys = [],
sortByValue = function(a, b) {
return neighborValues[a] - neighborValues[b];
};
for (var i = 0, xl = options.xSegments + 1, yl = options.ySegments + 1; i < xl; i++) {
for (var j = 0; j < yl; j++) {
neighborValues.length = 0;
neighborKeys.length = 0;
for (var n = -1; n <= 1; n++) {
for (var m = -1; m <= 1; m++) {
var key = (j+n)*xl + i + m;
if (typeof g[key] !== 'undefined' && i+m >= 0 && j+n >= 0 && i+m < xl && j+n < yl) {
neighborValues.push(g[key]);
neighborKeys.push(key);
}
}
}
neighborKeys.sort(sortByValue);
var halfKey = Math.floor(neighborKeys.length*0.5),
median;
if (neighborKeys.length % 2 === 1) {
median = g[neighborKeys[halfKey]];
}
else {
median = (g[neighborKeys[halfKey-1]] + g[neighborKeys[halfKey]]) * 0.5;
}
heightmap[j*xl + i] = median;
}
}
for (var k = 0, l = g.length; k < l; k++) {
g[k] = heightmap[k];
}
};
/**
* Smooth the terrain by clamping each point within its neighbors' extremes.
*
* @param {Float32Array} g
* The geometry's z-positions to modify with heightmap data.
* @param {Object} options
* A map of settings that control how the terrain is constructed and
* displayed. Valid values are the same as those for the `options` parameter
* of {@link THREE.Terrain}().
* @param {Number} [multiplier=1]
* By default, this filter clamps each point within the highest and lowest
* value of its neighbors. This parameter is a multiplier for the range
* outside of which the point will be clamped. Higher values mean that the
* point can be farther outside the range of its neighbors.
*/
THREE.Terrain.SmoothConservative = function(g, options, multiplier) {
var heightmap = new Float32Array(g.length);
for (var i = 0, xl = options.xSegments + 1, yl = options.ySegments + 1; i < xl; i++) {
for (var j = 0; j < yl; j++) {
var max = -Infinity,
min = Infinity;
for (var n = -1; n <= 1; n++) {
for (var m = -1; m <= 1; m++) {
var key = (j+n)*xl + i + m;
if (typeof g[key] !== 'undefined' && n && m && i+m >= 0 && j+n >= 0 && i+m < xl && j+n < yl) {
if (g[key] < min) min = g[key];
if (g[key] > max) max = g[key];
}
}
}
var kk = j*xl + i;
if (typeof multiplier === 'number') {
var halfdiff = (max - min) * 0.5,
middle = min + halfdiff;
max = middle + halfdiff * multiplier;
min = middle - halfdiff * multiplier;
}
heightmap[kk] = g[kk] > max ? max : (g[kk] < min ? min : g[kk]);
}
}
for (var k = 0, l = g.length; k < l; k++) {
g[k] = heightmap[k];
}
};
/**
* Partition a terrain into flat steps.
*
* @param {Float32Array} g
* The geometry's z-positions to modify with heightmap data.
* @param {Number} [levels]
* The number of steps to divide the terrain into. Defaults to
* (g.length/2)^(1/4).
*/
THREE.Terrain.Step = function(g, levels) {
// Calculate the max, min, and avg values for each bucket
var i = 0,
j = 0,
l = g.length,
inc = Math.floor(l / levels),
heights = new Array(l),
buckets = new Array(levels);
if (typeof levels === 'undefined') {
levels = Math.floor(Math.pow(l*0.5, 0.25));
}
for (i = 0; i < l; i++) {
heights[i] = g[i];
}
heights.sort(function(a, b) { return a - b; });
for (i = 0; i < levels; i++) {
// Bucket by population (bucket size) not range size
var subset = heights.slice(i*inc, (i+1)*inc),
sum = 0,
bl = subset.length;
for (j = 0; j < bl; j++) {
sum += subset[j];
}
buckets[i] = {
min: subset[0],
max: subset[subset.length-1],
avg: sum / bl,
};
}
// Set the height of each vertex to the average height of its bucket
for (i = 0; i < l; i++) {
var startHeight = g[i];
for (j = 0; j < levels; j++) {
if (startHeight >= buckets[j].min && startHeight <= buckets[j].max) {
g[i] = buckets[j].avg;
break;
}
}
}
};
/**
* Transform to turbulent noise.
*