webgl2 1.1.4

WebGL2 shader compiler, emulator, and debugger
Documentation
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
// Environment detection
const isNode = typeof process !== 'undefined' && process.versions && process.versions.node;

// Import fs only in Node
let fs;
async function initFS() {
    if (isNode) {
        const fsModule = await import('fs');
        fs = fsModule.default;
    }
}

// Animation state for browser
const animationState = {
    running: false,
    frameCount: 0,
    lastFpsTime: Date.now(),
    fps: 0,
    fpsElement: null,
    button: null,
    canvas: null,
    ctx: null,
    width: 0,
    height: 0,
    startTime: null
};

// Global rendering context (lazy initialized)
let renderContext = null;

async function initializeRenderContext() {
    if (renderContext) return renderContext;
    
    let loadLocal =
        isNode || (
            typeof location !== 'undefined' &&
            typeof location?.hostname === 'string' &&
            location.hostname.toString() === 'localhost'
        );
    const { webGL2 } = await import(
        loadLocal ? './index.js' :
        'https://esm.run/webgl2'
    );

    const gl = await webGL2();
    gl.verbosity = 0; // Disable debug logs for this demo
    gl.viewport(0, 0, 640, 480);
    
    // Shaders
    const vsSource = `#version 300 es
    layout(location = 0) in vec3 position;
    layout(location = 1) in vec2 uv;
    
    uniform mat4 u_mvp;
    
    out vec2 v_uv;
    
    void main() {
        v_uv = uv;
        gl_Position = u_mvp * vec4(position, 1.0);
    }
    `;
    
    const fsSource = `#version 300 es
    precision highp float;
    uniform texture2D u_texture;
    uniform sampler u_sampler;
    in vec2 v_uv;
    out vec4 fragColor;
    
    void main() {
        fragColor = texture(sampler2D(u_texture, u_sampler), v_uv);
        // fragColor = vec4(v_uv, 0.0, 1.0);
    }
    `;
    
    const vs = gl.createShader(gl.VERTEX_SHADER);
    gl.shaderSource(vs, vsSource);
    gl.compileShader(vs);
    
    const fsShader = gl.createShader(gl.FRAGMENT_SHADER);
    gl.shaderSource(fsShader, fsSource);
    gl.compileShader(fsShader);
    
    const program = gl.createProgram();
    gl.attachShader(program, vs);
    gl.attachShader(program, fsShader);
    gl.linkProgram(program);
    gl.useProgram(program);
    
    // Cube data
    const vertices = new Float32Array([
        // Front face
        -0.5, -0.5,  0.5,  0.0, 0.0,
         0.5, -0.5,  0.5,  1.0, 0.0,
         0.5,  0.5,  0.5,  1.0, 1.0,
        -0.5, -0.5,  0.5,  0.0, 0.0,
         0.5,  0.5,  0.5,  1.0, 1.0,
        -0.5,  0.5,  0.5,  0.0, 1.0,
        
        // Back face
        -0.5, -0.5, -0.5,  0.0, 0.0,
        -0.5,  0.5, -0.5,  0.0, 1.0,
         0.5,  0.5, -0.5,  1.0, 1.0,
        -0.5, -0.5, -0.5,  0.0, 0.0,
         0.5,  0.5, -0.5,  1.0, 1.0,
         0.5, -0.5, -0.5,  1.0, 0.0,
         
        // Top face
        -0.5,  0.5, -0.5,  0.0, 0.0,
        -0.5,  0.5,  0.5,  0.0, 1.0,
         0.5,  0.5,  0.5,  1.0, 1.0,
        -0.5,  0.5, -0.5,  0.0, 0.0,
         0.5,  0.5,  0.5,  1.0, 1.0,
         0.5,  0.5, -0.5,  1.0, 0.0,
         
        // Bottom face
        -0.5, -0.5, -0.5,  0.0, 0.0,
         0.5, -0.5, -0.5,  1.0, 0.0,
         0.5, -0.5,  0.5,  1.0, 1.0,
        -0.5, -0.5, -0.5,  0.0, 0.0,
         0.5, -0.5,  0.5,  1.0, 1.0,
        -0.5, -0.5,  0.5,  0.0, 1.0,
        
        // Right face
         0.5, -0.5, -0.5,  0.0, 0.0,
         0.5,  0.5, -0.5,  0.0, 1.0,
         0.5,  0.5,  0.5,  1.0, 1.0,
         0.5, -0.5, -0.5,  0.0, 0.0,
         0.5,  0.5,  0.5,  1.0, 1.0,
         0.5, -0.5,  0.5,  1.0, 0.0,
         
        // Left face
        -0.5, -0.5, -0.5,  0.0, 0.0,
        -0.5, -0.5,  0.5,  1.0, 0.0,
        -0.5,  0.5,  0.5,  1.0, 1.0,
        -0.5, -0.5, -0.5,  0.0, 0.0,
        -0.5,  0.5,  0.5,  1.0, 1.0,
        -0.5,  0.5, -0.5,  0.0, 1.0,
    ]);
    
    const buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
    
    gl.enableVertexAttribArray(0);
    gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 20, 0);
    gl.enableVertexAttribArray(1);
    gl.vertexAttribPointer(1, 2, gl.FLOAT, false, 20, 12);
    
    // Texture
    const tex = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, tex);
    const texData = new Uint8Array(16 * 16 * 4);
    for (let y = 0; y < 16; y++) {
        for (let x = 0; x < 16; x++) {
            const idx = (y * 16 + x) * 4;
            const isCheck = ((x >> 2) ^ (y >> 2)) & 1;
            if (isCheck) {
                texData[idx] = 255; texData[idx+1] = 215; texData[idx+2] = 0; texData[idx+3] = 255; // Gold
            } else {
                texData[idx] = 100; texData[idx+1] = 149; texData[idx+2] = 237; texData[idx+3] = 255; // CornflowerBlue
            }
        }
    }
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, texData);
    
    const uTextureLoc = gl.getUniformLocation(program, "u_texture");
    gl.uniform1i(uTextureLoc, 0);
    const uSamplerLoc = gl.getUniformLocation(program, "u_sampler");
    gl.uniform1i(uSamplerLoc, 0);
    
    // Matrix math functions
    function perspective(fovy, aspect, near, far) {
        const f = 1.0 / Math.tan(fovy / 2);
        const nf = 1 / (near - far);
        return [
            f / aspect, 0, 0, 0,
            0, f, 0, 0,
            0, 0, (far + near) * nf, -1,
            0, 0, (2 * far * near) * nf, 0
        ];
    }
    
    function multiply(a, b) {
        const out = new Float32Array(16);
        for (let col = 0; col < 4; col++) {
            for (let row = 0; row < 4; row++) {
                let sum = 0;
                for (let k = 0; k < 4; k++) {
                    sum += a[k * 4 + row] * b[col * 4 + k];
                }
                out[col * 4 + row] = sum;
            }
        }
        return out;
    }
    
    function rotateY(m, angle) {
        const c = Math.cos(angle);
        const s = Math.sin(angle);
        const r = [
            c, 0, -s, 0,
            0, 1, 0, 0,
            s, 0, c, 0,
            0, 0, 0, 1
        ];
        return multiply(m, r);
    }

    function rotateX(m, angle) {
        const c = Math.cos(angle);
        const s = Math.sin(angle);
        const r = [
            1, 0, 0, 0,
            0, c, s, 0,
            0, -s, c, 0,
            0, 0, 0, 1
        ];
        return multiply(m, r);
    }
    
    function translate(m, x, y, z) {
        const t = [
            1, 0, 0, 0,
            0, 1, 0, 0,
            0, 0, 1, 0,
            x, y, z, 1
        ];
        return multiply(m, t);
    }
    
    // Calculate initial MVP matrix
    let mvp = perspective(Math.PI / 4, 640 / 480, 0.1, 100.0);
    mvp = translate(mvp, 0, 0, -3);
    mvp = rotateX(mvp, 0.5);
    mvp = rotateY(mvp, 0.8);
    
    const mvpLoc = gl.getUniformLocation(program, "u_mvp");
    
    renderContext = {
        gl,
        program,
        mvpLoc,
        mvp: new Float32Array(mvp),
        // Store functions and base values for dynamic rotation
        perspective,
        translate,
        rotateX,
        rotateY,
        multiply
    };
    
    return renderContext;
}

