/
Planet_Rendering.html
1770 lines (1434 loc) · 58 KB
/
Planet_Rendering.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js PathTracing Renderer - Planet Rendering (preview - WIP)</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1">
<style>
html, body {
width: 100%;
height: 100%;
font-family: Monospace;
background-color: #000;
color: #000;
margin: 0px;
overflow: hidden;
touch-action: none;
cursor: default;
}
#info {
position: fixed;
top: 5px;
width: 100%;
text-align: center;
color: #ffffff;
cursor: default;
user-select: none;
}
#cameraInfo {
position: fixed;
left: 3%;
bottom: 2%;
font-family: Arial;
color: #ffffff;
cursor: default;
user-select: none;
}
.toggleButton {
position:fixed;
background-color: gray;
border: none;
color: white;
top: 5px;
right: 5px;
padding: 10px 20px;
text-align: center;
text-decoration: none;
font-size: 14px;
margin: 4px 2px;
cursor: pointer;
user-select: none;
z-index: 11;
}
#timePauseButton {
top: 50px;
}
</style>
</head>
<body>
<div id="container"> </div>
<div id="info">three.js PathTracing Renderer - Planet Rendering (preview - WIP)</div>
<button id="cameraPosButton" class="toggleButton" onclick="toggleCameraPos()">Teleport to Surface</button>
<button id="timePauseButton" class="toggleButton" onclick="toggleTimePause()">Pause Time</button>
<div id="cameraInfo"> </div>
<script src="js/three.min.js"> </script>
<script src="js/pathTracingCommon.js"> </script>
<script src="js/threex.keyboardstate.js"> </script>
<!-- <script src="js/FirstPersonCameraControls.js"> </script> -->
<script>
// this demo's camera code requires a slight change to yawObject.rotation, as seen below
var FirstPersonCameraControls = function ( camera ) {
camera.rotation.set( 0, 0, 0 );
var pitchObject = new THREE.Object3D();
pitchObject.add( camera );
var yawObject = new THREE.Object3D();
yawObject.add( pitchObject );
var movementX = 0;
var movementY = 0;
var onMouseMove = function ( event ) {
movementX = event.movementX || event.mozMovementX || 0;
movementY = event.movementY || event.mozMovementY || 0;
/// yawObject.rotation.y -= movementX * 0.002;
yawObject.rotateOnWorldAxis(yawObject.up, -movementX * 0.002);
pitchObject.rotation.x -= movementY * 0.002;
// clamp the camera's vertical movement (around the x-axis) to the scene's 'ceiling' and 'floor'
pitchObject.rotation.x = Math.max( - PI_2, Math.min( PI_2, pitchObject.rotation.x ) );
};
document.addEventListener( 'mousemove', onMouseMove, false );
this.getObject = function () {
return yawObject;
};
this.getYawObject = function () {
return yawObject;
};
this.getPitchObject = function () {
return pitchObject;
};
this.getDirection = function() {
var te = pitchObject.matrixWorld.elements;
return function( v ) {
v.set( te[ 8 ], te[ 9 ], te[ 10 ] ).negate();
return v;
};
}();
this.getUpVector = function() {
var te = pitchObject.matrixWorld.elements;
return function( v ) {
v.set( te[ 4 ], te[ 5 ], te[ 6 ] );
return v;
};
}();
this.getRightVector = function() {
var te = pitchObject.matrixWorld.elements;
return function( v ) {
v.set( te[ 0 ], te[ 1 ], te[ 2 ] );
return v;
};
}();
};
</script>
<script src="js/MobileJoystickControls.js"> </script>
<script src="js/stats.min.js"> </script>
<script id="pathTracingVertexShader" type="x-shader/x-vertex">
precision highp float;
precision highp int;
varying vec2 vUv;
void main()
{
vUv = uv;
gl_Position = vec4( position, 1.0 );
}
</script>
<script id="pathTracingFragmentShader" type="x-shader/x-fragment">
precision highp float;
precision highp int;
precision highp sampler2D;
uniform sampler2D t_PerlinNoise;
uniform vec3 uSunDirection;
uniform vec3 uCameraFrameForward;
uniform vec3 uCameraFrameRight;
uniform vec3 uCameraFrameUp;
uniform float uCameraUnderWater;
uniform float uSunAngle;
uniform bool uCameraWithinAtmosphere;
#include <pathtracing_uniforms_and_defines>
#define N_SPHERES 2
//-----------------------------------------------------------------------
struct Ray { vec3 origin; vec3 direction; };
struct Sphere { float radius; vec3 position; vec3 emission; vec3 color; int type; };
struct Intersection { vec3 normal; vec3 emission; vec3 color; vec2 uv; int type; };
Sphere spheres[N_SPHERES];
#include <pathtracing_random_functions>
#include <pathtracing_sphere_intersect>
#include <pathtracing_plane_intersect>
#define EARTH_RADIUS 6360.0 // in Km
#define ATMOSPHERE_RADIUS 6420.0 // in Km
vec3 hash33(vec3 p)
{
p = fract(p * vec3(443.8975,397.2973, 491.1871));
p += dot(p.zxy, p.yxz+19.27);
return fract(vec3(p.x * p.y, p.z*p.x, p.y*p.z));
}
vec3 stars(in vec3 p)
{
vec3 c = vec3(0);
float res = uResolution.x;
for (float i = 0.0; i < 4.0; i++)
{
vec3 q = fract(p*(.15*res))-0.5;
vec3 id = floor(p*(.15*res));
vec2 rn = hash33(id).xy;
float c2 = 1.-smoothstep(0.,.6,length(q));
c2 *= step(rn.x,.0005+i*i*0.001);
c += c2*(mix(vec3(1.0,0.49,0.1),vec3(0.75,0.9,1.),clamp(rn.y,0.0,1.0))*0.1+0.9);
p *= 1.3;
}
return vec3(pow(max(0.0,c.r), 5.0), pow(max(0.0,c.g), 7.0), pow(max(0.0,c.b), 6.5));
}
/*
float starRand(vec3 v)
{
return fract(sin(dot(v ,vec3(12.9898,78.233,.0235))) * 43758.5453);
}
*/
//----------------------------------------------------------------------------------------
bool PlanetSphereIntersect( Ray ray, float rad, vec3 pos, inout float t0, inout float t1 )
//----------------------------------------------------------------------------------------
{
vec3 L = ray.origin - pos;
float a = dot( ray.direction, ray.direction );
float b = 2.0 * dot( ray.direction, L );
float c = dot( L, L ) - (rad * rad);
if (!solveQuadratic( a, b, c, t0, t1))
return false;
float temp;
if (t0 > t1)
{
temp = t0;
t0 = t1;
t1 = temp;
}
return true;
}
vec3 computeIncidentLight(Ray r, float tmin, float tmax)
{
vec3 betaR = vec3(3.8e-3, 13.5e-3, 33.1e-3);
vec3 betaM = vec3(21e-3);
float Hr = 7.994;
float Hm = 1.200;
float t0, t1;
if (!PlanetSphereIntersect(r, ATMOSPHERE_RADIUS, vec3(0), t0, t1) || t1 < 0.0) return vec3(0);
if (t0 > tmin && t0 > 0.0) tmin = t0;
if (t1 < tmax) tmax = t1;
int numSamples = 16;
int numSamplesLight = 8;
float segmentLength = (tmax - tmin) / float(numSamples);
float tCurrent = tmin;
vec3 sumR = vec3(0); // rayleigh contribution
vec3 sumM = vec3(0); // mie contribution
float opticalDepthR = 0.0;
float opticalDepthM = 0.0;
float mu = dot(r.direction, uSunDirection); // mu in the paper which is the cosine of the angle between the sun direction and the ray direction
float phaseR = 3.0 / (16.0 * PI) * (1.0 + mu * mu);
float g = 0.76;
float phaseM = 3.0 / (8.0 * PI) * ((1.0 - g * g) * (1.0 + mu * mu)) / ((2.0 + g * g) * pow(max(0.0, 1.0 + g * g - 2.0 * g * mu), 1.5));
for (int i = 0; i < 16; ++i)
{
vec3 samplePosition = r.origin + (tCurrent + segmentLength * 0.5) * r.direction;
float height = length(samplePosition) - EARTH_RADIUS;
// compute optical depth for light
float hr = exp(-height / Hr) * segmentLength;
float hm = exp(-height / Hm) * segmentLength;
opticalDepthR += hr;
opticalDepthM += hm;
// light optical depth
float t0Light, t1Light;
PlanetSphereIntersect(Ray(samplePosition, uSunDirection), ATMOSPHERE_RADIUS, vec3(0), t0Light, t1Light);
float segmentLengthLight = t1Light / float(numSamplesLight);
float tCurrentLight = 0.0;
float opticalDepthLightR = 0.0;
float opticalDepthLightM = 0.0;
int jCounter = 0;
for (int j = 0; j < 8; ++j)
{
vec3 samplePositionLight = samplePosition + (tCurrentLight + segmentLengthLight * 0.5) * uSunDirection;
float heightLight = length(samplePositionLight) - EARTH_RADIUS;
if (heightLight < 0.0) break;
jCounter += 1;
opticalDepthLightR += exp(-heightLight / Hr) * segmentLengthLight;
opticalDepthLightM += exp(-heightLight / Hm) * segmentLengthLight;
tCurrentLight += segmentLengthLight;
}
if (jCounter == numSamplesLight)
{
vec3 tau = betaR * (opticalDepthR + opticalDepthLightR) + betaM * 1.1 * (opticalDepthM + opticalDepthLightM);
vec3 attenuation = vec3(exp(-tau.x), exp(-tau.y), exp(-tau.z));
sumR += attenuation * hr;
sumM += attenuation * hm;
}
tCurrent += segmentLength;
}
return (sumR * betaR * phaseR + sumM * betaM * phaseM) * 20.0;
}
// TERRAIN
#define TERRAIN_HEIGHT 4.0 // max height in Km
#define TERRAIN_SAMPLE_SCALE 0.02
#define TERRAIN_LIFT -2.0 // (Km) how much to lift or drop the entire terrain
#define TERRAIN_FAR 100.0
float getTerrainHeight( in vec3 pos )
{
vec2 uv;
pos *= TERRAIN_SAMPLE_SCALE;
uv.x = dot(pos, uCameraFrameRight);
uv.y = dot(pos, uCameraFrameForward);
float h = 0.0;
float amp = TERRAIN_HEIGHT;
for (int i = 0; i < 4; i ++)
{
h += amp * texture2D(t_PerlinNoise, uv + 0.5).x;
amp *= 0.5;
uv *= 2.0;
}
return h + TERRAIN_LIFT + EARTH_RADIUS;
}
float getTerrainHeight_Detail( in vec3 pos )
{
vec2 uv;
pos *= TERRAIN_SAMPLE_SCALE;
uv.x = dot(pos, uCameraFrameRight);
uv.y = dot(pos, uCameraFrameForward);
float h = 0.0;
float amp = TERRAIN_HEIGHT;
for (int i = 0; i < 9; i ++)
{
h += amp * texture2D(t_PerlinNoise, uv + 0.5).x;
amp *= 0.5;
uv *= 2.0;
}
return h;
}
vec3 terrain_calcNormal( vec3 pos, float t )
{
float e = 0.001;
vec3 c = pos + (uCameraFrameUp * getTerrainHeight_Detail(pos));
vec3 xPos = c + (uCameraFrameRight*e);
vec3 zPos = c + (uCameraFrameForward*e);
vec3 xNeg = c - (uCameraFrameRight*e);
vec3 zNeg = c - (uCameraFrameForward*e);
float xPosH = getTerrainHeight_Detail(xPos);
float zPosH = getTerrainHeight_Detail(zPos);
float xNegH = getTerrainHeight_Detail(xNeg);
float zNegH = getTerrainHeight_Detail(zNeg);
xPos += (uCameraFrameUp * xPosH);
zPos += (uCameraFrameUp * zPosH);
xNeg += (uCameraFrameUp * xNegH);
zNeg += (uCameraFrameUp * zNegH);
vec3 xVec = normalize(xPos - xNeg);
vec3 zVec = normalize(zPos - zNeg);
return normalize(cross(zVec, xVec));
}
bool terrain_isSunVisible( vec3 pos, vec3 n, vec3 dirToLight)
{
float h = 1.0;
float a = 0.0;
float t = 0.0;
float terrainHeight = TERRAIN_HEIGHT * 2.0 + TERRAIN_LIFT + EARTH_RADIUS;
pos += n * 0.02;
if (dot(n, dirToLight) < 0.0)
return false;
for(int i = 0; i < 300; i++)
{
a = length(pos);
h = a - getTerrainHeight(pos);
pos += dirToLight * h;
if (a > terrainHeight || h < 0.01) break;
}
return h >= 0.01;
}
float TerrainIntersect( Ray r )
{
vec3 pos = r.origin;
vec3 dir = (r.direction);
float h = 0.0;
float t = 0.0;
float precisionFactor = 0.5;
for (int i = 0; i < 300; i++)
{
h = length(pos) - getTerrainHeight(pos);
if (t > TERRAIN_FAR || h < 0.01) break;
t += h * precisionFactor;
pos += dir * h * precisionFactor;
}
return (h <= 0.01) ? t : INFINITY;
}
// WATER
/* Credit: some of the following water code is borrowed from https://www.shadertoy.com/view/Ms2SD1 posted by user 'TDM' */
#define WATER_SAMPLE_SCALE 1.0 // higher equals more repitition
#define MAX_WAVE_HEIGHT 0.001 // (in Km) Max water wave amplitude
#define WATER_FREQ 100.0 // wave density: lower = spread out, higher = close together
#define WATER_CHOPPY 2.0 // smaller beachfront-type waves, they travel in parallel
#define WATER_SPEED 0.005 // how quickly time passes
#define WATER_FAR 2.0 // (in Km) how far to draw wave details
#define OCTAVE_M mat2(1.6, 1.2, -1.2, 1.6);
float hash( vec2 p )
{
float h = dot(p,vec2(127.1,311.7));
return fract(sin(h)*43758.5453123);
}
float noise( in vec2 p )
{
vec2 i = floor( p );
vec2 f = fract( p );
vec2 u = f*f*(3.0-2.0*f);
return -1.0+2.0*mix( mix( hash( i + vec2(0.0,0.0) ),
hash( i + vec2(1.0,0.0) ), u.x),
mix( hash( i + vec2(0.0,1.0) ),
hash( i + vec2(1.0,1.0) ), u.x), u.y);
}
float water_octave( vec2 uv, float choppy )
{
uv += noise(uv);
vec2 wv = 1.0 - abs(sin(uv));
vec2 swv = abs(cos(uv));
wv = mix(wv, swv, clamp(wv, 0.0, 1.0));
return pow(max(0.0, 1.0 - pow(max(0.0, wv.x * wv.y), 0.65)), choppy);
}
float getWaterHeight( vec3 pos )
{
float freq = WATER_FREQ;
float amp = MAX_WAVE_HEIGHT;
float choppy = WATER_CHOPPY;
float water_time = uTime * WATER_SPEED;
vec2 uv;
uv.x = dot(pos, uCameraFrameRight);
uv.y = dot(pos, uCameraFrameForward);
float d, h = 0.0;
for(int i = 0; i < 2; i++)
{
d = water_octave((uv + water_time) * freq, choppy);
d += water_octave((uv - water_time) * freq, choppy);
h += d * amp;
uv *= OCTAVE_M; freq *= 1.9; amp *= 0.22;
choppy = mix(choppy, 1.0, 0.2);
}
return h + EARTH_RADIUS + 1.0; // 1.0 Km above Earth surface
}
float getWaterHeight_Detail( vec3 pos )
{
float freq = WATER_FREQ;
float amp = MAX_WAVE_HEIGHT;
float choppy = WATER_CHOPPY;
float water_time = uTime * WATER_SPEED;
vec2 uv;
uv.x = dot(pos, uCameraFrameRight);
uv.y = dot(pos, uCameraFrameForward);
float d, h = 0.0;
for(int i = 0; i < 5; i++)
{
d = water_octave((uv + water_time) * freq, choppy);
d += water_octave((uv - water_time) * freq, choppy);
h += d * amp;
uv *= OCTAVE_M; freq *= 1.9; amp *= 0.22;
choppy = mix(choppy, 1.0, 0.2);
}
return h;
}
vec3 water_calcNormal( vec3 pos, float t )
{
float e = 0.005;
vec3 c = pos + (uCameraFrameUp * getWaterHeight_Detail(pos));
vec3 xPos = c + (uCameraFrameRight*e);
vec3 zPos = c + (uCameraFrameForward*e);
vec3 xNeg = c - (uCameraFrameRight*e);
vec3 zNeg = c - (uCameraFrameForward*e);
float xPosH = getWaterHeight_Detail(xPos);
float zPosH = getWaterHeight_Detail(zPos);
float xNegH = getWaterHeight_Detail(xNeg);
float zNegH = getWaterHeight_Detail(zNeg);
xPos += (uCameraFrameUp * xPosH);
zPos += (uCameraFrameUp * zPosH);
xNeg += (uCameraFrameUp * xNegH);
zNeg += (uCameraFrameUp * zNegH);
vec3 xVec = normalize(xPos - xNeg);
vec3 zVec = normalize(zPos - zNeg);
return normalize(cross(zVec, xVec));
}
float WaterIntersect( Ray r )
{
vec3 pos = r.origin;
vec3 dir = (r.direction);
float h = 0.0;
float t = 0.0;
float precisionFactor = 1.0;
for (int i = 0; i < 200; i++)
{
h = abs(length(pos) - getWaterHeight(pos));
if (t > WATER_FAR || h < 0.01) break;
t += h * precisionFactor;
pos += dir * h * precisionFactor;
}
return (h <=0.01) ? t : INFINITY;
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
float SceneIntersect( Ray r, inout Intersection intersec, bool checkWater )
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
{
float d = INFINITY;
float t = INFINITY;
float terrainHeight, waterHeight;
vec3 hitPos;
vec3 normal;
//if (uCameraWithinAtmosphere)
d = TerrainIntersect( r );
if (d > TERRAIN_FAR)
{
d = SphereIntersect(EARTH_RADIUS, vec3(0), r);
if (d < INFINITY)
{
hitPos = r.origin + r.direction * d;
terrainHeight = getTerrainHeight(hitPos);
//d = PlaneIntersect(vec4(uCameraFrameUp, terrainHeight), r);
d = SphereIntersect(terrainHeight, vec3(0), r);
}
}
if (d < t)
{
t = d;
hitPos = r.origin + r.direction * t;
intersec.normal = terrain_calcNormal(hitPos, t);
intersec.emission = vec3(1,0,1);
intersec.color = vec3(0);
intersec.type = TERRAIN;
}
if (!checkWater)
return t;
d = INFINITY; // reset d
//if (uCameraWithinAtmosphere)
d = WaterIntersect( r );
if (d > WATER_FAR)
{
d = SphereIntersect(EARTH_RADIUS, vec3(0), r);
if (d < INFINITY)
{
hitPos = r.origin + r.direction * d;
waterHeight = getWaterHeight(hitPos);
//d = PlaneIntersect(vec4(uCameraFrameUp, waterHeight), r);
d = SphereIntersect(waterHeight, vec3(0), r);
}
}
if (d < t)
{
t = d;
hitPos = r.origin + r.direction * t;
intersec.normal = water_calcNormal(hitPos, t);
//if ( !uCameraWithinAtmosphere )
// intersec.normal = normalize(hitPos);
intersec.emission = vec3(0);
intersec.color = vec3(0.7,0.8,0.9);
intersec.type = REFR;
}
if (t < INFINITY)
return t;
for (int i = 0; i < N_SPHERES; i++)
{
// Sun and Moon Spheres
d = SphereIntersect( spheres[i].radius, spheres[i].position, r );
if (d < t)
{
t = d;
intersec.normal = normalize((r.origin + r.direction * t) - spheres[i].position);
intersec.emission = spheres[i].emission;
intersec.color = spheres[i].color;
intersec.type = spheres[i].type;
}
}
return t;
}
//-----------------------------------------------------------------------
vec3 CalculateRadiance( Ray r, inout float seed, vec3 starRayDir )
//-----------------------------------------------------------------------
{
vec3 randVec = vec3(rand(seed) * 2.0 - 1.0, rand(seed) * 2.0 - 1.0, rand(seed) * 2.0 - 1.0);
Ray cameraRay = r;
Intersection intersec;
vec3 accumCol = vec3(0.0);
vec3 mask = vec3(1.0);
vec3 n, nl, x;
vec3 atmosphereColor = vec3(0);
vec3 firstX = vec3(0);
vec3 terrainColor = vec3(0);
float t0, t1, tMax = INFINITY;
float t = INFINITY;
bool terrainHit = false;
bool bounceIsSpecular = true;
bool checkWater = true;
bool isDayTime = true;
if (uCameraWithinAtmosphere && dot(uSunDirection, uCameraFrameUp) < 0.0)
{
isDayTime = false;
}
if (PlanetSphereIntersect(r, EARTH_RADIUS, vec3(0), t0, t1) && t1 > 0.0)
tMax = max(0.0, t0);
accumCol = computeIncidentLight(r, 0.0, tMax);
for (int depth = 0; depth < 2; depth++)
{
t = SceneIntersect(r, intersec, checkWater);
checkWater = false; // no need to check water a second time
tMax = INFINITY; //reset tMax
terrainHit = false;
if (PlanetSphereIntersect(r, EARTH_RADIUS, vec3(0), t0, t1) && t1 > 0.0)
tMax = max(0.0, t0);
// ray hits empty space
if (t == INFINITY)
{
if (depth == 1)
{
accumCol = computeIncidentLight(r, 0.0, tMax);
}
break;
}
// if we reached something bright, don't spawn any more rays
if (intersec.type == LIGHT) // Sun
{
//if (bounceIsSpecular)
{
accumCol = mix(computeIncidentLight(r, 0.0, tMax), intersec.emission, 0.5);
}
break;
}
// useful data
n = intersec.normal;
nl = dot(n,r.direction) <= 0.0 ? normalize(n) : normalize(n * -1.0);
x = r.origin + r.direction * t;
if (intersec.type == DIFF) // Moon
{
vec2 uv;
vec3 mn = n;
uv.x = (1.0 + atan(mn.z, mn.x) / PI) * 0.5;
uv.y = acos(mn.y) / PI;
uv.x *= 2.5;
float rockNoise = clamp(texture2D(t_PerlinNoise, uv).x, 0.2, 1.0);
intersec.color = clamp(intersec.color * rockNoise, 0.0, 1.0);
vec3 sampleSkyCol = computeIncidentLight(r, 0.0, tMax);
accumCol = mix(intersec.color, sampleSkyCol, clamp(0.7 * (sampleSkyCol.r + sampleSkyCol.b), 0.0, 1.0));
// * max(0.0, dot(nl, uSunDirection)); // for moon phases
break;
}
// ray hits terrain
if (intersec.type == TERRAIN)
{
firstX = x;
terrainHit = true;
float altitude = length(x) - EARTH_RADIUS;
vec2 uv;
uv.x = dot(x, uCameraFrameRight);
uv.y = dot(x, uCameraFrameForward);
float rockNoise = texture2D(t_PerlinNoise, (0.2 * uv)).x;
vec3 rockColor0 = vec3(0.2, 0.2, 0.2) * 0.01 * rockNoise;
vec3 rockColor1 = vec3(0.2, 0.2, 0.2) * rockNoise;
vec3 snowColor = vec3(0.7);
vec3 up = normalize(x);
float nY = max(0.0, dot(n, up));
vec3 sunDirection = uSunDirection;
vec3 randomSkyVec = normalize(n + (randVec * 0.2));
vec3 skyColor = computeIncidentLight(Ray(x, randomSkyVec), 0.0, tMax);
vec3 sunColor = computeIncidentLight(Ray(x, sunDirection), 0.0, tMax);
sunColor = clamp(sunColor + 0.5, 0.0, 1.0);
vec3 ambientColor;
float terrainLayer = clamp( (altitude + (rockNoise * 1.0) * nY) / (TERRAIN_HEIGHT * 1.5 + TERRAIN_LIFT), 0.0, 1.0 );
if (!isDayTime)
sunDirection *= -1.0;
if (terrainLayer > 0.7 && terrainLayer > 1.0 - nY)
{
intersec.color = snowColor;
ambientColor = skyColor * max(0.0, dot(up, n)); // ambient color from sky light
n = normalize(mix(n, sunDirection, terrainLayer * 0.5));
}
else
{
intersec.color = mix(rockColor0, rockColor1, clamp(terrainLayer * nY, 0.0, 1.0) );
ambientColor = intersec.color * skyColor * max(0.0, dot(randomSkyVec, n)); // ambient color from sky light
}
vec3 shadowRayDirection = normalize(sunDirection + (0.1 * randomSkyVec * max(dot(sunDirection, up), 0.0)));
if ( terrain_isSunVisible(x, n, shadowRayDirection) ) // in direct sunlight
{
if (isDayTime)
terrainColor = intersec.color * sunColor * max(0.0, dot(n, normalize(sunDirection + (randVec * 0.01))));
else
terrainColor = intersec.color * 0.002 * max(0.0, dot(n, normalize(sunDirection + (randVec * 0.01))));
}
else terrainColor = ambientColor;
if (isDayTime && altitude < 1.0) // terrain is under water
{
terrainColor = mix(rockColor0, terrainColor, clamp(0.1*altitude, 0.0, 1.0));
}
break;
}
if (intersec.type == REFR) // Ideal dielectric REFRACTION
{
float nc = 1.0; // IOR of air
float nt = 1.33; // IOR of water
float nnt = dot(r.direction, n) <= 0.0 ? (nc / nt) : (nt / nc); // Ray from outside going in?
vec3 tdir = refract(r.direction, nl, nnt);
// Original Fresnel equations
float cosThetaInc = dot(nl, r.direction);
float cosThetaTra = dot(nl, tdir);
float coefS = (nc * cosThetaInc - nt * cosThetaTra) / (nc * cosThetaInc + nt * cosThetaTra);
float coefP = (nc * cosThetaTra - nt * cosThetaInc) / (nc * cosThetaTra + nt * cosThetaInc);
float Re = ( (coefS * coefS) + (coefP * coefP) ) * 0.5; // Unpolarized
//Re *= 2.0; // tweak to add more reflectivity to water
if (rand(seed) < Re) // reflect ray from surface
{
r = Ray( x, reflect(r.direction, nl) );
//r.origin += r.direction * 1.0;
continue;
}
else // transmit ray through surface
{
mask *= intersec.color;
r = Ray(x, tdir);
//r.origin += r.direction * 1.0;
continue;
}
} // end if (intersec.type == REFR)
} // end for (int depth = 0; depth < 2; depth++)
// atmospheric haze effect (aerial perspective)
float hitDistance;
if (terrainHit)
{
hitDistance = distance(cameraRay.origin, firstX);
accumCol = mix( accumCol, terrainColor, clamp( exp2( -log(hitDistance * 0.02) ), 0.0, 1.0 ) );
// underwater fog effect
hitDistance *= uCameraUnderWater;
accumCol = mix( vec3(0.0,0.05,0.05), accumCol, clamp( exp2( -hitDistance * 1.0 ), 0.0, 1.0 ) );
}
// stars
if (t == INFINITY)
{
vec3 rotatedStarDir = starRayDir;
rotatedStarDir.x = starRayDir.x * cos(uSunAngle) + starRayDir.z * sin(uSunAngle);
rotatedStarDir.z = starRayDir.x * -sin(uSunAngle) + starRayDir.z * cos(uSunAngle);
vec3 starVal = stars(normalize(rotatedStarDir));
float altitude = length(cameraRay.origin);
if (altitude < ATMOSPHERE_RADIUS && isDayTime)
{
float starAlt = EARTH_RADIUS + 15.0; // in Km
if (altitude > starAlt)
starVal = mix(vec3(0), starVal, clamp(exp(-(ATMOSPHERE_RADIUS - altitude) * 0.07), 0.0, 1.0));
else
starVal = mix(vec3(0), starVal, clamp(dot(uCameraFrameUp, -uSunDirection), 0.0, 1.0));
}
accumCol += starVal;
}
return vec3(max(vec3(0), accumCol));
}
//-----------------------------------------------------------------------
void SetupScene(void)
//-----------------------------------------------------------------------
{
vec3 z = vec3(0); // no color value, black
vec3 L1 = vec3(1.0, 0.9, 0.8) * 5.0;// Sun Light
vec3 camPos = vec3( uCameraMatrix[3][0], uCameraMatrix[3][1], uCameraMatrix[3][2]);
spheres[0] = Sphere( 100.0, camPos + (normalize( uSunDirection) * 5000.0), L1, z, LIGHT);//spherical white Light1
spheres[1] = Sphere( 150.0, camPos + (normalize(-uSunDirection) * 5000.0), z, vec3(2), DIFF);//spherical white moon
}
void main( void )
{
vec3 camPos = vec3( uCameraMatrix[3][0], uCameraMatrix[3][1], uCameraMatrix[3][2]);
vec3 camRight = normalize( vec3( uCameraMatrix[0][0], uCameraMatrix[0][1], uCameraMatrix[0][2]) );
vec3 camUp = normalize( vec3( uCameraMatrix[1][0], uCameraMatrix[1][1], uCameraMatrix[1][2]) );
vec3 camForward = normalize( vec3(-uCameraMatrix[2][0], -uCameraMatrix[2][1], -uCameraMatrix[2][2]) );
// seed for rand() function
float seed = mod(uSampleCounter,1000.0) * uRandomVector.x - uRandomVector.y + uResolution.y * gl_FragCoord.x / uResolution.x + uResolution.x * gl_FragCoord.y / uResolution.y;
float r1 = 2.0 * rand(seed);
float r2 = 2.0 * rand(seed);
vec2 pixelPos = vec2(0);
vec2 offset = vec2(0);
//if ( !uCameraIsMoving )
{
offset.x = r1 < 1.0 ? sqrt(r1) - 1.0 : 1.0 - sqrt(2.0 - r1);
offset.y = r2 < 1.0 ? sqrt(r2) - 1.0 : 1.0 - sqrt(2.0 - r2);
}
offset /= (uResolution);
pixelPos = (2.0 * (vUv + offset) - 1.0);
vec2 starPixelPos = (2.0 * vUv - 1.0);
vec3 rayDir = normalize( pixelPos.x * camRight * uULen + pixelPos.y * camUp * uVLen + camForward );
vec3 starRayDir = normalize( starPixelPos.x * camRight * uULen + starPixelPos.y * camUp * uVLen + camForward );
// depth of field
vec3 focalPoint = uFocusDistance * rayDir;
float randomAngle = rand(seed) * TWO_PI; // pick random point on aperture
float randomRadius = rand(seed) * uApertureSize;
vec3 randomAperturePos = ( cos(randomAngle) * camRight + sin(randomAngle) * camUp ) * randomRadius;
// point on aperture to focal point
vec3 finalRayDir = normalize(focalPoint - randomAperturePos);
Ray ray = Ray( camPos + randomAperturePos, finalRayDir );
//Ray starRay = Ray( camPos + randomAperturePos, starRayDir );
SetupScene();
// perform path tracing and get resulting pixel color
vec3 pixelColor = CalculateRadiance( ray, seed, starRayDir );
vec3 previousColor = texture2D(tPreviousTexture, vUv).rgb;
if ( uCameraIsMoving )
{
previousColor *= 0.85; // motion-blur trail amount (old image)
pixelColor *= 0.15; // brightness of new image (noisy)
}
else
{
previousColor *= 0.9; // motion-blur trail amount (old image)
pixelColor *= 0.1; // brightness of new image (noisy)
}
gl_FragColor = vec4( pixelColor + previousColor, 1.0 );
}
</script>
<script>
var SCREEN_WIDTH;
var SCREEN_HEIGHT;
var container, stats;
var controls;
var pathTracingScene, screenTextureScene, screenOutputScene;
var pathTracingUniforms, screenTextureUniforms, screenOutputUniforms;
var PerlinNoiseTexture;
var pathTracingDefines;
var pathTracingGeometry, pathTracingMaterial, pathTracingMesh;
var screenTextureGeometry, screenTextureMaterial, screenTextureMesh;
var screenOutputGeometry, screenOutputMaterial, screenOutputMesh;
var pathTracingRenderTarget, screenOutputRenderTarget;
var quadCamera, worldCamera;
var renderer, clock;
var frameTime, elapsedTime;
var fovScale;
var increaseFOV = false;
var decreaseFOV = false;
var apertureSize = 0.0;
var increaseAperture = false;
var decreaseAperture = false;
var focusDistance = 1180.0;
var increaseFocusDist = false;
var decreaseFocusDist = false;
var pixelRatio = 0.5;
var TWO_PI = Math.PI * 2;
var sunAngle = 5.1;
var sunDirection = new THREE.Vector3();
var randomVector = new THREE.Vector3();
var sampleCounter = 1.0;
var keyboard = new THREEx.KeyboardState();
var cameraIsMoving = false;
var cameraJustStartedMoving = false;
var cameraRecentlyMoving = false;
var isPaused = true;
var oldYawRotation, oldPitchRotation;
var mobileJoystickControls = null;
var oldDeltaX = 0, oldDeltaY = 0;
var newDeltaX = 0, newDeltaY = 0;
var mobileControlsMoveX = 0;
var mobileControlsMoveY = 0;
var stillFlagX = true, stillFlagY = true;
var oldPinchWidthX = 0;
var oldPinchWidthY = 0;
var pinchDeltaX = 0;
var pinchDeltaY = 0;
var camFlightSpeed = 0;
var earthRadius = 6360;
var atmosphereRadius = 6420;
var altitude = 2000.0;
var oldRotationX = 0.0;
var oldRotationY = 0.0;
var cameraWithinAtmosphere = true;
var UniverseUp_Y_Vec = new THREE.Vector3(0,1,0);
var UniverseToCam_Z_Vec = new THREE.Vector3(0,0,1);
var centerOfEarthToCameraVec = new THREE.Vector3();
var newCameraDirectionVector = new THREE.Vector3();
var cameraFrameRight = new THREE.Vector3();
var cameraFrameForward = new THREE.Vector3();
var cameraDistFromCenterOfEarth = 0.0;
var amountToMoveCamera = 0.0;
var canUpdateCameraAtmosphereOrientation = true;
var canUpdateCameraSpaceOrientation = true;
var cameraUnderWater = false;
var fontAspect;
var camPosToggle = false;
var timePauseToggle = false;
// the following variables will be used to calculate rotations and directions from the camera
var cameraDirectionVector = new THREE.Vector3();//for moving where the camera is looking
var cameraRightVector = new THREE.Vector3();//for strafing the camera right and left
var cameraUpVector = new THREE.Vector3();//for moving camera up and down
var cameraWorldQuaternion = new THREE.Quaternion();//for rotating scene objects to match camera's current rotation
var cameraControlsObject;//for positioning and moving the camera itself
var cameraControlsYawObject;//allows access to control camera's left/right movements through mobile input
var cameraControlsPitchObject;//allows access to control camera's up/down movements through mobile input
var PI_2 = Math.PI / 2;//used by controls below
var infoElement = document.getElementById( 'info' );
var cameraInfoElement = document.getElementById( 'cameraInfo' );
var mouseControl = true;
function onMouseWheel( event ) {
event.preventDefault();
event.stopPropagation();
if ( event.deltaY > 0 ) {
increaseFOV = true;