-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.js
More file actions
491 lines (406 loc) · 13.2 KB
/
renderer.js
File metadata and controls
491 lines (406 loc) · 13.2 KB
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
import * as maths from "./maths.js";
import * as shapes from "./shapes.js";
import { DirectionalLight } from "./lights.js";
// Classes
/**
* Class that holds additional settings for the render
* and ray color functions
*/
export class SceneSettings{
/**
* Global settings fot the scene.
*
* @param {Number} ambientFactor Factor for the base ambient
* @param {Number} specularPower Intensity of the specular.
* (Lower = More Specular).
*
* @param {Number} shadowIntensity Intensity of apllied shadows.
* (Higher = Deeper Shadows).
*
* @param {boolean} doGammaCorrection Should gamma correction be apllied.
* @param {Number} msaaSampleCount Number of random samples to use for
* the multi sample anti aliasing (MSAA)
*
* @param {Number} maxReflectionBounces Max number of bounces the
* recursive reflection can use, for a continous sphere
* @param {Number} fresnelPower Power of the fresnel effect around the
* edge of the sphere.
*/
constructor(
ambientFactor,
specularPower,
shadowIntensity,
doGammaCorrection,
msaaSampleCount,
maxReflectionBounces,
fresnelPower
){
this.ambientFactor = ambientFactor;
this.specularPower = specularPower;
this.shadowIntensity = shadowIntensity;
this.doGammaCorrection = doGammaCorrection;
this.msaaSampleCount = msaaSampleCount;
this.maxReflectionBounces = maxReflectionBounces;
this.fresnelPower = fresnelPower;
}
}
// Drawing
/**
* Draw a single pixel on the canvas.
*
* @param {CanvasRenderingContext2D} canvasCtx Canvas' CTX variable
* @param {Number} x X position,
* @param {Number} y Y position,
* @param {maths.Vector3} pixelColour Pixel's colour to be placed
*/
export function drawPixel( canvasCtx, x, y, pixelColour ){
canvasCtx.fillStyle =
`rgb(${pixelColour.x}, ${pixelColour.y}, ${pixelColour.z})`;
canvasCtx.fillRect(x, y, 1, 1);
}
// Ray Calls
/**
* Traces the inputted ray, to test for intersections.
*
* @param {maths.Ray3} ray Ray fired from the cam to the screen.
* @param {Array<shapes.Sphere>} sphereList List of spheres.
*
* @returns {maths.RayResult3} Result of the traced ray.
*/
export function traceRay(ray, sphereList){
let t = 1000000000000000;
let closestIndex = -1;
// Gets the closest sphere
for ( let s = 0; s < sphereList.length; s++ ){
let currentT = sphereList[s].rayIntersect(ray);
if ( currentT > 0 && currentT < t ){
t = currentT;
closestIndex = s;
}
}
// Missed all the spheres
if (closestIndex < 0){
return rayMiss();
}
return rayHit(ray, t, sphereList[closestIndex] );
}
/**
* Return the colour for a point on the screen, and uses applies lighting
* model of:
*
* * Variable Lighting Colour
* * Phong - Ambient
* * Phong - Diffuse Lighting
* * Phong - Specular Lighting
* * Reflections
* * Fresnel Halo/Illumination
* * Shadow Casting
*
* @param {maths.Ray3} ray Ray fires from the camera to the screen.
* @param {Number} imageWidth Width of the canvas.
* @param {Number} imageHeight Height of the canvas.
* @param {maths.Vector3} camPos Position of the main camera in the scene.
* @param {Array<shapes.Sphere>} sphereList List of spheres.
* @param {DirectionalLight} globalLight The global directional light.
* @param {SceneSettings} sceneSettings Additional settings for the scene.
* @param {boolean} isPrimaryRay If the ray is the first to be fired.
*
* @returns {maths.Vector3} Pixel Colour, clamped from [0 min -> 1 max].
*/
export function rayColour(
ray,
camPos,
imageWidth,
imageHeight,
sphereList,
globalLight,
sceneSettings,
isPrimaryRay = true
){
// Object intersection tests
let rayResult = traceRay(ray, sphereList);
// Ray misses object
if (rayResult.t < 0 ){
return backgroundColour(ray);
}
const sphere = sphereList[ rayResult.sphereIndex ];
// Phong Albedo (Base Colour)
const albedo = sphere.colour;
// Phong Diffuse
const diffuseStrength = Math.max(
rayResult.normal.dot( globalLight.antiLightDirection ),
0
);
let diffuse = globalLight.lightColour.scaled( diffuseStrength )
// Fresnel lighting
let fresnelStrength = (1 -
Math.max(
0,
Math.min(
1,
rayResult.normal.normalised()
.dot( ray.direction.normalised()
.scaled( -1 )
)
)
)
) ** sceneSettings.fresnelPower
// Phong Specular
const reflectedLight = globalLight.lightDirection
.subbed( rayResult.normal
.scaled( 2 * rayResult.normal
.dot(globalLight.lightDirection)
)
);
const viewDirection = camPos.subbed(rayResult.pos );
const specularStrength = Math.max(
viewDirection.dot(reflectedLight),
0.0
) ** sceneSettings.specularPower;
const specular = globalLight.lightColour.scaled( specularStrength );
// Reflections
let reflective = new maths.Vector3(0, 0, 0);
// Starts a recursive tracer
if ( sphere.reflectivity > 0 ){
reflective = reflectiveColour(
ray,
rayResult,
camPos,
imageWidth,
imageHeight,
sphereList,
globalLight,
sceneSettings,
1
);
}
// Makes the colours
// Creates base colour
const diffuseColour = albedo
.scaled(1 - sphere.reflectivity)
.multiplied(diffuse)
const reflectionColour = reflective.scaled(sphere.reflectivity);
const fresnelColour = new maths.Vector3(
fresnelStrength,
fresnelStrength,
fresnelStrength
);
// Combines: phong ambient & phong diffuse & reflective
let colour = diffuseColour
.added( reflectionColour )
.added( fresnelColour )
.scaled( sceneSettings.ambientFactor );
// Shadow Casting
let shadowRay = new maths.Ray3(
rayResult.pos
.added( rayResult.normal
.scaled(0.05)),
globalLight.antiLightDirection );
let shadowRayResult = traceRay( shadowRay, sphereList )
// Priorities shadow > specular, so both arent incorrectly applied
if (shadowRayResult.t > 0){
// console.log(shadowColour)
colour.scale( 1 - sceneSettings.shadowIntensity )
}
// Only adds specular on the primary / first ray in a recursive chain,
// otherwise reflections are noticabley brighter than thier surrounding
else if (isPrimaryRay){
colour.add(specular);
}
// console.log("ambient", sceneSettings.ambientFactor, "albedo", albedo, "Diffuse", diffuse, "Specular", specular)
return colour
}
/**
* Calculates the colour of a simulated mirror ( or perfectly reflective )
* and returns its colour.
*
* * Colour = Mirror * ( reflectivity ) + albedo * ( 1 - reflectivity ).
*
* The function is recursively called when a reflective ray, hits another
* reflective surface, upto a max bounces limit set by:
* sceneSettings.maxReflectionBounces; where any more bounces return as a
* black colour.
*
* * Reflection ray hits nothing -> Background Colour Returned
*
* * Reflection ray hits non-reflective -> RayColour() on intersection
* sphere
*
* * Reflection ray hits reflective -> ReflectiveColour() on
* intersection sphere
*
* * Max bounces reached -> Returns Black Colour
*
* @param {maths.Ray3} ray Previous ray fired into a reflective.
* @param {maths.RayResult3} rayResult Result of the previous ray intersect.
*
* @param {maths.RayResult3} camPos Position of the main camera in the scene.
* @param {Number} imageWidth Width of the canvas.
* @param {Number} imageHeight Height of the canvas.
* @param {Array<shapes.Sphere>} sphereList List of scene spheres.
* @param {DirectionalLight} globalLight The global directional light.
*
* @param {SceneSettings} sceneSettings Additional settings for the scene.
* @param {Number} bounces Number of bounces the ray has taken.
*
* @returns {maths.Vector3} Pixel Colour, clamped from [0 min -> 1 max].
*/
export function reflectiveColour(
ray,
rayResult,
camPos,
imageWidth,
imageHeight,
sphereList,
globalLight,
sceneSettings,
bounces
){
/*
Failsafe, incase the rucursive goes on too long, and eats all the ram,
but more importantly causes a infinite loop where the reflections may,
never end as they are constanly bouncing between each other
*/
if (sceneSettings.maxReflectionBounces <= bounces){
//console.log(`Too many bounces aborting with black colour`)
return new maths.Vector3(0, 0, 0)
}
// Calculates reflection ray
const reflectedRay = new maths.Ray3(
// Scaled by small value to avoid self-sphere intersections,
// where the ray intersecs with the same sphere it has been,
// projected from. Causing black points on the sphere.
rayResult.pos
.added( rayResult.normal
.scaled(0.05)
),
ray.direction
.subbed( rayResult.normal
.scaled( 2 * rayResult.normal
.dot( ray.direction)
)
)
)
const reflectedRayResult = traceRay(
reflectedRay,
sphereList
);
// First recursion break
// Ray misses object
if ( reflectedRayResult.t < 0 ){
//console.log(`Missed`)
return backgroundColour( reflectedRay );
}
const sphere = sphereList[ reflectedRayResult.sphereIndex ];
// Recursively calls function (if material is reflective) to return,
// it's colour down the stack frame / recursive loop.
if (sphere.reflectivity > 0){
//console.log(`Bouncing`)
bounces += 1;
const reflectedColour = reflectiveColour(
reflectedRay,
reflectedRayResult,
camPos,
imageWidth,
imageHeight,
sphereList,
globalLight,
sceneSettings,
bounces
);
// Calculates the reflections' rayColor otherwise only the sphere's,
// reflective colour will be shown in the reflection and not the,
// entire lighting model, when reflectivity != 0
const baseColour = rayColour(
reflectedRay,
camPos,
imageWidth,
imageHeight,
sphereList,
globalLight,
sceneSettings,
false // Not a primary ray, dont iclude specular
)
// Applies reflectivity to the base colour, if the material is
// partially reflective, ( reflectivity != 1.00 )
return baseColour
.scaled( 1 - sphere.reflectivity )
.added( reflectedColour
.scaled( sphere.reflectivity) )
}
/*
Second recursive break
This ***should not*** start another reflective recursion as this,
material isnt reflective. And ***should not*** call reflectiveColour()
inside rayColour()
However when reflectivity approaches zero (but isnt at zero) the material,
is considered reflecive thus the max bounce was implemented to stop,
many bounces that wont noticabally change the look of the sphere
*/
//console.log(`Unreflective`)
return rayColour(
reflectedRay,
camPos,
imageWidth,
imageHeight,
sphereList,
globalLight,
sceneSettings,
false // Not a primary ray, so dont add the specular
);
}
/**
* Creates the background gradient by interpolating between blue and
* white colours.
*
* @param {maths.Ray3} ray Incident ray
* @returns {maths.Vector3} Colour for the background
*/
export function backgroundColour(ray){
const white = new maths.Vector3(1, 1, 1);
const blue = new maths.Vector3(0.3, 0.5, 0.9);
const t = 0.5 *( ray.direction.y + 1.0);
const interploatedColour = white.scaled( 1 - t ).added( blue.scaled(t) );
return interploatedColour;
}
/**
* Return a missed ray hit, with default miss variables.
*
* @returns {maths.RayResult3} Missed ray result.
*/
export function rayMiss(){
return new maths.RayResult3(
new maths.Vector3(0, 0, 0),
new maths.Vector3(0, 0, 0),
-1,
-1
)
}
/**
* Return a valid ray hit, and finds:
*
* * Hit Point - Vector3
* * Hit Normal - Vector3
*
* Using the inputted:
*
* * Ray - Ray3
* * Scalar value ( T ) - Number
* * Intersection Sphere - Shpere
*
* @param {maths.Ray3} ray Ray fired.
* @param {Number} t Time (or other scalar) value for the ray hit.
* @param {shapes.Sphere} sphere Sphere the ray intersected with.
*
* @returns {rays.RayResult3} Valid ray hit result.
*/
export function rayHit(ray, t, sphere){
let hitPoint = ray.at(t);
let normal = hitPoint.subbed( sphere.centre ).normalised();
return new maths.RayResult3(
hitPoint,
normal,
t,
sphere.index
)
}