-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathPathTracer.uclcg
1004 lines (828 loc) · 29.3 KB
/
PathTracer.uclcg
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
function setup()
{
UI = {};
UI.tabs = [];
UI.titleLong = 'Path Tracer';
UI.titleShort = 'PathTracer';
UI.numFrames = 100000;
UI.maxFPS = 1000;
UI.renderWidth = 512;
UI.renderHeight = 256;
UI.tabs.push(
{
visible: true,
type: `x-shader/x-fragment`,
title: `Raytracing`,
id: `TraceFS`,
initialValue: `#define SOLUTION_LIGHT
#define SOLUTION_BOUNCE
#define SOLUTION_THROUGHPUT
#define SOLUTION_HALTON
#define SOLUTION_NEXT_EVENT_ESTIMATION
#define SOLUTION_AA
precision highp float;
#define M_PI 3.1415
struct Material {
#ifdef SOLUTION_LIGHT
// Missing property
vec3 lightIntensity;
#endif
vec3 diffuse;
vec3 specular;
float glossiness;
};
struct Sphere {
vec3 position;
float radius;
Material material;
};
struct Plane {
vec3 normal;
float d;
Material material;
};
const int sphereCount = 4;
const int planeCount = 4;
const int emittingSphereCount = 2;
#ifdef SOLUTION_BOUNCE
// Insert correct value here
#else
const int maxPathLength = 1;
#endif
struct Scene {
Sphere[sphereCount] spheres;
Plane[planeCount] planes;
};
struct Ray {
vec3 origin;
vec3 direction;
};
// Contains all information pertaining to a ray/object intersection
struct HitInfo {
bool hit;
float t;
vec3 position;
vec3 normal;
Material material;
};
HitInfo getEmptyHit() {
Material emptyMaterial;
#ifdef SOLUTION_LIGHT
// Set the value of the missing property
#endif
emptyMaterial.diffuse = vec3(0.0);
emptyMaterial.specular = vec3(0.0);
emptyMaterial.glossiness = 0.0;
return HitInfo(false, 0.0, vec3(0.0), vec3(0.0), emptyMaterial);
}
// Sorts the two t values such that t1 is smaller than t2
void sortT(inout float t1, inout float t2) {
// Make t1 the smaller t
if(t2 < t1) {
float temp = t1;
t1 = t2;
t2 = temp;
}
}
// Tests if t is in an interval
bool isTInInterval(const float t, const float tMin, const float tMax) {
return t > tMin && t < tMax;
}
// Get the smallest t in an interval
bool getSmallestTInInterval(float t0, float t1, const float tMin, const float tMax, inout float smallestTInInterval) {
sortT(t0, t1);
// As t0 is smaller, test this first
if(isTInInterval(t0, tMin, tMax)) {
smallestTInInterval = t0;
return true;
}
// If t0 was not in the interval, still t1 could be
if(isTInInterval(t1, tMin, tMax)) {
smallestTInInterval = t1;
return true;
}
// None was
return false;
}
HitInfo intersectSphere(const Ray ray, const Sphere sphere, const float tMin, const float tMax) {
vec3 to_sphere = ray.origin - sphere.position;
float a = dot(ray.direction, ray.direction);
float b = 2.0 * dot(ray.direction, to_sphere);
float c = dot(to_sphere, to_sphere) - sphere.radius * sphere.radius;
float D = b * b - 4.0 * a * c;
if (D > 0.0)
{
float t0 = (-b - sqrt(D)) / (2.0 * a);
float t1 = (-b + sqrt(D)) / (2.0 * a);
float smallestTInInterval;
if(!getSmallestTInInterval(t0, t1, tMin, tMax, smallestTInInterval)) {
return getEmptyHit();
}
vec3 hitPosition = ray.origin + smallestTInInterval * ray.direction;
vec3 normal =
length(ray.origin - sphere.position) < sphere.radius + 0.001?
-normalize(hitPosition - sphere.position) :
normalize(hitPosition - sphere.position);
return HitInfo(
true,
smallestTInInterval,
hitPosition,
normal,
sphere.material);
}
return getEmptyHit();
}
HitInfo intersectPlane(Ray ray, Plane plane) {
float t = -(dot(ray.origin, plane.normal) + plane.d) / dot(ray.direction, plane.normal);
vec3 hitPosition = ray.origin + t * ray.direction;
return HitInfo(
true,
t,
hitPosition,
normalize(plane.normal),
plane.material);
return getEmptyHit();
}
float lengthSquared(const vec3 x) {
return dot(x, x);
}
HitInfo intersectScene(Scene scene, Ray ray, const float tMin, const float tMax)
{
HitInfo best_hit_info;
best_hit_info.t = tMax;
best_hit_info.hit = false;
for (int i = 0; i < sphereCount; ++i) {
Sphere sphere = scene.spheres[i];
HitInfo hit_info = intersectSphere(ray, sphere, tMin, tMax);
if( hit_info.hit &&
hit_info.t < best_hit_info.t &&
hit_info.t > tMin)
{
best_hit_info = hit_info;
}
}
for (int i = 0; i < planeCount; ++i) {
Plane plane = scene.planes[i];
HitInfo hit_info = intersectPlane(ray, plane);
if( hit_info.hit &&
hit_info.t < best_hit_info.t &&
hit_info.t > tMin)
{
best_hit_info = hit_info;
}
}
return best_hit_info;
}
// Converts a random integer in 15 bits to a float in (0, 1)
float randomInetegerToRandomFloat(int i) {
return float(i) / 32768.0;
}
// Returns a random integer for every pixel and dimension that remains the same in all iterations
int pixelIntegerSeed(const int dimensionIndex) {
vec3 p = vec3(gl_FragCoord.xy, dimensionIndex);
vec3 r = vec3(23.14069263277926, 2.665144142690225,7.358926345 );
return int(32768.0 * fract(cos(dot(p,r)) * 123456.0));
}
// Returns a random float for every pixel that remains the same in all iterations
float pixelSeed(const int dimensionIndex) {
return randomInetegerToRandomFloat(pixelIntegerSeed(dimensionIndex));
}
// The global random seed of this iteration
// It will be set to a new random value in each step
uniform int globalSeed;
int randomSeed;
void initRandomSequence() {
randomSeed = globalSeed + pixelIntegerSeed(0);
}
// Computesinteger x modulo y not available in most WEBGL SL implementations
int mod(const int x, const int y) {
return int(float(x) - floor(float(x) / float(y)) * float(y));
}
// Returns the next integer in a pseudo-random sequence
int rand() {
randomSeed = randomSeed * 1103515245 + 12345;
return mod(randomSeed / 65536, 32768);
}
// Returns the next float in this pixels pseudo-random sequence
float uniformRandom() {
return randomInetegerToRandomFloat(rand());
}
// Returns the ith prime number for the first 20
const int maxDimensionCount = 10;
int prime(const int index) {
if(index == 0) return 2;
if(index == 1) return 3;
if(index == 2) return 5;
if(index == 3) return 7;
if(index == 4) return 11;
if(index == 5) return 13;
if(index == 6) return 17;
if(index == 7) return 19;
if(index == 8) return 23;
if(index == 9) return 29;
if(index == 10) return 31;
if(index == 11) return 37;
if(index == 12) return 41;
if(index == 13) return 43;
if(index == 14) return 47;
if(index == 15) return 53;
return 2;
}
float halton(const int sampleIndex, const int dimensionIndex) {
#ifdef SOLUTION_HALTON
// Put your implemntation of halton here.
/*
WITHOUT THE SHIFT
We want to compute a random number between zero and one following the HALTON
algorithm.
Given in input a number (sampleIndex) and a dimension we obtain a random number with
the following procedure:
We get a prime number (let's call it prime) from the dimensionIndex with a lookup table
Then what we need to do is converting sampleIndex (from base 10) to base prime.
Then we flip the number and we make it floating point.
Making an example what we do is : suppose the converted number is something like 234567
the output is going to be 0.765432
WITH THE SHIFT
We notice that without any change we see patterns on the screen due to the pseudo-random nature
of the algorithm, therefore to remove these patterns a possible solution would be to
add a shift.
We want a shift produced per-pixel and per-dimension (but not per-sample) therefore what we
use is the already implemented method "pixelSeed" then following the .pdf sheet we add it
to the halton pseudo-random number and we take the fractional part.
*/
int base = prime(dimensionIndex);
float index = float(sampleIndex);
float invBase = 1.0/float(base);
float result = 0.0;
for (int i = 1 ; i < 100; i++)
{
float module = mod(index, float(base));
result += module/pow(float(base), float(i));
index*=invBase;
index = ceil(index);
if (index <= 1.0)
break;
}
return fract(result+pixelSeed(dimensionIndex));
#else
return 0.0;
#endif
}
// This is the index of the sample controlled by the framework.
// It increments by one in every call of this shader
uniform int baseSampleIndex;
// Returns a well-distributed number in (0,1) for the dimension dimensionIndex
float sample(const int dimensionIndex) {
#ifdef SOLUTION_HALTON
// Return your implemented halton function here
return halton(baseSampleIndex, dimensionIndex);
#else
// Replace the line below to use the Halton sequence for variance reduction
return uniformRandom();
#endif
}
// This is a helper function to sample two-dimensionaly in dimension dimensionIndex
vec2 sample2(const int dimensionIndex) {
return vec2(sample(dimensionIndex + 0), sample(dimensionIndex + 1));
}
vec3 sample3(const int dimensionIndex) {
return vec3(sample(dimensionIndex + 0), sample(dimensionIndex + 1), sample(dimensionIndex + 2));
}
// This is a register of all dimensions that we will want to sample.
// Thanks to Iliyan Georgiev from Solid Angle for explaining proper housekeeping of sample dimensions in ranomdized Quasi-Monte Carlo
//
// So if we want to use lens sampling, we call sample(LENS_SAMPLE_DIMENSION).
//
// There are infinitely many path sampling dimensions.
// These start at PATH_SAMPLE_DIMENSION.
// The 2D sample pair for vertex i is at PATH_SAMPLE_DIMENSION + PATH_SAMPLE_DIMENSION_MULTIPLIER * i + 0
#define ANTI_ALIAS_SAMPLE_DIMENSION 0
#define LENS_SAMPLE_DIMENSION 2
#define PATH_SAMPLE_DIMENSION 4
// This is 2 for two dimensions and 2 as we use it for two purposese: NEE and path connection
#define PATH_SAMPLE_DIMENSION_MULTIPLIER (2 * 2)
vec3 randomDirection(const int dimensionIndex) {
#ifdef SOLUTION_BOUNCE
// Put yout code to compute a random direction in 3D here
float xi_0 = sample(dimensionIndex);
float xi_1 = sample(dimensionIndex+1);
float theta = acos(2.0*xi_0 -1.0);
float phi = xi_1*2.0*M_PI;
float x = sin(theta)*cos(phi);
float y = sin(theta)*sin(phi);
float z = cos(theta);
return vec3(x,y,z);
#else
return vec3(0);
#endif
}
vec3 getEmission(const Material material, const vec3 normal) {
#ifdef SOLUTION_LIGHT
// Put the correct value here.
return material.lightIntensity ;
#else
// This is wrong. It just returns the diffuse color so that you see something to be sure it is working.
return material.diffuse;
#endif
}
vec3 getReflectance(
const Material material,
const vec3 normal,
const vec3 inDirection,
const vec3 outDirection)
{
#ifdef SOLUTION_THROUGHPUT
// Compute diffuse and specular contribution here
/*
Let's remember what is stored in the material struct
vec3 lightIntensity;
vec3 diffuse;
vec3 specular;
float glossiness;
This is the BRDF component, here we want to compute the "actual color" of the point hitted by the ray
in out pathtracer.
In order to do so we first compute the reflectance vector :
normal
\ /|\ /
input \ | /
ray \ t|t / reflected
\ | / ray
\|/
-------SURFACE------------
Then we compute the shading using the Physically-correct Phong formula
and then we add the diffuse component to the computed term.
*/
vec3 reflectanceVector = reflect(inDirection, normal);
return material.specular * ((material.glossiness + 2.0 )/(2.0*M_PI)) * pow(max(0.0, dot(outDirection, reflectanceVector)), material.glossiness) + material.diffuse;
#else
return vec3(1.0);
#endif
}
vec3 getGeometricTerm(
const Material material,
const vec3 normal,
const vec3 inDirection,
const vec3 outDirection)
{
#ifdef SOLUTION_THROUGHPUT
/*
Compute the geometric term here
//\ outgoing ray
normal /|\ /
|t/
___________|/__________SURFACE
the geometric term is computed as the cosine of the angle formed between
the normal of the hitted surface and the outgoing ray.
*/
float cos_theta = max(0.0, dot(outDirection, normal));
return vec3(cos_theta);
#else
return vec3(1.0);
#endif
}
mat4 rotationMatrixFromAngleAxis(float angle, vec3 axis)
{
axis = normalize(axis);
float s = sin(angle);
float c = cos(angle);
float oc = 1.0 - c;
return mat4(oc * axis.x * axis.x + c,
oc * axis.x * axis.y - axis.z * s,
oc * axis.z * axis.x + axis.y * s, 0.0,
oc * axis.x * axis.y + axis.z * s,
oc * axis.y * axis.y + c,
oc * axis.y * axis.z - axis.x * s, 0.0,
oc * axis.z * axis.x - axis.y * s,
oc * axis.y * axis.z + axis.x * s,
oc * axis.z * axis.z + c, 0.0,
0.0,
0.0,
0.0,
1.0);
}
vec3 getEmitterPosition(const vec3 position, const Sphere sphere, const int dimensionIndex) {
// This is a simplified version: Just report the sphere center. Will not do well with visibility.
//return sphere.position;
// This is the wrong simplified version: Take a random surface point.
//return sphere.position + randomDirection(dimensionIndex) * sphere.radius;
// Well we stick our fingers in
// The ground, heave and
// Turn the world around
// This has three main steps:
// 1) Make a direction
// 2) Orient it so it points to the sphere
// 3) Find a point on the sphere along this direction
// Step 1) Make a random direction in a cone orientedd along th up-pointing z direction
// .. the opening angle of a sphere in a certain distance
float apexAngle = asin(sphere.radius / length(position - sphere.position));
// The rotation around the z axis
float phi = sample(dimensionIndex + 1) * 2.0 * M_PI;
// z is the cosine of the angle.
// We need a random cosine of the angle (which is notthe same as the cosine of a random angle!)
float z = mix(1.0, cos(apexAngle), sample(dimensionIndex + 0));
vec3 alignedDirection = vec3(sqrt(1.0-z*z) * cos(phi), sqrt(1.0-z*z) * sin(phi), z);
// Step 2) Rotate the z axis-aligned dirction to point into the direction of the sphere
vec3 direction = normalize(sphere.position - position);
float rotationAngle = acos(dot(direction, vec3(0,0,1)));
vec3 rotationAxis = cross(direction, vec3(0,0,1));
mat4 rotationMatrix = rotationMatrixFromAngleAxis(rotationAngle, rotationAxis);
vec3 worldDirection = (rotationMatrix * vec4(alignedDirection, 0)).xyz;
// Step 3) Send a ray. it feels this should be easier, but Tobias does not see it.
Ray emitterRay;
emitterRay.origin = position;
emitterRay.direction = worldDirection;
return intersectSphere(emitterRay, sphere, 0.01, 100000.0).position;
}
vec3 samplePath(const Scene scene, const Ray initialRay) {
// Initial result is black
vec3 result = vec3(0);
Ray incomingRay = initialRay;
vec3 throughput = vec3(1.0);
const int maxPathLength = 3;
for(int i = 0; i < maxPathLength; i++) {
HitInfo hitInfo = intersectScene(scene, incomingRay, 0.001, 10000.0);
if(!hitInfo.hit) return result;
#ifdef SOLUTION_NEXT_EVENT_ESTIMATION
// Put the next event-estimation code here
/*
Because the lights might be very small the convergence time could be extremely long.
A natural question would be how can we speed up this ? Well a possible solution is
the Next Event Estimation.
Next event estimation at each bounce take in considaration the emission of the
lights computing the shading and dividing it but the squared distance, this is
done because lights that are far away from the hitted point have less chances to get
actually hitted during montecarlo integration.
Graphically:
LIGHT
|
CAMERA |
\ | /
first\ | / next bounce
bounce \| /
----SUFACE-----
NOTE: 1 - the visibility test is the same done in the first coursework
2 - In order to not count the light intensities twice we add the emission
of the surface we hit only in the first bounce.
*/
if (i == 0)
{
result += throughput * getEmission(hitInfo.material, hitInfo.position);
}
for (int j = 0; j < 2; j++)
{
vec3 emitterPosition = getEmitterPosition(hitInfo.position , scene.spheres[j], PATH_SAMPLE_DIMENSION_MULTIPLIER + 2* j);
float light2point_distance = distance(emitterPosition, hitInfo.position);
Ray lightRay;
lightRay.origin = hitInfo.position;
vec3 lightDirection = emitterPosition - hitInfo.position ;
lightRay.direction = normalize(lightDirection);
HitInfo shadow = intersectScene(scene, lightRay, 0.001, light2point_distance-0.0001);
float visibility = shadow.hit ? 0.0 : 1.0;
result += throughput *visibility* getGeometricTerm(hitInfo.material, hitInfo.normal,vec3(0.0) , lightRay.direction) * getReflectance(hitInfo.material,hitInfo.normal,incomingRay.direction,lightRay.direction) * getEmission(scene.spheres[j].material, emitterPosition) /pow(light2point_distance, 2.0);
}
#else
// This might need to change with NEE
result += throughput * getEmission(hitInfo.material, hitInfo.normal);
#endif
Ray outgoingRay;
#ifdef SOLUTION_BOUNCE
outgoingRay.direction = randomDirection(PATH_SAMPLE_DIMENSION_MULTIPLIER + 2 * i);
outgoingRay.origin = hitInfo.position;
#endif
#ifdef SOLUTION_THROUGHPUT
/*
Following the rendering equation the "getGeometricTerm" and "getReflectance" are multiplied together to compute
the final result
*/
throughput *= (getGeometricTerm(hitInfo.material, hitInfo.normal ,incomingRay.direction, outgoingRay.direction)*getReflectance(hitInfo.material, hitInfo.normal ,incomingRay.direction, outgoingRay.direction));
#else
// Placeholder throughput computation
throughput *= 0.1;
#endif
// With importance sampling, this value woudl change
float probability = 1.0;
throughput /= probability;
#ifdef SOLUTION_BOUNCE
// Put some handling of the next and the current ray here
incomingRay = outgoingRay;
#endif
}
return result;
}
uniform ivec2 resolution;
Ray getFragCoordRay(const vec2 fragCoord) {
float sensorDistance = 1.0;
vec3 origin = vec3(0, 0, sensorDistance);
vec2 sensorMin = vec2(-1, -0.5);
vec2 sensorMax = vec2(1, 0.5);
vec2 pixelSize = (sensorMax - sensorMin) / vec2(resolution);
vec3 direction = normalize(vec3(sensorMin + pixelSize * fragCoord, -sensorDistance));
float apertureSize = 0.0;
float focalPlane = 100.0;
vec3 sensorPosition = origin + focalPlane * direction;
origin.xy += apertureSize * (sample2(LENS_SAMPLE_DIMENSION) - vec2(0.5));
direction = normalize(sensorPosition - origin);
return Ray(origin, direction);
}
vec3 colorForFragment(const Scene scene, const vec2 fragCoord) {
initRandomSequence();
#ifdef SOLUTION_AA
// Put your anti-aliasing code here
/*
why do we want anti-aliasing ? is because we always shoot our rays at the center of each
pixel leaving a sort of gap between them. So with antialiasing we are trying to fill in
this gap randomly super-sampling our pixel.
Suppose x is the center of the pixel (we were always shooting our rays centered in x) using antialiasing
we shoot our rays centered in the dots. The perceived result is a slightly blurried output.
______
|. . .|
| . x |
|__._._|
How do we implement anti-aliasing ? at each fragmentCoordinate we add a random shift!
But careful !! The sample method return a positive random number between 0 and 1 AHA!
so we need to shif it so that the random sampling will reach all the corners of the pixel and also
because the resulting image will be shifted by half a pixel otherwise!
*/
vec2 sampleCoord ;
sampleCoord.x = fragCoord.x + (sample(ANTI_ALIAS_SAMPLE_DIMENSION)-0.5);
sampleCoord.y = fragCoord.y + (sample(ANTI_ALIAS_SAMPLE_DIMENSION + 1)-0.5);
return samplePath(scene, getFragCoordRay(sampleCoord));
#else
// No anti-aliasing
vec2 sampleCoord = fragCoord;
return samplePath(scene, getFragCoordRay(sampleCoord));
#endif
}
void loadScene1(inout Scene scene) {
scene.spheres[0].position = vec3( 7, -2, -12);
scene.spheres[0].radius = 2.0;
#ifdef SOLUTION_LIGHT
// Set the value of the missing property
scene.spheres[0].material.lightIntensity = 20.0 * vec3( 0.9, 0.5, 0.3);
#endif
scene.spheres[0].material.diffuse = vec3(0.0);
scene.spheres[0].material.specular = vec3(0.0);
scene.spheres[0].material.glossiness = 10.0;
scene.spheres[1].position = vec3(-8, 4, -13);
scene.spheres[1].radius = 1.0;
#ifdef SOLUTION_LIGHT
// Set the value of the missing property
scene.spheres[1].material.lightIntensity = 20.0 * vec3( 0.3, 0.9, 0.8);
#endif
scene.spheres[1].material.diffuse = vec3(0.0);
scene.spheres[1].material.specular = vec3(0.0);
scene.spheres[1].material.glossiness = 10.0;
scene.spheres[2].position = vec3(-2, -2, -12);
scene.spheres[2].radius = 3.0;
#ifdef SOLUTION_LIGHT
// Set the value of the missing property
scene.spheres[2].material.lightIntensity = vec3(0.0);
#endif
scene.spheres[2].material.diffuse = vec3(0.2, 0.5, 0.8);
scene.spheres[2].material.specular = vec3(0.8);
scene.spheres[2].material.glossiness = 40.0;
scene.spheres[3].position = vec3(3, -3.5, -14);
scene.spheres[3].radius = 1.0;
#ifdef SOLUTION_LIGHT
// Set the value of the missing property
scene.spheres[3].material.lightIntensity = vec3(0.0);
#endif
scene.spheres[3].material.diffuse = vec3(0.9, 0.8, 0.8);
scene.spheres[3].material.specular = vec3(1.0);
scene.spheres[3].material.glossiness = 10.0;
scene.planes[0].normal = vec3(0, 1, 0);
scene.planes[0].d = 4.5;
#ifdef SOLUTION_LIGHT
// Set the value of the missing property
scene.planes[0].material.lightIntensity = vec3(0.0);
#endif
scene.planes[0].material.diffuse = vec3(0.8);
scene.planes[0].material.specular = vec3(0);
scene.planes[0].material.glossiness = 50.0;
scene.planes[1].normal = vec3(0, 0, 1);
scene.planes[1].d = 18.5;
#ifdef SOLUTION_LIGHT
// Set the value of the missing property
scene.planes[1].material.lightIntensity = vec3(0.0);
#endif
scene.planes[1].material.diffuse = vec3(0.9, 0.6, 0.3);
scene.planes[1].material.specular = vec3(0.02);
scene.planes[1].material.glossiness = 3000.0;
scene.planes[2].normal = vec3(1, 0,0);
scene.planes[2].d = 10.0;
#ifdef SOLUTION_LIGHT
// Set the value of the missing property
scene.planes[2].material.lightIntensity = vec3(0.0);
#endif
scene.planes[2].material.diffuse = vec3(0.2);
scene.planes[2].material.specular = vec3(0.1);
scene.planes[2].material.glossiness = 100.0;
scene.planes[3].normal = vec3(-1, 0,0);
scene.planes[3].d = 10.0;
#ifdef SOLUTION_LIGHT
// Set the value of the missing property
scene.planes[3].material.lightIntensity = vec3(0.0);
#endif
scene.planes[3].material.diffuse = vec3(0.2);
scene.planes[3].material.specular = vec3(0.1);
scene.planes[3].material.glossiness = 100.0;
}
void main() {
// Setup scene
Scene scene;
loadScene1(scene);
// compute color for fragment
gl_FragColor.rgb = colorForFragment(scene, gl_FragCoord.xy);
gl_FragColor.a = 1.0;
}
`,
description: ``,
wrapFunctionStart: ``,
wrapFunctionEnd: ``
});
UI.tabs.push(
{
visible: true,
type: `x-shader/x-fragment`,
title: `Tonemapping`,
id: `CopyFS`,
initialValue: `precision highp float;
uniform sampler2D radianceTexture;
uniform int sampleCount;
uniform ivec2 resolution;
vec3 tonemap(vec3 color, float maxLuminance, float gamma) {
float luminance = length(color);
//float scale = luminance / maxLuminance;
float scale = luminance / (maxLuminance * luminance + 0.0000001);
return max(vec3(0.0), pow(scale * color, vec3(1.0 / gamma)));
}
void main(void) {
vec3 texel = texture2D(radianceTexture, gl_FragCoord.xy / vec2(resolution)).rgb;
vec3 radiance = texel / float(sampleCount);
gl_FragColor.rgb = tonemap(radiance, 1.0, 1.6);
gl_FragColor.a = 1.0;
}
`,
description: ``,
wrapFunctionStart: ``,
wrapFunctionEnd: ``
});
UI.tabs.push(
{
visible: false,
type: `x-shader/x-vertex`,
title: ``,
id: `VS`,
initialValue: `
attribute vec3 position;
void main(void) {
gl_Position = vec4(position, 1.0);
}
`,
description: ``,
wrapFunctionStart: ``,
wrapFunctionEnd: ``
});
return UI;
}//!setup
function getShader(gl, id) {
gl.getExtension('OES_texture_float');
//alert(gl.getSupportedExtensions());
var shaderScript = document.getElementById(id);
if (!shaderScript) {
return null;
}
var str = "";
var k = shaderScript.firstChild;
while (k) {
if (k.nodeType == 3) {
str += k.textContent;
}
k = k.nextSibling;
}
var shader;
if (shaderScript.type == "x-shader/x-fragment") {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (shaderScript.type == "x-shader/x-vertex") {
shader = gl.createShader(gl.VERTEX_SHADER);
} else {
return null;
}
console.log(str);
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
function RaytracingDemo() {
}
function initShaders() {
traceProgram = gl.createProgram();
gl.attachShader(traceProgram, getShader(gl, "VS"));
gl.attachShader(traceProgram, getShader(gl, "TraceFS"));
gl.linkProgram(traceProgram);
gl.useProgram(traceProgram);
traceProgram.vertexPositionAttribute = gl.getAttribLocation(traceProgram, "position");
gl.enableVertexAttribArray(traceProgram.vertexPositionAttribute);
copyProgram = gl.createProgram();
gl.attachShader(copyProgram, getShader(gl, "VS"));
gl.attachShader(copyProgram, getShader(gl, "CopyFS"));
gl.linkProgram(copyProgram);
gl.useProgram(copyProgram);
traceProgram.vertexPositionAttribute = gl.getAttribLocation(copyProgram, "position");
gl.enableVertexAttribArray(copyProgram.vertexPositionAttribute);
}
function initBuffers() {
triangleVertexPositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
var vertices = [
-1, -1, 0,
-1, 1, 0,
1, 1, 0,
-1, -1, 0,
1, -1, 0,
1, 1, 0,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
triangleVertexPositionBuffer.itemSize = 3;
triangleVertexPositionBuffer.numItems = 3 * 2;
}
function tick() {
// 1st pass: Trace
gl.bindFramebuffer(gl.FRAMEBUFFER, rttFramebuffer);
gl.useProgram(traceProgram);
gl.uniform1i(gl.getUniformLocation(traceProgram, "globalSeed"), Math.random() * 32768.0);
gl.uniform1i(gl.getUniformLocation(traceProgram, "baseSampleIndex"), getCurrentFrame());
gl.uniform2i(
gl.getUniformLocation(traceProgram, "resolution"),
getRenderTargetWidth(),
getRenderTargetHeight());
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
gl.vertexAttribPointer(
traceProgram.vertexPositionAttribute,
triangleVertexPositionBuffer.itemSize,
gl.FLOAT,
false,
0,
0);
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.disable(gl.DEPTH_TEST);
gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, gl.ONE);
gl.drawArrays(gl.TRIANGLES, 0, triangleVertexPositionBuffer.numItems);
// 2nd pass: Average
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.useProgram(copyProgram);
gl.uniform1i(gl.getUniformLocation(copyProgram, "sampleCount"), getCurrentFrame() + 1);
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
gl.vertexAttribPointer(
copyProgram.vertexPositionAttribute,
triangleVertexPositionBuffer.itemSize,
gl.FLOAT,
false,
0,
0);
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.disable(gl.DEPTH_TEST);
gl.disable(gl.BLEND);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, rttTexture);
gl.uniform1i(gl.getUniformLocation(copyProgram, "radianceTexture"), 0);
gl.uniform2i(
gl.getUniformLocation(copyProgram, "resolution"),
getRenderTargetWidth(),
getRenderTargetHeight());
gl.drawArrays(gl.TRIANGLES, 0, triangleVertexPositionBuffer.numItems);
gl.bindTexture(gl.TEXTURE_2D, null);
}
function init() {
initShaders();
initBuffers();
gl.clear(gl.COLOR_BUFFER_BIT);
rttFramebuffer = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, rttFramebuffer);
rttTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, rttTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, getRenderTargetWidth(), getRenderTargetHeight(), 0, gl.RGBA, gl.FLOAT, null);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, rttTexture, 0);
}
var oldWidth = 0;
var oldTraceProgram;
var oldCopyProgram;
function compute(canvas) {
if( getRenderTargetWidth() != oldWidth ||
oldTraceProgram != document.getElementById("TraceFS") ||
oldCopyProgram != document.getElementById("CopyFS"))
{
init();
oldWidth = getRenderTargetWidth();
oldTraceProgram = document.getElementById("TraceFS");
oldCopyProgram = document.getElementById("CopyFS");