async function renderCube(elapsedTime = 0) {
    const ctx = await initializeRenderContext();
    const { gl, program, mvpLoc, perspective, translate, rotateX, rotateY, multiply } = ctx;
    
    // Calculate rotation angle: 1 full rotation (2π) in 5 seconds
    const rotationAngle = (elapsedTime / 5000) * Math.PI * 2;
    
    // Recalculate MVP with time-based rotation
    let mvp = perspective(Math.PI / 4, 640 / 480, 0.1, 100.0);
    mvp = translate(mvp, 0, 0, -3);
    mvp = rotateX(mvp, 0.5);
    mvp = rotateY(mvp, 0.8 + rotationAngle);
    
    // Set MVP matrix
    gl.uniformMatrix4fv(mvpLoc, false, mvp);
    console.log("MVP Matrix:", mvp);
    
    // Render
    gl.clearColor(0.0, 0.0, 0.0, 0.0);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLES, 0, 36);
    
    // Read pixels
    const pixels = new Uint8Array(640 * 480 * 4);
    gl.readPixels(0, 0, 640, 480, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
    
    return { pixels, width: 640, height: 480 };
}

// Matrix from PNG rendering functions
function savePNG(width, height, pixels, filename) {
    // PNG Signature
    const signature = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);

    function createChunk(type, data) {
        const len = Buffer.alloc(4);
        len.writeUInt32BE(data.length, 0);
        const typeBuf = Buffer.from(type);
        const crc = Buffer.alloc(4);
        crc.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0);
        return Buffer.concat([len, typeBuf, data, crc]);
    }

    // IHDR
    const ihdrData = Buffer.alloc(13);
    ihdrData.writeUInt32BE(width, 0);
    ihdrData.writeUInt32BE(height, 4);
    ihdrData[8] = 8; // bit depth
    ihdrData[9] = 6; // color type (RGBA)
    ihdrData[10] = 0; // compression
    ihdrData[11] = 0; // filter
    ihdrData[12] = 0; // interlace
    const ihdr = createChunk('IHDR', ihdrData);

    // IDAT (ZLIB uncompressed)
    // Each scanline starts with a filter byte (0)
    const scanlineSize = width * 4 + 1;
    const uncompressedData = Buffer.alloc(height * scanlineSize);
    for (let y = 0; y < height; y++) {
        const srcY = height - 1 - y; // Flip Y for PNG (gl.readPixels is bottom-up)
        uncompressedData[y * scanlineSize] = 0; // Filter None
        pixels.copy(uncompressedData, y * scanlineSize + 1, srcY * width * 4, (srcY + 1) * width * 4);
    }

    // ZLIB wrap
    const zlibHeader = Buffer.from([0x78, 0x01]);
    const blocks = [];
    for (let i = 0; i < uncompressedData.length; i += 65535) {
        const remaining = uncompressedData.length - i;
        const blockSize = Math.min(remaining, 65535);
        const isLast = remaining <= 65535;
        const blockHeader = Buffer.alloc(5);
        blockHeader[0] = isLast ? 1 : 0;
        blockHeader.writeUInt16LE(blockSize, 1);
        blockHeader.writeUInt16LE(~blockSize & 0xFFFF, 3);
        blocks.push(blockHeader);
        blocks.push(uncompressedData.slice(i, i + blockSize));
    }
    const adler = Buffer.alloc(4);
    adler.writeUInt32BE(adler32(uncompressedData), 0);
    const idatData = Buffer.concat([zlibHeader, ...blocks, adler]);
    const idat = createChunk('IDAT', idatData);

    // IEND
    const iend = createChunk('IEND', Buffer.alloc(0));

    fs.writeFileSync(filename, Buffer.concat([signature, ihdr, idat, iend]));
}

