const t=!1,i=!0,e=new Float32Array(1),n=new Int32Array(e.buffer);class s{endianness=i;position=0;get length(){throw new Error("Deprecated, use 'capacity' instead")}set length(t){throw new Error("Deprecated, use 'capacity' instead")}capacity=1024;data=new ArrayBuffer(1024);dataView=new DataView(this.data);__data_uint8=new Uint8Array(this.data);__growFactor=1.1;get raw_bytes(){return this.__data_uint8}fromArrayBuffer(t){this.data=t,this.dataView=new DataView(t),this.__data_uint8=new Uint8Array(t),this.capacity=t.byteLength,this.position=0}trim(){return this.setCapacity(this.position),this}skip(t){this.position+=t}setCapacity(t){if(t<this.position)throw new Error(`Attempting to set capacity(=${t}) below current position(=${this.position})`);if(this.capacity===t)return;const i=this.__data_uint8,e=new Uint8Array(t);this.position>0&&function(t,i,e,n,s){let r,o;const a=function(t,i,e){const n=0|e;return 3&n?1&n?1:2:4}(0,0,s);4===a?(r=new Uint32Array(t,0,s>>>2),o=new Uint32Array(e,0,s>>>2)):2===a?(r=new Uint16Array(t,0,s>>>1),o=new Uint16Array(e,0,s>>>1)):(r=new Uint8Array(t,0,s),o=new Uint8Array(e,0,s)),o.set(r)}(i.buffer,0,e.buffer,0,Math.min(i.buffer.byteLength,e.buffer.byteLength,this.position)),this.data=e.buffer,this.__data_uint8=e,this.dataView=new DataView(this.data),this.capacity=t}ensureCapacity(t){const i=this.capacity;if(i>=t)return;const e=(n=Math.ceil(Math.max(t,i*this.__growFactor,i+1024)))+(4-n%4)%4;var n;this.setCapacity(e)}readFloat16(){return function(t){let i=0;const e=(31744&t)>>10,n=1023&t;let s=1;return t>>15&&(s=-1),i=0!==e?31===e?0!==n?NaN:Infinity*s:s*Math.pow(2,e-15)*(1+n/1024):s*(n/1024*6103515625e-14),i}(this.readUint16())}readFloat32(){const t=this.dataView.getFloat32(this.position,this.endianness);return this.position+=4,t}readFloat64(){const t=this.dataView.getFloat64(this.position,this.endianness);return this.position+=8,t}readInt8(){const t=this.dataView.getInt8(this.position);return this.position+=1,t}readInt16(){const t=this.dataView.getInt16(this.position,this.endianness);return this.position+=2,t}readInt16LE(){const t=this.dataView.getInt16(this.position,i);return this.position+=2,t}readInt16BE(){const i=this.dataView.getInt16(this.position,t);return this.position+=2,i}readInt32(){const t=this.dataView.getInt32(this.position,this.endianness);return this.position+=4,t}readInt32LE(){const t=this.dataView.getInt32(this.position,i);return this.position+=4,t}readInt32BE(){const i=this.dataView.getInt32(this.position,t);return this.position+=4,i}readInt64(){const t=this.dataView.getBigInt64(this.position,this.endianness);return this.position+=8,t}readUint8(){const t=this.dataView.getUint8(this.position);return this.position+=1,t}readUint16(){const t=this.dataView.getUint16(this.position,this.endianness);return this.position+=2,t}readUint16LE(){const t=this.dataView.getUint16(this.position,i);return this.position+=2,t}readUint16BE(){const i=this.dataView.getUint16(this.position,t);return this.position+=2,i}readUint24(){return this.endianness===t?this.readUint24BE():this.readUint24LE()}readUint24LE(){const t=this.dataView.getUint8(this.position),i=this.dataView.getUint8(this.position+1),e=this.dataView.getUint8(this.position+2);return this.position+=3,t|i<<8|e<<16}readUint24BE(){const t=this.dataView.getUint8(this.position),i=this.dataView.getUint8(this.position+1),e=this.dataView.getUint8(this.position+2);return this.position+=3,e|i<<8|t<<16}readUint32(){const t=this.dataView.getUint32(this.position,this.endianness);return this.position+=4,t}readUint32LE(){const t=this.dataView.getUint32(this.position,i);return this.position+=4,t}readUint32BE(){const i=this.dataView.getUint32(this.position,t);return this.position+=4,i}readUint64(){const t=this.dataView.getBigUint64(this.position,this.endianness);return this.position+=8,t}readUint8Array(t,i,e){for(let n=0;n<e;n++)t[n+i]=this.readUint8()}readUint16Array(t,i,e){for(let n=0;n<e;n++)t[n+i]=this.readUint16()}readUint32Array(t,i,e){for(let n=0;n<e;n++)t[n+i]=this.readUint32()}readInt8Array(t,i,e){for(let n=0;n<e;n++)t[n+i]=this.readInt8()}readInt16Array(t,i,e){for(let n=0;n<e;n++)t[n+i]=this.readInt16()}readInt32Array(t,i,e){for(let n=0;n<e;n++)t[n+i]=this.readInt32()}readFloat32Array(t,i,e){for(let n=0;n<e;n++)t[n+i]=this.readFloat32()}readFloat64Array(t,i,e){for(let n=0;n<e;n++)t[n+i]=this.readFloat64()}writeFloat32Array(t,i,e){for(let n=0;n<e;n++)this.writeFloat32(t[n+i])}writeFloat16Array(t,i,e){for(let n=0;n<e;n++)this.writeFloat16(t[n+i])}readFloat16Array(t,i,e){for(let n=0;n<e;n++)t[n+i]=this.readFloat16()}writeFloat16(t){const i=function(t){let i=t;Number.isFinite(i)&&(i>65504||i<-65504)&&(i=i>0?65504:-65504),e[0]=i;const s=n[0];let r=s>>16&32768,o=s>>12&2047;const a=s>>23&255;return a<103?r:a>142?(r|=31744,255===a&&8388607&s&&(r|=512),r):a<113?(o|=2048,r|=(o>>114-a)+(o>>113-a&1),r):(r|=a-112<<10|o>>1,r+=1&o,r)}(t);this.writeUint16(i)}writeFloat32(t){const i=this.position+4;this.ensureCapacity(i),this.dataView.setFloat32(this.position,t,this.endianness),this.position=i}writeFloat64(t){const i=this.position+8;this.ensureCapacity(i),this.dataView.setFloat64(this.position,t,this.endianness),this.position=i}writeInt8(t){const i=this.position+1;this.ensureCapacity(i),this.dataView.setInt8(this.position,t),this.position=i}writeInt16(t){const i=this.position+2;this.ensureCapacity(i),this.dataView.setInt16(this.position,t,this.endianness),this.position=i}writeInt16BE(i){const e=this.position+2;this.ensureCapacity(e),this.dataView.setInt16(this.position,i,t),this.position=e}writeInt16LE(t){const e=this.position+2;this.ensureCapacity(e),this.dataView.setInt16(this.position,t,i),this.position=e}writeInt32(t){const i=this.position+4;this.ensureCapacity(i),this.dataView.setInt32(this.position,t,this.endianness),this.position=i}writeInt32BE(i){const e=this.position+4;this.ensureCapacity(e),this.dataView.setInt32(this.position,i,t),this.position=e}writeInt32LE(t){const e=this.position+4;this.ensureCapacity(e),this.dataView.setInt32(this.position,t,i),this.position=e}writeInt64(t){const i=this.position+8;this.ensureCapacity(i),this.dataView.setBigInt64(this.position,t,this.endianness),this.position=i}writeInt8Array(t,i,e){this.ensureCapacity(this.position+e);for(let n=0;n<e;n++)this.writeInt8(t[i+n])}writeInt16Array(t,i,e){this.ensureCapacity(this.position+2*e);for(let n=0;n<e;n++)this.writeInt16(t[i+n])}writeInt32Array(t,i,e){this.ensureCapacity(this.position+4*e);for(let n=0;n<e;n++)this.writeInt32(t[i+n])}writeUint8(t){const i=this.position+1;this.ensureCapacity(i),this.dataView.setUint8(this.position,t),this.position=i}writeUint8Array(t,i,e){for(let n=0;n<e;n++)this.writeUint8(t[i+n])}writeUint16(t){const i=this.position+2;this.ensureCapacity(i),this.dataView.setUint16(this.position,t,this.endianness),this.position=i}writeUint16BE(i){const e=this.position+2;this.ensureCapacity(e),this.dataView.setUint16(this.position,i,t),this.position=e}writeUint16LE(t){const e=this.position+2;this.ensureCapacity(e),this.dataView.setUint16(this.position,t,i),this.position=e}writeUint16Array(t,i,e){for(let n=0;n<e;n++)this.writeUint16(t[i+n])}writeUint24(i){this.endianness===t?this.writeUint24BE(i):this.writeUint24LE(i)}writeUint24BE(t){const i=this.position+3;this.ensureCapacity(i);const e=255&t,n=t>>8&255,s=t>>16&255;this.dataView.setUint8(this.position,s),this.dataView.setUint8(this.position+1,n),this.dataView.setUint8(this.position+2,e),this.position=i}writeUint24LE(t){const i=this.position+3;this.ensureCapacity(i);const e=255&t,n=t>>8&255,s=t>>16&255;this.dataView.setUint8(this.position,e),this.dataView.setUint8(this.position+1,n),this.dataView.setUint8(this.position+2,s),this.position=i}writeUintVar(t){let i=!0,e=t;for(;i||0!==e;){i=!1;let t=127&e;e>>=7,e>0&&(t|=128),this.writeUint8(t)}}readUintVar(){let t=!0,i=0,e=0;for(;t;){let n=this.readUint8();t=!!(128&n),i|=(127&n)<<e,e+=7}return i}writeUint32(t){const i=this.position+4;this.ensureCapacity(i),this.dataView.setUint32(this.position,t,this.endianness),this.position=i}writeUint32BE(i){const e=this.position+4;this.ensureCapacity(e),this.dataView.setUint32(this.position,i,t),this.position=e}writeUint32LE(t){const e=this.position+4;this.ensureCapacity(e),this.dataView.setUint32(this.position,t,i),this.position=e}writeUint64(t){const i=this.position+8;this.ensureCapacity(i),this.dataView.setBigUint64(this.position,t,this.endianness),this.position=i}writeUint32Array(t,i,e){this.ensureCapacity(this.position+4*e);for(let n=0;n<e;n++)this.writeUint32(t[i+n])}writeBytes(t,i,e){const n=i+e,s=this.position,r=s+e;if(this.ensureCapacity(r),0===i&&t.length===e)this.__data_uint8.set(t,s);else if("function"==typeof t.subarray)this.__data_uint8.set(t.subarray(i,n),s);else for(let n=0;n<e;n++)this.__data_uint8[s+n]=t[i+n];this.position=r}readBytes(t,i,e){const n=this.position,s=n+e,r=this.__data_uint8;e<128?function(t,i,e,n,s){let r,o,a;for(a=0;a<s;a++)r=i+a,o=n+a,e[o]=t[r]}(r,n,t,i,e):t.set(r.subarray(n,s),i),this.position=s}writeUTF8String(t){if(null===t)return void this.writeUint32(4294967295);if(void 0===t)return void this.writeUint32(4294967294);let i=0;const e=t.length;if(e>=4294967294)throw new Error("String is too long");this.writeUint32(e);let n=this.position;const s=Math.max(32,e+(e>>1)+7);this.ensureCapacity(s+n);let r=this.__data_uint8,o=this.capacity;for(;i<e;){let s=t.charCodeAt(i++);if(s>=55296&&s<=56319){if(i<e){const e=t.charCodeAt(i);56320==(64512&e)&&(++i,s=((1023&s)<<10)+(1023&e)+65536)}s>=55296&&s<=56319&&(s=65533)}if(n+4>o&&(this.position=n,this.ensureCapacity(n+4),o=this.capacity,r=this.__data_uint8),4294967168&s){if(4294965248&s)if(4294901760&s){if(4292870144&s)continue;r[n++]=s>>18&7|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128}else r[n++]=s>>12&15|224,r[n++]=s>>6&63|128;else r[n++]=s>>6&31|192;r[n++]=63&s|128}else r[n++]=s}this.position=n}readUTF8String(){const t=this.readUint32();if(4294967295===t)return null;if(4294967294===t)return;const i=this.__data_uint8;let e="",n=this.position,s=0;for(;n<this.capacity&&s<t;){const t=i[n++];let r;if(0===t)break;128&t?192==(224&t)?r=(31&t)<<6|63&i[n++]:224==(240&t)?r=(31&t)<<12|(63&i[n++])<<6|63&i[n++]:240==(248&t)&&(r=(7&t)<<18|(63&i[n++])<<12|(63&i[n++])<<6|63&i[n++],r>65535&&(r-=65536,e+=String.fromCharCode(r>>>10&1023|55296),s++,r=56320|1023&r)):r=t,s++,e+=String.fromCharCode(r)}return this.position=n,e}writeASCIIString(t){const i=t.length,e=this.position,n=e+i;this.ensureCapacity(n);for(let n=0;n<i;n++){const i=t.charCodeAt(n);if(i>127)throw new Error(`Character ${String.fromCharCode(i)} can't be represented by a US-ASCII byte.`);this.__data_uint8[e+n]=i}this.position=n}readASCIICharacters(t,i=!1){let e="";for(let n=0;n<t;n++){const t=this.readUint8();if(i&&0===t)break;e+=String.fromCharCode(t)}return e}toString(){return`BinaryBuffer[position=${this.position}, capacity=${this.capacity}, endianness=${this.endianness}]`}toHexString(){const t=this.__data_uint8,i=Math.min(t.length,this.position);let e="";for(let n=0;n<i;n++)e+=t[n].toString(16).padStart(2,"0").toUpperCase();return e}static fromEndianness(t){const i=new s;return i.endianness=t,i}static fromArrayBuffer(t){const i=new s;return i.fromArrayBuffer(t),i}static copyUTF8String(t,i){const e=t.readUTF8String();return i.writeUTF8String(e),e}static copyUintVar(t,i){const e=t.readUintVar();return i.writeUintVar(e),e}static copyUint8(t,i){const e=t.readUint8();return i.writeUint8(e),e}static copyUint16(t,i){const e=t.readUint16();return i.writeUint16(e),e}static copyUint32(t,i){const e=t.readUint32();return i.writeUint32(e),e}static copyFloat32(t,i){const e=t.readFloat32();return i.writeFloat32(e),e}static copyFloat64(t,i){const e=t.readFloat64();return i.writeFloat64(e),e}static copyBytes(t,i,e){const n=new Uint8Array(e);return t.readBytes(n,0,e),i.writeBytes(n,0,e),n}}s.prototype.isBinaryBuffer=!0;let r=i,o=!1;async function a(t,i="deflate"){let e=0;const n=new ReadableStream({pull(i){e===t.length?i.close():i.enqueue(t[e++])}}).pipeThrough(new DecompressionStream(i));return new Uint8Array(await new Response(n).arrayBuffer())}async function h(t,i=!1){try{return await a(t)}catch(e){if(i){const i=function(t){const i=t.length;if(1===i)return t[0];let e=0;for(let n=0;n<i;n++)e+=t[n].length;const n=new Uint8Array(e);let s=0;for(let e=0;e<i;e++)n.set(t[e],s),s+=t[e].length;return n}(t),e=i[0],n=i[1];if(i.length>=6&&8==(15&e)&&e>>>4<=7&&(e<<8|n)%31==0&&!(32&n))try{return await a([i.subarray(2,i.length-4)],"deflate-raw")}catch{}}throw new Error(`failed to inflate zlib stream: ${e?.message||"invalid or truncated data"}`)}}const c=new Uint32Array(256);for(let t=0;t<256;t++){let i=t;for(let t=0;t<8;t++)1&i?i=3988292384^i>>>1:i>>>=1;c[t]=i}const p=Object.freeze([function(t,i,e,n,s,r,o){for(let n=0;n<o;n++)e[s+n]=t[i+n]},function(t,i,e,n,s,r,o){let a=0;for(;a<n;a++)e[s+a]=t[a+i];for(;a<o;a++){const r=s+a;e[r]=t[a+i]+e[r-n]&255}},function(t,i,e,n,s,r,o){let a,h,c=0;if(r<0)for(;c<o;c++)e[s+c]=t[c+i];else for(;c<o;c++)a=t[c+i],h=e[r+c],e[s+c]=a+h&255},function(t,i,e,n,s,r,o){let a,h,c,p=0;if(r<0){for(;p<n;p++)e[s+p]=t[p+i];for(;p<o;p++){const r=s+p;e[r]=t[p+i]+(e[r-n]>>1)&255}}else{for(;p<n;p++)e[s+p]=t[p+i]+(e[r+p]>>1)&255;for(;p<o;p++)a=t[p+i],h=e[s+p-n],c=e[r+p],e[s+p]=a+(h+c>>1)&255}},function(t,i,e,n,s,r,o){let a,h,c,p,d,f,l,u,w,y=0;if(r<0){for(;y<n;y++)e[s+y]=t[y+i];for(;y<o;y++)e[s+y]=t[y+i]+e[s+y-n]&255}else{for(;y<n;y++)e[s+y]=t[y+i]+e[r+y]&255;for(;y<o;y++)a=t[y+i],p=e[r+y-n],c=e[r+y],h=e[s+y-n],d=h+c-p,f=Math.abs(d-h),l=Math.abs(d-c),u=Math.abs(d-p),w=f<=l&&f<=u?h:l<=u?c:p,e[s+y]=a+w&255}}]);function d(t,i,e,n,s,r,o,a){const h=p[t];if(void 0===h)throw new Error(`unknown filtered scanline type '${t}'`);h(i,e,n,s,r,o,a)}function f(t,i,e,n,s,r){if(1!==e&&2!==e&&4!==e)throw new Error(`only bit depths below 8 are packed, got ${e}`);const o=(1<<e)-1;for(let a=0;a<n;a++){const n=a*e,h=t[i+(n>>3)],c=8-e-(7&n);s[r+a]=h>>>c&o}}class l{width=0;height=0;bitDepth=0;colorType=0;compressionMethod=0;filterMethod=0;interlaceMethod=0;colors=0;alpha=!1;palette=null;pixels=null;transparency_lookup=null;text={};getWidth(){return this.width}setWidth(t){this.width=t}getHeight(){return this.height}setHeight(t){this.height=t}getBitDepth(){return this.bitDepth}setBitDepth(t){if(-1===[1,2,4,8,16].indexOf(t))throw new Error("invalid bith depth "+t);this.bitDepth=t}getColorType(){return this.colorType}setColorType(t){let i=0,e=!1;switch(t){case 0:case 3:i=1;break;case 2:i=3;break;case 4:i=2,e=!0;break;case 6:i=4,e=!0;break;default:throw new Error("invalid color type")}this.colors=i,this.alpha=e,this.colorType=t}setCompressionMethod(t){if(0!==t)throw new Error("invalid compression method "+t);this.compressionMethod=t}setFilterMethod(t){if(0!==t)throw new Error("invalid filter method "+t);this.filterMethod=t}getInterlaceMethod(){return this.interlaceMethod}setInterlaceMethod(t){if(0!==t&&1!==t)throw new Error("invalid interlace method "+t);this.interlaceMethod=t}setPalette(t){if(t.length%3!=0)throw new Error("incorrect PLTE chunk length");if(t.length>3*Math.pow(2,this.bitDepth))throw new Error("palette has more colors than 2^bitdepth");this.palette=t}getUint8Data_case3(){const t=this.width*this.height;let i;const e=this.transparency_lookup;i=null!==e?4:3;const n=new Uint8Array(t*i),s=this.pixels,r=this.palette,o=this.colors*Math.ceil(this.bitDepth/8);for(let e=0;e<t;e++){const t=e*i,a=3*s[e*o];n[t]=r[a],n[t+1]=r[a+1],n[t+2]=r[a+2]}if(null!==e){const i=e.length;for(let r=0;r<t;r++){const t=s[r*o];n[4*r+3]=t>=i?255:e[t]}}return{data:n,itemSize:i}}getUint8Data(){let t,i=0;switch(this.colorType){case 0:t=this.pixels,i=1;break;case 2:t=this.pixels,i=3;break;case 3:const e=this.getUint8Data_case3();t=e.data,i=e.itemSize;break;case 4:t=this.pixels,i=2;break;case 6:t=this.pixels,i=4;break;default:throw new Error("Unsupported color type")}return{data:t,itemSize:i}}}const u=[137,80,78,71,13,10,26,10];function w(t,i){return t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3]}function y(t,i){return t[i]}function U(i){this.png=new l,this.dataChunks=[],this.buffer=new s,this.buffer.endianness=t,this.buffer.fromArrayBuffer(i),this.crc_enabled=!1}U.prototype.readBytes=function(t){const i=this.buffer,e=new Uint8Array(i.data,i.position,t);return i.skip(t),e},U.prototype.decodeHeader=function(){const t=this.buffer,i=new Uint8Array(u.length);if(t.readBytes(i,0,i.length),!function(t,i){const e=t.length;if(e!==i.length)return!1;for(let n=0;n<e;n++)if(t[n]!==i[n])return!1;return!0}(i,u))throw new Error("invalid PNGReader file (bad signature)")},U.prototype.decodeChunk=async function(){const t=this.buffer,i=t.readUint32();if(i<0)throw new Error("Bad chunk length "+(4294967295&i));const e=t.position,n=t.readASCIICharacters(4),r=this.readBytes(i);switch(t.readUint32(),this.crc_enabled&&function(t,i=0,e=t.length){!function(t,i,e,n){let s=4294967295;const r=e+n;for(let t=e;t<r;t++){const e=i[t];s=c[255&(s^e)]^s>>>8}}(0,t,i,e)}(t.raw_bytes,e,i+4),n){case"IHDR":this.decodeIHDR(r);break;case"PLTE":this.decodePLTE(r);break;case"IDAT":this.decodeIDAT(r);break;case"tRNS":this.decodeTRNS(r);break;case"IEND":this.decodeIEND(r);break;case"sRGB":this.decodesRGB(r);break;case"tIME":this.decodetIME(r);break;case"zTXt":await async function(t){const i=t.byteLength,e=t.buffer,n=t.byteOffset,r=s.fromArrayBuffer(e);r.position=n;const o=r.readASCIICharacters(79,!0),a=r.readUint8();let c;if(0!==a)throw new Error(`Unsupported compression method '${a}'`);{const t=r.position-n,s=new Uint8Array(e,r.position,i-t),o=await h([s]);r.fromArrayBuffer(o.buffer),c=r.readASCIICharacters(o.byteLength)}return{keyword:o,text:c}}(r);break;case"iTXt":await async function(t){const i=t.byteLength,e=t.buffer,n=t.byteOffset,r=n+i,o=s.fromArrayBuffer(e);o.position=n;const a=o.readASCIICharacters(79,!0),c=o.readUint8(),p=o.readUint8(),d=o.readASCIICharacters(Number.MAX_SAFE_INTEGER,!0),f=o.readASCIICharacters(Number.MAX_SAFE_INTEGER,!0),l=r-o.position;let u;if(0===c)u=o.readASCIICharacters(l);else{if(1!==c)throw new Error(`Invalid compression flag value '${c}'`);{if(0!==p)throw new Error("only compression_method 0 is supported");const t=await h([new Uint8Array(o.data,o.position,l)]);o.fromArrayBuffer(t.buffer),u=o.readASCIICharacters(t.byteLength)}}return{keyword:a,language_tag:d,translated_keyword:f,text:u}}(r)}return n},U.prototype.decodesRGB=function(t){y(t,0)},U.prototype.decodetIME=function(t){y(t,0),y(t,1),y(t,2),y(t,3),y(t,4),y(t,5),y(t,6)},U.prototype.decodetEXt=function(t){const i=s.fromArrayBuffer(t.buffer),e=i.readASCIICharacters(Number.POSITIVE_INFINITY,!0),n=i.readASCIICharacters(e.length-1,!1);this.png.text[e]=n},U.prototype.decodeiEXt=function(t){const i=s.fromArrayBuffer(t.buffer),e=i.readASCIICharacters(Number.POSITIVE_INFINITY,!0);if(i.readUint8(),i.readUint8(),i.readASCIICharacters(Number.POSITIVE_INFINITY,!0),i.readUTF8String(),0!==i.readUint8())throw new Error("Expected Null Separator after Translated keyword");const n=i.readUTF8String();this.png.text[e]=n},U.prototype.decodeIHDR=function(t){const i=this.png;i.setWidth(w(t,0)),i.setHeight(w(t,4)),i.setBitDepth(y(t,8)),i.setColorType(y(t,9)),i.setCompressionMethod(y(t,10)),i.setFilterMethod(y(t,11)),i.setInterlaceMethod(y(t,12))},U.prototype.decodePLTE=function(t){this.png.setPalette(t)},U.prototype.decodeIDAT=function(t){this.dataChunks.push(t)},U.prototype.decodeTRNS=function(t){this.png.transparency_lookup=t},U.prototype.decodeIEND=function(){},U.prototype.decodePixels=async function(){const e=this.png,n=await h(this.dataChunks,!0);if(0===e.getInterlaceMethod()?this.png.pixels=this.interlaceNone(n):this.png.pixels=this.interlaceAdam7(n),16===e.bitDepth&&function(){if(o)return r;const e=new ArrayBuffer(2),n=new Uint8Array(e),s=new Uint16Array(e);return n[0]=19,r=19==(255&s[0])?i:t,o=!0,r}()===i){const t=this.png.pixels;for(let i=0;i<t.length;i+=2){const e=t[i];t[i]=t[i+1],t[i+1]=e}}},U.prototype.interlaceNone=function(t){const i=this.png,e=i.bitDepth,n=i.colors,s=i.width,r=i.height,o=Math.max(1,Math.ceil(n*e/8)),a=Math.ceil(n*e*s/8);if(e<8)return function(t,i,e,n,s,r){const o=new Uint8Array(e*r),a=new Uint8Array(2*s),h=Math.floor(t.length/(s+1)),c=r<h?r:h;let p=0,l=-1;for(let r=0;r<c;r++){const h=(1&r)*s;d(t[p++],t,p,a,n,h,l,s),p+=s,f(a,h,i,e,o,r*e),l=h}return o}(t,e,n*s,o,a,r);const h=new Uint8Array(a*r);let c=0;const p=t.length;for(let i=0;i<p;i+=a+1){const e=i+1;d(t[i],t,e,h,o,c,c-a,a),c+=a}return h},U.prototype.interlaceAdam7=function(t){const i=this.png,e=i.bitDepth,n=i.colors,s=i.width,r=i.height,o=e<8,a=Math.max(1,Math.ceil(n*e/8)),h=n*(16===e?2:1),c=new Uint8Array(h*s*r),p=[{x:0,y:0,xStep:8,yStep:8},{x:4,y:0,xStep:8,yStep:8},{x:0,y:4,xStep:4,yStep:8},{x:2,y:0,xStep:4,yStep:4},{x:0,y:2,xStep:2,yStep:4},{x:1,y:0,xStep:2,yStep:2},{x:0,y:1,xStep:1,yStep:2}];let l=0;const u=new Uint8Array(2*Math.ceil(n*e*s/8)),w=o?new Uint8Array(n*s):null;for(let i=0;i<7;i++){const y=p[i],U=Math.ceil((s-y.x)/y.xStep),g=Math.ceil((r-y.y)/y.yStep);if(U<=0||g<=0)continue;const I=n*U,b=Math.ceil(I*e/8);let A=-1;for(let i=0;i<g;i++){const n=i%2*b;d(t[l++],t,l,u,a,n,A,b),l+=b,A=n;let p=u,g=n;o&&(f(u,n,e,I,w,0),p=w,g=0);for(let t=0;t<U;t++){const e=y.x+t*y.xStep,n=y.y+i*y.yStep;if(!(e>=s||n>=r))for(let i=0;i<h;i++)c[(n*s+e)*h+i]=p[g+t*h+i]}}}return c},U.prototype.unFilter=function(t,i,e,n,s,r,o,a){d(t,i,e,n,s,r,o,a)},U.prototype.parse=async function(){for(this.decodeHeader();"IEND"!==await this.decodeChunk(););return await this.decodePixels(),this.png},self.Lib={decode:async function(t,i="png"){if(!(t instanceof ArrayBuffer))throw new Error(".data argument must be an ArrayBuffer, instead was something else");if("png"===i.toLowerCase())return await async function(t){const i=await new U(t).parse(),e=i.getUint8Data();return{data:e.data.buffer,width:i.getWidth(),height:i.getHeight(),itemSize:e.itemSize,bitDepth:i.getBitDepth()}}(t);throw new Error("Unsupported type")}};
import { Sampler2D } from "@woosh/meep-engine/src/engine/graphics/texture/sampler/Sampler2D.js";
import {
sampler2d_srgb_to_linear
} from "@woosh/meep-engine/src/engine/graphics/texture/sampler/sampler2d_srgb_to_linear.js";
import {
sampler2d_to_f16
} from "@woosh/meep-engine/src/engine/graphics/texture/sampler/sampler2d_to_f16.js";
import {
sampler2d_from_image_bitmap
} from "@woosh/meep-engine/src/shade/renderer/scene/optimization/sampler2d_from_image_bitmap.js";
import { ColorSpace } from "@woosh/meep-engine/src/shade/renderer/texture/ColorSpace.js";
import { ShadeTexture } from "@woosh/meep-engine/src/shade/renderer/texture/ShadeTexture.js";
import { ShadeImage } from "@woosh/meep-engine/src/shade/renderer/texture/source/ShadeImage.js";
/**
* Load a single image that is *already* in the octahedral projection as the
* environment Shade lights from.
*
* Shade samples an environment as an octahedral map of linear radiance, and
* `set_environment_map` takes the projection on trust: hand it an
* equirectangular panorama and it samples as garbage rather than failing. The
* engine ships two ways in, and neither fits this example —
* `load_cube_environment` wants six faces and resamples them down to a fixed
* 128², and `load_environment_map` wants a Radiance `.hdr`. This scene's sky is
* one LDR image already in the right projection (see
* `tools/bake_sky_environment.mjs`), so all that is left is a decode and a
* transfer conversion — done in `radianceF16FromSrgb`, as one table lookup per
* channel.
*
* `colorSpaceConversion: 'none'` keeps the browser from applying a colour
* profile of its own before that sRGB decode, which would otherwise be applied
* twice.
*
* ## Why there is a `radiance` argument
*
* An 8-bit photograph has no absolute brightness in it: decoded, its whitest
* pixel is 1.0 and nothing can be brighter. Shade's lights, meanwhile, are
* photometric — a midday sun is tens of units, not one — so an environment left
* at photographic scale is some thirty times too dim to sit next to one. The
* scene still *looks* lit, because the sun is doing that; what goes wrong is the
* sky, which is drawn as the background at its own radiance and so comes out as
* a dark, dusk-blue ceiling over a sunlit street.
*
* (This does not show up while a scene has a sky *dome*, because the dome is
* emissive geometry composited by a different route. Deleting the dome is what
* exposes it.)
*
* So the decoded values are scaled to a radiance that belongs with the sun they
* are lit beside. It is a physical quantity, not a brightness dial: a sky of
* uniform radiance L delivers about `π · L` of illuminance onto flat ground, so
* a value near a third of the sun's own intensity is roughly the overcast-to-
* hazy balance you would measure outdoors.
*
* @param {string} url an octahedral environment image, sRGB-encoded
* @param {number} [radiance] what the image's white point should mean, in the
* same photometric units as the scene's lights
* @returns {Promise<ShadeTexture>}
*/
export async function loadOctahedralEnvironment(url, radiance = 1) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch environment '${url}': ${response.status} ${response.statusText}`);
}
const bitmap = await createImageBitmap(await response.blob(), { colorSpaceConversion: "none" });
const encoded = sampler2d_from_image_bitmap(bitmap);
bitmap.close();
const image = ShadeImage.fromSampler2D(radianceF16FromSrgb(encoded, radiance));
// radiance, not colour — the transfer curve came off above
image.color_space = ColorSpace.LinearSRGB;
return ShadeTexture.from(image);
}
/**
* Decode an 8-bit sRGB RGBA sampler into the half-float radiance the
* environment is uploaded as: linear light, RGB scaled by `radiance`, alpha
* kept as coverage.
*
* A channel holds one of only 256 byte values, so the conversion —
* `sampler2d_srgb_to_linear`, the scale, `sampler2d_to_f16` — runs once over
* those 256 values, and every texel is then a lookup of finished half-float
* bits. The table goes through the same functions as a texel-by-texel
* conversion, so it gives the same bits (`test/environment.test.js` checks this
* against the sky itself) in about a fifteenth of the time on a 2048² image.
*
* @param {Sampler2D} encoded 4 channels, 0-255, sRGB
* @param {number} radiance
* @returns {Sampler2D} 4 channels, `Float16Array` storage
*/
export function radianceF16FromSrgb(encoded, radiance) {
const [rgb, alpha] = radianceF16Tables(radiance);
const result = Sampler2D.float16(4, encoded.width, encoded.height);
const input = encoded.data;
// the half-float bit patterns go straight into the Float16Array's storage
const output = new Uint16Array(result.data.buffer);
const length = input.length;
for (let i = 0; i < length; i += 4) {
output[i] = rgb[input[i]];
output[i + 1] = rgb[input[i + 1]];
output[i + 2] = rgb[input[i + 2]];
output[i + 3] = alpha[input[i + 3]];
}
return result;
}
/**
* @param {number} radiance
* @returns {Uint16Array[]} half-float bits for each byte value, as [RGB, alpha]
*/
function radianceF16Tables(radiance) {
// texel k holds byte k in every channel
const ramp = Sampler2D.uint8(4, 256, 1);
for (let k = 0; k < 256; k++) {
ramp.data.fill(k, k * 4, k * 4 + 4);
}
const linear = sampler2d_srgb_to_linear(ramp);
const data = linear.data;
// RGB only — the fourth channel is coverage, and a scaled alpha would just be
// an invalid one. Half-float holds up to 65504, so there is headroom here for
// a sun-bright sky many times over.
for (let i = 0; i < data.length; i += 4) {
data[i] *= radiance;
data[i + 1] *= radiance;
data[i + 2] *= radiance;
}
const bits = new Uint16Array(sampler2d_to_f16(linear).data.buffer);
const rgb = new Uint16Array(256);
const alpha = new Uint16Array(256);
for (let k = 0; k < 256; k++) {
rgb[k] = bits[k * 4];
alpha[k] = bits[k * 4 + 3];
}
return [rgb, alpha];
}
// Screen-space reflections — a Meep example.
//
// A dense outdoor scene (a 1950s American town square, ported from the
// Babylon.js "Hill Valley" demo — see README for the conversion and the asset
// provenance) rendered with Shade's SSR pass on, and a key to turn it off.
//
// What SSR is, in one paragraph: the deferred pass has already produced a
// G-buffer and a lit colour buffer for this frame. For every pixel smooth enough
// to matter, SSR marches a reflection ray through the depth pyramid, and where
// the ray lands on something the camera can already see, it takes that pixel's
// colour as the reflected radiance. It is cheap and it is grounded in the actual
// scene — the car reflects the storefront next to it, a puddle reflects the
// building above it — but it can only reflect what is on screen. Rays that walk
// off the edge of the frame, or behind something, have nothing to sample, and
// Shade falls those back to the environment map. That is exactly the difference
// the toggle shows: with SSR off, every glossy surface is lit only by the
// environment, so it keeps a general sense of "sky above, ground below" and
// loses every specific thing around it.
//
// The scene was chosen for the surfaces, not the buildings:
//
// * the road carries puddles — mirror-flat, near-horizontal, and seen at a
// grazing angle, which is SSR's best case. They are decals, placed from the
// source scene's own wet mask (see `tools/make_puddles.mjs`); the asphalt
// around them stays close to dry, because an evenly glossy road has no shape
// to its reflections and shape is the whole point;
// * each storefront has a separate, opaque glazing pane over it, so the
// windows stay in the G-buffer and take reflections (the genuinely
// see-through windows are transmissive and composite later, which is why
// they show the environment instead);
// * the DeLorean's body is stainless steel — a metal, so its reflection is
// the whole of its specular response rather than a layer on top of diffuse.
import Quaternion from "@woosh/meep-engine/src/core/geom/Quaternion.js";
import Vector3 from "@woosh/meep-engine/src/core/geom/Vector3.js";
import { GameAssetType } from "@woosh/meep-engine/src/engine/asset/GameAssetType.js";
import { load_model_scene_bundle } from "@woosh/meep-engine/src/engine/asset/load_model_scene_bundle.js";
import { ArrayBufferLoader } from "@woosh/meep-engine/src/engine/asset/loaders/ArrayBufferLoader.js";
import {
GLTFSceneBundleAssetLoader
} from "@woosh/meep-engine/src/engine/asset/loaders/GLTFSceneBundleAssetLoader.js";
import {
ImageBitmapAssetLoader
} from "@woosh/meep-engine/src/engine/asset/loaders/image/ImageBitmapAssetLoader.js";
import Entity from "@woosh/meep-engine/src/engine/ecs/Entity.js";
import { Transform64 } from "@woosh/meep-engine/src/engine/ecs/transform/Transform64.js";
import { EngineHarness } from "@woosh/meep-engine/src/engine/EngineHarness.js";
import TopDownCameraController from "@woosh/meep-engine/src/engine/graphics/ecs/camera/topdown/TopDownCameraController.js";
import { Decal } from "@woosh/meep-engine/src/engine/graphics/ecs/decal/v2/Decal.js";
import { SGMesh } from "@woosh/meep-engine/src/engine/graphics/ecs/mesh-v2/aggregate/SGMesh.js";
import { DecalSystem } from "@woosh/meep-engine/src/engine/graphics3/DecalSystem.js";
import { MeshSystem } from "@woosh/meep-engine/src/engine/graphics3/MeshSystem.js";
import { ShadedGeometrySystem } from "@woosh/meep-engine/src/engine/graphics3/ShadedGeometrySystem.js";
import { loadOctahedralEnvironment } from "./lib/load_octahedral_environment.js";
import { PUDDLES, PUDDLE_TEXTURES } from "./puddleManifest.js";
// ─── Scene / camera framing ──────────────────────────────────────────────
//
// The square is about 190 units across and sits around the origin, with the
// courthouse to the east and the storefronts along its north and west sides.
const MODEL_URL = "./models/hill_valley/hill_valley.gltf";
const ENVIRONMENT_URL = "./textures/hill_valley_sky.png";
// Street level on the west side, framing the three surfaces this example is
// about at once: the parked car, the glazing behind it, and a long sweep of wet
// road across the foreground.
//
// The low camera is the point rather than a preference. Reflectance climbs
// steeply towards grazing incidence, so a near-horizontal surface like a road
// only shows what it can do from about eye height; from up on the rooftops the
// same asphalt is a dull grey and SSR looks like it is doing nothing.
const SCENE_FOCUS = new Vector3(-32, 1.1, -22);
const CAMERA_DISTANCE = 14;
const CAMERA_PITCH = 0.06;
const CAMERA_YAW = 5.0;
// Shade spreads the sun's shadow cascades over the camera's whole near..far
// range, so far only has to reach across the square: 250 units covers it from
// anywhere up to CAMERA_ZOOM_MAX, the furthest the camera zooms out.
const CAMERA_FAR = 250;
const CAMERA_ZOOM_MAX = 60;
// Shade's lights are photometric — a directional light's intensity is the
// illuminance it delivers, not a 0..1 dial, and a value in the low tens is dusk
// rather than noon. This scene needs more than most: its albedo maps are 1950s
// baked textures, dark to begin with, and the sun is what lifts them back to
// daylight.
const SUN_INTENSITY = 70;
const SUN_DIRECTION = new Vector3(-0.45, -1, 0.28);
// What the sky image's white point is worth, in the same photometric units as
// the sun above. See `load_octahedral_environment` for why a number is needed at
// all: an 8-bit photograph tops out at a radiance of 1, which is nothing beside
// a sun of 70, and a sky left at photographic scale draws as a dusk-blue ceiling
// over a sunlit street. A sky of uniform radiance L puts about `π · L` of
// illuminance on flat ground, so this is a sun-and-sky split of roughly 50/50 —
// a bright day with some haze in it, which is the day the textures were baked
// under.
const SKY_RADIANCE = 22;
const engine = await EngineHarness.bootstrap({
configuration: (config, engine) => {
// Every system that draws writes into the one Shade scene the harness
// hands out — lights included, or the model would be lit by nothing.
const scene = EngineHarness.shadeScene(engine);
// The glTF arrives as a Shade `SceneBundle`; the loader pulls the
// file's own `.bin` buffer and its images back through the asset
// manager, so those two types need loaders as well.
const gltfLoader = new GLTFSceneBundleAssetLoader();
config.addLoader(GameAssetType.ModelGLTF, gltfLoader);
config.addLoader(GameAssetType.ModelGLTF_JSON, gltfLoader);
config.addLoader(GameAssetType.ArrayBuffer, new ArrayBufferLoader());
config.addLoader(GameAssetType.ImageBitmap, new ImageBitmapAssetLoader());
// SGMesh loads the model; because it neither skins nor animates,
// MeshSystem expands it into one entity per glTF node, each carrying a
// ShadedGeometry that ShadedGeometrySystem gives a row in the scene.
config.addSystem(new MeshSystem(
engine.graphics,
scene,
url => load_model_scene_bundle(engine.assetManager, url)
));
config.addSystem(new ShadedGeometrySystem(engine.graphics, scene));
// Drives the puddles. It registers its own image loader for decal
// textures at startup, so nothing to add here.
config.addSystem(new DecalSystem(engine.graphics, engine.assetManager));
},
});
await EngineHarness.buildBasics({
engine,
enableTerrain: false,
enableWater: false,
enableLights: false,
focus: SCENE_FOCUS,
distance: CAMERA_DISTANCE,
pitch: CAMERA_PITCH,
yaw: CAMERA_YAW,
cameraFarDistance: CAMERA_FAR,
cameraController: true,
showFps: false,
});
engine.entityManager.dataset.getAnyComponent(TopDownCameraController).component.distanceMax = CAMERA_ZOOM_MAX;
await EngineHarness.buildLights({
engine,
castShadow: true,
// The square is ~190 units across; a shadow distance that covers it keeps
// the whole street in the same shadow cascade.
sunShadowDistance: 260,
sunIntensity: SUN_INTENSITY,
sunDirection: SUN_DIRECTION,
});
// ─── Environment ──────────────────────────────────────────────────────────
//
// One 2K octahedral image doing three jobs: the ambient term (Shade has no
// separate ambient light — `LightType.AMBIENT` entities are dropped), the
// fallback SSR resolves to wherever a reflection ray finds nothing on screen,
// and the background the frame is drawn against. Having one image in all three
// roles is what makes the SSR toggle read as "specific reflections" versus
// "generic ones" rather than as a brightness change.
//
// It is also why there is no sky dome in this scene any more. The source had
// both — a dome mesh and a separate 128² reflection cubemap — shot from two
// different skies, so anything reflective reflected clouds that were not in the
// picture. `tools/bake_sky_environment.mjs` ray-traces the dome into this map,
// and the dome mesh is dropped on the way in.
engine.graphics.set_environment_map(await loadOctahedralEnvironment(ENVIRONMENT_URL, SKY_RADIANCE));
const ecd = engine.entityManager.dataset;
// ─── Scene ────────────────────────────────────────────────────────────────
new Entity()
.add(new Transform64())
.add(SGMesh.fromURL(MODEL_URL))
.build(ecd);
// ─── Puddles ──────────────────────────────────────────────────────────────
//
// The road is asphalt, not a mirror — a uniformly glossy one has no shape to
// its reflections, which is the thing SSR is here to show. The shape comes from
// standing water, placed as decals.
//
// A decal is composited into the G-buffer *before* anything is lit, so a puddle
// is part of the road as far as reflections, occlusion and shading are
// concerned — it is not a transparent layer drawn over the top, and SSR traces
// against its roughness like any other surface. It is also the only way to get
// this detail onto the road: each puddle has a 512² texture over about four
// units, ~128 texels per unit, where one map stretched over the whole 165-unit
// road would have twelve.
//
// Where they go is not invented. The source scene ships a specular mask for its
// asphalt saying where it stands in water; that mask is on UV1 and unreachable
// at render time (see the README), so `tools/make_puddles.mjs` reads it offline,
// projects it through the road's UV1 into world space, and emits a puddle for
// each wet patch — at that patch's position, extent and orientation.
ecd.registerComponentType(Decal);
// Decals project along their local +Z, so a puddle's forward axis points down,
// into the road. `lookRotation`'s second argument then picks the other two axes:
// with this `up`, local +X lands along the wet patch's long axis and local +Y
// across it, which is what lets the scale below be read straight off the
// manifest.
const PUDDLE_FORWARD = new Vector3(0, -1, 0);
// How deep the projection box reaches. Each puddle is centred on the road's own
// height where it sits, so this only has to span the local camber — ±0.25 units
// against a road that varies by 0.35 over its whole length. It is deliberately
// short of the 0.33 that separates the road from the top of the kerb: a box deep
// enough to reach that would paint water up the side of the kerb wherever a pool
// sits near one.
const PUDDLE_DEPTH = 0.5;
for (const puddle of PUDDLES) {
const decal = new Decal();
decal.uri_albedo = PUDDLE_TEXTURES[puddle.variant];
// Standing water is mirror-smooth, and uniformly so — hence no ORM map. A
// decal without one gets the identity patch, whose roughness channel is
// white, so `roughness = mix(roughness, 1.0 * decal.roughness, coverage)`
// leaves this scalar as the answer wherever coverage is complete.
//
// Author zero roughness for the sharpest reflections. The deferred pass
// applies its numerical floor of 0.02 when it reads the G-buffer.
decal.roughness = 0;
const up = new Vector3(-Math.sin(puddle.angle), 0, Math.cos(puddle.angle));
const rotation = new Quaternion();
rotation.lookRotation(PUDDLE_FORWARD, up);
// DecalSystem reads the transform's matrix, and a Transform64 does not
// maintain it: compose it once, after the whole pose is written.
const transform = new Transform64();
transform.setTranslation(puddle.position[0], puddle.position[1], puddle.position[2]);
transform.setRotation(rotation.x, rotation.y, rotation.z, rotation.w);
transform.setScale(puddle.size[0], puddle.size[1], PUDDLE_DEPTH);
transform.updateMatrix();
new Entity()
.add(transform)
.add(decal)
.build(ecd);
}
// ─── SSR ──────────────────────────────────────────────────────────────────
//
// One flag. SSR is off by default because it is not free — it traces the depth
// pyramid, reprojects last frame's result and denoises it, all at render
// resolution — so an app opts in.
//
// The renderer only exists once the engine has started, which `bootstrap` above
// has already awaited. It is also replaced whenever the engine restarts, so an
// app that stops and starts would re-apply this rather than cache the object.
const renderer = engine.graphics.renderer;
renderer.feature_ssr_enabled = true;
// Exposure adapts to scene brightness on its own and takes a couple of seconds
// to settle after a cold start; this is the bias in f-stops in front of it.
renderer.exposure_compensation = 0.7;
const ssrEl = document.getElementById("ssr");
const ssrToggle = document.getElementById("ssr-toggle");
function setSSR(enabled) {
renderer.feature_ssr_enabled = enabled;
ssrEl.textContent = enabled ? "on" : "off";
ssrEl.classList.toggle("off", !enabled);
// The switch renders itself from `aria-pressed`, so the state a screen
// reader is told and the state the knob shows cannot drift apart.
ssrToggle.setAttribute("aria-pressed", String(enabled));
}
setSSR(renderer.feature_ssr_enabled);
ssrToggle.addEventListener("click", () => {
setSSR(!renderer.feature_ssr_enabled);
});
window.addEventListener("keydown", (event) => {
if (event.key === "r" || event.key === "R") {
setSSR(!renderer.feature_ssr_enabled);
}
});
// ─── HUD ──────────────────────────────────────────────────────────────────
const fpsEl = document.getElementById("fps");
const loadingEl = document.getElementById("loading");
let fpsWindow = 0;
let fpsFrames = 0;
let lastFrame = performance.now();
let settled = false;
engine.graphics.on.postRender.add(() => {
const now = performance.now();
const dt = (now - lastFrame) / 1000;
lastFrame = now;
// The model streams in over the first seconds; the overlay lifts once the
// scene actually has geometry in it rather than on a timer. A primitive is an
// entity holding a `meshes` row, and `mesh_rows_version` moves the first time
// one is attached.
if (!settled) {
const context = engine.graphics.scene_context(EngineHarness.shadeScene(engine));
if (context !== null && context.rows.mesh_rows_version > 0) {
settled = true;
loadingEl.classList.add("hidden");
}
}
fpsWindow += dt;
fpsFrames++;
if (fpsWindow >= 0.5) {
fpsEl.textContent = (fpsFrames / fpsWindow).toFixed(0);
fpsWindow = 0;
fpsFrames = 0;
}
});
console.log("%cScreen-space reflections — Meep example", "color:#88ddff;font-weight:bold;font-size:14px");
console.log("R toggles SSR. Drag to orbit, right-drag to pan, wheel to zoom.");
// Generated by tools/make_puddles.mjs — do not edit by hand.
//
// Puddles on the road, placed where the source scene's own specular mask says
// the asphalt stands in water. Each entry is one decal: a world position on the
// road surface, the extent of the wet patch it came from along its long and
// short axes, and the direction of that long axis in the ground plane.
export const PUDDLE_TEXTURES = [
"./textures/puddles/puddle_0_albedo.png",
"./textures/puddles/puddle_1_albedo.png",
"./textures/puddles/puddle_2_albedo.png",
"./textures/puddles/puddle_3_albedo.png"
];
export const PUDDLES = [
{
"position": [
-12.49,
0.97,
-25.71
],
"size": [
4.83,
2.47
],
"angle": 0.096,
"variant": 0
},
{
"position": [
-6.03,
0.97,
-25.09
],
"size": [
4.86,
2.24
],
"angle": 0.096,
"variant": 1
},
{
"position": [
-7.06,
0.97,
15.22
],
"size": [
5.33,
1.95
],
"angle": 0.055,
"variant": 2
},
{
"position": [
-0.71,
0.97,
15.57
],
"size": [
4.56,
2.21
],
"angle": 0.055,
"variant": 3
},
{
"position": [
-31.8,
0.97,
0.88
],
"size": [
5.6,
2.54
],
"angle": 1.039,
"variant": 0
},
{
"position": [
18.45,
0.97,
-26.91
],
"size": [
3.56,
2.4
],
"angle": 0.167,
"variant": 1
},
{
"position": [
-18.36,
0.97,
-25.55
],
"size": [
4.95,
1.56
],
"angle": -0.209,
"variant": 2
},
{
"position": [
-29.23,
0.97,
-7.56
],
"size": [
4.08,
1.63
],
"angle": 1.481,
"variant": 3
},
{
"position": [
-33.25,
0.97,
-26.07
],
"size": [
2.11,
1.62
],
"angle": 0.114,
"variant": 0
},
{
"position": [
-33.73,
0.97,
-27.32
],
"size": [
1.6,
1.39
],
"angle": -0.136,
"variant": 1
},
{
"position": [
-35.13,
0.97,
-26.12
],
"size": [
1.6,
1.86
],
"angle": -1.466,
"variant": 2
},
{
"position": [
2.28,
0.97,
16.04
],
"size": [
1.6,
1.91
],
"angle": 1.069,
"variant": 3
},
{
"position": [
41.21,
0.97,
-11.79
],
"size": [
3.77,
2.59
],
"angle": 2.006,
"variant": 0
},
{
"position": [
39.54,
0.97,
-35.46
],
"size": [
3.89,
3.3
],
"angle": 3.012,
"variant": 1
},
{
"position": [
59.21,
0.97,
-2.63
],
"size": [
3.93,
2.82
],
"angle": 0.651,
"variant": 2
},
{
"position": [
43.21,
0.97,
-22.13
],
"size": [
5.02,
3.84
],
"angle": 1.773,
"variant": 3
},
{
"position": [
53.54,
0.97,
3.54
],
"size": [
4.53,
3.35
],
"angle": 0.002,
"variant": 0
},
{
"position": [
38.54,
0.97,
-3.29
],
"size": [
4.67,
3.7
],
"angle": 0.494,
"variant": 1
},
{
"position": [
51.87,
0.97,
-14.13
],
"size": [
4.47,
3.45
],
"angle": 1.026,
"variant": 2
},
{
"position": [
32.71,
0.97,
-5.13
],
"size": [
3.87,
2.89
],
"angle": 1.76,
"variant": 3
},
{
"position": [
57.87,
0.97,
8.21
],
"size": [
3.6,
1.94
],
"angle": 3.113,
"variant": 0
},
{
"position": [
-95.46,
0.8,
-29.79
],
"size": [
1.95,
1.03
],
"angle": 2.417,
"variant": 1
},
{
"position": [
-45.29,
0.97,
-23.63
],
"size": [
4.38,
2.73
],
"angle": 0.597,
"variant": 2
},
{
"position": [
51.87,
0.97,
-2.46
],
"size": [
3.57,
2.8
],
"angle": 2.63,
"variant": 3
},
{
"position": [
63.37,
0.97,
11.21
],
"size": [
3.15,
2.42
],
"angle": 2.507,
"variant": 0
},
{
"position": [
-25.79,
0.97,
2.54
],
"size": [
3.28,
2.71
],
"angle": 2.801,
"variant": 1
},
{
"position": [
-27.63,
0.97,
-15.79
],
"size": [
4.95,
3.59
],
"angle": 1.225,
"variant": 2
},
{
"position": [
-27.46,
0.97,
-22.29
],
"size": [
2.38,
1.09
],
"angle": 1.654,
"variant": 3
},
{
"position": [
-16.63,
0.97,
-31.29
],
"size": [
3.67,
2.61
],
"angle": 2.925,
"variant": 0
},
{
"position": [
-31.79,
0.97,
7.04
],
"size": [
3.68,
2.05
],
"angle": 0.734,
"variant": 1
},
{
"position": [
57.54,
0.97,
-11.13
],
"size": [
2.17,
1.45
],
"angle": 1.021,
"variant": 2
},
{
"position": [
-54.96,
0.97,
-26.63
],
"size": [
4.71,
3.71
],
"angle": 2.704,
"variant": 3
},
{
"position": [
56.21,
0.97,
30.37
],
"size": [
4.54,
2.26
],
"angle": 0.667,
"variant": 0
},
{
"position": [
61.71,
0.97,
28.54
],
"size": [
3.17,
2.39
],
"angle": 1.407,
"variant": 1
}
];
// Convert a Babylon.js `.babylon` scene into the glTF that this example loads.
//
// node tools/babylon_to_gltf.mjs <scene.babylon> <textureDir> <outDir> [--no-bake]
//
// Run once to produce `public/models/hill_valley/`; the output is committed, so
// nothing here runs at build time. It exists because the source scene is a
// Babylon `.babylon` file — a 60 MB JSON of left-handed geometry and
// StandardMaterials — and Meep loads glTF with PBR metallic-roughness. The three
// conversions that matter are documented at their own steps below:
//
// 1. handedness left-handed Babylon → right-handed glTF
// 2. shading model Blinn-Phong specular/glossiness → metallic-roughness
// 3. second UV set Meep samples UV0 only, and this scene keeps its
// lightmaps and its wet-road spec mask on UV1
//
// (3) is the interesting one, and the reason this script rasterizes: rather than
// drop the UV1 data, each affected primitive is *baked* into a new texture in
// its own UV1 layout, and UV1 is then emitted as UV0. See `bakePrimitive`.
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
import { join, basename } from "node:path";
import sharp from "sharp";
const [, , scenePath, textureDir, outDir, ...flags] = process.argv;
if (scenePath === undefined || textureDir === undefined || outDir === undefined) {
console.error("usage: node babylon_to_gltf.mjs <scene.babylon> <textureDir> <outDir> [--no-bake]");
process.exit(2);
}
const DO_BAKE = !flags.includes("--no-bake");
const OUT_TEXTURES = join(outDir, "textures");
mkdirSync(OUT_TEXTURES, { recursive: true });
// Meshes that carry no geometry anyone should see: a camera look-at helper and
// the exporter's own metadata node.
//
// `Ciel` is the scene's sky dome, and it is dropped for a different reason: its
// sky is baked into the environment map instead (see bake_sky_environment.mjs).
// Meep's environment map is already what the background pass draws, so keeping
// the dome would mean two skies again — and they were different photographs,
// which is the mismatch the bake exists to fix. Dropping it also pulls the
// scene's radius in from 556 units to 203, so the far plane can come down with
// it and the depth buffer SSR traces through gets the precision back.
const SKIP_MESHES = new Set(["Camera01.Target", "EnoData", "Ciel"]);
// ─── Material tuning ──────────────────────────────────────────────────────
//
// Blinn-Phong has no notion of metalness and its "specular colour" is a free
// parameter an artist dialled in by eye, so the conversion below is a
// reasonable-looking default rather than a recovery of something that was ever
// there. These are the surfaces the demo is actually about, tuned by hand
// against the render: the shopfront glazing, the wet road, and the DeLorean's
// stainless-steel body. Keyed by Babylon material name.
const MATERIAL_TUNING = {
// Shopfront glazing. These are separate, opaque panes laid over each
// storefront, sharing the building's own baked texture — which is why they
// can stay in the G-buffer and take screen-space reflections, unlike the
// genuinely see-through `vitre_*` windows further down.
"Bank2": { roughness: 0.06, ior: 1.9 },
"Texaco2": { roughness: 0.06, ior: 1.9 },
"western_auto2": { roughness: 0.07, ior: 1.9 },
"sherwinn2": { roughness: 0.07, ior: 1.9 },
"Habt2": { roughness: 0.06, ior: 1.9 },
"roys_records2": { roughness: 0.07, ior: 1.9 },
"Foster2": { roughness: 0.09, ior: 1.8 },
"blue_bird2": { roughness: 0.08, ior: 1.8 },
"Ruth2": { roughness: 0.09, ior: 1.8 },
"Armstrong1": { roughness: 0.08, ior: 1.8 },
"DLporte2": { roughness: 0.10, ior: 1.7 },
"courthouse_vitre_02": { roughness: 0.10, ior: 1.7 },
// The DeLorean: brushed stainless steel, so an actual metal. Its wheels and
// trim stay dielectric.
"Ext Carrosserie": { roughness: 0.22, metallic: 1.0 },
"D1_ext_carrosserie_plate": { roughness: 0.35, metallic: 1.0 },
// Damp asphalt, not a mirror.
//
// The scene ships a specular mask for this road saying where it stands in
// water — on UV1, alongside the lightmap, and unreachable without flattening
// the road's 70× tiling into its UV1 layout (see `bakePrimitive`). Making
// the whole road glossy instead is the wrong answer in the other direction:
// an evenly polished road has no shape to its reflections, which is the one
// thing the example exists to show. So the road stays close to dry and the
// water is placed on it as puddle decals, from that same mask — see
// `tools/make_puddles.mjs`.
"New road": { roughness: 0.62, metallic: 0.0 },
"Parking lot": { roughness: 0.6 },
"Trottoir": { roughness: 0.7 },
"Trottoir2": { roughness: 0.7 },
"Trottoir3": { roughness: 0.7 },
// See-through glass. Transmissive, so Meep renders it in the forward
// transparent pass — after the G-buffer, which is why these panes show the
// environment rather than a screen-space reflection.
"vitre_trans_n": { roughness: 0.05, transmission: 0.9, ior: 1.5 },
"vitre_trans_s": { roughness: 0.05, transmission: 0.85, ior: 1.5 },
"memorial_vitre": { roughness: 0.05, transmission: 0.85, ior: 1.5 },
"D1_vitre_ext": { roughness: 0.05, transmission: 0.9, ior: 1.5 },
"delorean_vitre_int": { roughness: 0.08, transmission: 0.9, ior: 1.5 },
"Schwinn2": { roughness: 0.08, transmission: 0.7, ior: 1.5 },
};
// The painted mountain backdrops are lit in their own texture and must not be
// shaded again — they are emitted as pure emissive so they read as a distant
// horizon rather than as geometry standing in the scene's sunlight. (The sky
// dome used to be here too, before it moved into the environment map.)
const UNLIT_MATERIALS = new Set(["fond_mountain"]);
/**
* What an unlit backdrop's white point is worth, in the scene's photometric
* units.
*
* An 8-bit photograph carries no absolute brightness: decoded, its whitest pixel
* is 1.0. That is nothing beside a sun of 70, so a backdrop emitted at
* photographic scale is some forty times too dim and renders as a black
* silhouette against a sky that is lit correctly — which reads as a missing
* texture rather than as a units mismatch.
*
* **This must track `SKY_RADIANCE` in the example.** The mountain photograph and
* the sky photograph were taken of the same daylight, so putting them on the
* same white point is what makes the mountain sit at the right brightness
* against the sky behind it, without anyone grading it by eye.
*/
const BACKDROP_RADIANCE = 22;
// ─── Load ─────────────────────────────────────────────────────────────────
const scene = JSON.parse(readFileSync(scenePath, "utf8"));
const materialsById = new Map(scene.materials.map((m) => [m.id, m]));
const multiMaterialsById = new Map(scene.multiMaterials.map((m) => [m.id, m]));
/**
* Babylon's specular exponent is a Blinn-Phong lobe width; glTF roughness is a
* GGX perceptual roughness. `alpha = sqrt(2/(n+2))` is the usual lobe-matching
* identity, and glTF's roughness is its square root.
*
* A material with a black specular colour has no highlight at all in Babylon,
* so the exponent it carries is meaningless — those are pinned matte instead.
*/
function roughnessFromBlinnPhong(specularPower, specularMagnitude) {
if (specularMagnitude < 0.02) return 0.85;
const alpha = Math.sqrt(2 / (Math.max(specularPower, 2) + 2));
const roughness = Math.sqrt(alpha);
// A brighter specular colour reads as a tighter, glossier surface, which the
// exponent alone does not capture.
return Math.min(1, Math.max(0.04, roughness * (1 - 0.45 * specularMagnitude)));
}
// ─── Texture registry ─────────────────────────────────────────────────────
//
// Several materials share a texture and a few names carry stray spaces
// ("route_LM .jpg"), so names are sanitised once and deduplicated.
const textureFiles = new Map(); // sanitised file name → glTF image index
const gltfImages = [];
const gltfTextures = [];
const gltfSamplers = [{ wrapS: 10497, wrapT: 10497, magFilter: 9729, minFilter: 9987 }];
function sanitize(name) {
return name.replace(/\s+(?=\.[A-Za-z0-9]+$)/, "").replace(/[^A-Za-z0-9._-]/g, "_");
}
/** Register a file that already exists in `OUT_TEXTURES`, returning its texture index. */
function registerTextureFile(fileName) {
const existing = textureFiles.get(fileName);
if (existing !== undefined) return existing;
const imageIndex = gltfImages.length;
gltfImages.push({ uri: `textures/${fileName}` });
const textureIndex = gltfTextures.length;
gltfTextures.push({ sampler: 0, source: imageIndex });
textureFiles.set(fileName, textureIndex);
return textureIndex;
}
const copied = new Set();
/** Copy a source texture through to the output folder and register it. */
async function useSourceTexture(babylonName) {
const fileName = sanitize(babylonName).replace(/\.[^.]+$/, ".png");
const dest = join(OUT_TEXTURES, fileName);
if (!copied.has(fileName)) {
const src = join(textureDir, babylonName);
if (!existsSync(src)) {
console.warn(` missing texture: ${babylonName}`);
return undefined;
}
// Re-encode rather than copy: a few of the source PNGs are 8-bit
// palettes that decoders disagree about, and this normalises them.
// Lossless working assets avoid another generation of JPEG artifacts.
await sharp(src).png({ compressionLevel: 9 }).toFile(dest);
copied.add(fileName);
}
return registerTextureFile(fileName);
}
// ─── Image cache for the bake ─────────────────────────────────────────────
const rasterCache = new Map();
/** Decode a source texture to raw RGBA once, for sampling during the bake. */
async function loadRaster(babylonName) {
if (rasterCache.has(babylonName)) return rasterCache.get(babylonName);
const src = join(textureDir, babylonName);
if (!existsSync(src)) {
rasterCache.set(babylonName, undefined);
return undefined;
}
const { data, info } = await sharp(src).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
const raster = { data, width: info.width, height: info.height };
rasterCache.set(babylonName, raster);
return raster;
}
/**
* Bilinear sample with wrapping.
*
* Nearest is not good enough here even though this is "just" a bake. Every
* source in a bake is being resampled at some ratio — a lightmap island is
* magnified several times over, a tiled diffuse is walked at a fraction of a
* texel per step — and nearest turns the first into visible blocks and the
* second into aliasing. Both read as "the texture is low resolution" rather than
* as a filtering choice.
*/
function sampleWrapped(raster, u, v, out) {
const { data, width, height } = raster;
const x = u * width - 0.5;
const y = v * height - 0.5;
const x0 = Math.floor(x), y0 = Math.floor(y);
const fx = x - x0, fy = y - y0;
const wrap = (n, size) => ((n % size) + size) % size;
const ix0 = wrap(x0, width), iy0 = wrap(y0, height);
const ix1 = wrap(x0 + 1, width), iy1 = wrap(y0 + 1, height);
const i00 = (iy0 * width + ix0) * 4, i10 = (iy0 * width + ix1) * 4;
const i01 = (iy1 * width + ix0) * 4, i11 = (iy1 * width + ix1) * 4;
for (let c = 0; c < 4; c++) {
const top = data[i00 + c] * (1 - fx) + data[i10 + c] * fx;
const bottom = data[i01 + c] * (1 - fx) + data[i11 + c] * fx;
out[c] = top * (1 - fy) + bottom * fy;
}
}
// ─── Buffer assembly ──────────────────────────────────────────────────────
const chunks = [];
let bufferLength = 0;
const gltfBufferViews = [];
const gltfAccessors = [];
function pushBufferView(typedArray, target) {
// glTF requires accessor offsets to be aligned to their component size.
const padding = (4 - (bufferLength % 4)) % 4;
if (padding > 0) {
chunks.push(Buffer.alloc(padding));
bufferLength += padding;
}
const buf = Buffer.from(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
chunks.push(buf);
const view = { buffer: 0, byteOffset: bufferLength, byteLength: buf.length };
if (target !== undefined) view.target = target;
gltfBufferViews.push(view);
bufferLength += buf.length;
return gltfBufferViews.length - 1;
}
const COMPONENT = { f32: 5126, u16: 5123, u32: 5125 };
function pushAccessor(typedArray, componentType, type, count, target, minMax) {
const view = pushBufferView(typedArray, target);
const accessor = { bufferView: view, componentType, count, type };
if (minMax !== undefined) {
accessor.min = minMax.min;
accessor.max = minMax.max;
}
gltfAccessors.push(accessor);
return gltfAccessors.length - 1;
}
// ─── Materials ────────────────────────────────────────────────────────────
const gltfMaterials = [];
const materialIndexByKey = new Map();
/**
* Convert one Babylon StandardMaterial into a glTF material.
*
* `bake` is the result of `bakePrimitive` when this primitive was baked, in
* which case the baked textures replace the material's own.
*/
async function buildMaterial(babylonMaterial, bake, tint) {
// A baked primitive gets its own material: the bake is per-primitive, so two
// primitives sharing a Babylon material do not share the baked texture. A
// lightmap tint is per-primitive for the same reason, so it joins the key.
const key = bake !== undefined
? `baked:${bake.id}`
: `plain:${babylonMaterial.id}:${tint?.map((v) => v.toFixed(3)).join(",") ?? ""}`;
const existing = materialIndexByKey.get(key);
if (existing !== undefined) return existing;
const name = babylonMaterial.name;
const tuning = MATERIAL_TUNING[name] ?? {};
const specular = babylonMaterial.specular ?? [0, 0, 0, 1];
const specularMagnitude = Math.max(specular[0], specular[1], specular[2]);
const base = tint ?? [1, 1, 1];
const material = {
name,
pbrMetallicRoughness: {
baseColorFactor: [base[0], base[1], base[2], babylonMaterial.alpha ?? 1],
metallicFactor: tuning.metallic ?? 0,
roughnessFactor: tuning.roughness
?? roughnessFromBlinnPhong(babylonMaterial.specularPower ?? 10, specularMagnitude),
},
};
// ── base colour ──
if (bake !== undefined) {
material.pbrMetallicRoughness.baseColorTexture = { index: registerTextureFile(bake.albedoFile) };
if (bake.ormFile !== undefined) {
material.pbrMetallicRoughness.metallicRoughnessTexture = { index: registerTextureFile(bake.ormFile) };
}
} else if (babylonMaterial.diffuseTexture) {
const index = await useSourceTexture(babylonMaterial.diffuseTexture.name);
if (index !== undefined) material.pbrMetallicRoughness.baseColorTexture = { index };
} else if (babylonMaterial.opacityTexture) {
// `Fils` — overhead wires drawn purely by an opacity mask, with no
// colour of their own. The mask doubles as the base colour so the
// alpha test has something to read.
const index = await useSourceTexture(babylonMaterial.opacityTexture.name);
if (index !== undefined) material.pbrMetallicRoughness.baseColorTexture = { index };
material.pbrMetallicRoughness.baseColorFactor = [0.05, 0.05, 0.05, 1];
}
// ── transparency ──
const hasAlphaTexture = babylonMaterial.diffuseTexture?.hasAlpha === true
|| babylonMaterial.opacityTexture !== null && babylonMaterial.opacityTexture !== undefined;
const alpha = babylonMaterial.alpha ?? 1;
if (tuning.transmission !== undefined) {
material.extensions = material.extensions ?? {};
material.extensions.KHR_materials_transmission = { transmissionFactor: tuning.transmission };
material.alphaMode = "BLEND";
// Transmission carries the see-through; a low base alpha on top of it
// would double the effect and wash the pane out.
material.pbrMetallicRoughness.baseColorFactor = [base[0], base[1], base[2], 1];
} else if (alpha < 1) {
material.alphaMode = "BLEND";
} else if (hasAlphaTexture) {
// Foliage, wires and grilles: cut out, not blended, so they stay in the
// G-buffer and keep taking shadows and reflections.
material.alphaMode = "MASK";
material.alphaCutoff = 0.4;
}
if (tuning.ior !== undefined) {
material.extensions = material.extensions ?? {};
material.extensions.KHR_materials_ior = { ior: tuning.ior };
}
// ── unlit backdrops ──
if (UNLIT_MATERIALS.has(name)) {
const texture = material.pbrMetallicRoughness.baseColorTexture;
if (texture !== undefined) material.emissiveTexture = { index: texture.index };
material.emissiveFactor = [1, 1, 1];
// glTF's emissiveFactor is capped at 1, which is exactly the range that
// is too small here; KHR_materials_emissive_strength is the extension
// that exists to lift it, and Meep reads it.
material.extensions = material.extensions ?? {};
material.extensions.KHR_materials_emissive_strength = { emissiveStrength: BACKDROP_RADIANCE };
// Black base colour so the sun and the environment add nothing on top.
material.pbrMetallicRoughness.baseColorFactor = [0, 0, 0, 1];
material.pbrMetallicRoughness.roughnessFactor = 1;
}
// Babylon's `backFaceCulling: false` is glTF's `doubleSided`. The Babylon
// playground additionally forces it on two meshes whose exported flag is
// wrong; both are named here.
if (babylonMaterial.backFaceCulling === false || name === "Fils" || name === "cabane bois2") {
material.doubleSided = true;
}
// Alpha-masked foliage is modelled as single-sided cards, which disappear
// from half the orbit unless drawn from both sides.
if (material.alphaMode === "MASK") material.doubleSided = true;
gltfMaterials.push(material);
const index = gltfMaterials.length - 1;
materialIndexByKey.set(key, index);
return index;
}
// ─── The UV1 bake ─────────────────────────────────────────────────────────
//
// Meep samples UV0 only. This scene puts real data on UV1: a baked lightmap in
// `ambientTexture` (the ground's entire sense of light and shadow — its UV0 is a
// 70× tiled asphalt/grass texture that carries none of it) and, for the road, a
// specular mask marking where the surface is wet.
//
// Both are recovered by rasterizing the primitive in its own UV1 layout: for
// every texel, interpolate UV0 and UV1 across the triangle covering it, and
// write `diffuse(UV0 · uvScale) × lightmap(UV1)`. UV1 then becomes the emitted
// UV0. The same pass writes an ORM texture whose roughness channel is the
// inverted spec mask, so the wet road is the surface screen-space reflections
// land on hardest.
let bakeCounter = 0;
/**
* Largest bake this will produce, and equally the point past which it declines
* to bake at all. 2048 is about where a single ground primitive stops being
* worth its share of the download; nothing in this scene that stays under it
* loses meaningful detail.
*/
const MAX_BAKE_SIZE = 2048;
const skippedBakes = [];
async function bakePrimitive(babylonMaterial, positionsUV0, positionsUV1, indices) {
const diffuse = babylonMaterial.diffuseTexture;
const lightmap = babylonMaterial.ambientTexture;
const specular = babylonMaterial.specularTexture;
const diffuseRaster = diffuse ? await loadRaster(diffuse.name) : undefined;
const lightmapRaster = lightmap ? await loadRaster(lightmap.name) : undefined;
const specularRaster = specular?.coordinatesIndex === 1 ? await loadRaster(specular.name) : undefined;
if (lightmapRaster === undefined && specularRaster === undefined) return undefined;
// ── target resolution ──
//
// The resolution has to come from the *diffuse*, not the lightmap. A bake
// replaces the surface's whole texture, so it has to carry the finest thing
// that was on it — and the finest thing is almost never the lightmap, which
// is soft by construction. Sizing from the lightmap island instead (the
// obvious thing, since that is the layout being baked into) silently drops
// the diffuse to the lightmap's density: this scene's pavement is a texture
// tiled 386 times, and it was landing in 1024 pixels.
let uMin = Infinity, uMax = -Infinity, vMin = Infinity, vMax = -Infinity;
for (let i = 0; i < positionsUV1.length; i += 2) {
uMin = Math.min(uMin, positionsUV1[i]);
uMax = Math.max(uMax, positionsUV1[i]);
vMin = Math.min(vMin, positionsUV1[i + 1]);
vMax = Math.max(vMax, positionsUV1[i + 1]);
}
const spanU = Math.max(1e-4, uMax - uMin);
const spanV = Math.max(1e-4, vMax - vMin);
// How many diffuse texels the primitive actually spans, tiling included.
let uv0Min = Infinity, uv0Max = -Infinity, uv0MinV = Infinity, uv0MaxV = -Infinity;
for (let i = 0; i < positionsUV0.length; i += 2) {
uv0Min = Math.min(uv0Min, positionsUV0[i]);
uv0Max = Math.max(uv0Max, positionsUV0[i]);
uv0MinV = Math.min(uv0MinV, positionsUV0[i + 1]);
uv0MaxV = Math.max(uv0MaxV, positionsUV0[i + 1]);
}
const uScale = diffuse?.uScale ?? 1;
const vScale = diffuse?.vScale ?? 1;
const diffuseDetailU = diffuseRaster ? (uv0Max - uv0Min) * uScale * diffuseRaster.width : 0;
const diffuseDetailV = diffuseRaster ? (uv0MaxV - uv0MinV) * vScale * diffuseRaster.height : 0;
// ── or refuse to bake at all ──
//
// Past a point this stops being a resolution question. A surface tiled 70
// times needs 35,000 pixels to survive being flattened into a unique layout,
// and no cap makes that affordable — the honest answer is that a tiled
// surface cannot also carry a lightmap when the renderer samples one UV set,
// and the tiling is worth more. Those primitives keep UV0 and their own
// crisp texture, and give up their lightmap; the real-time sun and GTAO were
// already doing most of that job, whereas nothing else can put the detail
// back.
if (diffuseDetailU > MAX_BAKE_SIZE || diffuseDetailV > MAX_BAKE_SIZE) {
skippedBakes.push(
`${babylonMaterial.name}: needs ${Math.round(diffuseDetailU)}x${Math.round(diffuseDetailV)}`
);
return undefined;
}
const atlas = lightmapRaster ?? specularRaster;
const clampSize = (n) => Math.max(64, Math.min(MAX_BAKE_SIZE, 1 << Math.ceil(Math.log2(Math.max(1, n)))));
const width = clampSize(Math.max(diffuseDetailU, spanU * atlas.width));
const height = clampSize(Math.max(diffuseDetailV, spanV * atlas.height));
// Foliage, grilles and billboards are cut-outs: their diffuse texture is a
// leaf or a sign on a black field, and the alpha channel is the whole of the
// shape. Baking those to RGB drops the cut-out and every tree in the scene
// becomes an opaque black card — so a primitive whose diffuse carries alpha
// is baked to RGBA and written as PNG.
const keepsAlpha = diffuse?.hasAlpha === true && diffuseRaster !== undefined;
const channels = keepsAlpha ? 4 : 3;
const albedo = Buffer.alloc(width * height * channels);
const orm = specularRaster ? Buffer.alloc(width * height * 3) : undefined;
const covered = new Uint8Array(width * height);
// Bilinear sampling returns fractional values, so these are floats now.
const dRGBA = new Float64Array(4);
const lRGBA = new Float64Array(4);
const sRGBA = new Float64Array(4);
// ── rasterize ──
for (let t = 0; t < indices.length; t += 3) {
const a = indices[t], b = indices[t + 1], c = indices[t + 2];
// Triangle in the *cropped* UV1 space, in texels.
const ax = ((positionsUV1[a * 2] - uMin) / spanU) * width;
const ay = ((positionsUV1[a * 2 + 1] - vMin) / spanV) * height;
const bx = ((positionsUV1[b * 2] - uMin) / spanU) * width;
const by = ((positionsUV1[b * 2 + 1] - vMin) / spanV) * height;
const cx = ((positionsUV1[c * 2] - uMin) / spanU) * width;
const cy = ((positionsUV1[c * 2 + 1] - vMin) / spanV) * height;
const area = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
if (Math.abs(area) < 1e-9) continue;
// Expand by a texel so adjacent islands meet rather than leaving a seam.
const x0 = Math.max(0, Math.floor(Math.min(ax, bx, cx)) - 1);
const x1 = Math.min(width - 1, Math.ceil(Math.max(ax, bx, cx)) + 1);
const y0 = Math.max(0, Math.floor(Math.min(ay, by, cy)) - 1);
const y1 = Math.min(height - 1, Math.ceil(Math.max(ay, by, cy)) + 1);
for (let y = y0; y <= y1; y++) {
for (let x = x0; x <= x1; x++) {
const px = x + 0.5, py = y + 0.5;
let w0 = ((bx - px) * (cy - py) - (cx - px) * (by - py)) / area;
let w1 = ((cx - px) * (ay - py) - (ax - px) * (cy - py)) / area;
let w2 = 1 - w0 - w1;
// A small negative tolerance fills the expanded border, which the
// dilation below then relies on.
if (w0 < -0.06 || w1 < -0.06 || w2 < -0.06) continue;
w0 = Math.max(0, w0); w1 = Math.max(0, w1); w2 = Math.max(0, w2);
const sum = w0 + w1 + w2 || 1;
w0 /= sum; w1 /= sum; w2 /= sum;
const u0 = (positionsUV0[a * 2] * w0 + positionsUV0[b * 2] * w1 + positionsUV0[c * 2] * w2) * uScale;
const v0 = (positionsUV0[a * 2 + 1] * w0 + positionsUV0[b * 2 + 1] * w1 + positionsUV0[c * 2 + 1] * w2) * vScale;
const u1 = positionsUV1[a * 2] * w0 + positionsUV1[b * 2] * w1 + positionsUV1[c * 2] * w2;
const v1 = positionsUV1[a * 2 + 1] * w0 + positionsUV1[b * 2 + 1] * w1 + positionsUV1[c * 2 + 1] * w2;
const texel = y * width + x;
const o = texel * channels;
if (diffuseRaster) sampleWrapped(diffuseRaster, u0, v0, dRGBA);
else { dRGBA[0] = dRGBA[1] = dRGBA[2] = 255; dRGBA[3] = 255; }
if (lightmapRaster) sampleWrapped(lightmapRaster, u1, v1, lRGBA);
else { lRGBA[0] = lRGBA[1] = lRGBA[2] = 255; }
albedo[o] = (dRGBA[0] * lRGBA[0]) / 255;
albedo[o + 1] = (dRGBA[1] * lRGBA[1]) / 255;
albedo[o + 2] = (dRGBA[2] * lRGBA[2]) / 255;
if (keepsAlpha) albedo[o + 3] = dRGBA[3];
if (orm !== undefined) {
sampleWrapped(specularRaster, u1, v1, sRGBA);
// ORM: R occlusion (unused), G roughness, B metalness.
// A bright spec mask means a polished, wet patch.
const p = texel * 3;
orm[p] = 255;
orm[p + 1] = 255 - sRGBA[0];
orm[p + 2] = 0;
}
covered[texel] = 1;
}
}
}
// ── dilate ──
//
// Bilinear filtering and mip generation both reach past an island's edge, so
// uncovered texels are flooded from their neighbours to keep black seams
// from bleeding in.
// Colour is flooded outward; alpha is not, so a texel outside the island
// stays cut away rather than growing the leaf it borrowed its colour from.
dilate(albedo, covered.slice(), width, height, 4, channels);
if (orm !== undefined) dilate(orm, covered.slice(), width, height, 4, 3);
const id = bakeCounter++;
const albedoFile = `baked_${id}_albedo.png`;
const albedoImage = sharp(albedo, { raw: { width, height, channels } });
await albedoImage.png({ compressionLevel: 9 }).toFile(join(OUT_TEXTURES, albedoFile));
let ormFile;
if (orm !== undefined) {
// PNG, not JPEG. An ORM map is three independent scalars that happen to
// be stored in colour channels — and JPEG's chroma subsampling averages
// exactly those channels away, smearing roughness across a 2x2 block and
// then ringing it at every edge. Reflections come out blurred and
// blotchy for a reason that looks like a renderer bug.
ormFile = `baked_${id}_orm.png`;
await sharp(orm, { raw: { width, height, channels: 3 } })
.png({ compressionLevel: 9 })
.toFile(join(OUT_TEXTURES, ormFile));
}
return { id, albedoFile, ormFile, uMin, vMin, spanU, spanV, width, height };
}
/**
* The area-weighted mean of a primitive's lightmap, as a linear 0..1 tint.
*
* Sampled at triangle centroids rather than at vertices: a vertex sits on the
* edge of its UV island, where the atlas holds gutter pixels that belong to no
* surface. Weighted by 3D area so a floor made of one huge quad and a hundred
* small ones still averages to what the floor actually looks like.
*
* @returns {number[]} rgb, each 0..1
*/
async function averageLightmap(babylonMaterial, positions, uv1, indices) {
const lightmap = await loadRaster(babylonMaterial.ambientTexture.name);
if (lightmap === undefined) return undefined;
const sample = new Float64Array(4);
let r = 0, g = 0, b = 0, weight = 0;
for (let t = 0; t + 2 < indices.length; t += 3) {
const a = indices[t], b2 = indices[t + 1], c = indices[t + 2];
const e1x = positions[b2 * 3] - positions[a * 3];
const e1y = positions[b2 * 3 + 1] - positions[a * 3 + 1];
const e1z = positions[b2 * 3 + 2] - positions[a * 3 + 2];
const e2x = positions[c * 3] - positions[a * 3];
const e2y = positions[c * 3 + 1] - positions[a * 3 + 1];
const e2z = positions[c * 3 + 2] - positions[a * 3 + 2];
const cx = e1y * e2z - e1z * e2y;
const cy = e1z * e2x - e1x * e2z;
const cz = e1x * e2y - e1y * e2x;
const area = Math.hypot(cx, cy, cz) * 0.5;
if (!(area > 0)) continue;
const u = (uv1[a * 2] + uv1[b2 * 2] + uv1[c * 2]) / 3;
const v = (uv1[a * 2 + 1] + uv1[b2 * 2 + 1] + uv1[c * 2 + 1]) / 3;
sampleWrapped(lightmap, u, v, sample);
r += sample[0] * area;
g += sample[1] * area;
b += sample[2] * area;
weight += area;
}
if (weight === 0) return undefined;
return [r / weight / 255, g / weight / 255, b / weight / 255];
}
function dilate(pixels, covered, width, height, passes, channels) {
for (let pass = 0; pass < passes; pass++) {
const added = [];
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const i = y * width + x;
if (covered[i]) continue;
let r = 0, g = 0, b = 0, n = 0;
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) {
const nx = x + dx, ny = y + dy;
if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;
const j = ny * width + nx;
if (!covered[j]) continue;
const o = j * channels;
r += pixels[o]; g += pixels[o + 1]; b += pixels[o + 2]; n++;
}
}
if (n === 0) continue;
const o = i * channels;
pixels[o] = r / n; pixels[o + 1] = g / n; pixels[o + 2] = b / n;
added.push(i);
}
}
for (const i of added) covered[i] = 1;
if (added.length === 0) break;
}
}
// ─── The pre-transform ────────────────────────────────────────────────────
//
// Most meshes here are unrotated and unscaled, with a `position` and nothing
// else — but 21 are not, and they carry it in `localMatrix` rather than in
// `rotation`/`scaling`. Babylon's loader feeds that to `setPreTransformMatrix`,
// which makes it a pivot applied *before* the node's own transform:
//
// p_world = p · localMatrix + position
//
// (row-vector convention, which is Babylon's). Every DeLorean part is one of
// these — modelled at ~5.6× and rotated — so ignoring it leaves the car's body,
// glass and wheels at five times their size, scattered across the square in
// different directions. It reads as junk geometry rather than as a transform
// bug, which is why it is worth naming here.
const IDENTITY_4 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
/** The 3×3 linear part and the translation of a Babylon row-major 4×4. */
function parsePreTransform(localMatrix) {
if (localMatrix === undefined || localMatrix === null) return undefined;
if (localMatrix.every((v, i) => Math.abs(v - IDENTITY_4[i]) < 1e-9)) return undefined;
const m = [
[localMatrix[0], localMatrix[1], localMatrix[2]],
[localMatrix[4], localMatrix[5], localMatrix[6]],
[localMatrix[8], localMatrix[9], localMatrix[10]],
];
const determinant =
m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
- m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
// Normals do not ride along a scale the way positions do; they need the
// inverse transpose. It matters here because these matrices are a scale
// *and* a rotation, and a normal put through the raw matrix comes out
// shortened and — for anything non-uniform — pointing the wrong way.
const inverseTranspose = [
[
(m[1][1] * m[2][2] - m[1][2] * m[2][1]) / determinant,
(m[1][2] * m[2][0] - m[1][0] * m[2][2]) / determinant,
(m[1][0] * m[2][1] - m[1][1] * m[2][0]) / determinant,
],
[
(m[0][2] * m[2][1] - m[0][1] * m[2][2]) / determinant,
(m[0][0] * m[2][2] - m[0][2] * m[2][0]) / determinant,
(m[0][1] * m[2][0] - m[0][0] * m[2][1]) / determinant,
],
[
(m[0][1] * m[1][2] - m[0][2] * m[1][1]) / determinant,
(m[0][2] * m[1][0] - m[0][0] * m[1][2]) / determinant,
(m[0][0] * m[1][1] - m[0][1] * m[1][0]) / determinant,
],
];
return {
m,
inverseTranspose,
translation: [localMatrix[12], localMatrix[13], localMatrix[14]],
determinant,
};
}
// ─── Winding check ────────────────────────────────────────────────────────
//
// The handedness conversion is the one mistake in this script that does not
// look like a mistake — an inside-out scene renders as a town of black cut-outs,
// not as an obviously inverted one. So the invariant is asserted rather than
// trusted: the normal implied by a triangle's winding must point the same way as
// the vertex normal the exporter wrote.
let windingChecked = 0;
let windingFlipped = 0;
function checkWinding(name, positions, normals, indices) {
if (normals === undefined) return;
let agree = 0;
let disagree = 0;
for (let t = 0; t + 2 < indices.length && t < 900; t += 3) {
const a = indices[t], b = indices[t + 1], c = indices[t + 2];
const e1x = positions[b * 3] - positions[a * 3];
const e1y = positions[b * 3 + 1] - positions[a * 3 + 1];
const e1z = positions[b * 3 + 2] - positions[a * 3 + 2];
const e2x = positions[c * 3] - positions[a * 3];
const e2y = positions[c * 3 + 1] - positions[a * 3 + 1];
const e2z = positions[c * 3 + 2] - positions[a * 3 + 2];
const gx = e1y * e2z - e1z * e2y;
const gy = e1z * e2x - e1x * e2z;
const gz = e1x * e2y - e1y * e2x;
const length = Math.hypot(gx, gy, gz);
if (length < 1e-12) continue;
const dot = (gx * normals[a * 3] + gy * normals[a * 3 + 1] + gz * normals[a * 3 + 2]) / length;
if (dot > 0.2) agree++;
else if (dot < -0.2) disagree++;
}
windingChecked++;
if (disagree > agree) {
windingFlipped++;
console.warn(` ${name}: winding disagrees with vertex normals (${disagree} vs ${agree})`);
}
}
// ─── Meshes ───────────────────────────────────────────────────────────────
const gltfMeshes = [];
const gltfNodes = [];
let bakedCount = 0;
let primitiveCount = 0;
for (const mesh of scene.meshes) {
if (SKIP_MESHES.has(mesh.name)) continue;
if (mesh.isVisible === false || mesh.isEnabled === false) continue;
if (!mesh.positions || !mesh.indices || mesh.indices.length === 0) continue;
const positions = mesh.positions;
const normals = mesh.normals;
const uvs = mesh.uvs;
const uvs2 = mesh.uvs2;
const indices = mesh.indices;
// Resolve the material list: a multi-material mesh has one entry per
// submesh, a single-material mesh has exactly one.
const multi = multiMaterialsById.get(mesh.materialId);
const submeshes = mesh.subMeshes ?? [{ materialIndex: 0, indexStart: 0, indexCount: indices.length }];
const pre = parsePreTransform(mesh.localMatrix);
// A pre-transform that mirrors flips triangle orientation a second time,
// which cancels the handedness conversion below. None of this scene's do,
// but the check is cheap and its absence is invisible until something
// renders inside-out.
const flipWinding = pre !== undefined && pre.determinant < 0;
const primitives = [];
for (const sub of submeshes) {
const babylonMaterial = multi
? materialsById.get(multi.materials[sub.materialIndex])
: materialsById.get(mesh.materialId);
if (babylonMaterial === undefined) {
console.warn(` ${mesh.name}: submesh ${sub.materialIndex} has no material, skipped`);
continue;
}
// ── compact the submesh into its own vertex buffer ──
//
// Every primitive gets its own vertices. Submeshes of one mesh can want
// different UV sets (a baked primitive emits UV1 where its neighbour
// emits UV0) and different tiling scales, so a shared vertex buffer
// cannot serve them.
const slice = indices.slice(sub.indexStart, sub.indexStart + sub.indexCount);
const remap = new Map();
const localIndices = new Uint32Array(slice.length);
for (let i = 0; i < slice.length; i++) {
const source = slice[i];
let local = remap.get(source);
if (local === undefined) {
local = remap.size;
remap.set(source, local);
}
localIndices[i] = local;
}
const vertexCount = remap.size;
if (vertexCount === 0) continue;
const outPositions = new Float32Array(vertexCount * 3);
const outNormals = normals ? new Float32Array(vertexCount * 3) : undefined;
const outUV0 = uvs ? new Float32Array(vertexCount * 2) : undefined;
const outUV1 = uvs2 ? new Float32Array(vertexCount * 2) : undefined;
for (const [source, local] of remap) {
let px = positions[source * 3];
let py = positions[source * 3 + 1];
let pz = positions[source * 3 + 2];
let nx = normals ? normals[source * 3] : 0;
let ny = normals ? normals[source * 3 + 1] : 0;
let nz = normals ? normals[source * 3 + 2] : 0;
if (pre !== undefined) {
const [r0, r1, r2] = pre.m;
const x = px * r0[0] + py * r1[0] + pz * r2[0] + pre.translation[0];
const y = px * r0[1] + py * r1[1] + pz * r2[1] + pre.translation[1];
const z = px * r0[2] + py * r1[2] + pz * r2[2] + pre.translation[2];
px = x; py = y; pz = z;
if (normals) {
const [i0, i1, i2] = pre.inverseTranspose;
const ax = nx * i0[0] + ny * i1[0] + nz * i2[0];
const ay = nx * i0[1] + ny * i1[1] + nz * i2[1];
const az = nx * i0[2] + ny * i1[2] + nz * i2[2];
const length = Math.hypot(ax, ay, az) || 1;
nx = ax / length; ny = ay / length; nz = az / length;
}
}
// ── handedness ──
//
// Babylon is left-handed (+Z forward), glTF is right-handed
// (+Z toward the viewer), so the conversion is a mirror in Z.
//
// The winding is deliberately left alone (unless the pre-transform
// itself mirrors — see `flipWinding`). A mirror does flip triangle
// orientation, but Babylon's front faces are clockwise where glTF's
// are counter-clockwise, and those two flips cancel. Reversing the
// indices as well leaves every triangle facing into its own surface:
// the scene then renders as the *insides* of its buildings, lit by
// vertex normals pointing away from the camera, which reads as a
// town of black cut-outs rather than as an obviously inside-out one.
// `checkWinding` below is what catches this either way.
outPositions[local * 3] = px;
outPositions[local * 3 + 1] = py;
outPositions[local * 3 + 2] = -pz;
if (outNormals !== undefined) {
outNormals[local * 3] = nx;
outNormals[local * 3 + 1] = ny;
outNormals[local * 3 + 2] = -nz;
}
// Babylon's V runs bottom-up, glTF's runs top-down.
if (outUV0 !== undefined) {
outUV0[local * 2] = uvs[source * 2];
outUV0[local * 2 + 1] = 1 - uvs[source * 2 + 1];
}
if (outUV1 !== undefined) {
outUV1[local * 2] = uvs2[source * 2];
outUV1[local * 2 + 1] = 1 - uvs2[source * 2 + 1];
}
}
if (flipWinding) {
for (let i = 0; i < localIndices.length; i += 3) {
const swap = localIndices[i + 1];
localIndices[i + 1] = localIndices[i + 2];
localIndices[i + 2] = swap;
}
}
// ── bake, if this primitive has anything on UV1 ──
let bake;
const wantsBake = babylonMaterial.ambientTexture !== null && babylonMaterial.ambientTexture !== undefined
|| babylonMaterial.specularTexture?.coordinatesIndex === 1;
let tint;
if (DO_BAKE && wantsBake && outUV1 !== undefined && outUV0 !== undefined) {
bake = await bakePrimitive(babylonMaterial, outUV0, outUV1, localIndices);
if (bake !== undefined) {
bakedCount++;
} else if (babylonMaterial.ambientTexture) {
// The bake was declined, so this primitive keeps its tiling and
// loses the lightmap's *detail*. Its overall level is worth
// keeping though: a lightmap's average over a surface is a real
// measurement of how much light reached it, and throwing it away
// makes every shaded surface jump to full brightness. The road
// is the one that shows: dropped to raw asphalt it turns pale,
// its diffuse drowns the reflections, and the wet look goes with
// them. Folded into baseColorFactor instead, the tone survives
// and the real-time sun supplies the variation the map used to.
tint = await averageLightmap(babylonMaterial, outPositions, outUV1, localIndices);
}
}
// The emitted UV0 is either the material's own UV0 (with its tiling
// folded in, since Meep has no texture transform) or, for a baked
// primitive, its UV1 remapped into the crop the bake used.
let emittedUV;
if (bake !== undefined) {
emittedUV = new Float32Array(vertexCount * 2);
for (let i = 0; i < vertexCount; i++) {
emittedUV[i * 2] = (outUV1[i * 2] - bake.uMin) / bake.spanU;
emittedUV[i * 2 + 1] = (outUV1[i * 2 + 1] - bake.vMin) / bake.spanV;
}
} else if (outUV0 !== undefined) {
const uScale = babylonMaterial.diffuseTexture?.uScale ?? 1;
const vScale = babylonMaterial.diffuseTexture?.vScale ?? 1;
if (uScale !== 1 || vScale !== 1) {
emittedUV = new Float32Array(vertexCount * 2);
for (let i = 0; i < vertexCount; i++) {
emittedUV[i * 2] = outUV0[i * 2] * uScale;
emittedUV[i * 2 + 1] = outUV0[i * 2 + 1] * vScale;
}
} else {
emittedUV = outUV0;
}
}
// ── accessors ──
let min = [Infinity, Infinity, Infinity];
let max = [-Infinity, -Infinity, -Infinity];
for (let i = 0; i < vertexCount; i++) {
for (let k = 0; k < 3; k++) {
const value = outPositions[i * 3 + k];
if (value < min[k]) min[k] = value;
if (value > max[k]) max[k] = value;
}
}
const attributes = {
POSITION: pushAccessor(outPositions, COMPONENT.f32, "VEC3", vertexCount, 34962, { min, max }),
};
if (outNormals !== undefined) {
attributes.NORMAL = pushAccessor(outNormals, COMPONENT.f32, "VEC3", vertexCount, 34962);
}
if (emittedUV !== undefined) {
attributes.TEXCOORD_0 = pushAccessor(emittedUV, COMPONENT.f32, "VEC2", vertexCount, 34962);
}
const useU16 = vertexCount <= 65535;
const indexArray = useU16 ? Uint16Array.from(localIndices) : localIndices;
const indexAccessor = pushAccessor(
indexArray,
useU16 ? COMPONENT.u16 : COMPONENT.u32,
"SCALAR",
indexArray.length,
34963
);
checkWinding(mesh.name, outPositions, outNormals, localIndices);
primitives.push({
attributes,
indices: indexAccessor,
material: await buildMaterial(babylonMaterial, bake, tint),
});
primitiveCount++;
}
if (primitives.length === 0) continue;
gltfMeshes.push({ name: mesh.name, primitives });
// Every mesh in this scene is an unparented, unrotated, unscaled node, so
// the only transform to carry across is the translation — mirrored in Z with
// the geometry.
const position = mesh.position ?? [0, 0, 0];
gltfNodes.push({
name: mesh.name,
mesh: gltfMeshes.length - 1,
translation: [position[0], position[1], -position[2]],
});
}
// ─── Write ────────────────────────────────────────────────────────────────
const binName = "hill_valley.bin";
const binary = Buffer.concat(chunks);
writeFileSync(join(outDir, binName), binary);
const usedExtensions = new Set();
for (const material of gltfMaterials) {
for (const key of Object.keys(material.extensions ?? {})) usedExtensions.add(key);
}
const gltf = {
asset: {
version: "2.0",
generator: "babylon_to_gltf.mjs (meep-website screen-space-reflections example)",
},
scene: 0,
scenes: [{ nodes: gltfNodes.map((_, i) => i) }],
nodes: gltfNodes,
meshes: gltfMeshes,
materials: gltfMaterials,
textures: gltfTextures,
images: gltfImages,
samplers: gltfSamplers,
accessors: gltfAccessors,
bufferViews: gltfBufferViews,
buffers: [{ uri: binName, byteLength: binary.length }],
};
if (usedExtensions.size > 0) gltf.extensionsUsed = [...usedExtensions];
writeFileSync(join(outDir, "hill_valley.gltf"), JSON.stringify(gltf));
console.log(`nodes ${gltfNodes.length}`);
console.log(`winding ${windingChecked - windingFlipped}/${windingChecked} primitives agree with their vertex normals`);
console.log(`primitives ${primitiveCount} (${bakedCount} baked from UV1)`);
console.log(`kept tiled ${skippedBakes.length} primitives too finely tiled to bake, UV1 data dropped:`);
for (const line of skippedBakes) console.log(` ${line}`);
console.log(`materials ${gltfMaterials.length}`);
console.log(`textures ${gltfTextures.length}`);
console.log(`buffer ${(binary.length / 1e6).toFixed(1)} MB`);
// Bake the scene's sky dome into the environment map this example lights from.
//
// node tools/bake_sky_environment.mjs <scene.babylon> <textureDir> <out.png> [resolution]
//
// Run once to produce `public/textures/hill_valley_sky.png`; the output is
// committed and nothing runs this at build time.
//
// The source scene shows its sky twice, and the two do not agree: a `Ciel` dome
// mesh painted with a 1024² fisheye photograph, and — separately — a 128² cube
// map used for reflections, rendered from a different sky. Anything reflective
// therefore reflected clouds that were nowhere in the picture, and the cube map
// was too coarse to be a believable background besides.
//
// This resolves both into one image. Meep's environment map is the ambient
// term, the fallback for screen-space reflections, *and* what the background
// pass draws, so once the sky lives in it the dome geometry has no job left —
// the converter drops the mesh (see `SKIP_MESHES` in babylon_to_gltf.mjs).
//
// The output is octahedral, because that is the projection Shade samples an
// environment with; `load_octahedral_environment` in the example loads it.
//
// Two hemispheres, two sources:
//
// above the horizon the `Ciel` dome, ray-traced. The dome's UV mapping is a
// fisheye an artist authored, so rather than reconstruct it
// analytically this intersects the actual geometry and
// interpolates the actual UVs — whatever the mapping is, it
// comes out right.
// below the horizon the original cube map, which is a real (if coarse) render
// of the square from its centre: grass, kerbs, storefronts.
// Almost none of it is ever visible past the ground
// geometry; it is here so the bounce light onto undersides
// stays the colour the scene was authored with, rather than
// becoming more sky.
import { readFileSync } from "node:fs";
import { join } from "node:path";
import sharp from "sharp";
const [, , scenePath, textureDir, outPath, resolutionArg = "2048"] = process.argv;
if (scenePath === undefined || textureDir === undefined || outPath === undefined) {
console.error("usage: node bake_sky_environment.mjs <scene.babylon> <textureDir> <out.png> [resolution]");
process.exit(2);
}
const RESOLUTION = Number(resolutionArg);
const SKY_MESH = "Ciel";
const SKY_TEXTURE = "sky .jpg";
const CUBE_PREFIX = "cubmap_hhv";
// Half-width of the cross-fade between the two sources, in degrees of elevation.
// The dome's own rim is the seam; a couple of degrees is enough to keep it from
// reading as a line, and it sits below the horizon where the road covers it.
const BLEND_DEGREES = 2.5;
// ─── Octahedral decode & skirt ────────────────────────────────────────────
//
// CPU copies of the engine's `octahedral_z_pole_uv_to_direction` and
// `octahedral_skirt_source_texel`, which are themselves ports of the WGSL the
// GPU samples with. They must match the engine's mapping or the sky comes out
// folded or seamed; they are short enough to carry rather than to import from
// inside the engine's source tree.
function octahedralUvToDirection(target, u, v) {
let x = u * 2 - 1;
let y = v * 2 - 1;
const z = 1 - Math.abs(x) - Math.abs(y);
const t = Math.max(-z, 0);
x += x > 0 ? -t : t;
y += y > 0 ? -t : t;
const m = 1 / Math.sqrt(x * x + y * y + z * z);
target[0] = x * m;
target[1] = y * m;
target[2] = z * m;
}
function octahedralSkirtSourceTexel(out, x, y, size) {
const interior = size - 2;
const tx = x - 1;
const ty = y - 1;
const wrappedX = ((tx % interior) + interior) % interior;
const wrappedY = ((ty % interior) + interior) % interior;
const foldX = Math.abs(Math.trunc(tx / interior)) + (tx < 0 ? 1 : 0);
const foldY = Math.abs(Math.trunc(ty / interior)) + (ty < 0 ? 1 : 0);
if (((foldX ^ foldY) & 1) !== 0) {
out[0] = interior - wrappedX;
out[1] = interior - wrappedY;
} else {
out[0] = wrappedX + 1;
out[1] = wrappedY + 1;
}
}
function fillOctahedralSkirt(rgbBuffer, size) {
const source = new Uint32Array(2);
const last = size - 1;
function copyTexel(x, y) {
octahedralSkirtSourceTexel(source, x, y, size);
const targetOffset = (y * size + x) * 3;
const sourceOffset = (source[1] * size + source[0]) * 3;
rgbBuffer[targetOffset] = rgbBuffer[sourceOffset];
rgbBuffer[targetOffset + 1] = rgbBuffer[sourceOffset + 1];
rgbBuffer[targetOffset + 2] = rgbBuffer[sourceOffset + 2];
}
for (let i = 0; i < size; i++) {
copyTexel(i, 0);
copyTexel(i, last);
copyTexel(0, i);
copyTexel(last, i);
}
}
// ─── Sources ──────────────────────────────────────────────────────────────
async function loadRaster(name) {
const { data, info } = await sharp(join(textureDir, name))
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
return { data, width: info.width, height: info.height };
}
function sampleBilinear(raster, u, v, out) {
const { data, width, height } = raster;
const x = Math.min(Math.max(u * width - 0.5, 0), width - 1);
const y = Math.min(Math.max(v * height - 0.5, 0), height - 1);
const x0 = Math.floor(x), y0 = Math.floor(y);
const x1 = Math.min(x0 + 1, width - 1), y1 = Math.min(y0 + 1, height - 1);
const fx = x - x0, fy = y - y0;
const i00 = (y0 * width + x0) * 4, i10 = (y0 * width + x1) * 4;
const i01 = (y1 * width + x0) * 4, i11 = (y1 * width + x1) * 4;
for (let c = 0; c < 3; c++) {
const top = data[i00 + c] * (1 - fx) + data[i10 + c] * fx;
const bottom = data[i01 + c] * (1 - fx) + data[i11 + c] * fx;
out[c] = top * (1 - fy) + bottom * fy;
}
}
/**
* Sample a six-face cube map by direction, in the scene's own (left-handed)
* axes — the standard face selection every cube map is authored against.
*/
function sampleCube(faces, dx, dy, dz, out) {
const ax = Math.abs(dx), ay = Math.abs(dy), az = Math.abs(dz);
let face, sc, tc, ma;
if (ax >= ay && ax >= az) {
ma = ax;
if (dx > 0) { face = "px"; sc = -dz; tc = -dy; }
else { face = "nx"; sc = dz; tc = -dy; }
} else if (ay >= az) {
ma = ay;
if (dy > 0) { face = "py"; sc = dx; tc = dz; }
else { face = "ny"; sc = dx; tc = -dz; }
} else {
ma = az;
if (dz > 0) { face = "pz"; sc = dx; tc = -dy; }
else { face = "nz"; sc = -dx; tc = -dy; }
}
sampleBilinear(faces[face], 0.5 * (sc / ma + 1), 0.5 * (tc / ma + 1), out);
}
// ─── Dome geometry ────────────────────────────────────────────────────────
const scene = JSON.parse(readFileSync(scenePath, "utf8"));
const dome = scene.meshes.find((m) => m.name === SKY_MESH);
if (dome === undefined) {
console.error(`mesh '${SKY_MESH}' not found in ${scenePath}`);
process.exit(1);
}
// The dome is a hemisphere whose local origin is its sphere centre, so its world
// position is the point every direction is measured from. Measuring from there
// rather than from the camera is what puts the dome's rim exactly on the horizon
// and makes the fisheye fill exactly the upper hemisphere.
//
// Z is mirrored to match the geometry conversion (see babylon_to_gltf.mjs): the
// directions this map is sampled for are Meep's, not Babylon's.
const domeCentre = [dome.position[0], dome.position[1], -dome.position[2]];
const positions = dome.positions;
const uvs = dome.uvs;
const indices = dome.indices;
const triangleCount = indices.length / 3;
// Vertices relative to the dome centre, mirrored in Z, with V flipped the same
// way the geometry conversion flips it.
const vertices = new Float64Array((positions.length / 3) * 3);
const texcoords = new Float64Array((positions.length / 3) * 2);
for (let i = 0; i < positions.length / 3; i++) {
vertices[i * 3] = positions[i * 3];
vertices[i * 3 + 1] = positions[i * 3 + 1];
vertices[i * 3 + 2] = -positions[i * 3 + 2];
texcoords[i * 2] = uvs[i * 2];
texcoords[i * 2 + 1] = 1 - uvs[i * 2 + 1];
}
// ─── Direction index ──────────────────────────────────────────────────────
//
// 160 triangles is few enough to brute-force per ray, but not 17 million times
// over. The dome is star-shaped about its own centre, so each triangle covers a
// contiguous patch of directions: bucket them by azimuth and elevation once, and
// a ray tests a handful instead of all of them.
const GRID_AZIMUTH = 128;
const GRID_ELEVATION = 64;
const buckets = Array.from({ length: GRID_AZIMUTH * GRID_ELEVATION }, () => []);
function bucketIndex(azimuthCell, elevationCell) {
return ((azimuthCell % GRID_AZIMUTH) + GRID_AZIMUTH) % GRID_AZIMUTH * GRID_ELEVATION + elevationCell;
}
for (let t = 0; t < triangleCount; t++) {
let azimuthMin = Infinity, azimuthMax = -Infinity;
let elevationMin = Infinity, elevationMax = -Infinity;
const azimuths = [];
for (let k = 0; k < 3; k++) {
const vi = indices[t * 3 + k];
const x = vertices[vi * 3], y = vertices[vi * 3 + 1], z = vertices[vi * 3 + 2];
const length = Math.hypot(x, y, z) || 1;
const azimuth = Math.atan2(z, x);
const elevation = Math.asin(Math.min(1, Math.max(-1, y / length)));
azimuths.push(azimuth);
elevationMin = Math.min(elevationMin, elevation);
elevationMax = Math.max(elevationMax, elevation);
}
azimuthMin = Math.min(...azimuths);
azimuthMax = Math.max(...azimuths);
// A triangle spanning more than half a turn in azimuth is one straddling the
// ±π seam, not a genuinely huge one — it belongs to both ends of the range.
const wraps = azimuthMax - azimuthMin > Math.PI;
const toAzimuthCell = (a) => Math.floor(((a + Math.PI) / (Math.PI * 2)) * GRID_AZIMUTH);
const toElevationCell = (e) => Math.floor(((e + Math.PI / 2) / Math.PI) * GRID_ELEVATION);
const e0 = Math.max(0, toElevationCell(elevationMin) - 1);
const e1 = Math.min(GRID_ELEVATION - 1, toElevationCell(elevationMax) + 1);
const ranges = wraps
? [[0, toAzimuthCell(azimuthMin) + 1], [toAzimuthCell(azimuthMax) - 1, GRID_AZIMUTH - 1]]
: [[toAzimuthCell(azimuthMin) - 1, toAzimuthCell(azimuthMax) + 1]];
for (const [a0, a1] of ranges) {
for (let a = a0; a <= a1; a++) {
for (let e = e0; e <= e1; e++) {
buckets[bucketIndex(a, Math.min(GRID_ELEVATION - 1, Math.max(0, e)))].push(t);
}
}
}
}
/**
* Möller–Trumbore, from the dome centre outwards. Returns the interpolated UV of
* the nearest hit, or null. The origin is inside a convex shell, so the first
* hit found is the only one.
*/
const hitUV = new Float64Array(2);
const ALL_TRIANGLES = Array.from({ length: triangleCount }, (_, i) => i);
let fellBackToBruteForce = 0;
function intersectDome(dx, dy, dz) {
const azimuth = Math.atan2(dz, dx);
const elevation = Math.asin(Math.min(1, Math.max(-1, dy)));
const a = Math.floor(((azimuth + Math.PI) / (Math.PI * 2)) * GRID_AZIMUTH);
const e = Math.min(GRID_ELEVATION - 1, Math.max(0, Math.floor(((elevation + Math.PI / 2) / Math.PI) * GRID_ELEVATION)));
if (intersectTriangles(buckets[bucketIndex(a, e)], dx, dy, dz)) return true;
// The index is an optimisation, not the answer. Azimuth cells converge at
// the poles, where a triangle's azimuth bounding box stops describing it, so
// a bucket miss near the zenith is not proof the ray missed the dome —
// without this the sky ends up with a hole in the top of it. 160 triangles
// is cheap enough to check exhaustively on the few rays that get here.
if (intersectTriangles(ALL_TRIANGLES, dx, dy, dz)) {
fellBackToBruteForce++;
return true;
}
return false;
}
function intersectTriangles(candidates, dx, dy, dz) {
for (let c = 0; c < candidates.length; c++) {
const t = candidates[c];
const i0 = indices[t * 3], i1 = indices[t * 3 + 1], i2 = indices[t * 3 + 2];
const ax = vertices[i0 * 3], ay = vertices[i0 * 3 + 1], az = vertices[i0 * 3 + 2];
const e1x = vertices[i1 * 3] - ax, e1y = vertices[i1 * 3 + 1] - ay, e1z = vertices[i1 * 3 + 2] - az;
const e2x = vertices[i2 * 3] - ax, e2y = vertices[i2 * 3 + 1] - ay, e2z = vertices[i2 * 3 + 2] - az;
const px = dy * e2z - dz * e2y;
const py = dz * e2x - dx * e2z;
const pz = dx * e2y - dy * e2x;
const det = e1x * px + e1y * py + e1z * pz;
if (Math.abs(det) < 1e-12) continue;
const inv = 1 / det;
// The ray starts at the dome centre, so the vector to the first vertex is
// just that vertex.
const tx = -ax, ty = -ay, tz = -az;
const u = (tx * px + ty * py + tz * pz) * inv;
if (u < -1e-6 || u > 1 + 1e-6) continue;
const qx = ty * e1z - tz * e1y;
const qy = tz * e1x - tx * e1z;
const qz = tx * e1y - ty * e1x;
const v = (dx * qx + dy * qy + dz * qz) * inv;
if (v < -1e-6 || u + v > 1 + 1e-6) continue;
const distance = (e2x * qx + e2y * qy + e2z * qz) * inv;
if (distance <= 0) continue;
const w = 1 - u - v;
hitUV[0] = texcoords[i0 * 2] * w + texcoords[i1 * 2] * u + texcoords[i2 * 2] * v;
hitUV[1] = texcoords[i0 * 2 + 1] * w + texcoords[i1 * 2 + 1] * u + texcoords[i2 * 2 + 1] * v;
return true;
}
return false;
}
// ─── Bake ─────────────────────────────────────────────────────────────────
const sky = await loadRaster(SKY_TEXTURE);
const faces = {};
for (const face of ["px", "nx", "py", "ny", "pz", "nz"]) {
faces[face] = await loadRaster(`${CUBE_PREFIX}_${face}.jpg`);
}
const output = Buffer.alloc(RESOLUTION * RESOLUTION * 3);
// A rotated 2×2 grid inside each texel: the fisheye is stretched hardest near
// the horizon, and a single sample there aliases the cloud edges into steps.
const SUPER_SAMPLES = [[0.25, 0.25], [0.75, 0.25], [0.25, 0.75], [0.75, 0.75]];
const direction = new Float64Array(3);
const skyColour = new Float64Array(3);
const groundColour = new Float64Array(3);
const blend = Math.sin((BLEND_DEGREES * Math.PI) / 180);
let missed = 0;
let traced = 0;
// Shade's environment maps carry a one-texel octahedral skirt around an
// `(RESOLUTION - 2)²` interior so hardware bilinear filtering wraps cleanly
// across the octahedron's edges.
const interior = RESOLUTION - 2;
for (let y = 1; y <= interior; y++) {
for (let x = 1; x <= interior; x++) {
let r = 0, g = 0, b = 0;
for (const [ox, oy] of SUPER_SAMPLES) {
octahedralUvToDirection(direction, (x - 1 + ox) / interior, (y - 1 + oy) / interior);
const dx = direction[0], dy = direction[1], dz = direction[2];
// The cube map is authored in the scene's left-handed axes; the
// geometry conversion mirrored Z, so sampling it back needs the
// mirror undone.
sampleCube(faces, dx, dy, -dz, groundColour);
let skyWeight = 0;
if (dy > -blend && intersectDome(dx, dy, dz)) {
sampleBilinear(sky, hitUV[0], hitUV[1], skyColour);
skyWeight = Math.min(1, Math.max(0, (dy + blend) / (2 * blend)));
traced++;
} else if (dy > 0) {
missed++;
}
r += skyColour[0] * skyWeight + groundColour[0] * (1 - skyWeight);
g += skyColour[1] * skyWeight + groundColour[1] * (1 - skyWeight);
b += skyColour[2] * skyWeight + groundColour[2] * (1 - skyWeight);
}
const o = (y * RESOLUTION + x) * 3;
output[o] = Math.round(r / SUPER_SAMPLES.length);
output[o + 1] = Math.round(g / SUPER_SAMPLES.length);
output[o + 2] = Math.round(b / SUPER_SAMPLES.length);
}
}
fillOctahedralSkirt(output, RESOLUTION);
const image = sharp(output, { raw: { width: RESOLUTION, height: RESOLUTION, channels: 3 } });
// Keep the re-projection lossless so later corrections cannot accumulate
// compression artifacts in the visible sky or reflection fallback.
await image.png({ compressionLevel: 9 }).toFile(outPath);
console.log(`resolution ${RESOLUTION}x${RESOLUTION} octahedral`);
console.log(`dome ${triangleCount} triangles, centre ${domeCentre.map((v) => v.toFixed(1)).join(", ")}`);
console.log(`traced ${traced} sky samples`);
console.log(`index misses ${fellBackToBruteForce} rays needed the exhaustive test`);
console.log(`below rim ${missed} upward samples found no dome (expect 0)`);
console.log(`wrote ${outPath}`);
// Author the road's puddles: four decal textures, and placements taken from the
// source scene's own wet mask.
//
// node tools/make_puddles.mjs <scene.babylon> <textureDir> <outDir> <manifest.js>
//
// Run once; the textures and the manifest are committed.
//
// ## Why this exists
//
// The scene ships a specular mask for its road — `route_spec.png`, painted on
// UV1 beside the lightmap — saying where the asphalt is polished and where it is
// dry. Meep samples UV0 only, and the road's UV0 tiles its asphalt 70 times, so
// the mask cannot be reached without flattening the road into its UV1 layout and
// losing that tiling (see babylon_to_gltf.mjs). Leaving the road uniformly wet
// instead is the wrong trade in the other direction: an evenly glossy road has
// no shape to its reflections, which is precisely what screen-space reflections
// are for showing.
//
// So the mask is used for what it is good for — *where* — and the puddles
// themselves are authored. This projects the mask through the road's UV1 into
// world space, finds the wettest patches, and emits a puddle decal at each.
//
// ## Why decals
//
// A decal composites into the G-buffer before anything is lit, so a puddle is
// part of the surface as far as reflections, occlusion and shading are
// concerned. It is also the only way to put detail on this road at a useful
// density: a puddle 4 units across gets a 512² texture to itself, ~128 texels
// per unit, where a single map over the whole 165-unit road would have 12.
//
// One constraint shapes the textures. In `shader_decal_composite` coverage comes
// from the albedo's alpha and gates everything:
//
// albedo = source.rgb + albedo * (1 - coverage)
// roughness = mix(roughness, orm.g * decal.roughness, coverage)
//
// so there is no such thing as a roughness-only decal — a puddle that smooths
// the road must also repaint it. That is fine here, because a puddle *is* darker
// than the asphalt around it, and it is why each variant is an albedo with the
// pool's outline in its alpha. Roughness needs no map at all: it is uniform
// across standing water, so the scalar on the component carries it.
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { join } from "node:path";
import sharp from "sharp";
const [, , scenePath, textureDir, outDir, manifestPath] = process.argv;
if (scenePath === undefined || textureDir === undefined || outDir === undefined || manifestPath === undefined) {
console.error("usage: node make_puddles.mjs <scene.babylon> <textureDir> <outDir> <manifest.js>");
process.exit(2);
}
mkdirSync(outDir, { recursive: true });
const ROAD_MESH = "Road1";
const SPEC_TEXTURE = "route_spec.png";
const VARIANTS = 4;
const TEXTURE_SIZE = 512;
// Placement search, in world units.
const PROJECTION_SCALE = 6; // raster pixels per world unit
const WET_THRESHOLD = 205; // spec value above which the mask reads as standing water
const MIN_PUDDLE = 1.6;
// A wet patch longer than this is broken into a chain of puddles rather than
// stretched into one. The mask's wet areas run in long streaks along the camber,
// and a single decal covering one reads as an oil slick — a run of separate
// pools is both what standing water does and what gives the reflections edges to
// break on.
const MAX_PUDDLE = 6;
const MAX_PUDDLES = 34;
// ─── A small deterministic noise ──────────────────────────────────────────
//
// Seeded rather than `Math.random`, so re-running the tool produces the same
// puddles and the committed manifest does not churn.
function mulberry32(seed) {
return function random() {
seed |= 0;
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
/** Smooth 1D noise around a circle, so the puddle outline joins up. */
function makeAngularNoise(random, harmonics) {
const terms = [];
for (let h = 1; h <= harmonics; h++) {
terms.push({ frequency: h, phase: random() * Math.PI * 2, amplitude: 1 / h });
}
return (theta) => {
let sum = 0;
for (const t of terms) sum += Math.sin(theta * t.frequency + t.phase) * t.amplitude;
return sum;
};
}
const smoothstep = (edge0, edge1, x) => {
const t = Math.min(1, Math.max(0, (x - edge0) / (edge1 - edge0)));
return t * t * (3 - 2 * t);
};
// ─── Textures ─────────────────────────────────────────────────────────────
/**
* One puddle: an irregular pool of standing water.
*
* The albedo is dark and the alpha is the pool's own outline, which the atlas
* premultiplies on ingest — so this is authored in straight alpha, like any
* other image.
*
* There is no ORM map. Standing water is near-mirror and uniformly so, and a
* decal with no ORM gets the identity patch — white — so its roughness is simply
* the scalar on the component:
* `roughness = mix(roughness, 1.0 * decal.roughness, coverage)`. A map would
* only be worth its four files if the roughness varied across the pool.
*/
async function writeVariant(index) {
const random = mulberry32(0x9e37 + index * 7919);
// Two or three overlapping lobes, each with a wobbling radius. A single lobe
// reads as a circle no matter how much noise is on it.
const lobeCount = 2 + (index % 2);
const lobes = [];
for (let i = 0; i < lobeCount; i++) {
lobes.push({
x: (random() - 0.5) * 0.34,
y: (random() - 0.5) * 0.34,
radius: 0.26 + random() * 0.16,
wobble: makeAngularNoise(random, 5),
strength: 0.16 + random() * 0.14,
});
}
const albedo = Buffer.alloc(TEXTURE_SIZE * TEXTURE_SIZE * 4);
// Wet asphalt, in sRGB — the albedo atlas is an sRGB format, so this is
// authored the way an image is.
//
// Dark, but nowhere near black, and the difference matters more than it
// looks. Water is transparent: what a puddle shows is the asphalt beneath it
// darkened by the film, plus the reflection on top. Authoring it near-black
// to "let the reflection do the work" backfires twice over — there is no
// diffuse left to carry the surface, and a reflection ray leaving a puddle at
// a grazing angle spends its first steps travelling over that same puddle, so
// what it reflects is the black. The puddles come out as holes in the road.
const WET = [46, 48, 52];
for (let y = 0; y < TEXTURE_SIZE; y++) {
for (let x = 0; x < TEXTURE_SIZE; x++) {
const px = (x + 0.5) / TEXTURE_SIZE - 0.5;
const py = (y + 0.5) / TEXTURE_SIZE - 0.5;
// Signed "insideness": how far inside the union of the lobes.
let inside = -Infinity;
for (const lobe of lobes) {
const dx = px - lobe.x;
const dy = py - lobe.y;
const distance = Math.hypot(dx, dy);
const theta = Math.atan2(dy, dx);
const radius = lobe.radius * (1 + lobe.strength * lobe.wobble(theta));
inside = Math.max(inside, radius - distance);
}
// Coverage: solid through the body, feathered over the last of it.
// The feather is a few texels wide rather than a smooth gradient —
// standing water has a definite edge.
const coverage = smoothstep(0, 0.018, inside);
const i4 = (y * TEXTURE_SIZE + x) * 4;
albedo[i4] = WET[0];
albedo[i4 + 1] = WET[1];
albedo[i4 + 2] = WET[2];
albedo[i4 + 3] = Math.round(coverage * 255);
}
}
const albedoFile = `puddle_${index}_albedo.png`;
await sharp(albedo, { raw: { width: TEXTURE_SIZE, height: TEXTURE_SIZE, channels: 4 } })
.png({ compressionLevel: 9 })
.toFile(join(outDir, albedoFile));
return { albedoFile };
}
// ─── Where the road is wet ────────────────────────────────────────────────
const scene = JSON.parse(readFileSync(scenePath, "utf8"));
const road = scene.meshes.find((m) => m.name === ROAD_MESH);
if (road === undefined) {
console.error(`mesh '${ROAD_MESH}' not found`);
process.exit(1);
}
const positions = road.positions;
const uv1 = road.uvs2;
const indices = road.indices;
const offset = road.position;
// World space, matching the geometry conversion: Z mirrored, mesh position added.
const worldX = (i) => positions[i * 3] + offset[0];
const worldY = (i) => positions[i * 3 + 1] + offset[1];
const worldZ = (i) => -(positions[i * 3 + 2] + offset[2]);
let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity;
for (let i = 0; i < positions.length / 3; i++) {
minX = Math.min(minX, worldX(i)); maxX = Math.max(maxX, worldX(i));
minZ = Math.min(minZ, worldZ(i)); maxZ = Math.max(maxZ, worldZ(i));
}
const width = Math.round((maxX - minX) * PROJECTION_SCALE);
const height = Math.round((maxZ - minZ) * PROJECTION_SCALE);
const spec = await sharp(join(textureDir, SPEC_TEXTURE)).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
function sampleSpec(u, v) {
const w = spec.info.width, h = spec.info.height;
const x = Math.min(w - 1, Math.max(0, Math.round(u * w - 0.5)));
// V is flipped to match the geometry conversion.
const y = Math.min(h - 1, Math.max(0, Math.round((1 - v) * h - 0.5)));
return spec.data[(y * w + x) * 4];
}
// Two rasters over the road's footprint, seen from above: how wet the mask says
// each point is, and how high the road is there — the second one is what a
// puddle's decal box gets centred on.
const wetness = new Uint8Array(width * height);
const surfaceY = new Float32Array(width * height);
for (let t = 0; t < indices.length; t += 3) {
const a = indices[t], b = indices[t + 1], c = indices[t + 2];
const ax = (worldX(a) - minX) * PROJECTION_SCALE, az = (worldZ(a) - minZ) * PROJECTION_SCALE;
const bx = (worldX(b) - minX) * PROJECTION_SCALE, bz = (worldZ(b) - minZ) * PROJECTION_SCALE;
const cx = (worldX(c) - minX) * PROJECTION_SCALE, cz = (worldZ(c) - minZ) * PROJECTION_SCALE;
const area = (bx - ax) * (cz - az) - (cx - ax) * (bz - az);
if (Math.abs(area) < 1e-9) continue;
const x0 = Math.max(0, Math.floor(Math.min(ax, bx, cx)));
const x1 = Math.min(width - 1, Math.ceil(Math.max(ax, bx, cx)));
const y0 = Math.max(0, Math.floor(Math.min(az, bz, cz)));
const y1 = Math.min(height - 1, Math.ceil(Math.max(az, bz, cz)));
for (let y = y0; y <= y1; y++) {
for (let x = x0; x <= x1; x++) {
const px = x + 0.5, py = y + 0.5;
const w0 = ((bx - px) * (cz - py) - (cx - px) * (bz - py)) / area;
const w1 = ((cx - px) * (az - py) - (ax - px) * (cz - py)) / area;
const w2 = 1 - w0 - w1;
if (w0 < 0 || w1 < 0 || w2 < 0) continue;
const u = uv1[a * 2] * w0 + uv1[b * 2] * w1 + uv1[c * 2] * w2;
const v = uv1[a * 2 + 1] * w0 + uv1[b * 2 + 1] * w1 + uv1[c * 2 + 1] * w2;
const i = y * width + x;
wetness[i] = sampleSpec(u, v);
surfaceY[i] = worldY(a) * w0 + worldY(b) * w1 + worldY(c) * w2;
}
}
}
// ─── Blobs ────────────────────────────────────────────────────────────────
//
// Flood-fill the above-threshold pixels into connected patches. Each surviving
// patch becomes one puddle, sized and oriented to the patch: the mask's wet
// areas are streaks along the camber and gutters, not discs, so a puddle that
// inherits its aspect and angle sits in the road the way the paint intended.
const visited = new Uint8Array(width * height);
const blobs = [];
for (let seed = 0; seed < wetness.length; seed++) {
if (visited[seed] || wetness[seed] < WET_THRESHOLD) continue;
const stack = [seed];
const pixels = [];
visited[seed] = 1;
while (stack.length > 0) {
const i = stack.pop();
pixels.push(i);
const x = i % width, y = (i / width) | 0;
for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
const nx = x + dx, ny = y + dy;
if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;
const j = ny * width + nx;
if (visited[j] || wetness[j] < WET_THRESHOLD) continue;
visited[j] = 1;
stack.push(j);
}
}
if (pixels.length < 8) continue;
// Centroid, and the covariance that gives the patch its axes.
let sx = 0, sy = 0;
for (const i of pixels) { sx += i % width; sy += (i / width) | 0; }
const cx = sx / pixels.length, cy = sy / pixels.length;
let xx = 0, yy = 0, xy = 0;
for (const i of pixels) {
const dx = (i % width) - cx, dy = ((i / width) | 0) - cy;
xx += dx * dx; yy += dy * dy; xy += dx * dy;
}
xx /= pixels.length; yy /= pixels.length; xy /= pixels.length;
// Principal axis of the patch, and the spread along each axis. Two standard
// deviations covers the patch without chasing its stragglers.
const angle = 0.5 * Math.atan2(2 * xy, xx - yy);
const common = Math.sqrt(Math.max(0, (xx - yy) * (xx - yy) / 4 + xy * xy));
const major = Math.sqrt(Math.max(0, (xx + yy) / 2 + common));
const minor = Math.sqrt(Math.max(0, (xx + yy) / 2 - common));
blobs.push({
x: minX + cx / PROJECTION_SCALE,
z: minZ + cy / PROJECTION_SCALE,
y: surfaceY[Math.round(cy) * width + Math.round(cx)] || 1,
sizeX: (4 * major) / PROJECTION_SCALE,
sizeZ: (4 * minor) / PROJECTION_SCALE,
angle,
pixels: pixels.length,
});
}
// Biggest first, then filtered to the ones worth a draw call.
blobs.sort((a, b) => b.pixels - a.pixels);
const placements = [];
const jitter = mulberry32(0x51ed);
for (const blob of blobs) {
if (placements.length >= MAX_PUDDLES) break;
if (blob.sizeX < MIN_PUDDLE * 0.6 && blob.sizeZ < MIN_PUDDLE * 0.6) continue;
const sizeZ = Math.min(MAX_PUDDLE, Math.max(MIN_PUDDLE, blob.sizeZ));
// Lay a chain of pools along the patch rather than one stretched decal.
const segments = Math.max(1, Math.min(4, Math.round(blob.sizeX / MAX_PUDDLE)));
const along = blob.sizeX / segments;
const dx = Math.cos(blob.angle);
const dz = Math.sin(blob.angle);
for (let s = 0; s < segments; s++) {
if (placements.length >= MAX_PUDDLES) break;
// Centre of this segment along the patch, nudged so a chain does not
// read as a dashed line.
const offset = (s - (segments - 1) / 2) * along;
const wobble = (jitter() - 0.5) * along * 0.25;
const centreX = blob.x + dx * (offset + wobble);
const centreZ = blob.z + dz * (offset + wobble);
const sizeX = Math.max(MIN_PUDDLE, along * (0.72 + jitter() * 0.3));
placements.push({
position: [
Number(centreX.toFixed(2)),
Number(blob.y.toFixed(2)),
Number(centreZ.toFixed(2)),
],
// Across the wet patch's long axis, then its short one.
size: [
Number(sizeX.toFixed(2)),
Number((sizeZ * (0.8 + jitter() * 0.4)).toFixed(2)),
],
// Direction of that long axis on the ground plane, as an angle in
// the XZ plane: the patch runs along `(cos a, 0, sin a)`. The blob
// was measured in a top-down raster whose +y is world +Z, so the
// angle carries over unchanged.
angle: Number(blob.angle.toFixed(3)),
variant: placements.length % VARIANTS,
});
}
}
// ─── Filling in ───────────────────────────────────────────────────────────
//
// The mask has about ten patches bright enough to be standing water, which over
// a road 165 units long leaves most of it bare. The rest of the mask is not
// uniform though — it is brighter down the camber and along the gutters, darker
// on the crown — so the remaining puddles are scattered with the mask as a
// probability rather than placed by hand. Density follows the paint even where
// no single patch was strong enough to name.
const SCATTER_FLOOR = 150; // below this the mask reads as dry road
const SCATTER_SPACING = 5.5; // world units between puddle centres
const scatter = mulberry32(0x2f6d);
function tooClose(x, z) {
for (const p of placements) {
const dx = p.position[0] - x;
const dz = p.position[2] - z;
if (dx * dx + dz * dz < SCATTER_SPACING * SCATTER_SPACING) return true;
}
return false;
}
for (let attempt = 0; attempt < 6000 && placements.length < MAX_PUDDLES; attempt++) {
const px = Math.floor(scatter() * width);
const py = Math.floor(scatter() * height);
const i = py * width + px;
const wet = wetness[i];
if (wet < SCATTER_FLOOR) continue;
// Accept in proportion to how wet the mask says this spot is.
if (scatter() > (wet - SCATTER_FLOOR) / (255 - SCATTER_FLOOR)) continue;
const x = minX + px / PROJECTION_SCALE;
const z = minZ + py / PROJECTION_SCALE;
if (tooClose(x, z)) continue;
const major = 1.8 + scatter() * 3.4;
placements.push({
position: [
Number(x.toFixed(2)),
Number((surfaceY[i] || 1).toFixed(2)),
Number(z.toFixed(2)),
],
size: [Number(major.toFixed(2)), Number((major * (0.45 + scatter() * 0.4)).toFixed(2))],
angle: Number((scatter() * Math.PI).toFixed(3)),
variant: placements.length % VARIANTS,
});
}
// ─── Write ────────────────────────────────────────────────────────────────
const files = [];
for (let i = 0; i < VARIANTS; i++) files.push(await writeVariant(i));
const manifest = `// Generated by tools/make_puddles.mjs — do not edit by hand.
//
// Puddles on the road, placed where the source scene's own specular mask says
// the asphalt stands in water. Each entry is one decal: a world position on the
// road surface, the extent of the wet patch it came from along its long and
// short axes, and the direction of that long axis in the ground plane.
export const PUDDLE_TEXTURES = ${JSON.stringify(
files.map((f) => `./textures/puddles/${f.albedoFile}`),
null,
4
)};
export const PUDDLES = ${JSON.stringify(placements, null, 4)};
`;
writeFileSync(manifestPath, manifest);
console.log(`variants ${VARIANTS} textures at ${TEXTURE_SIZE}x${TEXTURE_SIZE}`);
console.log(`projection ${width}x${height} over ${(maxX - minX).toFixed(0)}x${(maxZ - minZ).toFixed(0)} units`);
console.log(`blobs ${blobs.length} wet patches found`);
console.log(`puddles ${placements.length} placed`);
console.log(`sizes ${placements.map((p) => p.size[0].toFixed(1)).slice(0, 10).join(", ")} ...`);
console.log(`wrote ${manifestPath}`);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Screen-space reflections · Meep</title>
<meta name="robots" content="noindex">
<style>
*, *::before, *::after { box-sizing: border-box; }
html, body {
margin: 0; padding: 0;
width: 100%; height: 100%;
overflow: hidden;
background: #07090c;
color: #e6edf3;
font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
user-select: none;
}
canvas { display: block; }
.panel {
position: fixed;
z-index: 100;
background: rgba(7, 9, 12, 0.76);
border: 1px solid #1f2731;
border-radius: 10px;
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
box-shadow: 0 12px 32px rgba(0,0,0,0.4);
}
.hud {
top: 1rem; left: 1rem;
padding: 0.75rem 1rem;
font-family: ui-monospace, "JetBrains Mono", "Fira Code", monospace;
font-size: 0.8rem;
line-height: 1.65;
color: #9aa5b1;
min-width: 170px;
font-variant-numeric: tabular-nums;
}
.hud .label {
color: #6b7785;
text-transform: uppercase;
letter-spacing: 0.08em;
font-size: 0.65rem;
margin-right: 0.5rem;
}
.hud .value { color: #4ef0a8; font-variant-numeric: tabular-nums; }
.hud .value.off { color: #6b7785; }
/* SSR switch. A real button so it takes focus, keyboard and screen readers
for free; `aria-pressed` carries the state the track and knob show. */
.toggle {
display: flex;
align-items: center;
gap: 0.6rem;
margin: 0.1rem 0 0.45rem;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
}
.toggle .track {
position: relative;
width: 34px; height: 18px;
flex: none;
border-radius: 999px;
background: #11161d;
border: 1px solid #2a3441;
transition: background 0.18s ease, border-color 0.18s ease;
}
.toggle .knob {
position: absolute;
top: 2px; left: 2px;
width: 12px; height: 12px;
border-radius: 50%;
background: #6b7785;
transition: transform 0.18s ease, background 0.18s ease;
}
.toggle[aria-pressed="true"] .track {
background: rgba(78,240,168,0.22);
border-color: rgba(78,240,168,0.55);
}
.toggle[aria-pressed="true"] .knob {
transform: translateX(16px);
background: #4ef0a8;
}
.toggle .caption {
font-family: ui-monospace, "JetBrains Mono", "Fira Code", monospace;
font-size: 0.72rem;
letter-spacing: 0.08em;
text-transform: uppercase;
color: #9aa5b1;
}
.toggle:focus-visible { outline: 2px solid #4ef0a8; outline-offset: 2px; border-radius: 6px; }
.toggle .hint {
display: inline-block;
font-family: ui-monospace, "JetBrains Mono", "Fira Code", monospace;
font-size: 0.68rem;
line-height: 1.2;
color: #e6edf3;
background: #11161d;
border: 1px solid #2a3441;
border-bottom-width: 2px;
padding: 0.06rem 0.32rem;
border-radius: 4px;
}
.legend {
bottom: 1rem; left: 1rem;
padding: 0.8rem 1rem;
font-size: 0.8rem;
line-height: 1.55;
max-width: 470px;
color: #9aa5b1;
}
.legend strong { color: #e6edf3; font-weight: 600; }
.legend kbd {
display: inline-block;
font-family: ui-monospace, "JetBrains Mono", "Fira Code", monospace;
font-size: 0.72rem;
line-height: 1.2;
color: #e6edf3;
background: #11161d;
border: 1px solid #2a3441;
border-bottom-width: 2px;
padding: 0.08rem 0.38rem;
border-radius: 4px;
}
.loading {
position: fixed;
inset: 0;
z-index: 200;
display: flex;
align-items: center;
justify-content: center;
background: #07090c;
color: #6b7785;
font-family: ui-monospace, "JetBrains Mono", "Fira Code", monospace;
font-size: 0.82rem;
letter-spacing: 0.08em;
text-transform: uppercase;
transition: opacity 0.6s ease;
}
.loading.hidden { opacity: 0; pointer-events: none; }
</style>
</head>
<body>
<div class="loading" id="loading">loading Hill Valley…</div>
<div class="panel hud">
<button type="button" class="toggle" id="ssr-toggle" aria-pressed="true">
<span class="track"><span class="knob"></span></span>
<span class="caption">ssr <span class="value" id="ssr">on</span></span>
<span class="hint" aria-hidden="true">R</span>
</button>
<div><span class="label">fps</span><span class="value" id="fps">–</span></div>
</div>
<div class="panel legend">
<strong>Screen-space reflections.</strong> The puddles, the shopfront glazing
and the car body reflect what is on screen; everything SSR cannot see falls
back to the environment map.
<kbd>R</kbd> or the switch toggles SSR · <kbd>drag</kbd> orbit ·
<kbd>right-drag</kbd> pan · <kbd>wheel</kbd> zoom
</div>
<script type="module" src="./src/main.js"></script>
</body>
</html>
{
"name": "@meep-examples/screen-space-reflections",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "Screen-space reflections over a dense town-square scene — wet road, shopfront glazing and a chrome car body, with SSR toggleable against the environment-map fallback.",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@woosh/meep-engine": "3.71.0"
},
"devDependencies": {
"@rollup/plugin-strip": "^3.0.4",
"vite": "^8.0.13"
}
}
# Screen-space reflections
A 1950s American town square — puddles on the asphalt, shopfront glazing and a
stainless-steel car body — rendered with Shade's SSR pass, with a key to switch
it off.
**Drag** to orbit, **right-drag** to pan, **wheel** to zoom, **R** to toggle SSR.
## What SSR is doing
By the time SSR runs, the deferred pass has already produced a G-buffer and a
lit colour buffer for the frame. For every pixel smooth enough to matter, SSR
marches a reflection ray through the depth pyramid; where the ray lands on
something the camera can already see, it takes that pixel's colour as the
reflected radiance. So a surface reflects the *actual scene around it* — the
road reflects the building above it, the car reflects the storefront beside it —
without a second render of anything.
The limit is in the name: SSR can only reflect what is on screen. Rays that walk
off the edge of the frame, or behind an occluder, find nothing, and Shade
resolves those to the environment map instead. That is the whole of what the
**R** key shows. With SSR off, every glossy surface in the scene is lit by the
environment alone: it keeps a general sense of "bright sky above, ground below"
and loses every specific thing around it, so the puddles in the road turn into
flat pale patches of sky.
Turning it on is one flag:
```js
engine.graphics.renderer.feature_ssr_enabled = true;
```
It is off by default because it is not free — a trace through the depth
pyramid, a reprojection of last frame's result and a denoise, all at render
resolution.
The renderer is `null` until the engine has started and is replaced on every
restart, so an app that stops and starts re-applies this rather than caching the
object.
## Why this scene
The buildings are set dressing; the example is about three surfaces.
- **The puddles.** A large, near-horizontal surface at a grazing angle is SSR's
best case, which is why the camera starts near the road rather than up on the
rooftops. But an *evenly* glossy road is not: reflectance without shape reads
as a sheen, and the point of screen-space reflections is that they have shape.
So the asphalt stays close to dry and the water sits on it as puddles — decals,
which composite into the G-buffer before anything is lit, so a puddle is part
of the road as far as reflections and shading are concerned rather than a
layer over it. See `tools/make_puddles.mjs`; where they go is read from the
source scene's own wet mask.
- **The shopfront glazing.** Each storefront has a separate, opaque glazing pane
laid over it. Being opaque, those panes are in the G-buffer and take
reflections. The genuinely see-through windows next to them are transmissive
and composite *after* the deferred pass, which is why they show the
environment instead — a useful thing to see in the same frame.
- **The car body.** Stainless steel, so an actual metal: its reflection is the
whole of its specular response rather than a sheen on top of diffuse.
## The environment map
One 2K octahedral image does three jobs: it is the ambient term (Shade has no
separate ambient light, and `LightType.AMBIENT` entities are dropped), it is the
background the frame is drawn against, and it is what SSR falls back to. Using
one image for all three is deliberate — it makes the **R** toggle read as
"specific reflections versus generic ones" rather than as a brightness change.
The source scene showed its sky twice and the two did not agree: a `Ciel` dome
mesh painted with a fisheye photograph, and separately a 128² cube map used for
reflections, rendered from a different sky. Anything reflective reflected clouds
that were nowhere in the picture. `tools/bake_sky_environment.mjs` resolves both
into one map — it ray-traces the actual dome geometry with its actual UVs, so
whatever fisheye mapping the artist used comes out right without reconstructing
it — and the converter then drops the dome mesh, which has no job left. Dropping
it also shrinks the scene's radius from 556 units to 203, so the far plane comes
down with it and the depth buffer SSR marches through gets that precision back.
Below the dome's rim the map keeps the original cube map's content: a real, if
coarse, render of the square. Almost none of it is ever visible past the ground
geometry; it is there so bounce light onto undersides stays the colour the scene
was authored with instead of becoming more sky. It is still 128² at heart, so an
orbit that climbs above the rooftops will find it soft.
**An 8-bit sky needs a radiance to go with it.** Decoded, a photograph's whitest
pixel is 1.0, and Shade's lights are photometric — this scene's sun is 70. An
environment left at photographic scale is some thirty times too dim to sit next
to one, and draws as a dusk-blue ceiling over a sunlit street. So the loader
takes the value that white should mean (`SKY_RADIANCE`), and the mountain
backdrops — the other unlit photograph in the scene — are emitted on the same
white point via `KHR_materials_emissive_strength`, which is what keeps them from
rendering as black silhouettes. A scene with a sky dome hides all of this,
because the dome is emissive geometry composited by a different route; deleting
the dome is what exposes it.
## Assets
The scene is the **Hill Valley** demo scene from Babylon.js
(<https://www.babylonjs.com/Scenes/hillvalley/>), modelled by Michel Rousseau.
> **Licensing — read before reusing this scene.** Babylon.js's asset repository
> is CC-BY-4.0 "unless specified otherwise", but this scene is one of the
> exceptions in practice: it depicts Hill Valley from *Back to the Future*, and
> the Babylon forums are consistent that Universal permits the imagery for
> **non-commercial use only** and that commercial use needs Universal's
> permission, not Babylon's. The textures also carry real third-party
> trademarks (Texaco, Western Auto, Bank of America). This example is included
> as a rendering study; it is not cleared for commercial use, and the surfaces
> it demonstrates are not specific to it — any scene with a wet road, glazing
> and a metal prop shows the same thing.
`tools/babylon_to_gltf.mjs` converts the source `.babylon` scene to the glTF in
`public/models/hill_valley/`. It is a one-off — the output is committed and
nothing runs it at build time — but it is kept here because the three
conversions it performs are each a place a port of this kind goes wrong:
1. **Handedness.** Babylon is left-handed, glTF is right-handed, so geometry is
mirrored in Z. The winding is deliberately *not* reversed as well: Babylon's
front faces are clockwise where glTF's are counter-clockwise, and those two
flips cancel. Getting this wrong renders the insides of every building, lit
by normals pointing away from the camera — which looks like a lighting bug,
not a winding one. The converter asserts the invariant (the geometric normal
from a triangle's winding must agree with its vertex normal) and reports it.
2. **The pre-transform.** Most meshes here are a translation and nothing else,
but 21 carry a rotation and scale in `localMatrix`, which Babylon applies
*before* the node's own transform. Every DeLorean part is one of those, at
~5.6× and rotated; ignoring it scatters oversized car parts across the
square, which reads as junk geometry rather than as a transform bug.
3. **The second UV set.** Meep's standard material samples UV0 only — a second
set rides through the geometry pipeline, but only the virtual-texturing path
reads it and no material can select one — and this scene keeps its lightmaps,
and the road's wet mask, on UV1. Where it is affordable, the
converter rasterizes the primitive in its own UV1 layout, writing
`diffuse(UV0) × lightmap(UV1)` into a new texture and emitting UV1 as UV0.
Foliage is baked to RGBA so its cut-out survives; baking a tree to RGB turns
every canopy into an opaque black card.
**A bake is sized by its diffuse, and refused when the diffuse is tiled.**
Sizing from the lightmap island instead — the obvious thing, since that is
the layout being written into — silently drops the surface to the lightmap's
density, which is soft by construction. That is how the pavement, a texture
tiled 386 times, ended up in 1024 pixels. And past a point it stops being a
resolution question at all: the road tiles its asphalt 70 times and would need
35,000 pixels to survive being flattened. So a primitive whose diffuse detail
exceeds 2048 keeps UV0 and its own texture, and gives up its lightmap — 20 of
them here, all ground and props. What it keeps is the lightmap's *average*,
folded into `baseColorFactor`: the mean is a real measurement of how much
light reached that surface, and without it the road drops to raw asphalt,
pale enough that its diffuse drowns the reflections. The real-time sun and
GTAO supply the variation the map would have.
What the road loses this way is its wet mask, and that comes back as decals.
`tools/make_puddles.mjs` reads the mask offline, projects it through the
road's UV1 into world space, finds the patches the paint says stand in water,
and emits a puddle at each — position, extent and orientation from the patch,
with the rest scattered by the mask as a probability so density follows it
even where no single patch was strong enough to name. Long streaks become
chains of pools rather than one stretched decal.
Two things about authoring those, both of which look like renderer faults:
coverage in `shader_decal_composite` comes from the albedo's alpha and gates
*everything*, roughness included, so a roughness-only decal does not exist —
a puddle that smooths the road must also repaint it. And the repaint must not
be near-black, however tempting it is to "let the reflection do the work": a
reflection ray leaving a puddle at a grazing angle spends its first steps
travelling over that same puddle, so what it reflects is whatever the puddle
is, and the pools come out as holes cut in the road.
One filtering detail that reads as "low resolution" rather than as a bug: the
bake samples bilinearly. Nearest turns a magnified lightmap into visible
blocks and a minified diffuse into aliasing, and neither looks like a
filtering choice. (The converter writes all textures as PNG; chroma
subsampling would average away the very channels an ORM map
keeps roughness and metalness in — though with the road declined, no primitive
in *this* scene ends up needing one.)
The committed color atlases have numerical direct-shadow compensation and
conservative deblocking, with the existing baked GI retained. Their dimensions,
UV layouts and foliage alpha are preserved. The atlases and environment map are
lossless PNGs so future edits do not add another generation of JPEG artifacts.
Regenerating from the original scene restores its original baked lighting;
the converter does not perform this retouching.
Regenerating these (the source scene is a 60 MB download, not vendored here;
the tools need `sharp`, which the repo declares as a root devDependency):
```bash
curl -O https://www.babylonjs.com/Scenes/hillvalley/HillValley.babylon
# ...and the textures it names, into ./textures/
node tools/babylon_to_gltf.mjs HillValley.babylon ./textures public/models/hill_valley
node tools/bake_sky_environment.mjs HillValley.babylon ./textures public/textures/hill_valley_sky.png 2048
node tools/make_puddles.mjs HillValley.babylon ./textures public/textures/puddles src/puddleManifest.js
```
The committed scene is ~68 MB: a 21 MB vertex buffer (positions, normals and UVs
as floats — no quantization), ~42 MB of textures, a 4.2 MB environment map and
0.2 MB of puddle decals.
`BACKDROP_RADIANCE` in the converter and `SKY_RADIANCE` in `src/main.js` are the
same quantity and have to move together; see the environment section above.
## Run
```bash
npm install
npm run dev # http://localhost:5173/demo.html
npm run build # writes to ../../public/examples/screen-space-reflections
```
import { defineConfig } from "vite";
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { resolve, dirname } from "node:path";
import strip from "@rollup/plugin-strip";
const __dirname = dirname(fileURLToPath(import.meta.url));
// See the entity-stress-test example for the rationale on `base: "./"` and
// `emptyOutDir: false`.
export default defineConfig({
// Vite's dependency pre-bundling rewrites the engine's own asset imports and
// loses their URLs, so a dev server ends up serving ".../deps/undefined" for
// the renderer's data files. The engine is source-only ESM and needs no
// pre-bundling - but its CommonJS dependencies do, or the import of them from inside
// the excluded engine finds no default export.
optimizeDeps: {
exclude: ["@woosh/meep-engine"],
include: ["dat.gui", "opentype.js"],
},
plugins: [
{
// Copy the committed source thumbnail into the generated gallery folder.
// public/examples/<id>/ is build output (gitignored); thumbnail.png is
// kept in source here and copied through on every build so the gallery
// (src/data/examples.ts) can resolve it.
name: "copy-thumbnail",
apply: "build",
closeBundle() {
const thumb = resolve(__dirname, "thumbnail.png");
const dst = resolve(__dirname, "../../public/examples/screen-space-reflections");
if (existsSync(thumb)) {
mkdirSync(dst, { recursive: true });
copyFileSync(thumb, resolve(dst, "thumbnail.png"));
}
},
},
],
base: "./",
build: {
outDir: resolve(__dirname, "../../public/examples/screen-space-reflections"),
emptyOutDir: false,
rollupOptions: {
input: resolve(__dirname, "demo.html"),
plugins: [
{
// this will remove all assert statements from the production build
...strip(),
apply: 'build'
}
],
},
target: "es2022",
},
});
allstateDiffuseMap.png · 330.0 KB
armstrongDiffuseMap.png · 976.4 KB
baked_0_albedo.png · 37.0 KB
baked_1_albedo.png · 34.3 KB
baked_10_albedo.png · 378.2 KB
baked_11_albedo.png · 462.6 KB
baked_12_albedo.png · 130.3 KB
baked_13_albedo.png · 406.0 KB
baked_14_albedo.png · 14.6 KB
baked_15_albedo.png · 304.9 KB