Repository navigation
Expand file tree
/
Copy pathchapter-3.html
More file actions
572 lines (501 loc) · 24.1 KB
/
Copy pathchapter-3.html
File metadata and controls
572 lines (501 loc) · 24.1 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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ray Tracing: The Rest of Your Life</title>
<style>
body { background-color: #1a1a1a; color: white; font-family: sans-serif; display: flex; flex-direction: column; align-items: center; margin-top: 1rem; }
canvas { background-color: black; box-shadow: 0 4px 15px rgba(0,0,0,0.8); border-radius: 4px; margin-bottom: 1rem; }
.dashboard { display: flex; gap: 2rem; flex-wrap: wrap; justify-content: center; max-width: 900px; }
.control-panel { background: #2a2a2a; padding: 1.5rem; border-radius: 8px; display: flex; flex-direction: column; gap: 1rem; flex: 1; min-width: 250px; }
.panel-title { font-weight: bold; margin-bottom: 0.5rem; color: #4CAF50; border-bottom: 1px solid #444; padding-bottom: 0.5rem; text-align: center; }
.control-group { display: flex; justify-content: space-between; align-items: center; font-size: 0.9em; }
input[type="range"] { cursor: pointer; width: 120px; }
input[type="color"], input[type="checkbox"] { cursor: pointer; height: 25px; border: none; border-radius: 4px; background: none; }
#status { font-family: monospace; color: #ffeb3b; font-weight: bold; margin-bottom: 1rem; font-size: 1.1em; }
</style>
</head>
<body>
<h2>Ray Tracing: The Rest of Your Life</h2>
<div id="status">Ready</div>
<canvas id="renderCanvas" width="400" height="400"></canvas>
<div class="dashboard">
<div class="control-panel">
<div class="panel-title">Render Engine</div>
<div class="control-group">
<label>Enable Two-pass simple denoiser:</label>
<input type="checkbox" id="denoiseToggle">
</div>
<div class="control-group">
<label>Samples/Pixel:</label>
<div><span id="samplesVal">50</span> <input type="range" id="samplesSlider" min="1" max="1000" step="1" value="50"></div>
</div>
<div class="control-group">
<label>Max Bounce Depth:</label>
<div><span id="depthVal">15</span> <input type="range" id="depthSlider" min="1" max="50" value="15"></div>
</div>
<div class="control-group">
<label>Light Intensity:</label>
<div><span id="intensityVal">15</span> <input type="range" id="intensitySlider" min="1" max="50" value="15"></div>
</div>
</div>
<div class="control-panel">
<div class="panel-title">Material Properties</div>
<div class="control-group">
<label>Left Metal (Roughness):</label>
<div><span id="roughnessVal">0.05</span> <input type="range" id="roughnessSlider" min="0" max="1" step="0.05" value="0.05"></div>
</div>
<div class="control-group">
<label>Right Glass (IOR):</label>
<div><span id="iorVal">1.50</span> <input type="range" id="iorSlider" min="1.0" max="3.0" step="0.05" value="1.50"></div>
</div>
</div>
</div>
<script>
const workerScript = `
class Vec3 {
constructor(x, y, z) { this.x = x; this.y = y; this.z = z; }
add(v) { return new Vec3(this.x + v.x, this.y + v.y, this.z + v.z); }
sub(v) { return new Vec3(this.x - v.x, this.y - v.y, this.z - v.z); }
mul(t) { return new Vec3(this.x * t, this.y * t, this.z * t); }
mulV(v) { return new Vec3(this.x * v.x, this.y * v.y, this.z * v.z); }
div(t) { return this.mul(1/t); }
lengthSq() { return this.x*this.x + this.y*this.y + this.z*this.z; }
length() { return Math.sqrt(this.lengthSq()); }
normalize() { return this.div(this.length()); }
static dot(u, v) { return u.x*v.x + u.y*v.y + u.z*v.z; }
static cross(u, v) { return new Vec3(u.y*v.z - u.z*v.y, u.z*v.x - u.x*v.z, u.x*v.y - u.y*v.x); }
static random(min=0, max=1) { return new Vec3(min + Math.random()*(max-min), min + Math.random()*(max-min), min + Math.random()*(max-min)); }
static randomInUnitSphere() {
while (true) { let p = Vec3.random(-1, 1); if (p.lengthSq() < 1) return p; }
}
static randomUnitVector() { return Vec3.randomInUnitSphere().normalize(); }
static reflect(v, n) { return v.sub(n.mul(2 * Vec3.dot(v, n))); }
static refract(uv, n, etai_over_etat) {
let cos_theta = Math.min(Vec3.dot(uv.mul(-1), n), 1.0);
let r_out_perp = uv.add(n.mul(cos_theta)).mul(etai_over_etat);
let r_out_parallel = n.mul(-Math.sqrt(Math.abs(1.0 - r_out_perp.lengthSq())));
return r_out_perp.add(r_out_parallel);
}
}
class Ray {
constructor(origin, direction) { this.origin = origin; this.direction = direction; }
at(t) { return this.origin.add(this.direction.mul(t)); }
}
// --- PRE-COMPUTED LUT OPTIMIZATION ---
function computeHaltonLUT(base, size) {
let lut = new Float32Array(size);
for (let k = 0; k < size; k++) {
let result = 0;
let f = 1.0 / base;
let i = k + 1;
while (i > 0) {
result = result + f * (i % base);
i = Math.floor(i / base);
f = f / base;
}
lut[k] = result;
}
return lut;
}
// Pre-compute 1024 values per dimension when the worker starts
const LUT_SIZE = 1024;
const halton2 = computeHaltonLUT(2, LUT_SIZE); // Pixel X anti-aliasing
const halton3 = computeHaltonLUT(3, LUT_SIZE); // Pixel Y anti-aliasing
// --- QUASI-MONTE CARLO (HALTON SEQUENCE) ---
// Instead of computing the Halton value from scratch for each sample,
// we use a pre-computed LUT and apply a Cranley-Patterson rotation to
// ensure good distribution without visible patterns.
function halton(index, base) {
let result = 0;
let f = 1.0 / base;
let i = index;
while (i > 0) {
result = result + f * (i % base);
i = Math.floor(i / base);
f = f / base;
}
return result;
}
class Material {
emitted() { return new Vec3(0, 0, 0); }
scatter(ray, rec) { return null; }
}
class Lambertian extends Material {
constructor(albedo) { super(); this.albedo = albedo; }
scatter(ray, rec) {
let scatter_dir = rec.normal.add(Vec3.randomUnitVector());
if (scatter_dir.lengthSq() < 1e-8) scatter_dir = rec.normal;
return { ray: new Ray(rec.p, scatter_dir), attenuation: this.albedo };
}
}
class Metal extends Material {
constructor(albedo, fuzz) { super(); this.albedo = albedo; this.fuzz = fuzz < 1 ? fuzz : 1; }
scatter(ray, rec) {
let reflected = Vec3.reflect(ray.direction.normalize(), rec.normal);
let scattered = new Ray(rec.p, reflected.add(Vec3.randomInUnitSphere().mul(this.fuzz)));
if (Vec3.dot(scattered.direction, rec.normal) > 0) return { ray: scattered, attenuation: this.albedo };
return null;
}
}
class Dielectric extends Material {
constructor(ir) { super(); this.ir = ir; }
scatter(ray, rec) {
let refraction_ratio = rec.front_face ? (1.0 / this.ir) : this.ir;
let unit_direction = ray.direction.normalize();
let cos_theta = Math.min(Vec3.dot(unit_direction.mul(-1), rec.normal), 1.0);
let sin_theta = Math.sqrt(1.0 - cos_theta*cos_theta);
let cannot_refract = refraction_ratio * sin_theta > 1.0;
let direction;
if (cannot_refract || this.reflectance(cos_theta, refraction_ratio) > Math.random()) {
direction = Vec3.reflect(unit_direction, rec.normal);
} else {
direction = Vec3.refract(unit_direction, rec.normal, refraction_ratio);
}
return { ray: new Ray(rec.p, direction), attenuation: new Vec3(1.0, 1.0, 1.0) };
}
reflectance(cosine, ref_idx) {
let r0 = (1 - ref_idx) / (1 + ref_idx); r0 = r0 * r0;
return r0 + (1 - r0) * Math.pow((1 - cosine), 5);
}
}
class DiffuseLight extends Material {
constructor(color) { super(); this.color = color; }
scatter(ray, rec) { return null; }
emitted() { return this.color; }
}
class Quad {
constructor(Q, u, v, material) {
this.Q = Q; this.u = u; this.v = v; this.material = material;
let n = Vec3.cross(u, v);
this.normal = n.normalize();
this.D = Vec3.dot(this.normal, Q);
this.w = n.div(Vec3.dot(n, n));
}
hit(ray, t_min, t_max) {
let denom = Vec3.dot(this.normal, ray.direction);
if (Math.abs(denom) < 1e-8) return null;
let t = (this.D - Vec3.dot(this.normal, ray.origin)) / denom;
if (t < t_min || t > t_max) return null;
let intersection = ray.at(t);
let planar_hitpt_vector = intersection.sub(this.Q);
let alpha = Vec3.dot(this.w, Vec3.cross(planar_hitpt_vector, this.v));
let beta = Vec3.dot(this.w, Vec3.cross(this.u, planar_hitpt_vector));
if (alpha < 0 || alpha > 1 || beta < 0 || beta > 1) return null;
let front_face = Vec3.dot(ray.direction, this.normal) < 0;
let normal = front_face ? this.normal : this.normal.mul(-1);
return { t: t, p: intersection, normal: normal, front_face: front_face, material: this.material };
}
}
class Sphere {
constructor(center, radius, material) { this.center = center; this.radius = radius; this.material = material; }
hit(ray, t_min, t_max) {
let oc = ray.origin.sub(this.center);
let a = ray.direction.lengthSq();
let half_b = Vec3.dot(oc, ray.direction);
let c = oc.lengthSq() - this.radius * this.radius;
let discriminant = half_b * half_b - a * c;
if (discriminant < 0) return null;
let sqrtd = Math.sqrt(discriminant);
let root = (-half_b - sqrtd) / a;
if (root <= t_min || t_max <= root) {
root = (-half_b + sqrtd) / a;
if (root <= t_min || t_max <= root) return null;
}
let p = ray.at(root);
let outward_normal = p.sub(this.center).div(this.radius);
let front_face = Vec3.dot(ray.direction, outward_normal) < 0;
let normal = front_face ? outward_normal : outward_normal.mul(-1);
return { t: root, p: p, normal: normal, front_face: front_face, material: this.material };
}
}
class HittableList {
constructor() { this.objects = []; }
add(obj) { this.objects.push(obj); }
hit(ray, t_min, t_max) {
let temp_rec = null;
let closest_so_far = t_max;
for (let obj of this.objects) {
let rec = obj.hit(ray, t_min, closest_so_far);
if (rec) { closest_so_far = rec.t; temp_rec = rec; }
}
return temp_rec;
}
}
function rayColor(ray, world, depth) {
if (depth <= 0) return new Vec3(0, 0, 0);
let rec = world.hit(ray, 0.001, Infinity);
if (!rec) return new Vec3(0, 0, 0);
let emitted = rec.material.emitted();
let scatterResult = rec.material.scatter(ray, rec);
if (scatterResult) {
let colorFromBounce = rayColor(scatterResult.ray, world, depth - 1);
return emitted.add(scatterResult.attenuation.mulV(colorFromBounce));
}
return emitted;
}
function buildCornellBox(lightConfig, matConfig) {
let world = new HittableList();
let red = new Lambertian(new Vec3(.65, .05, .05));
let white = new Lambertian(new Vec3(.73, .73, .73));
let green = new Lambertian(new Vec3(.12, .45, .15));
let lightColor = new Vec3(lightConfig.r, lightConfig.g, lightConfig.b);
let lightMat = new DiffuseLight(lightColor.mul(lightConfig.intensity));
world.add(new Quad(new Vec3(555,0,0), new Vec3(0,555,0), new Vec3(0,0,555), green));
world.add(new Quad(new Vec3(0,0,0), new Vec3(0,555,0), new Vec3(0,0,555), red));
world.add(new Quad(new Vec3(0,0,0), new Vec3(555,0,0), new Vec3(0,0,555), white));
world.add(new Quad(new Vec3(0,555,0), new Vec3(555,0,0), new Vec3(0,0,555), white));
world.add(new Quad(new Vec3(0,0,555), new Vec3(555,0,0), new Vec3(0,555,0), white));
world.add(new Quad(new Vec3(213,554,227), new Vec3(130,0,0), new Vec3(0,0,105), lightMat));
let leftMat = new Metal(new Vec3(0.8, 0.8, 0.9), matConfig.roughness);
let rightMat = new Dielectric(matConfig.ior);
world.add(new Sphere(new Vec3(180, 100, 350), 100, leftMat));
world.add(new Sphere(new Vec3(380, 100, 200), 100, rightMat));
return world;
}
self.onmessage = function(e) {
const { startX, startY, tileWidth, tileHeight, imageWidth, imageHeight, samples, maxDepth, camParams, lightConfig, matConfig } = e.data;
const buffer = new Uint8ClampedArray(tileWidth * tileHeight * 4);
const world = buildCornellBox(lightConfig, matConfig);
let theta = camParams.vfov * Math.PI / 180.0;
let h = Math.tan(theta/2);
let viewport_height = 2.0 * h * camParams.focus_dist;
let viewport_width = viewport_height * (imageWidth / imageHeight);
let lookfrom = new Vec3(camParams.lookfrom.x, camParams.lookfrom.y, camParams.lookfrom.z);
let lookat = new Vec3(camParams.lookat.x, camParams.lookat.y, camParams.lookat.z);
let vup = new Vec3(camParams.vup.x, camParams.vup.y, camParams.vup.z);
let w = lookfrom.sub(lookat).normalize();
let u = Vec3.cross(vup, w).normalize();
let v = Vec3.cross(w, u);
let origin = lookfrom;
let horizontal = u.mul(viewport_width);
let vertical = v.mul(viewport_height);
let lower_left_corner = origin.sub(horizontal.div(2)).sub(vertical.div(2)).sub(w.mul(camParams.focus_dist));
let endY = startY + tileHeight;
let endX = startX + tileWidth;
let ptr = 0;
for (let j = endY - 1; j >= startY; --j) {
for (let i = startX; i < endX; ++i) {
// CRANLEY-PATTERSON ROTATION: Give each pixel a unique sub-seed so the Halton
// pattern doesn't create visible structural lines across the screen.
let pixel_hash = (i * 73856093) ^ (j * 19349663);
let rand_offset_x = (pixel_hash & 0xFFFF) / 65535.0;
let rand_offset_y = ((pixel_hash >> 16) & 0xFFFF) / 65535.0;
let pixel_color = new Vec3(0, 0, 0);
for (let s = 0; s < samples; ++s) {
// FAST PRE-COMPUTED LUT LOOKUP
let s_idx = s % LUT_SIZE;
let u_offset = (halton2[s_idx] + rand_offset_x) % 1.0;
let v_offset = (halton3[s_idx] + rand_offset_y) % 1.0;
let s_u = (i + u_offset) / (imageWidth - 1);
let s_v = (j + v_offset) / (imageHeight - 1);
let dir = lower_left_corner.add(horizontal.mul(s_u)).add(vertical.mul(s_v)).sub(origin);
let r = new Ray(origin, dir);
pixel_color = pixel_color.add(rayColor(r, world, maxDepth));
}
let scale = 1.0 / samples;
let c_r = Math.sqrt(pixel_color.x * scale);
let c_g = Math.sqrt(pixel_color.y * scale);
let c_b = Math.sqrt(pixel_color.z * scale);
buffer[ptr++] = 256 * Math.max(0.0, Math.min(0.999, c_r));
buffer[ptr++] = 256 * Math.max(0.0, Math.min(0.999, c_g));
buffer[ptr++] = 256 * Math.max(0.0, Math.min(0.999, c_b));
buffer[ptr++] = 255;
}
}
self.postMessage({ startX, startY, tileWidth, tileHeight, buffer }, [buffer.buffer]);
};
`;
const canvas = document.getElementById('renderCanvas');
const ctx = canvas.getContext('2d');
const statusText = document.getElementById('status');
const blob = new Blob([workerScript], { type: 'application/javascript' });
const workerUrl = URL.createObjectURL(blob);
// DOM Elements
const elements = {
samples: document.getElementById('samplesSlider'),
depth: document.getElementById('depthSlider'),
intensity: document.getElementById('intensitySlider'),
roughness: document.getElementById('roughnessSlider'),
ior: document.getElementById('iorSlider'),
denoise: document.getElementById('denoiseToggle')
};
let workers = [];
let activeWorkers = 0;
let taskQueue = [];
let rawImageData = null;
function applyDenoiser() {
if (!rawImageData) return;
statusText.innerText = "Applying Advanced 2-Pass Denoiser...";
setTimeout(() => {
const width = canvas.width;
const height = canvas.height;
const data = rawImageData.data;
const size = width * height * 4;
// PASS 1: FIREFLY REJECTION
const clampedData = new Uint8ClampedArray(size);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const idx = (y * width + x) * 4;
if (x === 0 || x === width - 1 || y === 0 || y === height - 1) {
clampedData[idx] = data[idx]; clampedData[idx+1] = data[idx+1];
clampedData[idx+2] = data[idx+2]; clampedData[idx+3] = 255; continue;
}
let minR = 255, minG = 255, minB = 255;
let maxR = 0, maxG = 0, maxB = 0;
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) {
if (dx === 0 && dy === 0) continue;
const nIdx = ((y + dy) * width + (x + dx)) * 4;
const r = data[nIdx], g = data[nIdx+1], b = data[nIdx+2];
if (r < minR) minR = r; if (r > maxR) maxR = r;
if (g < minG) minG = g; if (g > maxG) maxG = g;
if (b < minB) minB = b; if (b > maxB) maxB = b;
}
}
clampedData[idx] = Math.max(minR, Math.min(maxR, data[idx]));
clampedData[idx+1] = Math.max(minG, Math.min(maxG, data[idx+1]));
clampedData[idx+2] = Math.max(minB, Math.min(maxB, data[idx+2]));
clampedData[idx+3] = 255;
}
}
// PASS 2: BILATERAL FILTER
const output = new Uint8ClampedArray(size);
const radius = 2;
const sigmaSpatial = 2.0;
const sigmaColor = 0.25 * 255;
const spatialWeights = [];
for (let dy = -radius; dy <= radius; dy++) {
for (let dx = -radius; dx <= radius; dx++) {
spatialWeights.push(Math.exp(-(dx*dx + dy*dy) / (2 * sigmaSpatial * sigmaSpatial)));
}
}
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const idx = (y * width + x) * 4;
const r = clampedData[idx]; const g = clampedData[idx+1]; const b = clampedData[idx+2];
let rSum = 0, gSum = 0, bSum = 0, wSum = 0; let wIdx = 0;
for (let dy = -radius; dy <= radius; dy++) {
const ny = y + dy;
if (ny < 0 || ny >= height) { wIdx += (radius*2+1); continue; }
const rowOffset = ny * width;
for (let dx = -radius; dx <= radius; dx++) {
const nx = x + dx;
if (nx < 0 || nx >= width) { wIdx++; continue; }
const nIdx = (rowOffset + nx) * 4;
const nr = clampedData[nIdx]; const ng = clampedData[nIdx+1]; const nb = clampedData[nIdx+2];
const distColorSq = (r-nr)*(r-nr) + (g-ng)*(g-ng) + (b-nb)*(b-nb);
const colorWeight = Math.exp(-distColorSq / (2 * sigmaColor * sigmaColor));
const weight = spatialWeights[wIdx++] * colorWeight;
rSum += nr * weight; gSum += ng * weight; bSum += nb * weight;
wSum += weight;
}
}
output[idx] = rSum / wSum; output[idx+1] = gSum / wSum;
output[idx+2] = bSum / wSum; output[idx+3] = 255;
}
}
ctx.putImageData(new ImageData(output, width, height), 0, 0);
statusText.innerText = "Render & Denoise Complete";
}, 10);
}
function startRender() {
workers.forEach(w => w.terminate());
workers = [];
activeWorkers = 0;
taskQueue = [];
rawImageData = null;
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
const camParams = {
lookfrom: {x: 278, y: 278, z: -800},
lookat: {x: 278, y: 278, z: 0},
vup: {x: 0, y: 1, z: 0},
vfov: 40,
focus_dist: 10.0,
defocus_angle: 0.0
};
const lightConfig = {
intensity: parseFloat(elements.intensity.value),
r: 1, g: 1, b: 1
};
const matConfig = {
roughness: parseFloat(elements.roughness.value),
ior: parseFloat(elements.ior.value)
};
const samples = parseInt(elements.samples.value);
const maxDepth = parseInt(elements.depth.value);
const width = canvas.width;
const height = canvas.height;
const TILE_SIZE = 64;
for (let y = 0; y < height; y += TILE_SIZE) {
for (let x = 0; x < width; x += TILE_SIZE) {
taskQueue.push({
startX: x,
startY: y,
tileWidth: Math.min(TILE_SIZE, width - x),
tileHeight: Math.min(TILE_SIZE, height - y)
});
}
}
taskQueue.reverse();
const numCores = navigator.hardwareConcurrency || 4;
statusText.innerText = `Ray Tracing Scene... (${numCores} threads)`;
let startTime = performance.now();
function assignNextTask(worker) {
if (taskQueue.length > 0) {
const task = taskQueue.shift();
worker.postMessage({
...task, imageWidth: width, imageHeight: height, samples, maxDepth, camParams, lightConfig, matConfig
});
} else {
worker.terminate();
activeWorkers--;
if (activeWorkers === 0) {
rawImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
if (elements.denoise.checked) applyDenoiser();
else statusText.innerText = `Render Finished in ${((performance.now() - startTime) / 1000).toFixed(2)}s`;
}
}
}
for (let i = 0; i < numCores; i++) {
if (taskQueue.length === 0) break;
const worker = new Worker(workerUrl);
workers.push(worker);
activeWorkers++;
worker.onmessage = (e) => {
const { startX, startY, tileWidth, tileHeight, buffer } = e.data;
const imageData = new ImageData(new Uint8ClampedArray(buffer), tileWidth, tileHeight);
const canvasY = height - startY - tileHeight;
ctx.putImageData(imageData, startX, canvasY);
assignNextTask(worker);
};
assignNextTask(worker);
}
}
Object.keys(elements).forEach(key => {
if (key === 'denoise') {
elements[key].addEventListener('change', (e) => {
if (activeWorkers > 0) return;
if (e.target.checked) applyDenoiser();
else if (rawImageData) {
ctx.putImageData(rawImageData, 0, 0);
statusText.innerText = "Denoiser Disabled (Showing Raw Output)";
}
});
return;
}
elements[key].addEventListener('change', (e) => {
const valSpan = document.getElementById(key + 'Val');
if(valSpan) {
valSpan.innerText = e.target.step && e.target.step.includes('.')
? parseFloat(e.target.value).toFixed(2)
: e.target.value;
}
startRender();
});
});
startRender();
</script>
</body>
</html>