@monogrid/gainmap-js 3.5.0 → 3.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +111 -133
  3. package/dist/{QuadRenderer-DIHDdKl6.js → QuadRenderer-Bhn3yOPC.js} +1 -1
  4. package/dist/{QuadRenderer-DPiEee1I.js → QuadRenderer-DMno-Vj6.js} +1 -1
  5. package/dist/{_commonjsHelpers-S7tZmPW-.js → _commonjsHelpers-C8qmDUO8.js} +1 -1
  6. package/dist/{_commonjsHelpers-DVRbpukU.js → _commonjsHelpers-DFuDJEaJ.js} +1 -1
  7. package/dist/{compress-5gFn7Y4a.js → compress-TBp7MS8D.js} +1 -1
  8. package/dist/{compress-CTBeaiI1.js → compress-oIjJuPa8.js} +1 -2
  9. package/dist/decode/shared/index.d.ts +1 -0
  10. package/dist/decode/shared/utils/create-textures.d.ts +26 -0
  11. package/dist/decode/shared/utils/warn-deprecated.d.ts +8 -0
  12. package/dist/decode/webgl/decode.d.ts +1 -0
  13. package/dist/decode/webgl/index.d.ts +4 -0
  14. package/dist/decode/webgl/loaders/GainMapLoader.d.ts +3 -1
  15. package/dist/decode/webgl/loaders/HDRJPGLoader.d.ts +3 -1
  16. package/dist/decode/webgl/materials/GainMapDecoderMaterial.d.ts +1 -0
  17. package/dist/decode/webgpu/core/QuadRenderer.d.ts +1 -0
  18. package/dist/decode/webgpu/decode.d.ts +1 -0
  19. package/dist/decode/webgpu/index.d.ts +7 -0
  20. package/dist/decode/webgpu/loaders/GainMapLoader.d.ts +3 -1
  21. package/dist/decode/webgpu/loaders/GainMapNodeLoader.d.ts +42 -0
  22. package/dist/decode/webgpu/loaders/HDRJPGLoader.d.ts +3 -1
  23. package/dist/decode/webgpu/loaders/HDRJPGNodeLoader.d.ts +41 -0
  24. package/dist/decode/webgpu/loaders/LoaderBaseNode.d.ts +24 -0
  25. package/dist/decode/webgpu/materials/GainMapDecoderMaterial.d.ts +1 -0
  26. package/dist/decode/webgpu/nodes/GainMapNode.d.ts +142 -0
  27. package/dist/decode.js +18 -5
  28. package/dist/decode.min.js +2 -2
  29. package/dist/decode.umd.cjs +86 -32
  30. package/dist/decode.umd.min.cjs +2 -2
  31. package/dist/decode.webgpu.js +472 -10
  32. package/dist/decode.webgpu.min.js +2 -2
  33. package/dist/decode.webgpu.umd.cjs +542 -35
  34. package/dist/decode.webgpu.umd.min.cjs +2 -2
  35. package/dist/encode.js +3 -3
  36. package/dist/encode.min.js +2 -2
  37. package/dist/encode.umd.cjs +1 -2
  38. package/dist/encode.umd.min.cjs +1 -1
  39. package/dist/{iso-gainmap-metadata-Dk2F4Eoz.js → iso-gainmap-metadata-C1io5isX.js} +1 -1
  40. package/dist/{iso-gainmap-metadata-DNTSE4Qp.js → iso-gainmap-metadata-Oi7gAKNC.js} +1 -1
  41. package/dist/libultrahdr.js +2 -2
  42. package/dist/libultrahdr.min.js +2 -2
  43. package/dist/libultrahdr.umd.cjs +1 -1
  44. package/dist/libultrahdr.umd.min.cjs +1 -1
  45. package/dist/{Loader-CL7itwBq.js → warn-deprecated-DtCQWGKi.js} +74 -35
  46. package/dist/{Loader-BdKdEGSJ.js → warn-deprecated-gLZfP_DV.js} +2 -2
  47. package/dist/worker-interface.js +2 -2
  48. package/dist/worker-interface.min.js +2 -2
  49. package/dist/worker-interface.umd.cjs +1 -1
  50. package/dist/worker-interface.umd.min.cjs +1 -1
  51. package/dist/worker.js +3 -3
  52. package/dist/worker.min.js +2 -2
  53. package/dist/worker.umd.cjs +1 -2
  54. package/dist/worker.umd.min.cjs +1 -1
  55. package/package.json +35 -42
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.5.0
2
+ * @monogrid/gainmap-js v3.6.1
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three")):"function"==typeof define&&define.amd?define(["exports","three"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@monogrid/gainmap-js"]={},e.three)}(this,function(e,t){"use strict";const r=(e,r,a)=>{let i;switch(e){case t.UnsignedByteType:i=new Uint8ClampedArray(r*a*4);break;case t.HalfFloatType:i=new Uint16Array(r*a*4);break;case t.UnsignedIntType:i=new Uint32Array(r*a*4);break;case t.ByteType:i=new Int8Array(r*a*4);break;case t.ShortType:i=new Int16Array(r*a*4);break;case t.IntType:i=new Int32Array(r*a*4);break;case t.FloatType:i=new Float32Array(r*a*4);break;default:throw new Error("Unsupported data type")}return i};let a;class i{_renderer;_rendererIsDisposable=!1;_material;_scene;_camera;_quad;_renderTarget;_width;_height;_type;_colorSpace;_supportsReadPixels=!0;constructor(e){this._width=e.width,this._height=e.height,this._type=e.type,this._colorSpace=e.colorSpace;const n={format:t.RGBAFormat,depthBuffer:!1,stencilBuffer:!1,type:this._type,colorSpace:this._colorSpace,anisotropy:void 0!==e.renderTargetOptions?.anisotropy?e.renderTargetOptions?.anisotropy:1,generateMipmaps:void 0!==e.renderTargetOptions?.generateMipmaps&&e.renderTargetOptions?.generateMipmaps,magFilter:void 0!==e.renderTargetOptions?.magFilter?e.renderTargetOptions?.magFilter:t.LinearFilter,minFilter:void 0!==e.renderTargetOptions?.minFilter?e.renderTargetOptions?.minFilter:t.LinearFilter,samples:void 0!==e.renderTargetOptions?.samples?e.renderTargetOptions?.samples:void 0,wrapS:void 0!==e.renderTargetOptions?.wrapS?e.renderTargetOptions?.wrapS:t.ClampToEdgeWrapping,wrapT:void 0!==e.renderTargetOptions?.wrapT?e.renderTargetOptions?.wrapT:t.ClampToEdgeWrapping};if(this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=i.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new t.Scene,this._camera=new t.OrthographicCamera,this._camera.position.set(0,0,10),this._camera.left=-.5,this._camera.right=.5,this._camera.top=.5,this._camera.bottom=-.5,this._camera.updateProjectionMatrix(),!((e,i,n,s)=>{if(void 0!==a)return a;const o=new t.WebGLRenderTarget(1,1,s);i.setRenderTarget(o);const d=new t.Mesh(new t.PlaneGeometry,new t.MeshBasicMaterial({color:16777215}));i.render(d,n),i.setRenderTarget(null);const p=r(e,o.width,o.height);return i.readRenderTargetPixels(o,0,0,o.width,o.height,p),o.dispose(),d.geometry.dispose(),d.material.dispose(),a=0!==p[0],a})(this._type,this._renderer,this._camera,n)){let e;if(this._type===t.HalfFloatType)e=this._renderer.extensions.has("EXT_color_buffer_float")?t.FloatType:void 0;void 0!==e?(console.warn(`This browser does not support reading pixels from ${this._type} RenderTargets, switching to ${t.FloatType}`),this._type=e):(this._supportsReadPixels=!1,console.warn("This browser dos not support toArray or toDataTexture, calls to those methods will result in an error thrown"))}this._quad=new t.Mesh(new t.PlaneGeometry,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new t.WebGLRenderTarget(this.width,this.height,n),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:t.UVMapping}static instantiateRenderer(){const e=new t.WebGLRenderer;return e.setSize(128,128),e}render=()=>{this._renderer.setRenderTarget(this._renderTarget);try{this._renderer.render(this._scene,this._camera)}catch(e){throw this._renderer.setRenderTarget(null),e}this._renderer.setRenderTarget(null)};toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");const e=r(this._type,this._width,this._height);return this._renderer.readRenderTargetPixels(this._renderTarget,0,0,this._width,this._height,e),e}toDataTexture(e){const r=new t.DataTexture(this.toArray(),this.width,this.height,t.RGBAFormat,this._type,e?.mapping||t.UVMapping,e?.wrapS||t.ClampToEdgeWrapping,e?.wrapT||t.ClampToEdgeWrapping,e?.magFilter||t.LinearFilter,e?.minFilter||t.LinearFilter,e?.anisotropy||1,t.LinearSRGBColorSpace);return r.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,r}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&(this._renderer.dispose(),this._renderer.forceContextLoss())}dispose(e){this.disposeOnDemandRenderer(),e&&this.renderTarget.dispose(),this.material instanceof t.ShaderMaterial&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof t.Texture&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof t.Texture&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose()}get width(){return this._width}set width(e){this._width=e,this._renderTarget.setSize(this._width,this._height)}get height(){return this._height}set height(e){this._height=e,this._renderTarget.setSize(this._width,this._height)}get renderer(){return this._renderer}get renderTarget(){return this._renderTarget}set renderTarget(e){this._renderTarget=e,this._width=e.width,this._height=e.height}get material(){return this._material}get type(){return this._type}get colorSpace(){return this._colorSpace}}function n(e){return r=>{const{sdr:a,gainMap:i,renderer:n}=r;a.colorSpace!==t.SRGBColorSpace&&(console.warn("SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically"),a.colorSpace=t.SRGBColorSpace),a.needsUpdate=!0,i.colorSpace!==t.LinearSRGBColorSpace&&(console.warn("Gainmap Colorspace needs to be *LinearSRGBColorSpace*, setting it automatically"),i.colorSpace=t.LinearSRGBColorSpace),i.needsUpdate=!0;const s=e.createMaterial({...r,sdr:a,gainMap:i});return e.createQuadRenderer({width:a.image.width,height:a.image.height,type:t.HalfFloatType,colorSpace:t.LinearSRGBColorSpace,material:s,renderer:n,renderTargetOptions:r.renderTargetOptions})}}class s extends Error{}class o extends Error{}const d=e=>{const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let r=0;const a=()=>{const e=t.getUint16(r);return r+=2,e},i=()=>{const e=t.getUint32(r);return r+=4,e},n=a();if(0!==n)throw new Error(`Unsupported ISO 21496-1 minimum_version ${n}`);a();const s=t.getUint8(r++);if(4&s)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const o=128&s?3:1,d=8&s?i():void 0,p=e=>{const a=e?(()=>{const e=t.getInt32(r);return r+=4,e})():i(),n=d??i();if(0===n)throw new Error("Invalid ISO 21496-1 fraction with zero denominator");return a/n},h=p(!1),l=p(!1);if(h>l)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const c=[],g=[],m=[],f=[],u=[];for(let e=0;e<o;e++)c.push(p(!0)),g.push(p(!0)),m.push(p(!1)),f.push(p(!0)),u.push(p(!0));const y=e=>3===o?e:[e[0],e[0],e[0]];return{gainMapMin:y(c),gainMapMax:y(g),gamma:y(m),offsetSdr:y(f),offsetHdr:y(u),hdrCapacityMin:h,hdrCapacityMax:l}},p=Array.from("urn:iso:std:iso:ts:21496:-1\0",e=>e.charCodeAt(0)),h=e=>{const t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=4+p.length;for(let a=0;a+r<e.length;a++){if(255!==e[a]||226!==e[a+1])continue;if(!p.every((t,r)=>e[a+4+r]===t))continue;const i=Math.min(e.length,a+2+t.getUint16(a+2));if(!(i-(a+r)<=4))try{return d(e.subarray(a+r,i))}catch(e){return}}},l=(e,t,r)=>{const a=new RegExp(`${t}="([^"]*)"`,"i").exec(e);if(a)return a[1];const i=new RegExp(`<${t}[^>]*>([\\s\\S]*?)</${t}>`,"i").exec(e);if(i){const e=i[1].match(/<rdf:li>([^<]*)<\/rdf:li>/g);return e&&3===e.length?e.map(e=>e.replace(/<\/?rdf:li>/g,"")):i[1].trim()}if(void 0!==r)return r;throw new Error(`Can't find ${t} in gainmap metadata`)},c=e=>{let t;t="undefined"!=typeof TextDecoder?(new TextDecoder).decode(e):e.toString();let r=t.indexOf("<x:xmpmeta");for(;-1!==r;){const e=t.indexOf("x:xmpmeta>",r),a=t.slice(r,e+10);try{const e=l(a,"hdrgm:GainMapMin","0"),t=l(a,"hdrgm:GainMapMax"),r=l(a,"hdrgm:Gamma","1"),i=l(a,"hdrgm:OffsetSDR","0.015625"),n=l(a,"hdrgm:OffsetHDR","0.015625"),s=/hdrgm:HDRCapacityMin="([^"]*)"/.exec(a),o=s?s[1]:"0",d=/hdrgm:HDRCapacityMax="([^"]*)"/.exec(a);if(!d)throw new Error("Incomplete gainmap metadata");const p=d[1];return{gainMapMin:Array.isArray(e)?e.map(e=>parseFloat(e)):[parseFloat(e),parseFloat(e),parseFloat(e)],gainMapMax:Array.isArray(t)?t.map(e=>parseFloat(e)):[parseFloat(t),parseFloat(t),parseFloat(t)],gamma:Array.isArray(r)?r.map(e=>parseFloat(e)):[parseFloat(r),parseFloat(r),parseFloat(r)],offsetSdr:Array.isArray(i)?i.map(e=>parseFloat(e)):[parseFloat(i),parseFloat(i),parseFloat(i)],offsetHdr:Array.isArray(n)?n.map(e=>parseFloat(e)):[parseFloat(n),parseFloat(n),parseFloat(n)],hdrCapacityMin:parseFloat(o),hdrCapacityMax:parseFloat(p)}}catch(e){}r=t.indexOf("<x:xmpmeta",e)}};class g{options;constructor(e){this.options={debug:!(!e||void 0===e.debug)&&e.debug,extractFII:!e||void 0===e.extractFII||e.extractFII,extractNonFII:!e||void 0===e.extractNonFII||e.extractNonFII}}extract(e){return new Promise((t,r)=>{const a=this.options.debug,i=new DataView(e.buffer);if(65496!==i.getUint16(0))return void r(new Error("Not a valid jpeg"));const n=i.byteLength;let s,o=2,d=0;for(;o<n;){if(++d>250)return void r(new Error(`Found no marker after ${d} loops 😵`));if(255!==i.getUint8(o))return void r(new Error(`Not a valid marker at offset 0x${o.toString(16)}, found: 0x${i.getUint8(o).toString(16)}`));if(s=i.getUint8(o+1),a&&console.log(`Marker: ${s.toString(16)}`),226===s){a&&console.log("Found APP2 marker (0xffe2)");const e=o+4;if(1297106432===i.getUint32(e)){const a=e+4;let n;if(18761===i.getUint16(a))n=!1;else{if(19789!==i.getUint16(a))return void r(new Error("No valid endianness marker found in TIFF header"));n=!0}if(42!==i.getUint16(a+2,!n))return void r(new Error("Not valid TIFF data! (no 0x002A marker)"));const s=i.getUint32(a+4,!n);if(s<8)return void r(new Error("Not valid TIFF data! (First offset less than 8)"));const o=a+s,d=i.getUint16(o,!n),p=o+2;let h=0;for(let e=p;e<p+12*d;e+=12)45057===i.getUint16(e,!n)&&(h=i.getUint32(e+8,!n));const l=o+2+12*d+4,c=[];for(let e=l;e<l+16*h;e+=16){const t={MPType:i.getUint32(e,!n),size:i.getUint32(e+4,!n),dataOffset:i.getUint32(e+8,!n),dependantImages:i.getUint32(e+12,!n),start:-1,end:-1,isFII:!1};t.dataOffset?(t.start=a+t.dataOffset,t.isFII=!1):(t.start=0,t.isFII=!0),t.end=t.start+t.size,c.push(t)}if(this.options.extractNonFII&&c.length){const e=new Blob([i]),r=[];for(const t of c){if(t.isFII&&!this.options.extractFII)continue;const a=e.slice(t.start,t.end+1,"image/jpeg");r.push(a)}t(r)}}}o+=2+i.getUint16(o+2)}})}}const m=async e=>{const t=h(e)??c(e);if(!t)throw new o("Gain map XMP metadata not found");const r=new g({extractFII:!0,extractNonFII:!0}),a=await r.extract(e);if(2!==a.length)throw new s("Gain map recovery image not found");return{sdr:new Uint8Array(await a[0].arrayBuffer()),gainMap:new Uint8Array(await a[1].arrayBuffer()),metadata:t}},f=e=>new Promise((t,r)=>{const a=document.createElement("img");a.onload=()=>{t(a)},a.onerror=e=>{r(e)},a.src=URL.createObjectURL(e)});class u extends t.Loader{_renderer;_renderTargetOptions;_internalLoadingManager;_config;constructor(e,r){super(r),this._config=e,e.renderer&&(this._renderer=e.renderer),this._internalLoadingManager=new t.LoadingManager}setRenderer(e){return this._renderer=e,this}setRenderTargetOptions(e){return this._renderTargetOptions=e,this}prepareQuadRenderer(){this._renderer||console.warn("WARNING: A Renderer was not passed to this Loader constructor or in setRenderer, the result of this Loader will need to be converted to a Data Texture with toDataTexture() before you can use it in your renderer.");const e=this._config.createMaterial({gainMapMax:[1,1,1],gainMapMin:[0,0,0],gamma:[1,1,1],offsetHdr:[1,1,1],offsetSdr:[1,1,1],hdrCapacityMax:1,hdrCapacityMin:0,maxDisplayBoost:1,gainMap:new t.Texture,sdr:new t.Texture});return this._config.createQuadRenderer({width:16,height:16,type:t.HalfFloatType,colorSpace:t.LinearSRGBColorSpace,material:e,renderer:this._renderer,renderTargetOptions:this._renderTargetOptions})}async processImages(e,t,r){const a=t?new Blob([t],{type:"image/jpeg"}):void 0,i=new Blob([e],{type:"image/jpeg"});let n,s,o=!1;if("undefined"==typeof createImageBitmap){const e=await Promise.all([a?f(a):Promise.resolve(void 0),f(i)]);s=e[0],n=e[1],o="flipY"===r}else{const e=await Promise.all([a?createImageBitmap(a,{imageOrientation:r||"flipY"}):Promise.resolve(void 0),createImageBitmap(i,{imageOrientation:r||"flipY"})]);s=e[0],n=e[1]}return{sdrImage:n,gainMapImage:s,needsFlip:o}}createTextures(e,r,a){const i=new t.Texture(r||new ImageData(2,2),t.UVMapping,t.ClampToEdgeWrapping,t.ClampToEdgeWrapping,t.LinearFilter,t.LinearMipMapLinearFilter,t.RGBAFormat,t.UnsignedByteType,1,t.LinearSRGBColorSpace);i.flipY=a,i.needsUpdate=!0;const n=new t.Texture(e,t.UVMapping,t.ClampToEdgeWrapping,t.ClampToEdgeWrapping,t.LinearFilter,t.LinearMipMapLinearFilter,t.RGBAFormat,t.UnsignedByteType,1,t.SRGBColorSpace);return n.flipY=a,n.needsUpdate=!0,{gainMap:i,sdr:n}}updateQuadRenderer(e,t,r,a,i){e.width=t.width,e.height=t.height,e.material.gainMap=r,e.material.sdr=a,e.material.gainMapMin=i.gainMapMin,e.material.gainMapMax=i.gainMapMax,e.material.offsetHdr=i.offsetHdr,e.material.offsetSdr=i.offsetSdr,e.material.gamma=i.gamma,e.material.hdrCapacityMin=i.hdrCapacityMin,e.material.hdrCapacityMax=i.hdrCapacityMax,e.material.maxDisplayBoost=Math.pow(2,i.hdrCapacityMax),e.material.needsUpdate=!0}}class y extends t.ShaderMaterial{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;constructor({gamma:e,offsetHdr:r,offsetSdr:a,gainMapMin:i,gainMapMax:n,maxDisplayBoost:s,hdrCapacityMin:o,hdrCapacityMax:d,sdr:p,gainMap:h}){super({name:"GainMapDecoderMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n// min half float value\n#define HALF_FLOAT_MIN vec3( -65504, -65504, -65504 )\n// max half float value\n#define HALF_FLOAT_MAX vec3( 65504, 65504, 65504 )\n\nuniform sampler2D sdr;\nuniform sampler2D gainMap;\nuniform vec3 gamma;\nuniform vec3 offsetHdr;\nuniform vec3 offsetSdr;\nuniform vec3 gainMapMin;\nuniform vec3 gainMapMax;\nuniform float weightFactor;\n\nvarying vec2 vUv;\n\nvoid main() {\n vec3 rgb = texture2D( sdr, vUv ).rgb;\n vec3 recovery = texture2D( gainMap, vUv ).rgb;\n vec3 logRecovery = pow( recovery, gamma );\n vec3 logBoost = gainMapMin * ( 1.0 - logRecovery ) + gainMapMax * logRecovery;\n vec3 hdrColor = (rgb + offsetSdr) * exp2( logBoost * weightFactor ) - offsetHdr;\n vec3 clampedHdrColor = max( HALF_FLOAT_MIN, min( HALF_FLOAT_MAX, hdrColor ));\n gl_FragColor = vec4( clampedHdrColor , 1.0 );\n}\n",uniforms:{sdr:{value:p},gainMap:{value:h},gamma:{value:new t.Vector3(1/e[0],1/e[1],1/e[2])},offsetHdr:{value:(new t.Vector3).fromArray(r)},offsetSdr:{value:(new t.Vector3).fromArray(a)},gainMapMin:{value:(new t.Vector3).fromArray(i)},gainMapMax:{value:(new t.Vector3).fromArray(n)},weightFactor:{value:(Math.log2(s)-o)/(d-o)}},blending:t.NoBlending,depthTest:!1,depthWrite:!1}),this._maxDisplayBoost=s,this._hdrCapacityMin=o,this._hdrCapacityMax=d,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get sdr(){return this.uniforms.sdr.value}set sdr(e){this.uniforms.sdr.value=e}get gainMap(){return this.uniforms.gainMap.value}set gainMap(e){this.uniforms.gainMap.value=e}get offsetHdr(){return this.uniforms.offsetHdr.value.toArray()}set offsetHdr(e){this.uniforms.offsetHdr.value.fromArray(e)}get offsetSdr(){return this.uniforms.offsetSdr.value.toArray()}set offsetSdr(e){this.uniforms.offsetSdr.value.fromArray(e)}get gainMapMin(){return this.uniforms.gainMapMin.value.toArray()}set gainMapMin(e){this.uniforms.gainMapMin.value.fromArray(e)}get gainMapMax(){return this.uniforms.gainMapMax.value.toArray()}set gainMapMax(e){this.uniforms.gainMapMax.value.fromArray(e)}get gamma(){const e=this.uniforms.gamma.value;return[1/e.x,1/e.y,1/e.z]}set gamma(e){const t=this.uniforms.gamma.value;t.x=1/e[0],t.y=1/e[1],t.z=1/e[2]}get hdrCapacityMin(){return this._hdrCapacityMin}set hdrCapacityMin(e){this._hdrCapacityMin=e,this.calculateWeight()}get hdrCapacityMax(){return this._hdrCapacityMax}set hdrCapacityMax(e){this._hdrCapacityMax=e,this.calculateWeight()}get maxDisplayBoost(){return this._maxDisplayBoost}set maxDisplayBoost(e){this._maxDisplayBoost=Math.max(1,Math.min(65504,e)),this.calculateWeight()}calculateWeight(){const e=(Math.log2(this._maxDisplayBoost)-this._hdrCapacityMin)/(this._hdrCapacityMax-this._hdrCapacityMin);this.uniforms.weightFactor.value=Math.max(0,Math.min(1,e))}}const w=n({renderer:t.WebGLRenderer,createMaterial:e=>new y(e),createQuadRenderer:e=>new i(e)});class M extends u{constructor(e,t){super({renderer:e,createMaterial:e=>new y(e),createQuadRenderer:e=>new i(e)},t)}async render(e,t,r,a){const{sdrImage:i,gainMapImage:n,needsFlip:s}=await this.processImages(r,a,"flipY"),{gainMap:o,sdr:d}=this.createTextures(i,n,s);this.updateQuadRenderer(e,i,o,d,t),e.render()}}class _ extends M{load(e,r,a,i){const n=this.prepareQuadRenderer(),d=new t.FileLoader(this._internalLoadingManager);return d.setResponseType("arraybuffer"),d.setRequestHeader(this.requestHeader),d.setPath(this.path),d.setWithCredentials(this.withCredentials),this.manager.itemStart(e),d.load(e,async t=>{if("string"==typeof t)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const a=new Uint8Array(t);let d,p,h;try{const e=await m(a);d=e.sdr,p=e.gainMap,h=e.metadata}catch(t){if(!(t instanceof o||t instanceof s))throw t;console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`),h={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},d=a}try{await this.render(n,h,d.buffer,p?.buffer)}catch(t){return this.manager.itemError(e),"function"==typeof i&&i(t),void n.disposeOnDemandRenderer()}"function"==typeof r&&r(n),this.manager.itemEnd(e),n.disposeOnDemandRenderer()},a,t=>{this.manager.itemError(e),"function"==typeof i&&i(t)}),n}}e.GainMapDecoderMaterial=y,e.GainMapLoader=class extends M{load([e,r,a],i,n,s){const o=this.prepareQuadRenderer();let d,p,h;const l=async()=>{if(d&&p&&h){try{await this.render(o,h,d,p)}catch(t){return this.manager.itemError(e),this.manager.itemError(r),this.manager.itemError(a),"function"==typeof s&&s(t),void o.disposeOnDemandRenderer()}"function"==typeof i&&i(o),this.manager.itemEnd(e),this.manager.itemEnd(r),this.manager.itemEnd(a),o.disposeOnDemandRenderer()}};let c=!0,g=0,m=0,f=!0,u=0,y=0,w=!0,M=0,_=0;const x=()=>{if("function"==typeof n){n(new ProgressEvent("progress",{lengthComputable:c&&f&&w,loaded:m+y+_,total:g+u+M}))}};this.manager.itemStart(e),this.manager.itemStart(r),this.manager.itemStart(a);const v=new t.FileLoader(this._internalLoadingManager);v.setResponseType("arraybuffer"),v.setRequestHeader(this.requestHeader),v.setPath(this.path),v.setWithCredentials(this.withCredentials),v.load(e,async e=>{if("string"==typeof e)throw new Error("Invalid sdr buffer");d=e,await l()},e=>{c=e.lengthComputable,m=e.loaded,g=e.total,x()},t=>{this.manager.itemError(e),"function"==typeof s&&s(t)});const T=new t.FileLoader(this._internalLoadingManager);T.setResponseType("arraybuffer"),T.setRequestHeader(this.requestHeader),T.setPath(this.path),T.setWithCredentials(this.withCredentials),T.load(r,async e=>{if("string"==typeof e)throw new Error("Invalid gainmap buffer");p=e,await l()},e=>{f=e.lengthComputable,y=e.loaded,u=e.total,x()},e=>{this.manager.itemError(r),"function"==typeof s&&s(e)});const F=new t.FileLoader(this._internalLoadingManager);return F.setRequestHeader(this.requestHeader),F.setPath(this.path),F.setWithCredentials(this.withCredentials),F.load(a,async e=>{if("string"!=typeof e)throw new Error("Invalid metadata string");h=JSON.parse(e),await l()},e=>{w=e.lengthComputable,_=e.loaded,M=e.total,x()},e=>{this.manager.itemError(a),"function"==typeof s&&s(e)}),o}},e.GainMapNotFoundError=s,e.HDRJPGLoader=_,e.JPEGRLoader=_,e.LoaderBaseShared=u,e.MPFExtractor=g,e.QuadRenderer=i,e.XMPMetadataNotFoundError=o,e.createDecodeFunction=n,e.decode=e=>{if(!e.renderer)throw new Error("Renderer is required for decode function");const t=w({...e,renderer:e.renderer});try{t.render()}catch(e){throw t.disposeOnDemandRenderer(),e}return t},e.extractGainmapFromJPEG=m,e.extractISO=h,e.extractXMP=c});
5
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three")):"function"==typeof define&&define.amd?define(["exports","three"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@monogrid/gainmap-js"]={},e.three)}(this,function(e,t){"use strict";const r=(e,r,a)=>{let n;switch(e){case t.UnsignedByteType:n=new Uint8ClampedArray(r*a*4);break;case t.HalfFloatType:n=new Uint16Array(r*a*4);break;case t.UnsignedIntType:n=new Uint32Array(r*a*4);break;case t.ByteType:n=new Int8Array(r*a*4);break;case t.ShortType:n=new Int16Array(r*a*4);break;case t.IntType:n=new Int32Array(r*a*4);break;case t.FloatType:n=new Float32Array(r*a*4);break;default:throw new Error("Unsupported data type")}return n};let a;class n{_renderer;_rendererIsDisposable=!1;_material;_scene;_camera;_quad;_renderTarget;_width;_height;_type;_colorSpace;_supportsReadPixels=!0;constructor(e){this._width=e.width,this._height=e.height,this._type=e.type,this._colorSpace=e.colorSpace;const i={format:t.RGBAFormat,depthBuffer:!1,stencilBuffer:!1,type:this._type,colorSpace:this._colorSpace,anisotropy:void 0!==e.renderTargetOptions?.anisotropy?e.renderTargetOptions?.anisotropy:1,generateMipmaps:void 0!==e.renderTargetOptions?.generateMipmaps&&e.renderTargetOptions?.generateMipmaps,magFilter:void 0!==e.renderTargetOptions?.magFilter?e.renderTargetOptions?.magFilter:t.LinearFilter,minFilter:void 0!==e.renderTargetOptions?.minFilter?e.renderTargetOptions?.minFilter:t.LinearFilter,samples:void 0!==e.renderTargetOptions?.samples?e.renderTargetOptions?.samples:void 0,wrapS:void 0!==e.renderTargetOptions?.wrapS?e.renderTargetOptions?.wrapS:t.ClampToEdgeWrapping,wrapT:void 0!==e.renderTargetOptions?.wrapT?e.renderTargetOptions?.wrapT:t.ClampToEdgeWrapping};if(this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=n.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new t.Scene,this._camera=new t.OrthographicCamera,this._camera.position.set(0,0,10),this._camera.left=-.5,this._camera.right=.5,this._camera.top=.5,this._camera.bottom=-.5,this._camera.updateProjectionMatrix(),!((e,n,i,s)=>{if(void 0!==a)return a;const o=new t.WebGLRenderTarget(1,1,s);n.setRenderTarget(o);const d=new t.Mesh(new t.PlaneGeometry,new t.MeshBasicMaterial({color:16777215}));n.render(d,i),n.setRenderTarget(null);const p=r(e,o.width,o.height);return n.readRenderTargetPixels(o,0,0,o.width,o.height,p),o.dispose(),d.geometry.dispose(),d.material.dispose(),a=0!==p[0],a})(this._type,this._renderer,this._camera,i)){let e;if(this._type===t.HalfFloatType)e=this._renderer.extensions.has("EXT_color_buffer_float")?t.FloatType:void 0;void 0!==e?(console.warn(`This browser does not support reading pixels from ${this._type} RenderTargets, switching to ${t.FloatType}`),this._type=e):(this._supportsReadPixels=!1,console.warn("This browser dos not support toArray or toDataTexture, calls to those methods will result in an error thrown"))}this._quad=new t.Mesh(new t.PlaneGeometry,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new t.WebGLRenderTarget(this.width,this.height,i),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:t.UVMapping}static instantiateRenderer(){const e=new t.WebGLRenderer;return e.setSize(128,128),e}render=()=>{this._renderer.setRenderTarget(this._renderTarget);try{this._renderer.render(this._scene,this._camera)}catch(e){throw this._renderer.setRenderTarget(null),e}this._renderer.setRenderTarget(null)};toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");const e=r(this._type,this._width,this._height);return this._renderer.readRenderTargetPixels(this._renderTarget,0,0,this._width,this._height,e),e}toDataTexture(e){const r=new t.DataTexture(this.toArray(),this.width,this.height,t.RGBAFormat,this._type,e?.mapping||t.UVMapping,e?.wrapS||t.ClampToEdgeWrapping,e?.wrapT||t.ClampToEdgeWrapping,e?.magFilter||t.LinearFilter,e?.minFilter||t.LinearFilter,e?.anisotropy||1,t.LinearSRGBColorSpace);return r.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,r}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&(this._renderer.dispose(),this._renderer.forceContextLoss())}dispose(e){this.disposeOnDemandRenderer(),e&&this.renderTarget.dispose(),this.material instanceof t.ShaderMaterial&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof t.Texture&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof t.Texture&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose()}get width(){return this._width}set width(e){this._width=e,this._renderTarget.setSize(this._width,this._height)}get height(){return this._height}set height(e){this._height=e,this._renderTarget.setSize(this._width,this._height)}get renderer(){return this._renderer}get renderTarget(){return this._renderTarget}set renderTarget(e){this._renderTarget=e,this._width=e.width,this._height=e.height}get material(){return this._material}get type(){return this._type}get colorSpace(){return this._colorSpace}}function i(e){return r=>{const{sdr:a,gainMap:n,renderer:i}=r;a.colorSpace!==t.SRGBColorSpace&&(console.warn("SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically"),a.colorSpace=t.SRGBColorSpace),a.needsUpdate=!0,n.colorSpace!==t.LinearSRGBColorSpace&&(console.warn("Gainmap Colorspace needs to be *LinearSRGBColorSpace*, setting it automatically"),n.colorSpace=t.LinearSRGBColorSpace),n.needsUpdate=!0;const s=e.createMaterial({...r,sdr:a,gainMap:n});return e.createQuadRenderer({width:a.image.width,height:a.image.height,type:t.HalfFloatType,colorSpace:t.LinearSRGBColorSpace,material:s,renderer:i,renderTargetOptions:r.renderTargetOptions})}}class s extends Error{}class o extends Error{}const d=e=>{const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let r=0;const a=()=>{const e=t.getUint16(r);return r+=2,e},n=()=>{const e=t.getUint32(r);return r+=4,e},i=a();if(0!==i)throw new Error(`Unsupported ISO 21496-1 minimum_version ${i}`);a();const s=t.getUint8(r++);if(4&s)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const o=128&s?3:1,d=8&s?n():void 0,p=e=>{const a=e?(()=>{const e=t.getInt32(r);return r+=4,e})():n(),i=d??n();if(0===i)throw new Error("Invalid ISO 21496-1 fraction with zero denominator");return a/i},h=p(!1),c=p(!1);if(h>c)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const g=[],l=[],m=[],f=[],u=[];for(let e=0;e<o;e++)g.push(p(!0)),l.push(p(!0)),m.push(p(!1)),f.push(p(!0)),u.push(p(!0));const y=e=>3===o?e:[e[0],e[0],e[0]];return{gainMapMin:y(g),gainMapMax:y(l),gamma:y(m),offsetSdr:y(f),offsetHdr:y(u),hdrCapacityMin:h,hdrCapacityMax:c}},p=Array.from("urn:iso:std:iso:ts:21496:-1\0",e=>e.charCodeAt(0)),h=e=>{const t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=4+p.length;for(let a=0;a+r<e.length;a++){if(255!==e[a]||226!==e[a+1])continue;if(!p.every((t,r)=>e[a+4+r]===t))continue;const n=Math.min(e.length,a+2+t.getUint16(a+2));if(!(n-(a+r)<=4))try{return d(e.subarray(a+r,n))}catch(e){return}}},c=(e,t,r)=>{const a=new RegExp(`${t}="([^"]*)"`,"i").exec(e);if(a)return a[1];const n=new RegExp(`<${t}[^>]*>([\\s\\S]*?)</${t}>`,"i").exec(e);if(n){const e=n[1].match(/<rdf:li>([^<]*)<\/rdf:li>/g);return e&&3===e.length?e.map(e=>e.replace(/<\/?rdf:li>/g,"")):n[1].trim()}if(void 0!==r)return r;throw new Error(`Can't find ${t} in gainmap metadata`)},g=e=>{let t;t="undefined"!=typeof TextDecoder?(new TextDecoder).decode(e):e.toString();let r=t.indexOf("<x:xmpmeta");for(;-1!==r;){const e=t.indexOf("x:xmpmeta>",r),a=t.slice(r,e+10);try{const e=c(a,"hdrgm:GainMapMin","0"),t=c(a,"hdrgm:GainMapMax"),r=c(a,"hdrgm:Gamma","1"),n=c(a,"hdrgm:OffsetSDR","0.015625"),i=c(a,"hdrgm:OffsetHDR","0.015625"),s=/hdrgm:HDRCapacityMin="([^"]*)"/.exec(a),o=s?s[1]:"0",d=/hdrgm:HDRCapacityMax="([^"]*)"/.exec(a);if(!d)throw new Error("Incomplete gainmap metadata");const p=d[1];return{gainMapMin:Array.isArray(e)?e.map(e=>parseFloat(e)):[parseFloat(e),parseFloat(e),parseFloat(e)],gainMapMax:Array.isArray(t)?t.map(e=>parseFloat(e)):[parseFloat(t),parseFloat(t),parseFloat(t)],gamma:Array.isArray(r)?r.map(e=>parseFloat(e)):[parseFloat(r),parseFloat(r),parseFloat(r)],offsetSdr:Array.isArray(n)?n.map(e=>parseFloat(e)):[parseFloat(n),parseFloat(n),parseFloat(n)],offsetHdr:Array.isArray(i)?i.map(e=>parseFloat(e)):[parseFloat(i),parseFloat(i),parseFloat(i)],hdrCapacityMin:parseFloat(o),hdrCapacityMax:parseFloat(p)}}catch(e){}r=t.indexOf("<x:xmpmeta",e)}};class l{options;constructor(e){this.options={debug:!(!e||void 0===e.debug)&&e.debug,extractFII:!e||void 0===e.extractFII||e.extractFII,extractNonFII:!e||void 0===e.extractNonFII||e.extractNonFII}}extract(e){return new Promise((t,r)=>{const a=this.options.debug,n=new DataView(e.buffer);if(65496!==n.getUint16(0))return void r(new Error("Not a valid jpeg"));const i=n.byteLength;let s,o=2,d=0;for(;o<i;){if(++d>250)return void r(new Error(`Found no marker after ${d} loops 😵`));if(255!==n.getUint8(o))return void r(new Error(`Not a valid marker at offset 0x${o.toString(16)}, found: 0x${n.getUint8(o).toString(16)}`));if(s=n.getUint8(o+1),a&&console.log(`Marker: ${s.toString(16)}`),226===s){a&&console.log("Found APP2 marker (0xffe2)");const e=o+4;if(1297106432===n.getUint32(e)){const a=e+4;let i;if(18761===n.getUint16(a))i=!1;else{if(19789!==n.getUint16(a))return void r(new Error("No valid endianness marker found in TIFF header"));i=!0}if(42!==n.getUint16(a+2,!i))return void r(new Error("Not valid TIFF data! (no 0x002A marker)"));const s=n.getUint32(a+4,!i);if(s<8)return void r(new Error("Not valid TIFF data! (First offset less than 8)"));const o=a+s,d=n.getUint16(o,!i),p=o+2;let h=0;for(let e=p;e<p+12*d;e+=12)45057===n.getUint16(e,!i)&&(h=n.getUint32(e+8,!i));const c=o+2+12*d+4,g=[];for(let e=c;e<c+16*h;e+=16){const t={MPType:n.getUint32(e,!i),size:n.getUint32(e+4,!i),dataOffset:n.getUint32(e+8,!i),dependantImages:n.getUint32(e+12,!i),start:-1,end:-1,isFII:!1};t.dataOffset?(t.start=a+t.dataOffset,t.isFII=!1):(t.start=0,t.isFII=!0),t.end=t.start+t.size,g.push(t)}if(this.options.extractNonFII&&g.length){const e=new Blob([n]),r=[];for(const t of g){if(t.isFII&&!this.options.extractFII)continue;const a=e.slice(t.start,t.end+1,"image/jpeg");r.push(a)}t(r)}}}o+=2+n.getUint16(o+2)}})}}const m=async e=>{const t=h(e)??g(e);if(!t)throw new o("Gain map XMP metadata not found");const r=new l({extractFII:!0,extractNonFII:!0}),a=await r.extract(e);if(2!==a.length)throw new s("Gain map recovery image not found");return{sdr:new Uint8Array(await a[0].arrayBuffer()),gainMap:new Uint8Array(await a[1].arrayBuffer()),metadata:t}},f=e=>new Promise((t,r)=>{const a=document.createElement("img");a.onload=()=>{t(a)},a.onerror=e=>{r(e)},a.src=URL.createObjectURL(e)}),u=async(e,t,r)=>{const a=t?new Blob([t],{type:"image/jpeg"}):void 0,n=new Blob([e],{type:"image/jpeg"});let i,s,o=!1;if("undefined"==typeof createImageBitmap){const e=await Promise.all([a?f(a):Promise.resolve(void 0),f(n)]);s=e[0],i=e[1],o="flipY"===r}else{const e=await Promise.all([a?createImageBitmap(a,{imageOrientation:r||"flipY"}):Promise.resolve(void 0),createImageBitmap(n,{imageOrientation:r||"flipY"})]);s=e[0],i=e[1]}return{sdrImage:i,gainMapImage:s,needsFlip:o}},y=(e,r,a)=>{const n=new t.Texture(r||new ImageData(2,2),t.UVMapping,t.ClampToEdgeWrapping,t.ClampToEdgeWrapping,t.LinearFilter,t.LinearMipMapLinearFilter,t.RGBAFormat,t.UnsignedByteType,1,t.LinearSRGBColorSpace);n.flipY=a,n.needsUpdate=!0;const i=new t.Texture(e,t.UVMapping,t.ClampToEdgeWrapping,t.ClampToEdgeWrapping,t.LinearFilter,t.LinearMipMapLinearFilter,t.RGBAFormat,t.UnsignedByteType,1,t.SRGBColorSpace);return i.flipY=a,i.needsUpdate=!0,{gainMap:n,sdr:i}};class w extends t.Loader{_renderer;_renderTargetOptions;_internalLoadingManager;_config;constructor(e,r){super(r),this._config=e,e.renderer&&(this._renderer=e.renderer),this._internalLoadingManager=new t.LoadingManager}setRenderer(e){return this._renderer=e,this}setRenderTargetOptions(e){return this._renderTargetOptions=e,this}prepareQuadRenderer(){this._renderer||console.warn("WARNING: A Renderer was not passed to this Loader constructor or in setRenderer, the result of this Loader will need to be converted to a Data Texture with toDataTexture() before you can use it in your renderer.");const e=this._config.createMaterial({gainMapMax:[1,1,1],gainMapMin:[0,0,0],gamma:[1,1,1],offsetHdr:[1,1,1],offsetSdr:[1,1,1],hdrCapacityMax:1,hdrCapacityMin:0,maxDisplayBoost:1,gainMap:new t.Texture,sdr:new t.Texture});return this._config.createQuadRenderer({width:16,height:16,type:t.HalfFloatType,colorSpace:t.LinearSRGBColorSpace,material:e,renderer:this._renderer,renderTargetOptions:this._renderTargetOptions})}processImages(e,t,r){return u(e,t,r)}createTextures(e,t,r){return y(e,t,r)}updateQuadRenderer(e,t,r,a,n){e.width=t.width,e.height=t.height,e.material.gainMap=r,e.material.sdr=a,e.material.gainMapMin=n.gainMapMin,e.material.gainMapMax=n.gainMapMax,e.material.offsetHdr=n.offsetHdr,e.material.offsetSdr=n.offsetSdr,e.material.gamma=n.gamma,e.material.hdrCapacityMin=n.hdrCapacityMin,e.material.hdrCapacityMax=n.hdrCapacityMax,e.material.maxDisplayBoost=Math.pow(2,n.hdrCapacityMax),e.material.needsUpdate=!0}}const M=new Set,_=(e,t,r)=>{const a=`${t}:${e}`;M.has(a)||(M.add(a),console.warn(`gainmap-js: ${e} from '${t}' is deprecated and will be removed in v4.0.0. Use ${r} from '@monogrid/gainmap-js/webgpu' with WebGPURenderer (which also has a WebGL2 backend) instead. It is not a drop-in replacement (it returns a GainMapNode, not a render target), see https://github.com/MONOGRID/gainmap-js#migrating-to-v400`))};class x extends t.ShaderMaterial{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;constructor({gamma:e,offsetHdr:r,offsetSdr:a,gainMapMin:n,gainMapMax:i,maxDisplayBoost:s,hdrCapacityMin:o,hdrCapacityMax:d,sdr:p,gainMap:h}){super({name:"GainMapDecoderMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n// min half float value\n#define HALF_FLOAT_MIN vec3( -65504, -65504, -65504 )\n// max half float value\n#define HALF_FLOAT_MAX vec3( 65504, 65504, 65504 )\n\nuniform sampler2D sdr;\nuniform sampler2D gainMap;\nuniform vec3 gamma;\nuniform vec3 offsetHdr;\nuniform vec3 offsetSdr;\nuniform vec3 gainMapMin;\nuniform vec3 gainMapMax;\nuniform float weightFactor;\n\nvarying vec2 vUv;\n\nvoid main() {\n vec3 rgb = texture2D( sdr, vUv ).rgb;\n vec3 recovery = texture2D( gainMap, vUv ).rgb;\n vec3 logRecovery = pow( recovery, gamma );\n vec3 logBoost = gainMapMin * ( 1.0 - logRecovery ) + gainMapMax * logRecovery;\n vec3 hdrColor = (rgb + offsetSdr) * exp2( logBoost * weightFactor ) - offsetHdr;\n vec3 clampedHdrColor = max( HALF_FLOAT_MIN, min( HALF_FLOAT_MAX, hdrColor ));\n gl_FragColor = vec4( clampedHdrColor , 1.0 );\n}\n",uniforms:{sdr:{value:p},gainMap:{value:h},gamma:{value:new t.Vector3(1/e[0],1/e[1],1/e[2])},offsetHdr:{value:(new t.Vector3).fromArray(r)},offsetSdr:{value:(new t.Vector3).fromArray(a)},gainMapMin:{value:(new t.Vector3).fromArray(n)},gainMapMax:{value:(new t.Vector3).fromArray(i)},weightFactor:{value:(Math.log2(s)-o)/(d-o)}},blending:t.NoBlending,depthTest:!1,depthWrite:!1}),this._maxDisplayBoost=s,this._hdrCapacityMin=o,this._hdrCapacityMax=d,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get sdr(){return this.uniforms.sdr.value}set sdr(e){this.uniforms.sdr.value=e}get gainMap(){return this.uniforms.gainMap.value}set gainMap(e){this.uniforms.gainMap.value=e}get offsetHdr(){return this.uniforms.offsetHdr.value.toArray()}set offsetHdr(e){this.uniforms.offsetHdr.value.fromArray(e)}get offsetSdr(){return this.uniforms.offsetSdr.value.toArray()}set offsetSdr(e){this.uniforms.offsetSdr.value.fromArray(e)}get gainMapMin(){return this.uniforms.gainMapMin.value.toArray()}set gainMapMin(e){this.uniforms.gainMapMin.value.fromArray(e)}get gainMapMax(){return this.uniforms.gainMapMax.value.toArray()}set gainMapMax(e){this.uniforms.gainMapMax.value.fromArray(e)}get gamma(){const e=this.uniforms.gamma.value;return[1/e.x,1/e.y,1/e.z]}set gamma(e){const t=this.uniforms.gamma.value;t.x=1/e[0],t.y=1/e[1],t.z=1/e[2]}get hdrCapacityMin(){return this._hdrCapacityMin}set hdrCapacityMin(e){this._hdrCapacityMin=e,this.calculateWeight()}get hdrCapacityMax(){return this._hdrCapacityMax}set hdrCapacityMax(e){this._hdrCapacityMax=e,this.calculateWeight()}get maxDisplayBoost(){return this._maxDisplayBoost}set maxDisplayBoost(e){this._maxDisplayBoost=Math.max(1,Math.min(65504,e)),this.calculateWeight()}calculateWeight(){const e=(Math.log2(this._maxDisplayBoost)-this._hdrCapacityMin)/(this._hdrCapacityMax-this._hdrCapacityMin);this.uniforms.weightFactor.value=Math.max(0,Math.min(1,e))}}const v=i({renderer:t.WebGLRenderer,createMaterial:e=>new x(e),createQuadRenderer:e=>new n(e)});class T extends w{constructor(e,t){super({renderer:e,createMaterial:e=>new x(e),createQuadRenderer:e=>new n(e)},t)}async render(e,t,r,a){const{sdrImage:n,gainMapImage:i,needsFlip:s}=await this.processImages(r,a,"flipY"),{gainMap:o,sdr:d}=this.createTextures(n,i,s);this.updateQuadRenderer(e,n,o,d,t),e.render()}}class F extends T{constructor(e,t){super(e,t),_("HDRJPGLoader","@monogrid/gainmap-js","HDRJPGNodeLoader")}load(e,r,a,n){const i=this.prepareQuadRenderer(),d=new t.FileLoader(this._internalLoadingManager);return d.setResponseType("arraybuffer"),d.setRequestHeader(this.requestHeader),d.setPath(this.path),d.setWithCredentials(this.withCredentials),this.manager.itemStart(e),d.load(e,async t=>{if("string"==typeof t)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const a=new Uint8Array(t);let d,p,h;try{const e=await m(a);d=e.sdr,p=e.gainMap,h=e.metadata}catch(t){if(!(t instanceof o||t instanceof s))throw t;console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`),h={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},d=a}try{await this.render(i,h,d.buffer,p?.buffer)}catch(t){return this.manager.itemError(e),"function"==typeof n&&n(t),void i.disposeOnDemandRenderer()}"function"==typeof r&&r(i),this.manager.itemEnd(e),i.disposeOnDemandRenderer()},a,t=>{this.manager.itemError(e),"function"==typeof n&&n(t)}),i}}e.GainMapDecoderMaterial=x,e.GainMapLoader=class extends T{constructor(e,t){super(e,t),_("GainMapLoader","@monogrid/gainmap-js","GainMapNodeLoader")}load([e,r,a],n,i,s){const o=this.prepareQuadRenderer();let d,p,h;const c=async()=>{if(d&&p&&h){try{await this.render(o,h,d,p)}catch(t){return this.manager.itemError(e),this.manager.itemError(r),this.manager.itemError(a),"function"==typeof s&&s(t),void o.disposeOnDemandRenderer()}"function"==typeof n&&n(o),this.manager.itemEnd(e),this.manager.itemEnd(r),this.manager.itemEnd(a),o.disposeOnDemandRenderer()}};let g=!0,l=0,m=0,f=!0,u=0,y=0,w=!0,M=0,_=0;const x=()=>{if("function"==typeof i){i(new ProgressEvent("progress",{lengthComputable:g&&f&&w,loaded:m+y+_,total:l+u+M}))}};this.manager.itemStart(e),this.manager.itemStart(r),this.manager.itemStart(a);const v=new t.FileLoader(this._internalLoadingManager);v.setResponseType("arraybuffer"),v.setRequestHeader(this.requestHeader),v.setPath(this.path),v.setWithCredentials(this.withCredentials),v.load(e,async e=>{if("string"==typeof e)throw new Error("Invalid sdr buffer");d=e,await c()},e=>{g=e.lengthComputable,m=e.loaded,l=e.total,x()},t=>{this.manager.itemError(e),"function"==typeof s&&s(t)});const T=new t.FileLoader(this._internalLoadingManager);T.setResponseType("arraybuffer"),T.setRequestHeader(this.requestHeader),T.setPath(this.path),T.setWithCredentials(this.withCredentials),T.load(r,async e=>{if("string"==typeof e)throw new Error("Invalid gainmap buffer");p=e,await c()},e=>{f=e.lengthComputable,y=e.loaded,u=e.total,x()},e=>{this.manager.itemError(r),"function"==typeof s&&s(e)});const F=new t.FileLoader(this._internalLoadingManager);return F.setRequestHeader(this.requestHeader),F.setPath(this.path),F.setWithCredentials(this.withCredentials),F.load(a,async e=>{if("string"!=typeof e)throw new Error("Invalid metadata string");h=JSON.parse(e),await c()},e=>{w=e.lengthComputable,_=e.loaded,M=e.total,x()},e=>{this.manager.itemError(a),"function"==typeof s&&s(e)}),o}},e.GainMapNotFoundError=s,e.HDRJPGLoader=F,e.JPEGRLoader=F,e.LoaderBaseShared=w,e.MPFExtractor=l,e.QuadRenderer=n,e.XMPMetadataNotFoundError=o,e.createDecodeFunction=i,e.createTextures=y,e.decode=e=>{if(_("decode()","@monogrid/gainmap-js","gainMapNode()"),!e.renderer)throw new Error("Renderer is required for decode function");const t=v({...e,renderer:e.renderer});try{t.render()}catch(e){throw t.disposeOnDemandRenderer(),e}return t},e.extractGainmapFromJPEG=m,e.extractISO=h,e.extractXMP=g,e.processImages=u});
@@ -1,18 +1,19 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.5.0
2
+ * @monogrid/gainmap-js v3.6.1
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
6
- import { c as createDecodeFunction, L as LoaderBaseShared, e as extractGainmapFromJPEG, X as XMPMetadataNotFoundError, G as GainMapNotFoundError } from './Loader-CL7itwBq.js';
7
- export { M as MPFExtractor, a as extractISO, b as extractXMP } from './Loader-CL7itwBq.js';
8
- import { ClampToEdgeWrapping, LinearFilter, Scene, OrthographicCamera, Mesh, PlaneGeometry, RenderTarget, RGBAFormat, UVMapping, WebGPURenderer, DataTexture, LinearSRGBColorSpace, ShaderMaterial, Texture, MeshBasicNodeMaterial, NoBlending, Vector3, FileLoader } from 'three/webgpu';
6
+ import { w as warnDeprecated, c as createDecodeFunction, L as LoaderBaseShared, p as processImages, a as createTextures, e as extractGainmapFromJPEG, X as XMPMetadataNotFoundError, G as GainMapNotFoundError } from './warn-deprecated-DtCQWGKi.js';
7
+ export { M as MPFExtractor, b as extractISO, d as extractXMP } from './warn-deprecated-DtCQWGKi.js';
8
+ import { ClampToEdgeWrapping, LinearFilter, Scene, OrthographicCamera, Mesh, PlaneGeometry, RenderTarget, RGBAFormat, UVMapping, WebGPURenderer, DataTexture, LinearSRGBColorSpace, ShaderMaterial, Texture, MeshBasicNodeMaterial, NoBlending, Vector3, FileLoader, TextureNode, LinearMipmapLinearFilter, HalfFloatType, NodeUpdateType, QuadMesh, RendererUtils, Loader } from 'three/webgpu';
9
9
  import 'three';
10
- import { vec3, texture, uniform } from 'three/tsl';
11
- import './iso-gainmap-metadata-Dk2F4Eoz.js';
10
+ import { vec3, texture, uniform, mix, saturate, log2, exp2, vec4 } from 'three/tsl';
11
+ import './iso-gainmap-metadata-C1io5isX.js';
12
12
 
13
13
  /**
14
14
  * Utility class used for rendering a texture with a material (WebGPU version)
15
15
  *
16
+ * @deprecated Will be removed in v4.0.0. The WebGPU decode now happens in {@link GainMapNode}, use {@link HDRJPGNodeLoader}, {@link GainMapNodeLoader} or {@link gainMapNode}, see the [migration guide](https://github.com/MONOGRID/gainmap-js#migrating-to-v400).
16
17
  * @category Core
17
18
  * @group Core
18
19
  */
@@ -114,7 +115,20 @@ class QuadRenderer {
114
115
  if (!this._supportsReadPixels)
115
116
  throw new Error('Can\'t read pixels in this browser');
116
117
  const out = await this._renderer.readRenderTargetPixelsAsync(this._renderTarget, 0, 0, this._width, this._height);
117
- return out;
118
+ if (!this._renderer.backend.isWebGPUBackend) {
119
+ return out;
120
+ }
121
+ // the WebGPU backend returns rows top-down, each padded to 256 bytes,
122
+ // the WebGL backend returns tightly packed rows bottom-up:
123
+ // repack to the WebGL layout so both backends return the same data
124
+ const rowLength = this._width * 4;
125
+ const paddedRowLength = Math.ceil(rowLength * out.BYTES_PER_ELEMENT / 256) * 256 / out.BYTES_PER_ELEMENT;
126
+ const packed = new out.constructor(rowLength * this._height);
127
+ for (let y = 0; y < this._height; y++) {
128
+ const start = (this._height - 1 - y) * paddedRowLength;
129
+ packed.set(out.subarray(start, start + rowLength), y * rowLength);
130
+ }
131
+ return packed;
118
132
  }
119
133
  /**
120
134
  * Performs a readPixel operation in the renderTarget
@@ -238,10 +252,11 @@ class QuadRenderer {
238
252
  // min half float value
239
253
  const HALF_FLOAT_MIN = vec3(-65504, -65504, -65504);
240
254
  // max half float value
241
- const HALF_FLOAT_MAX = vec3(65504, 65504, 65504);
255
+ const HALF_FLOAT_MAX$1 = vec3(65504, 65504, 65504);
242
256
  /**
243
257
  * A Material which is able to decode the Gainmap into a full HDR Representation using TSL (Three.js Shading Language)
244
258
  *
259
+ * @deprecated Will be removed in v4.0.0. The decode now happens in {@link GainMapNode}, see the [migration guide](https://github.com/MONOGRID/gainmap-js#migrating-to-v400).
245
260
  * @category Materials
246
261
  * @group Materials
247
262
  */
@@ -292,7 +307,7 @@ class GainMapDecoderMaterial extends MeshBasicNodeMaterial {
292
307
  // the mathematically equivalent pow(2, x) which has proper vec3 typings.
293
308
  const gain = vec3(2).pow(logBoost.mul(this._weightFactorUniform));
294
309
  const hdrColor = rgb.add(this._offsetSdrUniform).mul(gain).sub(this._offsetHdrUniform);
295
- const clampedHdrColor = hdrColor.min(HALF_FLOAT_MAX).max(HALF_FLOAT_MIN);
310
+ const clampedHdrColor = hdrColor.min(HALF_FLOAT_MAX$1).max(HALF_FLOAT_MIN);
296
311
  this.colorNode = clampedHdrColor;
297
312
  }
298
313
  get sdr() { return this._sdrTexture.value; }
@@ -395,6 +410,7 @@ const decodeImpl = createDecodeFunction({
395
410
  /**
396
411
  * Decodes a gain map using WebGPU RenderTarget
397
412
  *
413
+ * @deprecated Will be removed in v4.0.0. Use {@link gainMapNode} instead: it is **not a drop-in replacement**, it returns a {@link GainMapNode} instead of a render target, see the [migration guide](https://github.com/MONOGRID/gainmap-js#migrating-to-v400).
398
414
  * @category Decoding Functions
399
415
  * @group Decoding Functions
400
416
  * @example
@@ -448,6 +464,7 @@ const decodeImpl = createDecodeFunction({
448
464
  * @throws {Error} if the WebGPURenderer fails to render the gain map
449
465
  */
450
466
  const decode = async (params) => {
467
+ warnDeprecated('decode()', '@monogrid/gainmap-js/webgpu', 'gainMapNode()');
451
468
  // Ensure renderer is defined for the base function
452
469
  if (!params.renderer) {
453
470
  throw new Error('Renderer is required for decode function');
@@ -498,6 +515,7 @@ class LoaderBaseWebGPU extends LoaderBaseShared {
498
515
  /**
499
516
  * A Three.js Loader for the gain map format (WebGPU version).
500
517
  *
518
+ * @deprecated Will be removed in v4.0.0. Use {@link GainMapNodeLoader} instead: it is **not a drop-in replacement**, it returns a {@link GainMapNode} instead of a render target, see the [migration guide](https://github.com/MONOGRID/gainmap-js#migrating-to-v400).
501
519
  * @category Loaders
502
520
  * @group Loaders
503
521
  *
@@ -544,6 +562,10 @@ class LoaderBaseWebGPU extends LoaderBaseShared {
544
562
  *
545
563
  */
546
564
  class GainMapLoader extends LoaderBaseWebGPU {
565
+ constructor(renderer, manager) {
566
+ super(renderer, manager);
567
+ warnDeprecated('GainMapLoader', '@monogrid/gainmap-js/webgpu', 'GainMapNodeLoader');
568
+ }
547
569
  /**
548
570
  * Loads a gainmap using separate data
549
571
  * * sdr image
@@ -681,9 +703,349 @@ class GainMapLoader extends LoaderBaseWebGPU {
681
703
  }
682
704
  }
683
705
 
706
+ // max half float value
707
+ const HALF_FLOAT_MAX = 65504;
708
+ /**
709
+ * A TSL texture node holding the HDR image decoded from an SDR image + gain map.
710
+ *
711
+ * The decode runs on the GPU into a HalfFloat render target, and only when something changed
712
+ * (textures loaded/swapped or any uniform value changed): sampling the node costs a single
713
+ * texture read, like any other texture.
714
+ *
715
+ * The node updates itself before rendering whenever it is part of a rendered node graph
716
+ * (material, `scene.backgroundNode`, ...). When only its texture is used (`node.value`,
717
+ * e.g. `scene.environment = node.value`) call {@link GainMapNode.decode} yourself.
718
+ *
719
+ * Re-decoding also flags the texture for PMREM regeneration,
720
+ * so environment maps are recomputed only when the image actually changes.
721
+ *
722
+ * `node.value` gets its final size once loaded: three.js PMREMs don't follow texture resizes,
723
+ * so assign it to `scene.environment` (or `pmremTexture()`) after load.
724
+ *
725
+ * @category Nodes
726
+ * @group Nodes
727
+ *
728
+ * @example
729
+ * import { GainMapNode } from '@monogrid/gainmap-js/webgpu'
730
+ * import { equirectUV } from 'three/tsl'
731
+ *
732
+ * const hdr = new GainMapNode()
733
+ * .setTextures(sdrTexture, gainMapTexture)
734
+ * .setMetadata(metadata)
735
+ *
736
+ * material.colorNode = hdr
737
+ * scene.backgroundNode = hdr.sample(equirectUV())
738
+ * hdr.maxDisplayBoost.value = 2 // re-decodes once, on the next frame
739
+ */
740
+ class GainMapNode extends TextureNode {
741
+ static get type() { return 'GainMapNode'; }
742
+ /**
743
+ * Shared textures and uniforms
744
+ */
745
+ uniforms;
746
+ /**
747
+ * The render target holding the decoded HDR image
748
+ */
749
+ renderTarget;
750
+ _quadMesh;
751
+ _material;
752
+ // filled by RendererUtils.resetRendererState
753
+ _rendererState = {};
754
+ _state = [];
755
+ constructor() {
756
+ const renderTarget = new RenderTarget(1, 1, {
757
+ type: HalfFloatType,
758
+ colorSpace: LinearSRGBColorSpace,
759
+ depthBuffer: false,
760
+ generateMipmaps: true,
761
+ minFilter: LinearMipmapLinearFilter,
762
+ magFilter: LinearFilter
763
+ });
764
+ super(renderTarget.texture);
765
+ this.renderTarget = renderTarget;
766
+ this.updateBeforeType = NodeUpdateType.RENDER;
767
+ const u = this.uniforms = {
768
+ sdr: texture(new Texture()),
769
+ gainMap: texture(new Texture()),
770
+ gamma: uniform(new Vector3(1, 1, 1)),
771
+ offsetSdr: uniform(new Vector3()),
772
+ offsetHdr: uniform(new Vector3()),
773
+ gainMapMin: uniform(new Vector3()),
774
+ gainMapMax: uniform(new Vector3(1, 1, 1)),
775
+ hdrCapacityMin: uniform(0),
776
+ hdrCapacityMax: uniform(1),
777
+ maxDisplayBoost: uniform(1)
778
+ };
779
+ const logRecovery = u.gainMap.rgb.pow(vec3(1).div(u.gamma));
780
+ const logBoost = mix(u.gainMapMin, u.gainMapMax, logRecovery);
781
+ const weight = saturate(log2(u.maxDisplayBoost).sub(u.hdrCapacityMin).div(u.hdrCapacityMax.sub(u.hdrCapacityMin)));
782
+ const hdr = u.sdr.rgb.add(u.offsetSdr).mul(exp2(logBoost.mul(weight))).sub(u.offsetHdr);
783
+ this._material = new MeshBasicNodeMaterial();
784
+ this._material.name = 'GainMapDecoder';
785
+ this._material.colorNode = vec4(hdr.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX), 1);
786
+ this._quadMesh = new QuadMesh(this._material);
787
+ }
788
+ /** The SDR rendition texture (sRGB) */
789
+ get sdr() { return this.uniforms.sdr.value; }
790
+ /** The gain map recovery texture (linear) */
791
+ get gainMap() { return this.uniforms.gainMap.value; }
792
+ /** @see {@link GainMapMetadata.gamma} */
793
+ get gamma() { return this.uniforms.gamma; }
794
+ /** @see {@link GainMapMetadata.offsetSdr} */
795
+ get offsetSdr() { return this.uniforms.offsetSdr; }
796
+ /** @see {@link GainMapMetadata.offsetHdr} */
797
+ get offsetHdr() { return this.uniforms.offsetHdr; }
798
+ /** @see {@link GainMapMetadata.gainMapMin} */
799
+ get gainMapMin() { return this.uniforms.gainMapMin; }
800
+ /** @see {@link GainMapMetadata.gainMapMax} */
801
+ get gainMapMax() { return this.uniforms.gainMapMax; }
802
+ /** @see {@link GainMapMetadata.hdrCapacityMin} */
803
+ get hdrCapacityMin() { return this.uniforms.hdrCapacityMin; }
804
+ /** @see {@link GainMapMetadata.hdrCapacityMax} */
805
+ get hdrCapacityMax() { return this.uniforms.hdrCapacityMax; }
806
+ /**
807
+ * @see {@link GainmapDecodingParameters.maxDisplayBoost}
808
+ * @remarks Non Logarithmic space
809
+ */
810
+ get maxDisplayBoost() { return this.uniforms.maxDisplayBoost; }
811
+ /** Width of the SDR image, 0 until loaded */
812
+ get width() { return this.sdr.image?.width ?? 0; }
813
+ /** Height of the SDR image, 0 until loaded */
814
+ get height() { return this.sdr.image?.height ?? 0; }
815
+ /**
816
+ * Sets the SDR and gain map textures.
817
+ * The SDR texture is expected in sRGB color space, the gain map in linear.
818
+ *
819
+ * @param sdr
820
+ * @param gainMap
821
+ */
822
+ setTextures(sdr, gainMap) {
823
+ this.uniforms.sdr.value = sdr;
824
+ this.uniforms.gainMap.value = gainMap;
825
+ // size the render target right away, so `value` has its final size before the first decode
826
+ if (this.width > 0 && this.height > 0)
827
+ this.renderTarget.setSize(this.width, this.height);
828
+ return this;
829
+ }
830
+ /**
831
+ * Copies the gain map metadata into the uniforms.
832
+ * Also sets `maxDisplayBoost` to fully restore the HDR range.
833
+ *
834
+ * @param metadata
835
+ */
836
+ setMetadata(metadata) {
837
+ const u = this.uniforms;
838
+ u.gamma.value.fromArray(metadata.gamma);
839
+ u.offsetSdr.value.fromArray(metadata.offsetSdr);
840
+ u.offsetHdr.value.fromArray(metadata.offsetHdr);
841
+ u.gainMapMin.value.fromArray(metadata.gainMapMin);
842
+ u.gainMapMax.value.fromArray(metadata.gainMapMax);
843
+ u.hdrCapacityMin.value = metadata.hdrCapacityMin;
844
+ u.hdrCapacityMax.value = metadata.hdrCapacityMax;
845
+ u.maxDisplayBoost.value = Math.pow(2, metadata.hdrCapacityMax);
846
+ return this;
847
+ }
848
+ _currentState() {
849
+ const u = this.uniforms;
850
+ return [
851
+ this.sdr.id, this.sdr.version, this.gainMap.id, this.gainMap.version,
852
+ ...u.gamma.value.toArray(), ...u.offsetSdr.value.toArray(), ...u.offsetHdr.value.toArray(),
853
+ ...u.gainMapMin.value.toArray(), ...u.gainMapMax.value.toArray(),
854
+ u.hdrCapacityMin.value, u.hdrCapacityMax.value, u.maxDisplayBoost.value
855
+ ];
856
+ }
857
+ /**
858
+ * Decodes the image into {@link GainMapNode.renderTarget}, only if something changed since the last decode.
859
+ *
860
+ * Called automatically when the node is part of a rendered node graph.
861
+ *
862
+ * @param renderer
863
+ * @returns `true` if the image was decoded
864
+ */
865
+ decode(renderer) {
866
+ // not loaded yet
867
+ if (this.width === 0 || this.height === 0)
868
+ return false;
869
+ const state = this._currentState();
870
+ if (state.length === this._state.length && state.every((v, i) => v === this._state[i]))
871
+ return false;
872
+ this._state = state;
873
+ RendererUtils.resetRendererState(renderer, this._rendererState);
874
+ renderer.setRenderTarget(this.renderTarget);
875
+ this._quadMesh.render(renderer);
876
+ RendererUtils.restoreRendererState(renderer, this._rendererState);
877
+ this.value.needsPMREMUpdate = true;
878
+ return true;
879
+ }
880
+ /**
881
+ * Calls {@link GainMapNode.decode} once per render, before the node is evaluated.
882
+ *
883
+ * @param frame
884
+ */
885
+ updateBefore(frame) {
886
+ if (frame.renderer)
887
+ this.decode(frame.renderer);
888
+ return undefined;
889
+ }
890
+ set value(value) {
891
+ if (this.renderTarget && value !== this.renderTarget.texture) {
892
+ throw new Error('GainMapNode: the value of this node is its render target texture and can\'t be replaced');
893
+ }
894
+ }
895
+ get value() {
896
+ return this.renderTarget?.texture;
897
+ }
898
+ /**
899
+ * Clones created by `sample()` & co. are plain TextureNodes reading this node's texture,
900
+ * they keep it updated before rendering as well
901
+ */
902
+ clone() {
903
+ const node = new TextureNode(this.value, this.uvNode, this.levelNode, this.biasNode);
904
+ node.sampler = this.sampler;
905
+ node.updateBeforeType = NodeUpdateType.RENDER;
906
+ node.updateBefore = (frame) => this.updateBefore(frame);
907
+ return node;
908
+ }
909
+ /**
910
+ * Disposes the render target, the SDR and gain map textures
911
+ */
912
+ dispose() {
913
+ this.renderTarget.dispose();
914
+ this._material.dispose();
915
+ this.sdr.dispose();
916
+ this.gainMap.dispose();
917
+ super.dispose();
918
+ }
919
+ }
920
+ /**
921
+ * TSL function creating a {@link GainMapNode} from an SDR texture, a gain map texture and its metadata
922
+ *
923
+ * @param sdr
924
+ * @param gainMap
925
+ * @param metadata
926
+ */
927
+ const gainMapNode = (sdr, gainMap, metadata) => new GainMapNode().setTextures(sdr, gainMap).setMetadata(metadata);
928
+
929
+ /**
930
+ * Base class for loaders returning a {@link GainMapNode}
931
+ * @template TUrl - The type of URL used to load resources
932
+ */
933
+ class LoaderBaseNode extends Loader {
934
+ /**
935
+ * @private
936
+ * @param responseType
937
+ */
938
+ createFileLoader(responseType) {
939
+ const loader = new FileLoader(this.manager);
940
+ if (responseType)
941
+ loader.setResponseType(responseType);
942
+ loader.setRequestHeader(this.requestHeader);
943
+ loader.setPath(this.path);
944
+ loader.setWithCredentials(this.withCredentials);
945
+ return loader;
946
+ }
947
+ /**
948
+ * Decodes the images and feeds them to the node, together with the metadata
949
+ *
950
+ * @private
951
+ * @param node
952
+ * @param metadata
953
+ * @param sdrBuffer
954
+ * @param gainMapBuffer
955
+ */
956
+ async fillNode(node, metadata, sdrBuffer, gainMapBuffer) {
957
+ // flipY like any other three.js texture, so the node can be sampled with regular uvs
958
+ const { sdrImage, gainMapImage } = await processImages(sdrBuffer, gainMapBuffer, 'from-image');
959
+ const { sdr, gainMap } = createTextures(sdrImage, gainMapImage, true);
960
+ node.setTextures(sdr, gainMap).setMetadata(metadata);
961
+ }
962
+ }
963
+
964
+ /**
965
+ * A Three.js Loader for the gain map format stored as separate files (sdr image, gain map image, metadata json),
966
+ * returning a {@link GainMapNode} (a TSL texture node holding the decoded HDR image).
967
+ *
968
+ * No renderer is needed: `load` returns the node synchronously, it can be assigned to materials right away
969
+ * and it is decoded on the GPU once loaded.
970
+ *
971
+ * @category Loaders
972
+ * @group Loaders
973
+ *
974
+ * @example
975
+ * import { GainMapNodeLoader } from '@monogrid/gainmap-js/webgpu'
976
+ * import { MeshBasicNodeMaterial } from 'three/webgpu'
977
+ *
978
+ * const hdr = new GainMapNodeLoader().load([
979
+ * 'sdr.webp',
980
+ * 'gainmap.webp',
981
+ * 'metadata.json'
982
+ * ])
983
+ *
984
+ * const material = new MeshBasicNodeMaterial()
985
+ * material.colorNode = hdr
986
+ */
987
+ class GainMapNodeLoader extends LoaderBaseNode {
988
+ /**
989
+ * Loads a gainmap using separate data
990
+ * * sdr image
991
+ * * gain map image
992
+ * * metadata json
993
+ *
994
+ * useful for webp gain maps
995
+ *
996
+ * @param urls An array in the form of [sdr.jpg, gainmap.jpg, metadata.json]
997
+ * @param onLoad Load complete callback, will receive the node
998
+ * @param onProgress Progress callback, will receive a `ProgressEvent`
999
+ * @param onError Error callback
1000
+ * @returns a node which can be used immediately, it will hold the image once loaded
1001
+ */
1002
+ load(urls, onLoad, onProgress, onError) {
1003
+ const node = new GainMapNode();
1004
+ const progress = urls.map(() => ({ lengthComputable: true, loaded: 0, total: 0 }));
1005
+ const loadFile = (url, index, responseType) => new Promise((resolve, reject) => {
1006
+ this.manager.itemStart(url);
1007
+ this.createFileLoader(responseType).load(url, resolve, (e) => {
1008
+ progress[index] = { lengthComputable: e.lengthComputable, loaded: e.loaded, total: e.total };
1009
+ if (typeof onProgress === 'function') {
1010
+ onProgress(new ProgressEvent('progress', {
1011
+ lengthComputable: progress.every(p => p.lengthComputable),
1012
+ loaded: progress.reduce((sum, p) => sum + p.loaded, 0),
1013
+ total: progress.reduce((sum, p) => sum + p.total, 0)
1014
+ }));
1015
+ }
1016
+ }, reject);
1017
+ });
1018
+ const [sdrUrl, gainMapUrl, metadataUrl] = urls;
1019
+ Promise.all([
1020
+ loadFile(sdrUrl, 0, 'arraybuffer'),
1021
+ loadFile(gainMapUrl, 1, 'arraybuffer'),
1022
+ loadFile(metadataUrl, 2)
1023
+ ]).then(async ([sdr, gainMap, json]) => {
1024
+ /* istanbul ignore if
1025
+ this condition exists only because of three.js types + strict mode
1026
+ */
1027
+ if (typeof sdr === 'string' || typeof gainMap === 'string' || typeof json !== 'string')
1028
+ throw new Error('Invalid response types');
1029
+ // TODO: implement check on JSON file
1030
+ const metadata = JSON.parse(json);
1031
+ await this.fillNode(node, metadata, sdr, gainMap);
1032
+ }).then(() => {
1033
+ if (typeof onLoad === 'function')
1034
+ onLoad(node);
1035
+ urls.forEach(url => this.manager.itemEnd(url));
1036
+ }, (error) => {
1037
+ urls.forEach(url => this.manager.itemError(url));
1038
+ if (typeof onError === 'function')
1039
+ onError(error);
1040
+ });
1041
+ return node;
1042
+ }
1043
+ }
1044
+
684
1045
  /**
685
1046
  * A Three.js Loader for a JPEG with embedded gainmap metadata (WebGPU version).
686
1047
  *
1048
+ * @deprecated Will be removed in v4.0.0. Use {@link HDRJPGNodeLoader} instead: it is **not a drop-in replacement**, it returns a {@link GainMapNode} instead of a render target, see the [migration guide](https://github.com/MONOGRID/gainmap-js#migrating-to-v400).
687
1049
  * @category Loaders
688
1050
  * @group Loaders
689
1051
  *
@@ -730,6 +1092,10 @@ class GainMapLoader extends LoaderBaseWebGPU {
730
1092
  *
731
1093
  */
732
1094
  class HDRJPGLoader extends LoaderBaseWebGPU {
1095
+ constructor(renderer, manager) {
1096
+ super(renderer, manager);
1097
+ warnDeprecated('HDRJPGLoader', '@monogrid/gainmap-js/webgpu', 'HDRJPGNodeLoader');
1098
+ }
733
1099
  /**
734
1100
  * Loads a JPEG containing gain map metadata
735
1101
  * Renders a normal SDR image if gainmap data is not found
@@ -808,4 +1174,100 @@ class HDRJPGLoader extends LoaderBaseWebGPU {
808
1174
  }
809
1175
  }
810
1176
 
811
- export { GainMapDecoderMaterial, GainMapLoader, GainMapNotFoundError, HDRJPGLoader, HDRJPGLoader as JPEGRLoader, LoaderBaseShared, QuadRenderer, XMPMetadataNotFoundError, createDecodeFunction, decode, extractGainmapFromJPEG };
1177
+ /**
1178
+ * A Three.js Loader for a JPEG with embedded gain map metadata,
1179
+ * returning a {@link GainMapNode} (a TSL texture node holding the decoded HDR image).
1180
+ *
1181
+ * No renderer is needed: `load` returns the node synchronously
1182
+ * (like `TextureLoader` returns a `Texture`), it can be assigned to materials right away
1183
+ * and it is decoded on the GPU once loaded.
1184
+ *
1185
+ * @category Loaders
1186
+ * @group Loaders
1187
+ *
1188
+ * @example
1189
+ * import { HDRJPGNodeLoader } from '@monogrid/gainmap-js/webgpu'
1190
+ * import { equirectUV } from 'three/tsl'
1191
+ * import { MeshBasicNodeMaterial } from 'three/webgpu'
1192
+ *
1193
+ * const hdr = new HDRJPGNodeLoader().load('gainmap.jpeg')
1194
+ *
1195
+ * const material = new MeshBasicNodeMaterial()
1196
+ * material.colorNode = hdr
1197
+ *
1198
+ * scene.backgroundNode = hdr.sample(equirectUV())
1199
+ *
1200
+ * // all parameters are uniforms, changing them re-decodes the image once
1201
+ * hdr.maxDisplayBoost.value = 2
1202
+ */
1203
+ class HDRJPGNodeLoader extends LoaderBaseNode {
1204
+ /**
1205
+ * Loads a JPEG containing gain map metadata
1206
+ * Renders a normal SDR image if gainmap data is not found
1207
+ *
1208
+ * @param url Path to a JPEG file containing embedded gain map metadata
1209
+ * @param onLoad Load complete callback, will receive the node
1210
+ * @param onProgress Progress callback, will receive a `ProgressEvent`
1211
+ * @param onError Error callback
1212
+ * @returns a node which can be used immediately, it will hold the image once loaded
1213
+ */
1214
+ load(url, onLoad, onProgress, onError) {
1215
+ const node = new GainMapNode();
1216
+ this.manager.itemStart(url);
1217
+ this.createFileLoader('arraybuffer').load(url, async (jpeg) => {
1218
+ try {
1219
+ /* istanbul ignore if
1220
+ this condition exists only because of three.js types + strict mode
1221
+ */
1222
+ if (typeof jpeg === 'string')
1223
+ throw new Error('Invalid buffer, received [string], was expecting [ArrayBuffer]');
1224
+ const jpegBuffer = new Uint8Array(jpeg);
1225
+ let sdrJPEG;
1226
+ let gainMapJPEG;
1227
+ let metadata;
1228
+ try {
1229
+ const extractionResult = await extractGainmapFromJPEG(jpegBuffer);
1230
+ sdrJPEG = extractionResult.sdr;
1231
+ gainMapJPEG = extractionResult.gainMap;
1232
+ metadata = extractionResult.metadata;
1233
+ }
1234
+ catch (e) {
1235
+ // render the SDR version if this is not a gainmap
1236
+ if (e instanceof XMPMetadataNotFoundError || e instanceof GainMapNotFoundError) {
1237
+ console.warn(`Failure to reconstruct an HDR image from ${url}: Gain map metadata not found in the file, HDRJPGNodeLoader will render the SDR jpeg`);
1238
+ metadata = {
1239
+ gainMapMin: [0, 0, 0],
1240
+ gainMapMax: [1, 1, 1],
1241
+ gamma: [1, 1, 1],
1242
+ hdrCapacityMin: 0,
1243
+ hdrCapacityMax: 1,
1244
+ offsetHdr: [0, 0, 0],
1245
+ offsetSdr: [0, 0, 0]
1246
+ };
1247
+ sdrJPEG = jpegBuffer;
1248
+ }
1249
+ else {
1250
+ throw e;
1251
+ }
1252
+ }
1253
+ await this.fillNode(node, metadata, sdrJPEG.buffer, gainMapJPEG?.buffer);
1254
+ }
1255
+ catch (error) {
1256
+ this.manager.itemError(url);
1257
+ if (typeof onError === 'function')
1258
+ onError(error);
1259
+ return;
1260
+ }
1261
+ if (typeof onLoad === 'function')
1262
+ onLoad(node);
1263
+ this.manager.itemEnd(url);
1264
+ }, onProgress, (error) => {
1265
+ this.manager.itemError(url);
1266
+ if (typeof onError === 'function')
1267
+ onError(error);
1268
+ });
1269
+ return node;
1270
+ }
1271
+ }
1272
+
1273
+ export { GainMapDecoderMaterial, GainMapLoader, GainMapNode, GainMapNodeLoader, GainMapNotFoundError, HDRJPGLoader, HDRJPGNodeLoader, HDRJPGLoader as JPEGRLoader, LoaderBaseShared, QuadRenderer, XMPMetadataNotFoundError, createDecodeFunction, createTextures, decode, extractGainmapFromJPEG, gainMapNode, processImages };