// CRC32 implementation
const crcTable = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
    let c = i;
    for (let j = 0; j < 8; j++) {
        c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
    }
    crcTable[i] = c;
}

function crc32(buf) {
    let crc = 0xFFFFFFFF;
    for (let i = 0; i < buf.length; i++) {
        crc = crcTable[(crc ^ buf[i]) & 0xFF] ^ (crc >>> 8);
    }
    return (crc ^ 0xFFFFFFFF) >>> 0;
}

function adler32(buf) {
    let s1 = 1, s2 = 0;
    for (let i = 0; i < buf.length; i++) {
        s1 = (s1 + buf[i]) % 65521;
        s2 = (s2 + s1) % 65521;
    }
    return ((s2 << 16) | s1) >>> 0;
}

// Main entry point
async function displayFrame(pixels, width, height) {
    if (!animationState.ctx) return;
    
    const imageData = animationState.ctx.createImageData(width, height);
    
    // Flip Y axis: gl.readPixels is bottom-up, canvas is top-down
    const flipped = new Uint8ClampedArray(pixels.length);
    for (let y = 0; y < height; y++) {
        const srcY = height - 1 - y;
        const srcOffset = srcY * width * 4;
        const dstOffset = y * width * 4;
        flipped.set(pixels.subarray(srcOffset, srcOffset + width * 4), dstOffset);
    }
    
    imageData.data.set(flipped);
    animationState.ctx.putImageData(imageData, 0, 0);
}

function updateFpsCounter() {
    const now = Date.now();
    const deltaTime = now - animationState.lastFpsTime;
    
    if (deltaTime >= 500) {
        animationState.fps = Math.round((animationState.frameCount * 1000) / deltaTime);
        if (animationState.fpsElement) {
            animationState.fpsElement.textContent = `FPS: ${animationState.fps}`;
        }
        animationState.frameCount = 0;
        animationState.lastFpsTime = now;
    }
}

async function animate() {
    if (!animationState.running) return;
    
    const elapsedTime = Date.now() - animationState.startTime;
    const result = await renderCube(elapsedTime);
    const { pixels, width, height } = result;
    
    await displayFrame(pixels, width, height);
    animationState.frameCount++;
    updateFpsCounter();
    
    requestAnimationFrame(animate);
}

async function main() {
    await initFS();
    const result = await renderCube();
    const { pixels, width, height } = result;
    
    if (isNode) {
        // Node: Save to file
        savePNG(width, height, Buffer.from(pixels), 'output.png');
        console.log("Saved output.png");
    } else {
        // Browser: Apply styles and create UI
        const style = document.createElement('style');
        style.textContent = `
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body {
                background: #222;
                color: #fff;
                font-family: monospace;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                min-height: 100vh;
                padding: 20px;
                gap: 20px;
            }
            h1 {
                font-size: 24px;
                font-weight: normal;
            }
            #controls {
                display: flex;
                gap: 15px;
                align-items: center;
            }
            button {
                padding: 8px 16px;
                font-size: 14px;
                background: #444;
                color: #fff;
                border: 1px solid #666;
                border-radius: 4px;
                cursor: pointer;
                font-family: monospace;
            }
            button:hover {
                background: #555;
            }
            button:active {
                background: #333;
            }
            #fps {
                font-size: 14px;
                color: #aaa;
                min-width: 80px;
            }
            canvas {
                border: 2px solid #fff;
                background: #000;
                image-rendering: pixelated;
                image-rendering: crisp-edges;
            }
        `;
        document.head.appendChild(style);
        
        // Create title
        const h1 = document.createElement('h1');
        h1.textContent = 'WebGL2 Polymorphic Cube Renderer';
        document.body.appendChild(h1);
        
        // Create controls container
        const controls = document.createElement('div');
        controls.id = 'controls';
        
        // Create play/pause button
        const button = document.createElement('button');
        button.textContent = '▶ Play';
        button.onclick = () => {
            animationState.running = !animationState.running;
            if (animationState.running) {
                button.textContent = '⏸ Pause';
                animationState.frameCount = 0;
                animationState.lastFpsTime = Date.now();
                animationState.startTime = Date.now();
                requestAnimationFrame(animate);
            } else {
                button.textContent = '▶ Play';
            }
        };
        controls.appendChild(button);
        
        // Create FPS display
        const fpsDisplay = document.createElement('div');
        fpsDisplay.id = 'fps';
        fpsDisplay.textContent = 'FPS: 0';
        controls.appendChild(fpsDisplay);
        
        document.body.appendChild(controls);
        
        // Create canvas
        const canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        document.body.appendChild(canvas);
        
        const ctx = canvas.getContext('2d');
        
        // Store references in animationState
        animationState.button = button;
        animationState.canvas = canvas;
        animationState.ctx = ctx;
        animationState.width = width;
        animationState.height = height;
        animationState.fpsElement = fpsDisplay;
        
        // Display initial frame
        await displayFrame(pixels, width, height);
        
        console.log("Rendered cube to canvas");
    }
}

// Auto-run if this is Node, export for browser
if (isNode) {
    main().catch(console.error);
}

export { renderCube, main };