@mirage-engine/core 0.3.3 → 0.3.4

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.
@@ -1,11 +1,11 @@
1
- (function(y,S){typeof exports=="object"&&typeof module!="undefined"?S(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],S):(y=typeof globalThis!="undefined"?globalThis:y||self,S(y.MirageEngine={},y.THREE))})(this,function(y,S){"use strict";var ct=Object.defineProperty,lt=Object.defineProperties;var ht=Object.getOwnPropertyDescriptors;var Xe=Object.getOwnPropertySymbols;var dt=Object.prototype.hasOwnProperty,ut=Object.prototype.propertyIsEnumerable;var Ce=(y,S,M)=>S in y?ct(y,S,{enumerable:!0,configurable:!0,writable:!0,value:M}):y[S]=M,J=(y,S)=>{for(var M in S||(S={}))dt.call(S,M)&&Ce(y,M,S[M]);if(Xe)for(var M of Xe(S))ut.call(S,M)&&Ce(y,M,S[M]);return y},Se=(y,S)=>lt(y,ht(S));var g=(y,S,M)=>(Ce(y,typeof S!="symbol"?S+"":S,M),M);var Ye=(y,S,M)=>new Promise((b,te)=>{var P=D=>{try{A(M.next(D))}catch(B){te(B)}},re=D=>{try{A(M.throw(D))}catch(B){te(B)}},A=D=>D.done?b(D.value):Promise.resolve(D.value).then(P,re);A((M=M.apply(y,S)).next())});function M(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const b=M(S),te={INCLUDE_TREE:"include-tree",EXCLUDE_TREE:"exclude-tree",INCLUDE_SELF:"include-self",EXCLUDE_SELF:"exclude-self",END:"end"},P={NAME:"data-mirage-dom",KEY:"mirageDom",VALUES:{HIDE:"hide"}},re={TRAVELER:"traveler",NATIVE:"native",CAPTURE_1:"1",CAPTURE_2:"2",CAPTURE_3:"3",CAPTURE_4:"4",CAPTURE_5:"5"},A={NAME:"data-mirage-travel",KEY:"mirageTravel",VALUES:re,MAX_LAYERS:Object.keys(re).length-1},D={NAME:"data-mirage-filter",KEY:"mirageFilter",VALUES:te},B={NAME:"data-mirage-select",KEY:"mirageSelect",VALUES:te},Re={NAME:"data-mirage-shader",KEY:"mirageShader"},Ne={NAME:"data-mirage-sandwich",KEY:"mirageSandwich",VALUES:{FRONT:"front"}},ie=0,K=1,Q=2,Le=4,fe=8,ge=16;function ze(s){const e=s.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return e?{r:parseInt(e[1])/255,g:parseInt(e[2])/255,b:parseInt(e[3])/255}:{r:1,g:1,b:1}}function Me(s){const e={};if(s.opacity&&(e.opacity=parseFloat(s.opacity)),s.backgroundColor&&s.backgroundColor!=="rgba(0, 0, 0, 0)"){const t=ze(s.backgroundColor);e.backgroundColor=[t.r,t.g,t.b]}if(s.backgroundImage?e.backgroundImage=s.backgroundImage:s.background&&(e.backgroundImage=s.background),s.borderRadius&&(e.borderRadius=parseFloat(s.borderRadius)),s.width&&(e.width=parseFloat(s.width)),s.height&&(e.height=parseFloat(s.height)),s.transform&&s.transform!=="none"){const t=new DOMMatrix(s.transform);e.x=t.m41,e.y=t.m42,e.z=t.m43}return e}class De{constructor(e,t){g(this,"target");g(this,"observer");g(this,"pendingDeletions",new Set);g(this,"pendingStyles",new Map);g(this,"isDomDirty",!1);g(this,"isRunning",!1);g(this,"pendingMask",ie);g(this,"mutationTimer",null);g(this,"cssTimer",null);g(this,"resizeConfig");g(this,"resizeTimer",null);g(this,"isResizing",!1);g(this,"lastScrollX",0);g(this,"lastScrollY",0);g(this,"scrollTimer",null);g(this,"onBeforeRender",new Set);g(this,"onLayoutChange",new Set);g(this,"onStyleChange",new Set);g(this,"onScrollChange",new Set);g(this,"onRender",new Set);g(this,"onTransitionFinished",e=>{this.target.contains(e.target)&&this.mutationTimer===null&&(this.cssTimer&&clearTimeout(this.cssTimer),this.pendingStyles.size==0&&(this.pendingMask|=K|Q,this.cssTimer=window.setTimeout(()=>{this.isDomDirty=!0,this.cssTimer=null},50)))});g(this,"onWindowResize",()=>{if(!this.resizeConfig.enabled){this.isDomDirty=!0;return}this.isResizing||(this.isResizing=!0,this.resizeConfig.onStart&&this.resizeConfig.onStart()),this.resizeTimer&&clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout(()=>{this.isDomDirty=!0,this.resizeConfig.onEnd&&this.resizeConfig.onEnd(),this.isResizing=!1,this.resizeTimer=null},this.resizeConfig.delay)});g(this,"renderLoop",()=>{if(!this.isRunning)return;this.onBeforeRender.forEach(i=>i()),this.isDomDirty&&(this.isDomDirty=!1,this.onLayoutChange.forEach(i=>i(this.pendingMask,this.pendingDeletions)),this.pendingDeletions.clear(),this.pendingMask=ie);const e=window.scrollX,t=window.scrollY;(e!==this.lastScrollX||t!==this.lastScrollY)&&(this.onScrollChange.forEach(i=>i(e,t)),this.lastScrollX=e,this.lastScrollY=t,this.scrollTimer&&clearTimeout(this.scrollTimer),this.scrollTimer=window.setTimeout(()=>{this.pendingMask|=K,this.isDomDirty=!0,this.scrollTimer=null},150)),this.pendingStyles.size>0&&(this.onStyleChange.forEach(i=>i(this.pendingStyles)),this.pendingStyles.clear()),this.onRender.forEach(i=>i()),requestAnimationFrame(this.renderLoop)});var r,o;this.target=e;const i=(r=t.resizeDebounce)!=null?r:!0;i===!1?this.resizeConfig={enabled:!1,delay:0}:i===!0?this.resizeConfig={enabled:!0,delay:150}:this.resizeConfig={enabled:!0,delay:(o=i.delay)!=null?o:150,onStart:i.onStart,onEnd:i.onEnd},this.observer=new MutationObserver(n=>{let a=ie;for(const c of n)if(c.type==="childList")a|=fe,c.removedNodes.length>0&&c.removedNodes.forEach(l=>{l instanceof HTMLElement&&this.pendingDeletions.add(l)});else if(c.type==="attributes")if(c.attributeName==="style"){a|=K|Q;const l=c.target,d=Me(l.style);this.pendingStyles.set(l,d)}else(c.attributeName==="class"||c.attributeName&&c.attributeName.startsWith("data-"))&&(a|=K|Q);else c.type==="characterData"&&(a|=ge|K);if(a!==ie){if(this.pendingMask|=a,a&fe){this.clearTimers(),this.isDomDirty=!0;return}this.mutationTimer&&clearTimeout(this.mutationTimer),this.mutationTimer=window.setTimeout(()=>{this.mutationTimer=null,this.isDomDirty=!0},200)}})}start(){this.isRunning||(this.isRunning=!0,this.observer.observe(this.target,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),this.target.addEventListener("transitionend",this.onTransitionFinished),this.target.addEventListener("animationend",this.onTransitionFinished),window.addEventListener("resize",this.onWindowResize),this.isDomDirty=!0,this.lastScrollX=window.scrollX,this.lastScrollY=window.scrollY,this.renderLoop())}stop(){this.isRunning=!1,this.observer.disconnect(),this.clearTimers(),this.target.removeEventListener("transitionend",this.onTransitionFinished),this.target.removeEventListener("animationend",this.onTransitionFinished),window.removeEventListener("resize",this.onWindowResize)}clearTimers(){this.mutationTimer&&(clearTimeout(this.mutationTimer),this.mutationTimer=null),this.cssTimer&&(clearTimeout(this.cssTimer),this.cssTimer=null),this.scrollTimer&&(clearTimeout(this.scrollTimer),this.scrollTimer=null)}}const H=1,Z=2,Ve=0,_={BASE:0,SELECTED:1,getCaptureLayer:s=>31-s,HIDDEN:31},be=Object.values(D.VALUES);class Ae{static getBaseline(e){if(this.cache.has(e))return this.cache.get(e);const t=this.calculateBaselineFromDOM(e);return this.cache.set(e,t),t}static calculateBaselineFromDOM(e){if(typeof document=="undefined")return 0;const t=document.createElement("div"),i=document.createElement("span"),r=document.createElement("img");t.style.visibility="hidden",t.style.position="absolute",t.style.top="0px",t.style.left="0px",t.style.font=e,t.style.margin="0",t.style.padding="0",t.style.border="none",i.style.margin="0",i.style.padding="0",i.style.border="none",i.style.lineHeight="normal",r.width=1,r.height=1,r.style.verticalAlign="baseline",i.appendChild(document.createTextNode("Hidden Text")),t.appendChild(i),t.appendChild(r),document.body.appendChild(t);const o=r.offsetTop-i.offsetTop;return document.body.removeChild(t),o}}g(Ae,"cache",new Map);class We extends b.MeshBasicMaterial{constructor(t,i,r,o,n=2){super({transparent:!0,side:b.FrontSide,color:16777215});g(this,"canvas");g(this,"ctx");g(this,"qualityFactor");if(this.canvas=document.createElement("canvas"),this.ctx=this.canvas.getContext("2d"),!this.ctx)throw new Error("[Mirage] Failed to create canvas context");this.qualityFactor=n,this.map=new b.CanvasTexture(this.canvas),this.map.colorSpace=b.LinearSRGBColorSpace,this.map.minFilter=b.LinearFilter,this.map.magFilter=b.LinearFilter,this.updateText(t,i,r,o)}wrapText(t,i){const r=t.split(`
2
- `),o=[];return r.forEach(n=>{const a=n.match(/[^\s\-]+\-?|\-|\s+/g)||[];if(a.length===0){o.push("");return}let c=a[0];for(let l=1;l<a.length;l++){const d=a[l];this.ctx.measureText(c+d).width<=i+2?c+=d:(c&&o.push(c),c=d.trimStart())}c&&o.push(c)}),o}updateText(t,i,r,o,n){n!==void 0&&(this.qualityFactor=n);const c=(window.devicePixelRatio||1)*this.qualityFactor,l=r*c,d=o*c;this.canvas.width!==l||this.canvas.height!==d?(this.canvas.width=l,this.canvas.height=d):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.setTransform(c,0,0,c,0,0),this.ctx.font=i.font,this.ctx.fillStyle=i.color,this.ctx.textBaseline="alphabetic",this.ctx.globalAlpha=1;const h=this.wrapText(t,r),u=i.lineHeight,v=Ae.getBaseline(i.font);h.forEach((f,p)=>{const x=p*u+v;let I=0;i.textAlign==="center"?I=r/2:i.textAlign==="right"&&(I=r),this.ctx.textAlign=i.textAlign,this.ctx.fillText(f,I,x)}),this.map&&(this.map.needsUpdate=!0)}dispose(){this.map&&this.map.dispose(),super.dispose()}}function ee(s){return typeof s=="number"?s:parseFloat(s)||0}function se(s){if(!s||s==="transparent")return{color:new b.Color(16777215),alpha:0};const e=s.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);if(e){const t=parseInt(e[1],10),i=parseInt(e[2],10),r=parseInt(e[3],10),o=e[4]!==void 0?parseFloat(e[4]):1;return{color:new b.Color(`rgb(${t}, ${i}, ${r})`),alpha:o}}return{color:new b.Color(s),alpha:1}}function Pe(s){const e=[];let t="",i=0;for(let r=0;r<s.length;r++){const o=s[r];if(o==="(")i++;else if(o===")")i--;else if(o===","&&i===0){e.push(t.trim()),t="";continue}t+=o}return t&&e.push(t.trim()),e}function He(s){if(!s||typeof s!="string"||!s.includes("linear-gradient"))return null;const e=s.match(/linear-gradient\((.*)\)/);if(!e)return null;const t=e[1],i=Pe(t);let r=Math.PI,o=0;const n=i[0].trim();if(n.startsWith("to "))n==="to top"?r=0:n==="to right"?r=Math.PI/2:n==="to bottom"?r=Math.PI:n==="to left"?r=Math.PI*1.5:n==="to top right"||n==="to right top"?r=Math.PI/4:n==="to bottom right"||n==="to right bottom"?r=Math.PI*.75:n==="to bottom left"||n==="to left bottom"?r=Math.PI*1.25:(n==="to top left"||n==="to left top")&&(r=Math.PI*1.75),o=1;else if(n.endsWith("deg")||n.endsWith("rad")||n.endsWith("turn")){const c=parseFloat(n);n.endsWith("deg")?r=c*(Math.PI/180):n.endsWith("rad")?r=c:n.endsWith("turn")&&(r=c*Math.PI*2),o=1}const a=[];for(let c=o;c<i.length&&!(a.length>=8);c++){const l=i[c].trim(),d=l.lastIndexOf(" ");let h=l,u=null;if(d!==-1&&!l.endsWith(")")){const f=l.substring(d+1);(f.endsWith("%")||f.endsWith("px")||!isNaN(parseFloat(f)))&&(h=l.substring(0,d).trim(),u=f)}const v=se(h);a.push({color:v.color,alpha:v.alpha,rawStop:u,stop:0})}if(a.length>0){for(let l=0;l<a.length;l++)a[l].rawStop!==null&&(a[l].stop=parseFloat(a[l].rawStop)/100);a[0].rawStop===null&&(a[0].stop=0),a.length>1&&a[a.length-1].rawStop===null&&(a[a.length-1].stop=1);let c=0;for(let l=1;l<a.length;l++)if(a[l].rawStop!==null||l===a.length-1){const d=l-c;if(d>1){const h=a[c].stop,v=(a[l].stop-h)/d;for(let f=1;f<d;f++)a[c+f].stop=h+v*f}c=l}}return{angle:r,stops:a}}const Ge=`varying vec2 vUv;
1
+ (function(b,T){typeof exports=="object"&&typeof module!="undefined"?T(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],T):(b=typeof globalThis!="undefined"?globalThis:b||self,T(b.MirageEngine={},b.THREE))})(this,function(b,T){"use strict";var at=Object.defineProperty,ct=Object.defineProperties;var lt=Object.getOwnPropertyDescriptors;var Ue=Object.getOwnPropertySymbols;var ht=Object.prototype.hasOwnProperty,dt=Object.prototype.propertyIsEnumerable;var pe=(b,T,S)=>T in b?at(b,T,{enumerable:!0,configurable:!0,writable:!0,value:S}):b[T]=S,Z=(b,T)=>{for(var S in T||(T={}))ht.call(T,S)&&pe(b,S,T[S]);if(Ue)for(var S of Ue(T))dt.call(T,S)&&pe(b,S,T[S]);return b},_e=(b,T)=>ct(b,lt(T));var g=(b,T,S)=>(pe(b,typeof T!="symbol"?T+"":T,S),S);var Be=(b,T,S)=>new Promise((v,te)=>{var N=R=>{try{L(S.next(R))}catch(O){te(O)}},re=R=>{try{L(S.throw(R))}catch(O){te(O)}},L=R=>R.done?v(R.value):Promise.resolve(R.value).then(N,re);L((S=S.apply(b,T)).next())});function S(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const v=S(T),te={INCLUDE_TREE:"include-tree",EXCLUDE_TREE:"exclude-tree",INCLUDE_SELF:"include-self",EXCLUDE_SELF:"exclude-self",END:"end"},N={NAME:"data-mirage-dom",KEY:"mirageDom",VALUES:{HIDE:"hide",SHOW:"show"}},re={TRAVELER:"traveler",NATIVE:"native",CAPTURE_1:"1",CAPTURE_2:"2",CAPTURE_3:"3",CAPTURE_4:"4",CAPTURE_5:"5"},L={NAME:"data-mirage-travel",KEY:"mirageTravel",VALUES:re,MAX_LAYERS:Object.keys(re).length-1},R={NAME:"data-mirage-filter",KEY:"mirageFilter",VALUES:te},O={NAME:"data-mirage-select",KEY:"mirageSelect",VALUES:te},me={NAME:"data-mirage-shader",KEY:"mirageShader"},Fe={NAME:"data-mirage-sandwich",KEY:"mirageSandwich",VALUES:{FRONT:"front"}},ie=0,$=1,Q=2,ve=4,se=8,ae=16;function Ne(s){const e=s.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return e?{r:parseInt(e[1])/255,g:parseInt(e[2])/255,b:parseInt(e[3])/255}:{r:1,g:1,b:1}}function ye(s){const e={};if(s.opacity&&(e.opacity=parseFloat(s.opacity)),s.backgroundColor&&s.backgroundColor!=="rgba(0, 0, 0, 0)"){const t=Ne(s.backgroundColor);e.backgroundColor=[t.r,t.g,t.b]}if(s.backgroundImage?e.backgroundImage=s.backgroundImage:s.background&&(e.backgroundImage=s.background),s.borderRadius&&(e.borderRadius=parseFloat(s.borderRadius)),s.width&&(e.width=parseFloat(s.width)),s.height&&(e.height=parseFloat(s.height)),s.transform&&s.transform!=="none"){const t=new DOMMatrix(s.transform);e.x=t.m41,e.y=t.m42,e.z=t.m43}return e}class be{constructor(e,t){g(this,"target");g(this,"observer");g(this,"pendingDeletions",new Set);g(this,"pendingStyles",new Map);g(this,"isDomDirty",!1);g(this,"isRunning",!1);g(this,"pendingMask",ie);g(this,"mutationTimer",null);g(this,"cssTimer",null);g(this,"resizeConfig");g(this,"resizeTimer",null);g(this,"isResizing",!1);g(this,"lastScrollX",0);g(this,"lastScrollY",0);g(this,"scrollTimer",null);g(this,"onBeforeRender",new Set);g(this,"onLayoutChange",new Set);g(this,"onStyleChange",new Set);g(this,"onScrollChange",new Set);g(this,"onRender",new Set);g(this,"onTransitionFinished",e=>{this.target.contains(e.target)&&this.mutationTimer===null&&(this.cssTimer&&clearTimeout(this.cssTimer),this.pendingStyles.size==0&&(this.pendingMask|=$|Q,this.cssTimer=window.setTimeout(()=>{this.isDomDirty=!0,this.cssTimer=null},50)))});g(this,"onWindowResize",()=>{if(!this.resizeConfig.enabled){this.isDomDirty=!0;return}this.isResizing||(this.isResizing=!0,this.resizeConfig.onStart&&this.resizeConfig.onStart()),this.resizeTimer&&clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout(()=>{this.isDomDirty=!0,this.resizeConfig.onEnd&&this.resizeConfig.onEnd(),this.isResizing=!1,this.resizeTimer=null},this.resizeConfig.delay)});g(this,"renderLoop",()=>{if(!this.isRunning)return;this.onBeforeRender.forEach(r=>r()),this.isDomDirty&&(this.isDomDirty=!1,this.onLayoutChange.forEach(r=>r(this.pendingMask,this.pendingDeletions)),this.pendingDeletions.clear(),this.pendingMask=ie);const e=window.scrollX,t=window.scrollY;(e!==this.lastScrollX||t!==this.lastScrollY)&&(this.onScrollChange.forEach(r=>r(e,t)),this.lastScrollX=e,this.lastScrollY=t,this.scrollTimer&&clearTimeout(this.scrollTimer),this.scrollTimer=window.setTimeout(()=>{this.pendingMask|=$,this.isDomDirty=!0,this.scrollTimer=null},150)),this.pendingStyles.size>0&&(this.onStyleChange.forEach(r=>r(this.pendingStyles)),this.pendingStyles.clear()),this.onRender.forEach(r=>r()),requestAnimationFrame(this.renderLoop)});var i,o;this.target=e;const r=(i=t.resizeDebounce)!=null?i:!0;r===!1?this.resizeConfig={enabled:!1,delay:0}:r===!0?this.resizeConfig={enabled:!0,delay:150}:this.resizeConfig={enabled:!0,delay:(o=r.delay)!=null?o:150,onStart:r.onStart,onEnd:r.onEnd},this.observer=new MutationObserver(n=>{let a=ie;for(const l of n)if(l.type==="childList")a|=se,l.removedNodes.length>0&&l.removedNodes.forEach(c=>{c instanceof HTMLElement&&this.pendingDeletions.add(c)});else if(l.type==="attributes")if(l.attributeName==="style"){a|=$|Q;const c=l.target,d=ye(c.style);this.pendingStyles.set(c,d)}else l.attributeName==="class"?a|=$|Q:l.attributeName&&l.attributeName.startsWith("data-")&&(a|=$|Q,l.attributeName.startsWith("data-mirage")&&(a|=se));else l.type==="characterData"&&(a|=ae|$);if(a!==ie){if(this.pendingMask|=a,a&se){this.clearTimers(),this.isDomDirty=!0;return}this.mutationTimer&&clearTimeout(this.mutationTimer),this.mutationTimer=window.setTimeout(()=>{this.mutationTimer=null,this.isDomDirty=!0},200)}})}start(){this.isRunning||(this.isRunning=!0,this.observer.observe(this.target,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),this.target.addEventListener("transitionend",this.onTransitionFinished),this.target.addEventListener("animationend",this.onTransitionFinished),window.addEventListener("resize",this.onWindowResize),this.isDomDirty=!0,this.lastScrollX=window.scrollX,this.lastScrollY=window.scrollY,this.renderLoop())}stop(){this.isRunning=!1,this.observer.disconnect(),this.clearTimers(),this.target.removeEventListener("transitionend",this.onTransitionFinished),this.target.removeEventListener("animationend",this.onTransitionFinished),window.removeEventListener("resize",this.onWindowResize)}clearTimers(){this.mutationTimer&&(clearTimeout(this.mutationTimer),this.mutationTimer=null),this.cssTimer&&(clearTimeout(this.cssTimer),this.cssTimer=null),this.scrollTimer&&(clearTimeout(this.scrollTimer),this.scrollTimer=null)}}const X=1,j=2,Xe=0,A={BASE:0,SELECTED:1,getCaptureLayer:s=>31-s,HIDDEN:31},le=Object.values(R.VALUES);class Ee{static getBaseline(e){if(this.cache.has(e))return this.cache.get(e);const t=this.calculateBaselineFromDOM(e);return this.cache.set(e,t),t}static calculateBaselineFromDOM(e){if(typeof document=="undefined")return 0;const t=document.createElement("div"),r=document.createElement("span"),i=document.createElement("img");t.style.visibility="hidden",t.style.position="absolute",t.style.top="0px",t.style.left="0px",t.style.font=e,t.style.margin="0",t.style.padding="0",t.style.border="none",r.style.margin="0",r.style.padding="0",r.style.border="none",r.style.lineHeight="normal",i.width=1,i.height=1,i.style.verticalAlign="baseline",r.appendChild(document.createTextNode("Hidden Text")),t.appendChild(r),t.appendChild(i),document.body.appendChild(t);const o=i.offsetTop-r.offsetTop;return document.body.removeChild(t),o}}g(Ee,"cache",new Map);class ze extends v.MeshBasicMaterial{constructor(t,r,i,o,n=2){super({transparent:!0,side:v.FrontSide,color:16777215});g(this,"canvas");g(this,"ctx");g(this,"qualityFactor");if(this.canvas=document.createElement("canvas"),this.ctx=this.canvas.getContext("2d"),!this.ctx)throw new Error("[Mirage] Failed to create canvas context");this.qualityFactor=n,this.map=new v.CanvasTexture(this.canvas),this.map.colorSpace=v.LinearSRGBColorSpace,this.map.minFilter=v.LinearFilter,this.map.magFilter=v.LinearFilter,this.updateText(t,r,i,o)}wrapText(t,r){const i=t.split(`
2
+ `),o=[];return i.forEach(n=>{const a=n.match(/[^\s\-]+\-?|\-|\s+/g)||[];if(a.length===0){o.push("");return}let l=a[0];for(let c=1;c<a.length;c++){const d=a[c];this.ctx.measureText(l+d).width<=r+2?l+=d:(l&&o.push(l),l=d.trimStart())}l&&o.push(l)}),o}updateText(t,r,i,o,n){n!==void 0&&(this.qualityFactor=n);const l=(window.devicePixelRatio||1)*this.qualityFactor,c=i*l,d=o*l;this.canvas.width!==c||this.canvas.height!==d?(this.canvas.width=c,this.canvas.height=d):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.setTransform(l,0,0,l,0,0),this.ctx.font=r.font,this.ctx.fillStyle=r.color,this.ctx.textBaseline="alphabetic",this.ctx.globalAlpha=1;const h=this.wrapText(t,i),u=r.lineHeight,p=Ee.getBaseline(r.font);h.forEach((f,m)=>{const C=m*u+p;let k=0;r.textAlign==="center"?k=i/2:r.textAlign==="right"&&(k=i),this.ctx.textAlign=r.textAlign,this.ctx.fillText(f,k,C)}),this.map&&(this.map.needsUpdate=!0)}dispose(){this.map&&this.map.dispose(),super.dispose()}}function ee(s){return typeof s=="number"?s:parseFloat(s)||0}function ne(s){if(!s||s==="transparent")return{color:new v.Color(16777215),alpha:0};const e=s.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);if(e){const t=parseInt(e[1],10),r=parseInt(e[2],10),i=parseInt(e[3],10),o=e[4]!==void 0?parseFloat(e[4]):1;return{color:new v.Color(`rgb(${t}, ${r}, ${i})`),alpha:o}}return{color:new v.Color(s),alpha:1}}function Ye(s){const e=[];let t="",r=0;for(let i=0;i<s.length;i++){const o=s[i];if(o==="(")r++;else if(o===")")r--;else if(o===","&&r===0){e.push(t.trim()),t="";continue}t+=o}return t&&e.push(t.trim()),e}function Ve(s){if(!s||typeof s!="string"||!s.includes("linear-gradient"))return null;const e=s.match(/linear-gradient\((.*)\)/);if(!e)return null;const t=e[1],r=Ye(t);let i=Math.PI,o=0;const n=r[0].trim();if(n.startsWith("to "))n==="to top"?i=0:n==="to right"?i=Math.PI/2:n==="to bottom"?i=Math.PI:n==="to left"?i=Math.PI*1.5:n==="to top right"||n==="to right top"?i=Math.PI/4:n==="to bottom right"||n==="to right bottom"?i=Math.PI*.75:n==="to bottom left"||n==="to left bottom"?i=Math.PI*1.25:(n==="to top left"||n==="to left top")&&(i=Math.PI*1.75),o=1;else if(n.endsWith("deg")||n.endsWith("rad")||n.endsWith("turn")){const l=parseFloat(n);n.endsWith("deg")?i=l*(Math.PI/180):n.endsWith("rad")?i=l:n.endsWith("turn")&&(i=l*Math.PI*2),o=1}const a=[];for(let l=o;l<r.length&&!(a.length>=8);l++){const c=r[l].trim(),d=c.lastIndexOf(" ");let h=c,u=null;if(d!==-1&&!c.endsWith(")")){const f=c.substring(d+1);(f.endsWith("%")||f.endsWith("px")||!isNaN(parseFloat(f)))&&(h=c.substring(0,d).trim(),u=f)}const p=ne(h);a.push({color:p.color,alpha:p.alpha,rawStop:u,stop:0})}if(a.length>0){for(let c=0;c<a.length;c++)a[c].rawStop!==null&&(a[c].stop=parseFloat(a[c].rawStop)/100);a[0].rawStop===null&&(a[0].stop=0),a.length>1&&a[a.length-1].rawStop===null&&(a[a.length-1].stop=1);let l=0;for(let c=1;c<a.length;c++)if(a[c].rawStop!==null||c===a.length-1){const d=c-l;if(d>1){const h=a[l].stop,p=(a[c].stop-h)/d;for(let f=1;f<d;f++)a[l+f].stop=h+p*f}l=c}}return{angle:i,stops:a}}const We=`varying vec2 vUv;
3
3
  varying vec4 vScreenPos;
4
4
  void main() {
5
5
  vUv = uv;
6
6
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
7
7
  vScreenPos = gl_Position;
8
- }`,qe=`varying vec2 vUv;
8
+ }`,He=`varying vec2 vUv;
9
9
  uniform vec2 uSize;
10
10
  uniform vec4 uBorderRadius;
11
11
  uniform float uBorderWidth;
@@ -134,22 +134,22 @@ void main() {
134
134
 
135
135
  // #include <colorspace_fragment>
136
136
  }
137
- `,$e=`uniform sampler2D uTexture;
137
+ `,Pe=`uniform sampler2D uTexture;
138
138
  varying vec4 vScreenPos;
139
139
  uniform vec2 uTextureRepeat;
140
- uniform vec2 uTextureOffset;`,je=`vec2 screenUv = (vScreenPos.xy / vScreenPos.w) * 0.5 + 0.5;
140
+ uniform vec2 uTextureOffset;`,Ge=`vec2 screenUv = (vScreenPos.xy / vScreenPos.w) * 0.5 + 0.5;
141
141
  vec2 resultUv = screenUv;
142
142
 
143
- `,Ke=`vec4 texColor = texture2D(uTexture, resultUv);
144
- baseColor = blendSrcOver(baseColor, texColor);`,Ie={vertexShader:Ge,fragmentShader:qe},ye={declChunk:$e,uvChunk:je,baseColorChunk:Ke};function Je(s,e,t,i=null,r){var k;const o=i!==null||!!s.imageSrc;let n="";const a={};if(r!=null&&r.uniforms)for(const[T,E]of Object.entries(r.uniforms))typeof E=="number"?(n+=`uniform float ${T};
145
- `,a[T]={value:E}):Array.isArray(E)?E.length===2?(n+=`uniform vec2 ${T};
146
- `,a[T]={value:new b.Vector2(...E)}):E.length===3?(n+=`uniform vec3 ${T};
147
- `,a[T]={value:new b.Vector3(...E)}):E.length===4&&(n+=`uniform vec4 ${T};
148
- `,a[T]={value:new b.Vector4(...E)}):(n+=`uniform float ${T};
149
- `,a[T]={value:E});const c=(o?ye.declChunk:"")+`
150
- `+n,l=s.isTraveler?ye.uvChunk:`vec2 resultUv = vUv * uTextureRepeat + uTextureOffset;
151
- `,d=o?l+((r==null?void 0:r.uvModifier)||""):"",h=o?ye.baseColorChunk:"",u=(r==null?void 0:r.colorModifier)||"",v=Ie.fragmentShader.replace("#INJECT_DECLARATIONS",c).replace("#INJECT_UV_MODIFIER",d).replace("#INJECT_BASE_COLOR",h).replace("#INJECT_COLOR_MODIFIER",u),f=se(s.backgroundColor),p=se(s.borderColor),x={uSize:{value:new b.Vector2(e,t)},uBgColor:{value:new b.Vector4(f.color.r,f.color.g,f.color.b,f.alpha)},uBorderColor:{value:new b.Vector4(p.color.r,p.color.g,p.color.b,p.alpha)},uBorderRadius:{value:new b.Vector4(0,0,0,0)},uBorderWidth:{value:ee(s.borderWidth)},uOpacity:{value:(k=s.opacity)!=null?k:1},uTexture:{value:null},uTextureRepeat:{value:new b.Vector2(1,1)},uTextureOffset:{value:new b.Vector2(0,0)},uGradientCount:{value:0},uGradientAngle:{value:0},uGradientColors:{value:Array.from({length:8},()=>new b.Vector4(0,0,0,0))},uGradientStops:{value:new Float32Array(8)}};ke(x.uBorderRadius.value,s.borderRadius),o&&(x.uTexture.value=i);const I=new b.ShaderMaterial({uniforms:J(J({},x),a),vertexShader:Ie.vertexShader,fragmentShader:v,transparent:!0,side:b.FrontSide});return s.backgroundImage&&we(I,{backgroundImage:s.backgroundImage}),I}function Ze(s,e,t,i,r){const o=ee(e.borderWidth);we(s,{width:t,height:i,borderRadius:e.borderRadius,borderWidth:o,backgroundColor:e.backgroundColor,borderColor:e.borderColor,opacity:e.opacity,texture:r,backgroundImage:e.backgroundImage})}function we(s,e){var i,r,o;if(e.width!==void 0&&e.height!==void 0&&s.uniforms.uSize.value.set(e.width,e.height),e.borderRadius!==void 0&&ke(s.uniforms.uBorderRadius.value,e.borderRadius),e.borderWidth!==void 0&&(s.uniforms.uBorderWidth.value=e.borderWidth),e.backgroundColor!==void 0)if(Array.isArray(e.backgroundColor)){const n=s.uniforms.uBgColor.value.w;s.uniforms.uBgColor.value.set(e.backgroundColor[0],e.backgroundColor[1],e.backgroundColor[2],n)}else if(typeof e.backgroundColor=="string"){const n=se(e.backgroundColor);s.uniforms.uBgColor.value.set(n.color.r,n.color.g,n.color.b,n.alpha)}else{const n=s.uniforms.uBgColor.value.w;s.uniforms.uBgColor.value.set(e.backgroundColor.r,e.backgroundColor.g,e.backgroundColor.b,n)}if(e.borderColor!==void 0)if(Array.isArray(e.borderColor)){const n=s.uniforms.uBorderColor.value.w;s.uniforms.uBorderColor.value.set(e.borderColor[0],e.borderColor[1],e.borderColor[2],n)}else if(typeof e.borderColor=="string"){const n=se(e.borderColor);s.uniforms.uBorderColor.value.set(n.color.r,n.color.g,n.color.b,n.alpha)}else{const n=s.uniforms.uBorderColor.value.w;s.uniforms.uBorderColor.value.set(e.borderColor.r,e.borderColor.g,e.borderColor.b,n)}e.opacity!==void 0&&(s.uniforms.uOpacity.value=e.opacity),e.bgOpacity!==void 0&&(s.uniforms.uBgColor.value.w=e.bgOpacity),e.borderOpacity!==void 0&&(s.uniforms.uBorderColor.value.w=e.borderOpacity),s.uniforms.uTexture&&e.texture!==void 0&&(s.uniforms.uTexture.value=e.texture);const t=e.texture!==void 0?e.texture:(i=s.uniforms.uTexture)==null?void 0:i.value;if(t&&(t.image instanceof ImageBitmap||t.image instanceof HTMLImageElement||t.image instanceof HTMLCanvasElement)){const n=t.image.width,a=t.image.height,c=(r=e.width)!=null?r:s.uniforms.uSize.value.x,l=(o=e.height)!=null?o:s.uniforms.uSize.value.y;if(n&&a&&c&&l){const d=n/a,h=c/l;if(d>h){const u=h/d;s.uniforms.uTextureRepeat.value.set(u,1),s.uniforms.uTextureOffset.value.set((1-u)/2,0)}else{const u=d/h;s.uniforms.uTextureRepeat.value.set(1,u),s.uniforms.uTextureOffset.value.set(0,(1-u)/2)}}}else s.uniforms.uTextureRepeat&&(s.uniforms.uTextureRepeat.value.set(1,1),s.uniforms.uTextureOffset.value.set(0,0));if(e.backgroundImage!==void 0){const n=He(e.backgroundImage);if(n){s.uniforms.uGradientCount.value=n.stops.length,s.uniforms.uGradientAngle.value=n.angle;for(let a=0;a<8;a++)if(a<n.stops.length){const c=n.stops[a];s.uniforms.uGradientColors.value[a].set(c.color.r,c.color.g,c.color.b,c.alpha),s.uniforms.uGradientStops.value[a]=c.stop}else s.uniforms.uGradientColors.value[a].set(0,0,0,0),s.uniforms.uGradientStops.value[a]=1}else s.uniforms.uGradientCount.value=0}for(const n of Object.keys(e))n!=="width"&&n!=="height"&&n!=="borderRadius"&&n!=="borderWidth"&&n!=="backgroundColor"&&n!=="borderColor"&&n!=="opacity"&&n!=="bgOpacity"&&n!=="borderOpacity"&&n!=="texture"&&n!=="backgroundImage"&&s.uniforms[n]!==void 0&&(s.uniforms[n].value!==void 0&&s.uniforms[n].value!==null&&typeof s.uniforms[n].value.set=="function"?Array.isArray(e[n])?s.uniforms[n].value.set(...e[n]):e[n]!==void 0&&(e[n].copy?s.uniforms[n].value.copy(e[n]):s.uniforms[n].value=e[n]):s.uniforms[n].value=e[n])}function ke(s,e){var a,c,l,d;if(e==null){s.set(0,0,0,0);return}if(typeof e=="number"){s.set(e,e,e,e);return}if(Array.isArray(e)){s.set(e[0],e[1],e[2],e[3]);return}const t=e.split("/")[0].trim().split(/\s+/),i=ee(t[0]),r=ee((a=t[1])!=null?a:t[0]),o=ee((c=t[2])!=null?c:t[0]),n=ee((d=(l=t[3])!=null?l:t[1])!=null?d:t[0]);s.set(i,r,o,n)}const $={create(s,e,t,i,r,o=2,n=null,a){return s==="BOX"?Je(e,i,r,n,a):s==="TEXT"?new We(t||"",e,i,r,o):new b.MeshBasicMaterial({visible:!1})},update(s,e,t,i,r,o,n=2,a){e==="BOX"?Ze(s,t,r,o,a):e==="TEXT"&&s.updateText(i||"",t,r,o,n)},forceUpdateUniforms(s,e){we(s,e)}};class Qe{constructor(e,t=!0){g(this,"observer");g(this,"textures",new WeakMap);g(this,"loadStatus",new WeakMap);g(this,"elementUrls",new WeakMap);g(this,"onUpdate");this.onUpdate=e,t&&(this.observer=new IntersectionObserver(i=>{for(const r of i){const o=r.target;r.isIntersecting?this.loadTexture(o):this.disposeTexture(o)}},{rootMargin:"300px"}))}register(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return;this.elementUrls.get(e)!==t&&(this.elementUrls.set(e,t),this.observer?(this.observer.unobserve(e),this.observer.observe(e)):this.loadTexture(e))}unregister(e){e.nodeType===Node.ELEMENT_NODE&&this.observer&&this.observer.unobserve(e),this.disposeTexture(e),this.elementUrls.delete(e),this.loadStatus.delete(e)}loadTexture(e){return Ye(this,null,function*(){if(this.loadStatus.get(e)||this.textures.has(e))return;const t=this.elementUrls.get(e);if(t){this.loadStatus.set(e,!0);try{let i;if(t.startsWith("data:image/svg+xml"))i=yield new Promise((o,n)=>{const a=new Image;a.onload=()=>o(a),a.onerror=n,a.src=t});else{const n=yield(yield fetch(t)).blob();i=yield createImageBitmap(n,{imageOrientation:"flipY"})}if(this.elementUrls.get(e)!==t){"close"in i&&i.close();return}const r=new b.Texture(i);i instanceof HTMLImageElement||(r.flipY=!1),r.colorSpace=b.LinearSRGBColorSpace,r.needsUpdate=!0,this.textures.set(e,r),this.onUpdate(e,r)}catch(i){console.warn("[MirageEngine] Failed to load texture:",t,i)}finally{this.elementUrls.has(e)&&this.loadStatus.set(e,!1)}}})}disposeTexture(e){const t=this.textures.get(e);t&&(t.dispose(),this.textures.delete(e),this.onUpdate(e,null)),this.loadStatus.set(e,!1)}get(e){return this.textures.get(e)}disposeAll(){this.observer&&this.observer.disconnect()}}class et{constructor(e,t,i,r){g(this,"canvas");g(this,"scene");g(this,"camera");g(this,"renderer");g(this,"renderTargets",[]);g(this,"renderOrder",0);g(this,"qualityFactor",2);g(this,"mode","overlay");g(this,"canvasSize","viewport");g(this,"clipArea",1);g(this,"targetLayer","base");g(this,"overscan",200);g(this,"target");g(this,"mountContainer");g(this,"registry");g(this,"targetRect");g(this,"travelersByLayer",Array.from({length:A.MAX_LAYERS},()=>new Set));g(this,"textureManager");g(this,"fixedMeshes",new Set);var a,c,l,d,h;this.target=e,this.mountContainer=i,this.registry=r,this.mode=(a=t.mode)!=null?a:"overlay",this.canvasSize=(c=t.canvasSize)!=null?c:"viewport",this.clipArea=(l=t.travelerClipArea)!=null?l:1,this.targetLayer=(d=t.layer)!=null?d:"base",this.textureManager=new Qe((u,v)=>{const f=this.registry.get(u);f&&f.material instanceof b.ShaderMaterial&&$.forceUpdateUniforms(f.material,{texture:v})},this.isViewport),this.canvas=document.createElement("canvas"),this.scene=new b.Scene,this.targetRect=this.target.getBoundingClientRect();const o=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,n=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.camera=new b.OrthographicCamera(o/-2,o/2,n/2,n/-2,1,1e3),this.camera.position.z=100,this.camera.layers.set(this.getSceneLayer()),this.renderer=new b.WebGLRenderer({canvas:this.canvas,alpha:!0,antialias:!0}),b.ColorManagement.enabled=!1,this.renderer.outputColorSpace=b.LinearSRGBColorSpace,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(o,n),this.applyTextQuality((h=t.quality)!=null?h:"medium")}get isViewport(){return this.mode==="overlay"&&this.canvasSize==="viewport"}getSceneLayer(){return typeof this.targetLayer=="number"?this.targetLayer:this.targetLayer==="selected"?_.SELECTED:_.BASE}createRenderTarget(){for(let e=0;e<A.MAX_LAYERS;e++){const t=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,i=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.renderTargets.push(new b.WebGLRenderTarget(t*this.qualityFactor,i*this.qualityFactor,{minFilter:b.LinearFilter,magFilter:b.LinearFilter,format:b.RGBAFormat,stencilBuffer:!1,depthBuffer:!0}))}}applyTextQuality(e){if(typeof e=="number"){this.qualityFactor=Math.max(.1,e);return}switch(e){case"low":this.qualityFactor=1;break;case"high":this.qualityFactor=4;break;case"medium":this.qualityFactor=2;break;default:this.qualityFactor=2;break}}mount(){this.mountContainer.prepend(this.canvas),this.canvas.style.pointerEvents=this.mode==="overlay"?"none":"auto",this.updateCanvasLayout()}updateCanvasLayout(){const e=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,t=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.mode==="duplicate"?(this.canvas.style.position="",this.canvas.style.top="",this.canvas.style.left="",this.canvas.style.display="block"):(this.canvas.style.position=this.isViewport?"fixed":"absolute",this.canvas.style.top=this.isViewport?`-${this.overscan}px`:`${this.target.offsetTop}px`,this.canvas.style.left=this.isViewport?`-${this.overscan}px`:`${this.target.offsetLeft}px`,this.canvas.style.display="block")}updateUniforms(e,t){const i=this.registry.get(e);i&&(i.traverse(r=>{r.isMesh&&r.material&&$.forceUpdateUniforms(r.material,t)}),i.userData.nativeMesh&&i.userData.nativeMesh.traverse(r=>{r.isMesh&&r.material&&$.forceUpdateUniforms(r.material,t)}))}dispose(){this.renderer.dispose(),this.canvas.remove(),this.textureManager.disposeAll()}setSize(e,t){this.renderer.setSize(e,t);for(const i of this.renderTargets)i.setSize(e*this.qualityFactor,t*this.qualityFactor);this.camera.left=e/-2,this.camera.right=e/2,this.camera.top=t/2,this.camera.bottom=t/-2,this.camera.updateProjectionMatrix()}syncScene(e,t){const i=this.target.getBoundingClientRect(),r=this.isViewport?window.innerWidth+this.overscan*2:i.width,o=this.isViewport?window.innerHeight+this.overscan*2:i.height,n=this.isViewport?this.canvas.clientWidth:this.targetRect.width,a=this.isViewport?this.canvas.clientHeight:this.targetRect.height,c=Math.abs(r-n)>.1||Math.abs(o-a)>.1,l=this.mode==="overlay"&&(Math.abs(i.top-this.targetRect.top)>.1||Math.abs(i.left-this.targetRect.left)>.1);c?(this.targetRect=i,this.setSize(r,o),this.updateCanvasLayout()):l?(this.targetRect=i,this.updateCanvasLayout()):this.targetRect=i,this.renderOrder=0,this.reconcileNode(e),t.size>0&&t.forEach(d=>{const h=this.registry.get(d);if(h){this.scene.remove(h);for(const u of this.travelersByLayer)u.delete(h);this.fixedMeshes.delete(h),h.geometry.dispose(),h.userData.nativeMesh&&(this.scene.remove(h.userData.nativeMesh),Array.isArray(h.userData.nativeMesh.material)?h.userData.nativeMesh.material.forEach(u=>u.dispose()):h.userData.nativeMesh.material.dispose(),h.userData.nativeMesh.geometry.dispose()),h.traverse(u=>{u instanceof b.Mesh&&(u.geometry&&u.geometry.dispose(),u.material&&(Array.isArray(u.material)?u.material.forEach(v=>v.dispose()):u.material.dispose()))}),this.registry.remove(d),this.textureManager.unregister(d)}})}reconcileNode(e){var i;let t=this.registry.get(e.element);if(!t){const r=new b.PlaneGeometry(1,1),o=e.isTraveler?(i=this.renderTargets[e.captureLayer-2])==null?void 0:i.texture:this.textureManager.get(e.element),n=$.create("BOX",e.styles,"",e.rect.width,e.rect.height,this.qualityFactor,o,e.shaderHooks);t=new b.Mesh(r,n),e.type==="TEXT"&&(t.name="BG_MESH"),this.scene.add(t),this.registry.register(e.element,t),t.userData.baseMaterial=n}if(this.updateMeshProperties(t,e),this.updateMeshLayers(t,e),e.isTraveler)for(let r=0;r<A.MAX_LAYERS;r++)r===e.captureLayer-2?this.travelersByLayer[r].add(t):this.travelersByLayer[r].delete(t);else for(const r of this.travelersByLayer)r.delete(t);if(e.isFixed?this.fixedMeshes.add(t):this.fixedMeshes.delete(t),e.styles.imageSrc?this.textureManager.register(e.element,e.styles.imageSrc):this.textureManager.unregister(e.element),e.type==="BOX")for(const r of e.children)this.reconcileNode(r);else e.type==="TEXT"&&(this.reconcileTextChild(t,e,!1),t.userData.nativeMesh&&e.nativeStyles&&this.reconcileTextChild(t.userData.nativeMesh,e,!0))}reconcileTextChild(e,t,i){var l;const r=t.textLines||[{text:t.textContent||"",rect:t.rect}],o=i?t.nativeStyles:t.textStyles,n=JSON.stringify(o)+t.textContent+r.map(d=>d.text).join("|"),a=(l=e.userData)==null?void 0:l.textChildStyleHash;if(t.dirtyMask&ge||n!==a){e.children.filter(f=>f.name.startsWith("TEXT_CHILD")).forEach(f=>{var x;const p=f;(x=p.material.map)==null||x.dispose(),p.geometry.dispose(),e.remove(p)});const h=t.rect,u=h.x+h.width/2,v=h.y+h.height/2;r.forEach((f,p)=>{const x=$.create("TEXT",o,f.text,f.rect.width,f.rect.height,this.qualityFactor),I=new b.PlaneGeometry(1,1),k=new b.Mesh(I,x);k.name=`TEXT_CHILD_${p}`;const T=t.rect.width===0?1:f.rect.width/t.rect.width,E=t.rect.height===0?1:f.rect.height/t.rect.height;k.scale.set(T,E,1);const Y=f.rect.x+f.rect.width/2,O=f.rect.y+f.rect.height/2,N=Y-u,V=-(O-v);k.position.set(t.rect.width===0?0:N/t.rect.width,t.rect.height===0?0:V/t.rect.height,.005),e.add(k)}),e.userData.textChildStyleHash=n}e.children.forEach(d=>{if(!d.name.startsWith("TEXT_CHILD"))return;const h=d,u=t.visibility&H?_.BASE:_.HIDDEN;if(h.layers.set(u),t.visibility&Z&&h.layers.enable(_.SELECTED),t.visibility&H)if(!i&&t.nativeLayer!==void 0&&t.nativeStyles!==void 0)for(let v=t.captureLayer;v<t.nativeLayer;v++)h.layers.enable(_.getCaptureLayer(v));else if(i&&t.nativeLayer!==void 0)for(let v=Math.max(t.captureLayer,t.nativeLayer);v<=A.MAX_LAYERS+1;v++)h.layers.enable(_.getCaptureLayer(v));else for(let v=t.captureLayer;v<=A.MAX_LAYERS+1;v++)h.layers.enable(_.getCaptureLayer(v))})}updateMeshProperties(e,t){var T,E,Y;const{rect:i,styles:r}=t,o=this.renderer.getPixelRatio(),n=this.renderer.domElement.width/o,a=this.renderer.domElement.height/o;e.material=e.userData.baseMaterial,e.scale.set(i.width,i.height,1),e.userData.domRect=Se(J({},i),{width:i.width,height:i.height});const c=.001;this.renderOrder++;const l=this.targetRect.left+window.scrollX,d=this.targetRect.top+window.scrollY;let h,u;if(this.isViewport)h=i.x-window.innerWidth/2+i.width/2,u=-i.y+window.innerHeight/2-i.height/2;else{const O=i.x-l,N=i.y-d;h=O-n/2+i.width/2,u=-N+a/2-i.height/2}e.position.set(h,u,r.zIndex+this.renderOrder*c);const v=i.x,f=i.y;e.userData.basePosition={x:h,y:u},e.userData.originalBasePosition={x:h,y:u},e.userData.baseSize={width:i.width,height:i.height},e.userData.baseDOM={x:v,y:f},e.userData.isFixed=t.isFixed,e.userData.initialScroll={x:window.scrollX,y:window.scrollY};const p=t.element.nodeType===Node.TEXT_NODE?t.element.parentElement:t.element,x=window.getComputedStyle(p);let I=0,k=0;if(x.transform&&x.transform!=="none"){const O=new DOMMatrix(x.transform);I=O.m41,k=O.m42}if(e.userData.baseTransform={x:I,y:k},delete e.userData.originRatioX,delete e.userData.originRatioY,$.update(e.userData.baseMaterial,"BOX",r,"",i.width,i.height,this.qualityFactor,t.isTraveler?(T=this.renderTargets[t.captureLayer-2])==null?void 0:T.texture:this.textureManager.get(t.element)),t.nativeStyles&&t.nativeRect){if(!e.userData.nativeMesh){const F=$.create("BOX",t.nativeStyles,"",t.nativeRect.width,t.nativeRect.height,this.qualityFactor,t.isTraveler?(E=this.renderTargets[t.captureLayer-2])==null?void 0:E.texture:this.textureManager.get(t.element),t.shaderHooks),q=new b.Mesh(e.geometry,F);t.type==="TEXT"&&(q.name="BG_MESH"),this.scene.add(q),e.userData.nativeMesh=q}const O=e.userData.nativeMesh;let N,V;if(this.isViewport)N=t.nativeRect.x-window.innerWidth/2+t.nativeRect.width/2,V=-t.nativeRect.y+window.innerHeight/2-t.nativeRect.height/2;else{const F=t.nativeRect.x-l,q=t.nativeRect.y-d;N=F-n/2+t.nativeRect.width/2,V=-q+a/2-t.nativeRect.height/2}O.scale.set(t.nativeRect.width,t.nativeRect.height,1),O.position.set(N,V,t.nativeStyles.zIndex+this.renderOrder*c),$.update(O.material,"BOX",t.nativeStyles,"",t.nativeRect.width,t.nativeRect.height,this.qualityFactor,t.isTraveler?(Y=this.renderTargets[t.captureLayer-2])==null?void 0:Y.texture:this.textureManager.get(t.element))}else e.userData.nativeMesh&&(this.scene.remove(e.userData.nativeMesh),e.userData.nativeMesh.material instanceof b.Material&&e.userData.nativeMesh.material.dispose(),delete e.userData.nativeMesh)}updateMeshLayers(e,t){const i=t.visibility&H?_.BASE:_.HIDDEN;if(e.layers.set(i),t.visibility&Z&&e.layers.enable(_.SELECTED),e.userData.nativeMesh&&t.nativeLayer!==void 0){const r=e.userData.nativeMesh;if(r.layers.set(_.HIDDEN),t.visibility&H){for(let o=t.captureLayer;o<t.nativeLayer;o++)e.layers.enable(_.getCaptureLayer(o));for(let o=Math.max(t.captureLayer,t.nativeLayer);o<=A.MAX_LAYERS+1;o++)r.layers.enable(_.getCaptureLayer(o))}}else if(t.visibility&H)for(let r=t.captureLayer;r<=A.MAX_LAYERS+1;r++)e.layers.enable(_.getCaptureLayer(r))}captureRenderTarget(e,t,i){if(e.size===0||!i)return;const r=new b.Color,o=this.renderer.getClearAlpha();this.renderer.getClearColor(r),this.renderer.setClearColor(0,0),this.renderer.setRenderTarget(i),this.renderer.clear(),this.renderer.autoClear=!1,this.renderer.setScissorTest(!0),this.camera.layers.set(t);const n=new b.Vector3,a=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,c=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height,l=this.renderer.getPixelRatio();for(const d of e){n.setFromMatrixPosition(d.matrixWorld),n.project(this.camera);const h=(n.x+1)/2*a,u=(n.y+1)/2*c;let v=0,f=1;typeof this.clipArea=="number"?f=this.clipArea:this.clipArea.endsWith("%")?f=parseFloat(this.clipArea)/100:this.clipArea.endsWith("px")&&(v=parseFloat(this.clipArea));const p=d.scale.x*f+.5,x=d.scale.y*f+.5,I=h-p/2,k=u-x/2,T=(I*this.qualityFactor-v)/l,E=(k*this.qualityFactor-v)/l,Y=(p*this.qualityFactor+v*2)/l,O=(x*this.qualityFactor+v*2)/l;this.renderer.setScissor(T,E,Y,O),this.renderer.render(this.scene,this.camera)}this.renderer.setScissorTest(!1),this.renderer.autoClear=!0,this.renderer.setRenderTarget(null),this.camera.layers.set(this.getSceneLayer()),this.renderer.setClearColor(r,o)}render(){for(let e=0;e<A.MAX_LAYERS;e++){const t=e+1;this.captureRenderTarget(this.travelersByLayer[e],_.getCaptureLayer(t),this.renderTargets[e])}this.renderer.render(this.scene,this.camera)}updateCameraScroll(e,t){this.isViewport&&(this.camera.position.x=e,this.camera.position.y=-t,this.camera.updateMatrixWorld())}}function tt(s){const e=s.textContent||"",t=[];let i="",r=null,o=-1;const n=(l,d)=>{for(let h=0;h<l.length;h++){const u=l[h],v=document.createRange();v.setStart(s,d+h),v.setEnd(s,d+h+1);const f=v.getBoundingClientRect();if(f.width===0&&f.height===0){i+=u;continue}o===-1||Math.abs(f.top-o)>f.height/2?(i&&r&&t.push({text:i,rect:{left:r.left,top:r.top,width:r.right-r.left,height:r.bottom-r.top}}),i=u,r={left:f.left,top:f.top,right:f.right,bottom:f.bottom},o=f.top):(i+=u,r&&(r.left=Math.min(r.left,f.left),r.top=Math.min(r.top,f.top),r.right=Math.max(r.right,f.right),r.bottom=Math.max(r.bottom,f.bottom)))}},a=e.match(/[^\s\-]+\-?|\-|\s+/g)||[];let c=0;for(const l of a){const d=document.createRange();d.setStart(s,c),d.setEnd(s,c+l.length);const h=d.getClientRects();if(h.length>1)n(l,c);else{const u=h.length===1?h[0]:d.getBoundingClientRect();if(u.width===0&&u.height===0){i+=l,c+=l.length;continue}o===-1||Math.abs(u.top-o)>u.height/2?(i&&r&&t.push({text:i,rect:{left:r.left,top:r.top,width:r.right-r.left,height:r.bottom-r.top}}),i=l,r={left:u.left,top:u.top,right:u.right,bottom:u.bottom},o=u.top):(i+=l,r&&(r.left=Math.min(r.left,u.left),r.top=Math.min(r.top,u.top),r.right=Math.max(r.right,u.right),r.bottom=Math.max(r.bottom,u.bottom)))}c+=l.length}return i&&r&&t.push({text:i,rect:{left:r.left,top:r.top,width:r.right-r.left,height:r.bottom-r.top}}),t.filter(l=>l.text.trim().length>0&&l.rect.width>0&&l.rect.height>0)}function Oe(s){const e=parseFloat(s.fontSize);let t=parseFloat(s.lineHeight);isNaN(t)&&(t=e*1.2);let i=parseFloat(s.letterSpacing);return isNaN(i)&&(i=0),{font:`${s.fontStyle} ${s.fontWeight} ${s.fontSize} ${s.fontFamily}`,fontSize:s.fontSize,color:s.color,textAlign:s.textAlign||"start",textBaseline:"alphabetic",direction:s.direction||"inherit",lineHeight:t,letterSpacing:i}}function Ue(s,e=K|Q|Le|ge|fe,t,i=1,r=0,o=2,n,a){var oe,ae,ce,le,he,de;if(s.nodeType===Node.TEXT_NODE){const m=s;if(!m.textContent||!m.textContent.trim())return null;const R=m.textContent.replace(/\s+/g," ");if(R.length===0)return null;const U=tt(m);if(U.length===0)return null;const X=m.parentElement,L=X?window.getComputedStyle(X):null;if(!L)return null;const z=Math.min(...U.map(w=>w.rect.left)),C=Math.min(...U.map(w=>w.rect.top)),W=Math.max(...U.map(w=>w.rect.left+w.rect.width)),j=Math.max(...U.map(w=>w.rect.top+w.rect.height));return{id:Math.random().toString(36).substring(2,9),type:"TEXT",element:m,rect:{x:z+window.scrollX,y:C+window.scrollY,width:W-z,height:j-C},styles:{backgroundColor:"transparent",backgroundImage:"",opacity:X&&X.dataset[P.KEY]===P.VALUES.HIDE?1:parseFloat(L.opacity),zIndex:(isNaN(parseInt(L.zIndex))?0:parseInt(L.zIndex))+r,borderRadius:"0px",borderColor:"transparent",borderWidth:"0px",isTraveler:!1},textContent:R,textLines:U.map(w=>({text:w.text.trim(),rect:{x:w.rect.left+window.scrollX,y:w.rect.top+window.scrollY,width:w.rect.width,height:w.rect.height}})),textStyles:Oe(L),dirtyMask:e,visibility:t,isTraveler:!1,captureLayer:i,isFixed:L.position==="fixed",nativeLayer:n,nativeStyles:a?J(J({backgroundColor:"transparent",backgroundImage:"",opacity:X&&X.dataset[P.KEY]===P.VALUES.HIDE?1:parseFloat(L.opacity),zIndex:(isNaN(parseInt(L.zIndex))?0:parseInt(L.zIndex))+r,borderRadius:"0px",borderColor:"transparent",borderWidth:"0px",isTraveler:!1},Oe(L)),a):void 0,nativeRect:a?{x:z+window.scrollX,y:C+window.scrollY,width:W-z,height:j-C}:void 0,children:[]}}if(s.nodeType!==Node.ELEMENT_NODE)return null;const c=s,l=c.dataset[D.KEY];let d=t,h=t;if(l){const m=new Set(l.split(/\s+/));for(const R of m)if(!be.includes(R))throw new Error(`[MirageEngine] Invalid filter token: '${R}'. Expected one of: 'include-tree', 'exclude-tree', 'include-self', 'exclude-self', 'end'.`);if(m.has(D.VALUES.END))return null;if(m.has(D.VALUES.INCLUDE_TREE)&&m.has(D.VALUES.EXCLUDE_TREE))throw new Error("[MirageEngine] Conflicting filters: 'include-tree' and 'exclude-tree' cannot be used together on the same element.");if(m.has(D.VALUES.INCLUDE_SELF)&&m.has(D.VALUES.EXCLUDE_SELF))throw new Error("[MirageEngine] Conflicting filters: 'include-self' and 'exclude-self' cannot be used together on the same element.");m.has(D.VALUES.INCLUDE_TREE)?d=d|H:m.has(D.VALUES.EXCLUDE_TREE)&&(d=d&~H),h=d,m.has(D.VALUES.INCLUDE_SELF)?h=h|H:m.has(D.VALUES.EXCLUDE_SELF)&&(h=h&~H)}const u=c.dataset[B.KEY];if(u){const m=new Set(u.split(/\s+/));for(const R of m)if(!be.includes(R))throw new Error(`[MirageEngine] Invalid select token: '${R}'. Expected one of: 'include-tree', 'exclude-tree', 'include-self', 'exclude-self', 'end'.`);if(m.has(B.VALUES.END))return null;if(m.has(B.VALUES.INCLUDE_TREE)&&m.has(B.VALUES.EXCLUDE_TREE))throw new Error("[MirageEngine] Conflicting selects: 'include-tree' and 'exclude-tree' cannot be used together on the same element.");if(m.has(B.VALUES.INCLUDE_SELF)&&m.has(B.VALUES.EXCLUDE_SELF))throw new Error("[MirageEngine] Conflicting selects: 'include-self' and 'exclude-self' cannot be used together on the same element.");m.has(B.VALUES.INCLUDE_TREE)?d=d|Z:m.has(B.VALUES.EXCLUDE_TREE)&&(d=d&~Z),h=d,m.has(B.VALUES.INCLUDE_SELF)?h=h|Z:m.has(B.VALUES.EXCLUDE_SELF)&&(h=h&~Z)}const v=c.dataset[A.KEY];let f=!1,p=a?J({},a):{},x=n;if(v){let m=1;const R=v.indexOf("{"),U=v.lastIndexOf("}");let X=v;if(R!==-1&&U!==-1&&U>R){X=v.substring(0,R).trim();const C=v.substring(R,U+1);try{p=new Function("return "+C)()}catch(W){console.warn(`[MirageEngine] Failed to parse travel styles JSON: ${C}`)}}const L=X.split(/\s+/);let z=!1;if(L.includes(A.VALUES.TRAVELER)){f=!0,z=!0;const C=L.find(W=>!isNaN(parseInt(W,10)));C&&(m=parseInt(C,10))}else if(L.includes(A.VALUES.NATIVE)){f=!1;const C=L.find(W=>!isNaN(parseInt(W,10)));C&&(x=parseInt(C,10))}if(z){const C=m+1;if(C<i)throw new Error(`[MirageEngine] Traveler layer (${m}) cannot be smaller than inherited capture layer (${i-1}).`);i=Math.min(C,A.MAX_LAYERS+1)}}const I=c.dataset[Re.KEY];let k;I&&(k=JSON.parse(I));const T=c.getBoundingClientRect(),E=window.getComputedStyle(c);if(T.width===0||T.height===0||E.display==="none")return null;let Y=c.getAttribute("data-mid");Y||(Y=Math.random().toString(36).substring(2,11),c.setAttribute("data-mid",Y));const O=parseInt(E.zIndex),N=(isNaN(O)?0:O)+r;let V;if(c.tagName==="IMG")V=c.src;else if(c.tagName.toLowerCase()==="svg"){const m=c.cloneNode(!0),R=p==null?void 0:p.color,U=p==null?void 0:p.fill,X=p==null?void 0:p.stroke,L=p==null?void 0:p.opacity,z=(w,Fe)=>{const G=window.getComputedStyle(w),ue=Fe,ot=G.fill===G.color,at=G.stroke===G.color,Ee=U||(ot?R:void 0)||G.fill;Ee&&Ee!=="none"&&(ue.style.fill=Ee);const Te=X||(at?R:void 0)||G.stroke;Te&&Te!=="none"&&(ue.style.stroke=Te),G.strokeWidth&&G.strokeWidth!=="0px"&&(ue.style.strokeWidth=G.strokeWidth);const Be=R||G.color;Be&&(ue.style.color=Be);const xe=L||G.opacity;xe&&xe!=="1"&&(ue.style.opacity=xe);for(let ve=0;ve<w.children.length;ve++)z(w.children[ve],Fe.children[ve])};z(c,m);const C=c.getBoundingClientRect(),W=window.devicePixelRatio*o;m.hasAttribute("viewBox")||m.setAttribute("viewBox",`0 0 ${C.width} ${C.height}`),m.setAttribute("width",(C.width*W).toString()),m.setAttribute("height",(C.height*W).toString());let j=new XMLSerializer().serializeToString(m);j.includes("xmlns=")||(j=j.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),V=`data:image/svg+xml;utf8,${encodeURIComponent(j)}`}else if(E.backgroundImage&&E.backgroundImage!=="none"){const m=E.backgroundImage.match(/url\(['"]?(.*?)['"]?\)/);m&&(V=m[1])}const F={backgroundColor:E.backgroundColor,backgroundImage:E.backgroundImage,opacity:c.dataset[P.KEY]===P.VALUES.HIDE?1:parseFloat(E.opacity),zIndex:N,borderRadius:E.borderRadius,borderColor:E.borderColor,borderWidth:E.borderWidth,imageSrc:V,isTraveler:f},q=F;let pe,me;const ne=[];return c.tagName.toLowerCase()!=="svg"&&Array.from(c.childNodes).forEach(m=>{const R=m.nodeType===Node.TEXT_NODE?h:d,U=Ue(m,e,R,i,N,o,x,m.nodeType===Node.TEXT_NODE&&Object.keys(p).length>0?p:void 0);U&&ne.push(U)}),{id:Y,type:"BOX",element:c,rect:{x:T.left+window.scrollX,y:T.top+window.scrollY,width:T.width,height:T.height},styles:q,textContent:pe,textStyles:me,dirtyMask:e,visibility:h,isTraveler:f,captureLayer:i,nativeLayer:x,nativeStyles:x!==void 0?Se(J({},F),{backgroundColor:(oe=p.backgroundColor)!=null?oe:F.backgroundColor,backgroundImage:(ae=p.backgroundImage)!=null?ae:F.backgroundImage,opacity:(ce=p.opacity)!=null?ce:F.opacity,zIndex:p.zIndex!==void 0?p.zIndex+N:F.zIndex,borderRadius:(le=p.borderRadius)!=null?le:F.borderRadius,borderColor:(he=p.borderColor)!=null?he:F.borderColor,borderWidth:(de=p.borderWidth)!=null?de:F.borderWidth,isTraveler:F.isTraveler}):void 0,nativeRect:x!==void 0?{x:p.x!==void 0?parseFloat(p.x):T.left+window.scrollX,y:p.y!==void 0?parseFloat(p.y):T.top+window.scrollY,width:p.width!==void 0?parseFloat(p.width):T.width,height:p.height!==void 0?parseFloat(p.height):T.height}:void 0,isFixed:E.position==="fixed",children:ne,shaderHooks:k}}function rt(s,e){e.size!==0&&e.forEach((t,i)=>{var Y,O,N,V,F,q,pe,me,ne,oe,ae,ce,le,he,de,m,R,U;const r=s.get(i);if(!r||!r.userData.basePosition)return;let{x:o,y:n}=r.userData.basePosition;const{width:a,height:c}=r.userData.baseSize,l=(Y=t.width)!=null?Y:a,d=(O=t.height)!=null?O:c,h=l-a,u=d-c;if(t.width!==void 0&&r.userData.originRatioX===void 0&&Math.abs(h)>.1){const X=i.getBoundingClientRect(),L=(N=t.x)!=null?N:0,z=(F=(V=r.userData.baseTransform)==null?void 0:V.x)!=null?F:0,C=r.userData.isFixed?0:window.scrollX;let w=-(X.left+C-L+z-r.userData.baseDOM.x)/h;Math.abs(w)<.05?w=0:Math.abs(w-1)<.05?w=1:Math.abs(w-.5)<.05&&(w=.5),r.userData.originRatioX=w}if(t.height!==void 0&&r.userData.originRatioY===void 0&&Math.abs(u)>.1){const X=i.getBoundingClientRect(),L=(q=t.y)!=null?q:0,z=(me=(pe=r.userData.baseTransform)==null?void 0:pe.y)!=null?me:0,C=r.userData.isFixed?0:window.scrollY;let w=-(X.top+C-L+z-r.userData.baseDOM.y)/u;Math.abs(w)<.05?w=0:Math.abs(w-1)<.05?w=1:Math.abs(w-.5)<.05&&(w=.5),r.userData.originRatioY=w}const v=(ne=r.userData.originRatioX)!=null?ne:.5,f=(oe=r.userData.originRatioY)!=null?oe:.5,p=h*(.5-v),x=u*(.5-f),I=(ce=(ae=r.userData.baseTransform)==null?void 0:ae.x)!=null?ce:0,k=(he=(le=r.userData.baseTransform)==null?void 0:le.y)!=null?he:0,T=((de=t.x)!=null?de:I)-I,E=((m=t.y)!=null?m:k)-k;r.position.setX(o+p+T),r.position.setY(n-(x+E)),r.scale.set(l,d,1),$.forceUpdateUniforms(r.material,{backgroundColor:t.backgroundColor,backgroundImage:t.backgroundImage,opacity:t.opacity,borderRadius:(U=t.borderRadius)!=null?U:(R=r.userData.baseStyles)==null?void 0:R.borderRadius,width:l,height:d})})}function _e(s,e,t){s.forEach(i=>{if(i.userData.isFixed&&i.userData.initialScroll&&i.userData.originalBasePosition){const r=e-i.userData.initialScroll.x,o=t-i.userData.initialScroll.y;i.userData.basePosition.x=i.userData.originalBasePosition.x+r,i.userData.basePosition.y=i.userData.originalBasePosition.y-o,i.position.x=i.userData.basePosition.x,i.position.y=i.userData.basePosition.y}})}class it{constructor(e,t,i,r){g(this,"target");g(this,"renderer");g(this,"registry");g(this,"isTravelEnabled",!1);g(this,"tracker");this.target=e,this.renderer=t,this.registry=i,this.tracker=new De(e,{resizeDebounce:r.resizeDebounce}),this.tracker.onLayoutChange.add((o,n)=>{document.querySelector(`[${A.NAME}~='${A.VALUES.TRAVELER}']`)!==null&&!this.isTravelEnabled&&(this.isTravelEnabled=!0,this.renderer.createRenderTarget());const c=Ue(this.target,o,H,1,0,this.renderer.qualityFactor);c&&this.renderer.syncScene(c,n)}),this.tracker.onScrollChange.add((o,n)=>{_e(this.renderer.fixedMeshes,o,n),this.renderer.updateCameraScroll(o,n)}),this.tracker.onStyleChange.add(o=>{rt(this.registry,o)}),this.tracker.onRender.add(()=>{this.renderer.render()})}start(){this.tracker.start(),_e(this.renderer.fixedMeshes,window.scrollX,window.scrollY),this.renderer.updateCameraScroll(window.scrollX,window.scrollY)}stop(){this.tracker.stop()}}class st{constructor(){g(this,"store");this.store=new WeakMap}register(e,t){this.store.set(e,t)}get(e){return this.store.get(e)}has(e){return this.store.has(e)}remove(e){this.store.delete(e)}}class nt{constructor(e,t){g(this,"renderer");g(this,"syncer");g(this,"target");g(this,"registry");var r,o,n;if(this.target=e,this.registry=new st,!document.getElementById("mirage-engine-styles")){const a=document.createElement("style");a.id="mirage-engine-styles",a.textContent=`
152
- [${P.NAME}="${P.VALUES.HIDE}"] {
143
+ `,qe=`vec4 texColor = texture2D(uTexture, resultUv);
144
+ baseColor = blendSrcOver(baseColor, texColor);`,we={vertexShader:We,fragmentShader:He},he={declChunk:Pe,uvChunk:Ge,baseColorChunk:qe};function $e(s,e,t,r=null,i){var U;const o=r!==null||!!s.imageSrc;let n="";const a={};if(i!=null&&i.uniforms)for(const[w,E]of Object.entries(i.uniforms))typeof E=="number"?(n+=`uniform float ${w};
145
+ `,a[w]={value:E}):Array.isArray(E)?E.length===2?(n+=`uniform vec2 ${w};
146
+ `,a[w]={value:new v.Vector2(...E)}):E.length===3?(n+=`uniform vec3 ${w};
147
+ `,a[w]={value:new v.Vector3(...E)}):E.length===4&&(n+=`uniform vec4 ${w};
148
+ `,a[w]={value:new v.Vector4(...E)}):(n+=`uniform float ${w};
149
+ `,a[w]={value:E});const l=(o?he.declChunk:"")+`
150
+ `+n,c=s.isTraveler?he.uvChunk:`vec2 resultUv = vUv * uTextureRepeat + uTextureOffset;
151
+ `,d=o?c+((i==null?void 0:i.uvModifier)||""):"",h=o?he.baseColorChunk:"",u=(i==null?void 0:i.colorModifier)||"",p=we.fragmentShader.replace("#INJECT_DECLARATIONS",l).replace("#INJECT_UV_MODIFIER",d).replace("#INJECT_BASE_COLOR",h).replace("#INJECT_COLOR_MODIFIER",u),f=ne(s.backgroundColor),m=ne(s.borderColor),C={uSize:{value:new v.Vector2(e,t)},uBgColor:{value:new v.Vector4(f.color.r,f.color.g,f.color.b,f.alpha)},uBorderColor:{value:new v.Vector4(m.color.r,m.color.g,m.color.b,m.alpha)},uBorderRadius:{value:new v.Vector4(0,0,0,0)},uBorderWidth:{value:ee(s.borderWidth)},uOpacity:{value:(U=s.opacity)!=null?U:1},uTexture:{value:null},uTextureRepeat:{value:new v.Vector2(1,1)},uTextureOffset:{value:new v.Vector2(0,0)},uGradientCount:{value:0},uGradientAngle:{value:0},uGradientColors:{value:Array.from({length:8},()=>new v.Vector4(0,0,0,0))},uGradientStops:{value:new Float32Array(8)}};Te(C.uBorderRadius.value,s.borderRadius),o&&(C.uTexture.value=r);const k=new v.ShaderMaterial({uniforms:Z(Z({},C),a),vertexShader:we.vertexShader,fragmentShader:p,transparent:!0,side:v.FrontSide});return s.backgroundImage&&de(k,{backgroundImage:s.backgroundImage}),k}function je(s,e,t,r,i){const o=ee(e.borderWidth);de(s,{width:t,height:r,borderRadius:e.borderRadius,borderWidth:o,backgroundColor:e.backgroundColor,borderColor:e.borderColor,opacity:e.opacity,texture:i,backgroundImage:e.backgroundImage})}function de(s,e){var r,i,o;if(e.width!==void 0&&e.height!==void 0&&s.uniforms.uSize.value.set(e.width,e.height),e.borderRadius!==void 0&&Te(s.uniforms.uBorderRadius.value,e.borderRadius),e.borderWidth!==void 0&&(s.uniforms.uBorderWidth.value=e.borderWidth),e.backgroundColor!==void 0)if(Array.isArray(e.backgroundColor)){const n=s.uniforms.uBgColor.value.w;s.uniforms.uBgColor.value.set(e.backgroundColor[0],e.backgroundColor[1],e.backgroundColor[2],n)}else if(typeof e.backgroundColor=="string"){const n=ne(e.backgroundColor);s.uniforms.uBgColor.value.set(n.color.r,n.color.g,n.color.b,n.alpha)}else{const n=s.uniforms.uBgColor.value.w;s.uniforms.uBgColor.value.set(e.backgroundColor.r,e.backgroundColor.g,e.backgroundColor.b,n)}if(e.borderColor!==void 0)if(Array.isArray(e.borderColor)){const n=s.uniforms.uBorderColor.value.w;s.uniforms.uBorderColor.value.set(e.borderColor[0],e.borderColor[1],e.borderColor[2],n)}else if(typeof e.borderColor=="string"){const n=ne(e.borderColor);s.uniforms.uBorderColor.value.set(n.color.r,n.color.g,n.color.b,n.alpha)}else{const n=s.uniforms.uBorderColor.value.w;s.uniforms.uBorderColor.value.set(e.borderColor.r,e.borderColor.g,e.borderColor.b,n)}e.opacity!==void 0&&(s.uniforms.uOpacity.value=e.opacity),e.bgOpacity!==void 0&&(s.uniforms.uBgColor.value.w=e.bgOpacity),e.borderOpacity!==void 0&&(s.uniforms.uBorderColor.value.w=e.borderOpacity),s.uniforms.uTexture&&e.texture!==void 0&&(s.uniforms.uTexture.value=e.texture);const t=e.texture!==void 0?e.texture:(r=s.uniforms.uTexture)==null?void 0:r.value;if(t&&(t.image instanceof ImageBitmap||t.image instanceof HTMLImageElement||t.image instanceof HTMLCanvasElement)){const n=t.image.naturalWidth||t.image.videoWidth||t.image.width,a=t.image.naturalHeight||t.image.videoHeight||t.image.height,l=(i=e.width)!=null?i:s.uniforms.uSize.value.x,c=(o=e.height)!=null?o:s.uniforms.uSize.value.y;if(n&&a&&l&&c){const d=n/a,h=l/c;if(d>h){const u=h/d;s.uniforms.uTextureRepeat.value.set(u,1),s.uniforms.uTextureOffset.value.set((1-u)/2,0)}else{const u=d/h;s.uniforms.uTextureRepeat.value.set(1,u),s.uniforms.uTextureOffset.value.set(0,(1-u)/2)}}}else s.uniforms.uTextureRepeat&&(s.uniforms.uTextureRepeat.value.set(1,1),s.uniforms.uTextureOffset.value.set(0,0));if(e.backgroundImage!==void 0){const n=Ve(e.backgroundImage);if(n){s.uniforms.uGradientCount.value=n.stops.length,s.uniforms.uGradientAngle.value=n.angle;for(let a=0;a<8;a++)if(a<n.stops.length){const l=n.stops[a];s.uniforms.uGradientColors.value[a].set(l.color.r,l.color.g,l.color.b,l.alpha),s.uniforms.uGradientStops.value[a]=l.stop}else s.uniforms.uGradientColors.value[a].set(0,0,0,0),s.uniforms.uGradientStops.value[a]=1}else s.uniforms.uGradientCount.value=0}for(const n of Object.keys(e))n!=="width"&&n!=="height"&&n!=="borderRadius"&&n!=="borderWidth"&&n!=="backgroundColor"&&n!=="borderColor"&&n!=="opacity"&&n!=="bgOpacity"&&n!=="borderOpacity"&&n!=="texture"&&n!=="backgroundImage"&&s.uniforms[n]!==void 0&&(s.uniforms[n].value!==void 0&&s.uniforms[n].value!==null&&typeof s.uniforms[n].value.set=="function"?Array.isArray(e[n])?s.uniforms[n].value.set(...e[n]):e[n]!==void 0&&(e[n].copy?s.uniforms[n].value.copy(e[n]):s.uniforms[n].value=e[n]):s.uniforms[n].value=e[n])}function Te(s,e){var a,l,c,d;if(e==null){s.set(0,0,0,0);return}if(typeof e=="number"){s.set(e,e,e,e);return}if(Array.isArray(e)){s.set(e[0],e[1],e[2],e[3]);return}const t=e.split("/")[0].trim().split(/\s+/),r=ee(t[0]),i=ee((a=t[1])!=null?a:t[0]),o=ee((l=t[2])!=null?l:t[0]),n=ee((d=(c=t[3])!=null?c:t[1])!=null?d:t[0]);s.set(r,i,o,n)}const H={create(s,e,t,r,i,o=2,n=null,a){return s==="BOX"?$e(e,r,i,n,a):s==="TEXT"?new ze(t||"",e,r,i,o):new v.MeshBasicMaterial({visible:!1})},update(s,e,t,r,i,o,n=2,a){e==="BOX"?je(s,t,i,o,a):e==="TEXT"&&s.updateText(r||"",t,i,o,n)},forceUpdateUniforms(s,e){de(s,e)}};class Ke{constructor(e,t=!0){g(this,"observer");g(this,"textures",new WeakMap);g(this,"loadStatus",new WeakMap);g(this,"elementUrls",new WeakMap);g(this,"onUpdate");this.onUpdate=e,t&&(this.observer=new IntersectionObserver(r=>{for(const i of r){const o=i.target;i.isIntersecting?this.loadTexture(o):this.disposeTexture(o)}},{rootMargin:"300px"}))}register(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return;this.elementUrls.get(e)!==t&&(this.elementUrls.set(e,t),this.observer?(this.observer.unobserve(e),this.observer.observe(e)):this.loadTexture(e))}unregister(e){e.nodeType===Node.ELEMENT_NODE&&this.observer&&this.observer.unobserve(e),this.disposeTexture(e),this.elementUrls.delete(e),this.loadStatus.delete(e)}loadTexture(e){return Be(this,null,function*(){if(this.loadStatus.get(e)||this.textures.has(e))return;const t=this.elementUrls.get(e);if(t){this.loadStatus.set(e,!0);try{let r;if(t.startsWith("data:image/svg+xml"))r=yield new Promise((o,n)=>{const a=new Image;a.onload=()=>o(a),a.onerror=n,a.src=t});else{const n=yield(yield fetch(t)).blob();r=yield createImageBitmap(n,{imageOrientation:"flipY"})}if(this.elementUrls.get(e)!==t){"close"in r&&r.close();return}const i=new v.Texture(r);r instanceof HTMLImageElement||(i.flipY=!1),i.colorSpace=v.LinearSRGBColorSpace,i.needsUpdate=!0,this.textures.set(e,i),this.onUpdate(e,i)}catch(r){console.warn("[MirageEngine] Failed to load texture:",t,r)}finally{this.elementUrls.has(e)&&this.loadStatus.set(e,!1)}}})}disposeTexture(e){const t=this.textures.get(e);t&&(t.dispose(),this.textures.delete(e),this.onUpdate(e,null)),this.loadStatus.set(e,!1)}get(e){return this.textures.get(e)}disposeAll(){this.observer&&this.observer.disconnect()}}class Je{constructor(e,t,r,i){g(this,"canvas");g(this,"scene");g(this,"camera");g(this,"renderer");g(this,"renderTargets",[]);g(this,"renderOrder",0);g(this,"qualityFactor",2);g(this,"mode","overlay");g(this,"canvasSize","viewport");g(this,"clipArea",1);g(this,"targetLayer","base");g(this,"overscan",200);g(this,"target");g(this,"mountContainer");g(this,"registry");g(this,"targetRect");g(this,"travelersByLayer",Array.from({length:L.MAX_LAYERS},()=>new Set));g(this,"textureManager");g(this,"fixedMeshes",new Set);var a,l,c,d,h;this.target=e,this.mountContainer=r,this.registry=i,this.mode=(a=t.mode)!=null?a:"overlay",this.canvasSize=(l=t.canvasSize)!=null?l:"viewport",this.clipArea=(c=t.travelerClipArea)!=null?c:1,this.targetLayer=(d=t.layer)!=null?d:"base",this.textureManager=new Ke((u,p)=>{const f=this.registry.get(u);f&&f.material instanceof v.ShaderMaterial&&H.forceUpdateUniforms(f.material,{texture:p})},this.isViewport),this.canvas=document.createElement("canvas"),this.scene=new v.Scene,this.targetRect=this.target.getBoundingClientRect();const o=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,n=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.camera=new v.OrthographicCamera(o/-2,o/2,n/2,n/-2,1,1e3),this.camera.position.z=100,this.camera.layers.set(this.getSceneLayer()),this.renderer=new v.WebGLRenderer({canvas:this.canvas,alpha:!0,antialias:!0}),v.ColorManagement.enabled=!1,this.renderer.outputColorSpace=v.LinearSRGBColorSpace,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(o,n),this.applyTextQuality((h=t.quality)!=null?h:"medium")}get isViewport(){return this.mode==="overlay"&&this.canvasSize==="viewport"}getSceneLayer(){return typeof this.targetLayer=="number"?this.targetLayer:this.targetLayer==="selected"?A.SELECTED:A.BASE}createRenderTarget(){for(let e=0;e<L.MAX_LAYERS;e++){const t=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,r=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.renderTargets.push(new v.WebGLRenderTarget(t*this.qualityFactor,r*this.qualityFactor,{minFilter:v.LinearFilter,magFilter:v.LinearFilter,format:v.RGBAFormat,stencilBuffer:!1,depthBuffer:!0}))}}applyTextQuality(e){if(typeof e=="number"){this.qualityFactor=Math.max(.1,e);return}switch(e){case"low":this.qualityFactor=1;break;case"high":this.qualityFactor=4;break;case"medium":this.qualityFactor=2;break;default:this.qualityFactor=2;break}}mount(){this.mountContainer.prepend(this.canvas),this.canvas.style.pointerEvents=this.mode==="overlay"?"none":"auto",this.updateCanvasLayout()}updateCanvasLayout(){const e=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,t=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.mode==="duplicate"?(this.canvas.style.position="",this.canvas.style.top="",this.canvas.style.left="",this.canvas.style.display="block"):(this.canvas.style.position=this.isViewport?"fixed":"absolute",this.canvas.style.top=this.isViewport?`-${this.overscan}px`:`${this.target.offsetTop}px`,this.canvas.style.left=this.isViewport?`-${this.overscan}px`:`${this.target.offsetLeft}px`,this.canvas.style.display="block")}updateUniforms(e,t){const r=this.registry.get(e);r&&(r.traverse(i=>{i.isMesh&&i.material&&H.forceUpdateUniforms(i.material,t)}),r.userData.nativeMesh&&r.userData.nativeMesh.traverse(i=>{i.isMesh&&i.material&&H.forceUpdateUniforms(i.material,t)}))}dispose(){this.renderer.dispose(),this.canvas.remove(),this.textureManager.disposeAll()}setSize(e,t){this.renderer.setSize(e,t);for(const r of this.renderTargets)r.setSize(e*this.qualityFactor,t*this.qualityFactor);this.camera.left=e/-2,this.camera.right=e/2,this.camera.top=t/2,this.camera.bottom=t/-2,this.camera.updateProjectionMatrix()}syncScene(e,t){const r=this.target.getBoundingClientRect(),i=this.isViewport?window.innerWidth+this.overscan*2:r.width,o=this.isViewport?window.innerHeight+this.overscan*2:r.height,n=this.isViewport?this.canvas.clientWidth:this.targetRect.width,a=this.isViewport?this.canvas.clientHeight:this.targetRect.height,l=Math.abs(i-n)>.1||Math.abs(o-a)>.1,c=this.mode==="overlay"&&(Math.abs(r.top-this.targetRect.top)>.1||Math.abs(r.left-this.targetRect.left)>.1);l?(this.targetRect=r,this.setSize(i,o),this.updateCanvasLayout()):c?(this.targetRect=r,this.updateCanvasLayout()):this.targetRect=r,this.renderOrder=0,this.reconcileNode(e),t.size>0&&t.forEach(d=>{const h=this.registry.get(d);if(h){this.scene.remove(h);for(const u of this.travelersByLayer)u.delete(h);this.fixedMeshes.delete(h),h.geometry.dispose(),h.userData.nativeMesh&&(this.scene.remove(h.userData.nativeMesh),Array.isArray(h.userData.nativeMesh.material)?h.userData.nativeMesh.material.forEach(u=>u.dispose()):h.userData.nativeMesh.material.dispose(),h.userData.nativeMesh.geometry.dispose()),h.traverse(u=>{u instanceof v.Mesh&&(u.geometry&&u.geometry.dispose(),u.material&&(Array.isArray(u.material)?u.material.forEach(p=>p.dispose()):u.material.dispose()))}),this.registry.remove(d),this.textureManager.unregister(d)}})}reconcileNode(e){var i;let t=this.registry.get(e.element);const r=JSON.stringify(e.shaderHooks||null);if(t&&t.userData.shaderHash!==r&&(this.scene.remove(t),t.geometry.dispose(),t.material instanceof v.Material&&t.material.dispose(),this.registry.remove(e.element),t=void 0),!t){const o=new v.PlaneGeometry(1,1),n=e.isTraveler?(i=this.renderTargets[e.captureLayer-2])==null?void 0:i.texture:this.textureManager.get(e.element),a=H.create("BOX",e.styles,"",e.rect.width,e.rect.height,this.qualityFactor,n,e.shaderHooks);t=new v.Mesh(o,a),e.type==="TEXT"&&(t.name="BG_MESH"),this.scene.add(t),this.registry.register(e.element,t),t.userData.baseMaterial=a,t.userData.domElement=e.element,t.userData.shaderHash=r}if(this.updateMeshProperties(t,e),this.updateMeshLayers(t,e),e.isTraveler)for(let o=0;o<L.MAX_LAYERS;o++)o===e.captureLayer-2?this.travelersByLayer[o].add(t):this.travelersByLayer[o].delete(t);else for(const o of this.travelersByLayer)o.delete(t);if(e.isFixed?this.fixedMeshes.add(t):this.fixedMeshes.delete(t),e.styles.imageSrc?this.textureManager.register(e.element,e.styles.imageSrc):this.textureManager.unregister(e.element),e.type==="BOX")for(const o of e.children)this.reconcileNode(o);else e.type==="TEXT"&&(this.reconcileTextChild(t,e,!1),t.userData.nativeMesh&&e.nativeStyles&&this.reconcileTextChild(t.userData.nativeMesh,e,!0))}reconcileTextChild(e,t,r){var c;const i=t.textLines||[{text:t.textContent||"",rect:t.rect}],o=r?t.nativeStyles:t.textStyles,n=JSON.stringify(o)+t.textContent+i.map(d=>d.text).join("|"),a=(c=e.userData)==null?void 0:c.textChildStyleHash;if(t.dirtyMask&ae||n!==a){e.children.filter(f=>f.name.startsWith("TEXT_CHILD")).forEach(f=>{var C;const m=f;(C=m.material.map)==null||C.dispose(),m.geometry.dispose(),e.remove(m)});const h=t.rect,u=h.x+h.width/2,p=h.y+h.height/2;i.forEach((f,m)=>{const C=H.create("TEXT",o,f.text,f.rect.width,f.rect.height,this.qualityFactor),k=new v.PlaneGeometry(1,1),U=new v.Mesh(k,C);U.name=`TEXT_CHILD_${m}`;const w=t.rect.width===0?1:f.rect.width/t.rect.width,E=t.rect.height===0?1:f.rect.height/t.rect.height;U.scale.set(w,E,1);const z=f.rect.x+f.rect.width/2,_=f.rect.y+f.rect.height/2,Y=z-u,P=-(_-p);U.position.set(t.rect.width===0?0:Y/t.rect.width,t.rect.height===0?0:P/t.rect.height,.005),e.add(U)}),e.userData.textChildStyleHash=n}e.children.forEach(d=>{if(!d.name.startsWith("TEXT_CHILD"))return;const h=d,u=t.visibility&X?A.BASE:A.HIDDEN;if(h.layers.set(u),t.visibility&j&&h.layers.enable(A.SELECTED),t.visibility&X)if(!r&&t.nativeLayer!==void 0&&t.nativeStyles!==void 0)for(let p=t.captureLayer;p<t.nativeLayer;p++)h.layers.enable(A.getCaptureLayer(p));else if(r&&t.nativeLayer!==void 0)for(let p=Math.max(t.captureLayer,t.nativeLayer);p<=L.MAX_LAYERS+1;p++)h.layers.enable(A.getCaptureLayer(p));else for(let p=t.captureLayer;p<=L.MAX_LAYERS+1;p++)h.layers.enable(A.getCaptureLayer(p))})}updateMeshProperties(e,t){var w,E,z;const{rect:r,styles:i}=t,o=this.renderer.getPixelRatio(),n=this.renderer.domElement.width/o,a=this.renderer.domElement.height/o;e.material=e.userData.baseMaterial,e.scale.set(r.width,r.height,1),e.userData.domRect={x:r.x,y:r.y,width:r.width,height:r.height};const l=.001;this.renderOrder++;const c=this.targetRect.left+window.scrollX,d=this.targetRect.top+window.scrollY;let h,u;if(this.isViewport)h=r.x-window.innerWidth/2+r.width/2,u=-r.y+window.innerHeight/2-r.height/2;else{const _=r.x-c,Y=r.y-d;h=_-n/2+r.width/2,u=-Y+a/2-r.height/2}e.position.set(h,u,i.zIndex+this.renderOrder*l);const p=r.x,f=r.y;e.userData.basePosition={x:h,y:u},e.userData.originalBasePosition={x:h,y:u},e.userData.baseSize={width:r.width,height:r.height},e.userData.baseDOM={x:p,y:f},e.userData.isFixed=t.isFixed,e.userData.initialScroll={x:window.scrollX,y:window.scrollY};const m=t.element.nodeType===Node.TEXT_NODE?t.element.parentElement:t.element,C=window.getComputedStyle(m);let k=0,U=0;if(C.transform&&C.transform!=="none"){const _=new DOMMatrix(C.transform);k=_.m41,U=_.m42}if(e.userData.baseTransform={x:k,y:U},delete e.userData.originRatioX,delete e.userData.originRatioY,H.update(e.userData.baseMaterial,"BOX",i,"",r.width,r.height,this.qualityFactor,t.isTraveler?(w=this.renderTargets[t.captureLayer-2])==null?void 0:w.texture:this.textureManager.get(t.element)),t.nativeStyles&&t.nativeRect){if(!e.userData.nativeMesh){const F=H.create("BOX",t.nativeStyles,"",t.nativeRect.width,t.nativeRect.height,this.qualityFactor,t.isTraveler?(E=this.renderTargets[t.captureLayer-2])==null?void 0:E.texture:this.textureManager.get(t.element),t.shaderHooks),K=new v.Mesh(e.geometry,F);t.type==="TEXT"&&(K.name="BG_MESH"),this.scene.add(K),e.userData.nativeMesh=K}const _=e.userData.nativeMesh;let Y,P;if(this.isViewport)Y=t.nativeRect.x-window.innerWidth/2+t.nativeRect.width/2,P=-t.nativeRect.y+window.innerHeight/2-t.nativeRect.height/2;else{const F=t.nativeRect.x-c,K=t.nativeRect.y-d;Y=F-n/2+t.nativeRect.width/2,P=-K+a/2-t.nativeRect.height/2}_.scale.set(t.nativeRect.width,t.nativeRect.height,1),_.position.set(Y,P,t.nativeStyles.zIndex+this.renderOrder*l),H.update(_.material,"BOX",t.nativeStyles,"",t.nativeRect.width,t.nativeRect.height,this.qualityFactor,t.isTraveler?(z=this.renderTargets[t.captureLayer-2])==null?void 0:z.texture:this.textureManager.get(t.element))}else e.userData.nativeMesh&&(this.scene.remove(e.userData.nativeMesh),e.userData.nativeMesh.material instanceof v.Material&&e.userData.nativeMesh.material.dispose(),delete e.userData.nativeMesh)}updateMeshLayers(e,t){const r=t.visibility&X?A.BASE:A.HIDDEN;if(e.layers.set(r),t.visibility&j&&e.layers.enable(A.SELECTED),e.userData.nativeMesh&&t.nativeLayer!==void 0){const i=e.userData.nativeMesh;if(i.layers.set(A.HIDDEN),t.visibility&X){for(let o=t.captureLayer;o<t.nativeLayer;o++)e.layers.enable(A.getCaptureLayer(o));for(let o=Math.max(t.captureLayer,t.nativeLayer);o<=L.MAX_LAYERS+1;o++)i.layers.enable(A.getCaptureLayer(o))}}else if(t.visibility&X)for(let i=t.captureLayer;i<=L.MAX_LAYERS+1;i++)e.layers.enable(A.getCaptureLayer(i))}captureRenderTarget(e,t,r){if(e.size===0||!r)return;const i=new v.Color,o=this.renderer.getClearAlpha();this.renderer.getClearColor(i),this.renderer.setClearColor(0,0),this.renderer.setRenderTarget(r),this.renderer.clear(),this.renderer.autoClear=!1,this.renderer.setScissorTest(!0),this.camera.layers.set(t);const n=new v.Vector3,a=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,l=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height,c=this.renderer.getPixelRatio();for(const d of e){n.setFromMatrixPosition(d.matrixWorld),n.project(this.camera);const h=(n.x+1)/2*a,u=(n.y+1)/2*l;let p=0,f=1;typeof this.clipArea=="number"?f=this.clipArea:this.clipArea.endsWith("%")?f=parseFloat(this.clipArea)/100:this.clipArea.endsWith("px")&&(p=parseFloat(this.clipArea));const m=d.scale.x*f+.5,C=d.scale.y*f+.5,k=h-m/2,U=u-C/2,w=(k*this.qualityFactor-p)/c,E=(U*this.qualityFactor-p)/c,z=(m*this.qualityFactor+p*2)/c,_=(C*this.qualityFactor+p*2)/c;this.renderer.setScissor(w,E,z,_),this.renderer.render(this.scene,this.camera)}this.renderer.setScissorTest(!1),this.renderer.autoClear=!0,this.renderer.setRenderTarget(null),this.camera.layers.set(this.getSceneLayer()),this.renderer.setClearColor(i,o)}render(){for(let e=0;e<L.MAX_LAYERS;e++){const t=e+1;this.captureRenderTarget(this.travelersByLayer[e],A.getCaptureLayer(t),this.renderTargets[e])}this.renderer.render(this.scene,this.camera)}syncMeshesByDOM(){const e=this.targetRect.left+window.scrollX,t=this.targetRect.top+window.scrollY,r=this.renderer.getPixelRatio(),i=this.renderer.domElement.width/r,o=this.renderer.domElement.height/r;this.scene.children.forEach(n=>{const a=n;if(!a.userData||!a.userData.domElement)return;const l=a.userData.domElement;let c;if(l.nodeType===Node.TEXT_NODE){const h=document.createRange();h.selectNode(l),c=h.getBoundingClientRect()}else c=l.getBoundingClientRect();const d=a.userData.domRect;if(!d||Math.abs(c.x-d.x)>.5||Math.abs(c.y-d.y)>.5||Math.abs(c.width-d.width)>.5||Math.abs(c.height-d.height)>.5){a.userData.domRect={x:c.x,y:c.y,width:c.width,height:c.height};let h,u;if(this.isViewport)h=c.x-window.innerWidth/2+c.width/2,u=-c.y+window.innerHeight/2-c.height/2;else{const p=c.x-e,f=c.y-t;h=p-i/2+c.width/2,u=-f+o/2-c.height/2}if(a.position.setX(h),a.position.setY(u),a.scale.set(c.width,c.height,1),a.material instanceof v.ShaderMaterial&&H.forceUpdateUniforms(a.material,{width:c.width,height:c.height}),a.userData.nativeMesh){const p=a.userData.nativeMesh;p.position.setX(h),p.position.setY(u),p.scale.set(c.width,c.height,1)}}})}}function Ze(s){const e=s.textContent||"",t=[];let r="",i=null,o=-1;const n=(c,d)=>{for(let h=0;h<c.length;h++){const u=c[h],p=document.createRange();p.setStart(s,d+h),p.setEnd(s,d+h+1);const f=p.getBoundingClientRect();if(f.width===0&&f.height===0){r+=u;continue}o===-1||Math.abs(f.top-o)>f.height/2?(r&&i&&t.push({text:r,rect:{left:i.left,top:i.top,width:i.right-i.left,height:i.bottom-i.top}}),r=u,i={left:f.left,top:f.top,right:f.right,bottom:f.bottom},o=f.top):(r+=u,i&&(i.left=Math.min(i.left,f.left),i.top=Math.min(i.top,f.top),i.right=Math.max(i.right,f.right),i.bottom=Math.max(i.bottom,f.bottom)))}},a=e.match(/[^\s\-]+\-?|\-|\s+/g)||[];let l=0;for(const c of a){const d=document.createRange();d.setStart(s,l),d.setEnd(s,l+c.length);const h=d.getClientRects();if(h.length>1)n(c,l);else{const u=h.length===1?h[0]:d.getBoundingClientRect();if(u.width===0&&u.height===0){r+=c,l+=c.length;continue}o===-1||Math.abs(u.top-o)>u.height/2?(r&&i&&t.push({text:r,rect:{left:i.left,top:i.top,width:i.right-i.left,height:i.bottom-i.top}}),r=c,i={left:u.left,top:u.top,right:u.right,bottom:u.bottom},o=u.top):(r+=c,i&&(i.left=Math.min(i.left,u.left),i.top=Math.min(i.top,u.top),i.right=Math.max(i.right,u.right),i.bottom=Math.max(i.bottom,u.bottom)))}l+=c.length}return r&&i&&t.push({text:r,rect:{left:i.left,top:i.top,width:i.right-i.left,height:i.bottom-i.top}}),t.filter(c=>c.text.trim().length>0&&c.rect.width>0&&c.rect.height>0)}function Ce(s){const e=parseFloat(s.fontSize);let t=parseFloat(s.lineHeight);isNaN(t)&&(t=e*1.2);let r=parseFloat(s.letterSpacing);return isNaN(r)&&(r=0),{font:`${s.fontStyle} ${s.fontWeight} ${s.fontSize} ${s.fontFamily}`,fontSize:s.fontSize,color:s.color,textAlign:s.textAlign||"start",textBaseline:"alphabetic",direction:s.direction||"inherit",lineHeight:t,letterSpacing:r}}function xe(s,e=$|Q|ve|ae|se,t,r=1,i=0,o=2,n,a){var Re,Le,Me,De,Ae,Ie;if(s.nodeType===Node.TEXT_NODE){const y=s;if(!y.textContent||!y.textContent.trim())return null;const M=y.textContent.replace(/\s+/g," ");if(M.length===0)return null;const B=Ze(y);if(B.length===0)return null;const V=y.parentElement,I=V?window.getComputedStyle(V):null;if(!I)return null;const G=Math.min(...B.map(D=>D.rect.left)),x=Math.min(...B.map(D=>D.rect.top)),q=Math.max(...B.map(D=>D.rect.left+D.rect.width)),J=Math.max(...B.map(D=>D.rect.top+D.rect.height));return{id:Math.random().toString(36).substring(2,9),type:"TEXT",element:y,rect:{x:G+window.scrollX,y:x+window.scrollY,width:q-G,height:J-x},styles:{backgroundColor:"transparent",backgroundImage:"",opacity:V&&V.dataset[N.KEY]===N.VALUES.HIDE?1:parseFloat(I.opacity),zIndex:(isNaN(parseInt(I.zIndex))?0:parseInt(I.zIndex))+i,borderRadius:"0px",borderColor:"transparent",borderWidth:"0px",isTraveler:!1},textContent:M,textLines:B.map(D=>({text:D.text.trim(),rect:{x:D.rect.left+window.scrollX,y:D.rect.top+window.scrollY,width:D.rect.width,height:D.rect.height}})),textStyles:Ce(I),dirtyMask:e,visibility:t,isTraveler:!1,captureLayer:r,isFixed:I.position==="fixed",nativeLayer:n,nativeStyles:a?Z(Z({backgroundColor:"transparent",backgroundImage:"",opacity:V&&V.dataset[N.KEY]===N.VALUES.HIDE?1:parseFloat(I.opacity),zIndex:(isNaN(parseInt(I.zIndex))?0:parseInt(I.zIndex))+i,borderRadius:"0px",borderColor:"transparent",borderWidth:"0px",isTraveler:!1},Ce(I)),a):void 0,nativeRect:a?{x:G+window.scrollX,y:x+window.scrollY,width:q-G,height:J-x}:void 0,children:[]}}if(s.nodeType!==Node.ELEMENT_NODE)return null;const l=s,c=l.dataset[R.KEY];let d=t,h=t;if(c){const y=new Set(c.split(/\s+/));for(const M of y)if(!le.includes(M))throw new Error(`[MirageEngine] Invalid filter token: '${M}'. Expected one of: 'include-tree', 'exclude-tree', 'include-self', 'exclude-self', 'end'.`);if(y.has(R.VALUES.END))return null;if(y.has(R.VALUES.INCLUDE_TREE)&&y.has(R.VALUES.EXCLUDE_TREE))throw new Error("[MirageEngine] Conflicting filters: 'include-tree' and 'exclude-tree' cannot be used together on the same element.");if(y.has(R.VALUES.INCLUDE_SELF)&&y.has(R.VALUES.EXCLUDE_SELF))throw new Error("[MirageEngine] Conflicting filters: 'include-self' and 'exclude-self' cannot be used together on the same element.");y.has(R.VALUES.INCLUDE_TREE)?d=d|X:y.has(R.VALUES.EXCLUDE_TREE)&&(d=d&~X),h=d,y.has(R.VALUES.INCLUDE_SELF)?h=h|X:y.has(R.VALUES.EXCLUDE_SELF)&&(h=h&~X)}const u=l.dataset[O.KEY];if(u){const y=new Set(u.split(/\s+/));for(const M of y)if(!le.includes(M))throw new Error(`[MirageEngine] Invalid select token: '${M}'. Expected one of: 'include-tree', 'exclude-tree', 'include-self', 'exclude-self', 'end'.`);if(y.has(O.VALUES.END))return null;if(y.has(O.VALUES.INCLUDE_TREE)&&y.has(O.VALUES.EXCLUDE_TREE))throw new Error("[MirageEngine] Conflicting selects: 'include-tree' and 'exclude-tree' cannot be used together on the same element.");if(y.has(O.VALUES.INCLUDE_SELF)&&y.has(O.VALUES.EXCLUDE_SELF))throw new Error("[MirageEngine] Conflicting selects: 'include-self' and 'exclude-self' cannot be used together on the same element.");y.has(O.VALUES.INCLUDE_TREE)?d=d|j:y.has(O.VALUES.EXCLUDE_TREE)&&(d=d&~j),h=d,y.has(O.VALUES.INCLUDE_SELF)?h=h|j:y.has(O.VALUES.EXCLUDE_SELF)&&(h=h&~j)}const p=l.dataset[L.KEY];let f=!1,m=a?Z({},a):{},C=n;if(p){let y=1;const M=p.indexOf("{"),B=p.lastIndexOf("}");let V=p;if(M!==-1&&B!==-1&&B>M){V=p.substring(0,M).trim();const x=p.substring(M,B+1);try{m=new Function("return "+x)()}catch(q){console.warn(`[MirageEngine] Failed to parse travel styles JSON: ${x}`)}}const I=V.split(/\s+/);let G=!1;if(I.includes(L.VALUES.TRAVELER)){f=!0,G=!0;const x=I.find(q=>!isNaN(parseInt(q,10)));x&&(y=parseInt(x,10))}else if(I.includes(L.VALUES.NATIVE)){f=!1;const x=I.find(q=>!isNaN(parseInt(q,10)));x&&(C=parseInt(x,10))}if(G){const x=y+1;if(x<r)throw new Error(`[MirageEngine] Traveler layer (${y}) cannot be smaller than inherited capture layer (${r-1}).`);r=Math.min(x,L.MAX_LAYERS+1)}}const k=l.dataset[me.KEY];let U;k&&(U=JSON.parse(k));const w=l.getBoundingClientRect(),E=window.getComputedStyle(l);if(w.width===0||w.height===0||E.display==="none")return null;let z=l.getAttribute("data-mid");z||(z=Math.random().toString(36).substring(2,11),l.setAttribute("data-mid",z));const _=parseInt(E.zIndex),Y=(isNaN(_)?0:_)+i;let P;if(l.tagName==="IMG")P=l.src;else if(l.tagName.toLowerCase()==="svg"){const y=l.cloneNode(!0),M=m==null?void 0:m.color,B=m==null?void 0:m.fill,V=m==null?void 0:m.stroke,I=m==null?void 0:m.opacity,G=(D,ke)=>{const W=window.getComputedStyle(D),oe=ke,nt=W.fill===W.color,ot=W.stroke===W.color,ue=B||(nt?M:void 0)||W.fill;ue&&ue!=="none"&&(oe.style.fill=ue);const fe=V||(ot?M:void 0)||W.stroke;fe&&fe!=="none"&&(oe.style.stroke=fe),W.strokeWidth&&W.strokeWidth!=="0px"&&(oe.style.strokeWidth=W.strokeWidth);const Oe=M||W.color;Oe&&(oe.style.color=Oe);const ge=I||W.opacity;ge&&ge!=="1"&&(oe.style.opacity=ge);for(let ce=0;ce<D.children.length;ce++)G(D.children[ce],ke.children[ce])};G(l,y);const x=l.getBoundingClientRect(),q=window.devicePixelRatio*o;y.hasAttribute("viewBox")||y.setAttribute("viewBox",`0 0 ${x.width} ${x.height}`),y.setAttribute("width",(x.width*q).toString()),y.setAttribute("height",(x.height*q).toString());let J=new XMLSerializer().serializeToString(y);J.includes("xmlns=")||(J=J.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),P=`data:image/svg+xml;utf8,${encodeURIComponent(J)}`}else if(E.backgroundImage&&E.backgroundImage!=="none"){const y=E.backgroundImage.match(/url\(['"]?(.*?)['"]?\)/);y&&(P=y[1])}const F={backgroundColor:E.backgroundColor,backgroundImage:E.backgroundImage,opacity:l.dataset[N.KEY]===N.VALUES.HIDE?1:parseFloat(E.opacity),zIndex:Y,borderRadius:E.borderRadius,borderColor:E.borderColor,borderWidth:E.borderWidth,imageSrc:P,isTraveler:f},K=F;let it,st;const Se=[];return l.tagName.toLowerCase()!=="svg"&&Array.from(l.childNodes).forEach(y=>{const M=y.nodeType===Node.TEXT_NODE?h:d,B=xe(y,e,M,r,Y,o,C,y.nodeType===Node.TEXT_NODE&&Object.keys(m).length>0?m:void 0);B&&Se.push(B)}),{id:z,type:"BOX",element:l,rect:{x:w.left+window.scrollX,y:w.top+window.scrollY,width:w.width,height:w.height},styles:K,textContent:it,textStyles:st,dirtyMask:e,visibility:h,isTraveler:f,captureLayer:r,nativeLayer:C,nativeStyles:C!==void 0?_e(Z({},F),{backgroundColor:(Re=m.backgroundColor)!=null?Re:F.backgroundColor,backgroundImage:(Le=m.backgroundImage)!=null?Le:F.backgroundImage,opacity:(Me=m.opacity)!=null?Me:F.opacity,zIndex:m.zIndex!==void 0?m.zIndex+Y:F.zIndex,borderRadius:(De=m.borderRadius)!=null?De:F.borderRadius,borderColor:(Ae=m.borderColor)!=null?Ae:F.borderColor,borderWidth:(Ie=m.borderWidth)!=null?Ie:F.borderWidth,isTraveler:F.isTraveler}):void 0,nativeRect:C!==void 0?{x:m.x!==void 0?parseFloat(m.x):w.left+window.scrollX,y:m.y!==void 0?parseFloat(m.y):w.top+window.scrollY,width:m.width!==void 0?parseFloat(m.width):w.width,height:m.height!==void 0?parseFloat(m.height):w.height}:void 0,isFixed:E.position==="fixed",children:Se,shaderHooks:U}}function Qe(s,e){e.size!==0&&e.forEach((t,r)=>{var o,n;const i=s.get(r);!i||!i.userData.basePosition||H.forceUpdateUniforms(i.material,{backgroundColor:t.backgroundColor,backgroundImage:t.backgroundImage,opacity:t.opacity,borderRadius:(n=t.borderRadius)!=null?n:(o=i.userData.baseStyles)==null?void 0:o.borderRadius})})}class et{constructor(e,t,r,i){g(this,"target");g(this,"renderer");g(this,"registry");g(this,"isTravelEnabled",!1);g(this,"tracker");this.target=e,this.renderer=t,this.registry=r,this.tracker=new be(e,{resizeDebounce:i.resizeDebounce}),this.tracker.onLayoutChange.add((o,n)=>{document.querySelector(`[${L.NAME}~='${L.VALUES.TRAVELER}']`)!==null&&!this.isTravelEnabled&&(this.isTravelEnabled=!0,this.renderer.createRenderTarget());const l=xe(this.target,o,X,1,0,this.renderer.qualityFactor);l&&this.renderer.syncScene(l,n)}),this.tracker.onStyleChange.add(o=>{Qe(this.registry,o)}),this.tracker.onRender.add(()=>{this.renderer.syncMeshesByDOM(),this.renderer.render()})}start(){this.tracker.start()}stop(){this.tracker.stop()}}class tt{constructor(){g(this,"store");this.store=new WeakMap}register(e,t){this.store.set(e,t)}get(e){return this.store.get(e)}has(e){return this.store.has(e)}remove(e){this.store.delete(e)}}class rt{constructor(e,t){g(this,"renderer");g(this,"syncer");g(this,"target");g(this,"registry");var i,o,n;if(this.target=e,this.registry=new tt,!document.getElementById("mirage-engine-styles")){const a=document.createElement("style");a.id="mirage-engine-styles",a.textContent=`
152
+ [${N.NAME}="${N.VALUES.HIDE}"] {
153
153
  opacity: 0 !important;
154
154
  }
155
- `,document.head.appendChild(a)}let i;if(t.mode==="duplicate"?i=(o=(r=t.container)!=null?r:this.target.parentElement)!=null?o:void 0:i=(n=this.target.parentElement)!=null?n:void 0,!i)throw new Error("[Mirage] Cannot find a container (parent or option).");this.renderer=new et(this.target,t,i,this.registry),this.renderer.mount(),this.syncer=new it(this.target,this.renderer,this.registry,t)}start(){this.syncer.start()}stop(){this.syncer.stop()}dispose(){this.syncer.stop(),this.renderer.dispose()}getTracker(){return this.syncer.tracker}updateUniforms(e,t){this.renderer.updateUniforms(e,t)}getCanvas(){return this.renderer.canvas}test(){const e=this.registry.get(document.querySelector("#box2"));if(!e)return;const t={ArrowRight:!1,ArrowLeft:!1,ArrowUp:!1,ArrowDown:!1};window.addEventListener("keydown",o=>{t[o.key]!==void 0&&(t[o.key]=!0)}),window.addEventListener("keyup",o=>{t[o.key]!==void 0&&(t[o.key]=!1)});const i=2,r=()=>{requestAnimationFrame(r),t.ArrowRight&&e.position.setX(e.position.x+i),t.ArrowLeft&&e.position.setX(e.position.x-i),t.ArrowUp&&e.position.setY(e.position.y+i),t.ArrowDown&&e.position.setY(e.position.y-i)};r()}}y.ALLOWED_FILTERS=be,y.ATTR_DOM=P,y.ATTR_FILTER=D,y.ATTR_SANDWICH=Ne,y.ATTR_SELECT=B,y.ATTR_SHADER=Re,y.ATTR_TRAVEL=A,y.DIRTY_CONTENT=ge,y.DIRTY_NONE=ie,y.DIRTY_RECT=K,y.DIRTY_STRUCTURE=fe,y.DIRTY_STYLE=Q,y.DIRTY_ZINDEX=Le,y.EXCLUDED=Ve,y.Engine=nt,y.SELECT_LAYER=Z,y.THREE_LAYERS=_,y.TRAVEL_VALUES=re,y.Tracker=De,y.USER_LAYER=H,y.extractFromStyle=Me,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})});
155
+ `,document.head.appendChild(a)}let r;if(t.mode==="duplicate"?r=(o=(i=t.container)!=null?i:this.target.parentElement)!=null?o:void 0:r=(n=this.target.parentElement)!=null?n:void 0,!r)throw new Error("[Mirage] Cannot find a container (parent or option).");this.renderer=new Je(this.target,t,r,this.registry),this.renderer.mount(),this.syncer=new et(this.target,this.renderer,this.registry,t)}start(){this.syncer.start()}stop(){this.syncer.stop()}dispose(){this.syncer.stop(),this.renderer.dispose()}getTracker(){return this.syncer.tracker}updateUniforms(e,t){this.renderer.updateUniforms(e,t)}getCanvas(){return this.renderer.canvas}test(){const e=this.registry.get(document.querySelector("#box2"));if(!e)return;const t={ArrowRight:!1,ArrowLeft:!1,ArrowUp:!1,ArrowDown:!1};window.addEventListener("keydown",o=>{t[o.key]!==void 0&&(t[o.key]=!0)}),window.addEventListener("keyup",o=>{t[o.key]!==void 0&&(t[o.key]=!1)});const r=2,i=()=>{requestAnimationFrame(i),t.ArrowRight&&e.position.setX(e.position.x+r),t.ArrowLeft&&e.position.setX(e.position.x-r),t.ArrowUp&&e.position.setY(e.position.y+r),t.ArrowDown&&e.position.setY(e.position.y-r)};i()}}b.ALLOWED_FILTERS=le,b.ATTR_DOM=N,b.ATTR_FILTER=R,b.ATTR_SANDWICH=Fe,b.ATTR_SELECT=O,b.ATTR_SHADER=me,b.ATTR_TRAVEL=L,b.DIRTY_CONTENT=ae,b.DIRTY_NONE=ie,b.DIRTY_RECT=$,b.DIRTY_STRUCTURE=se,b.DIRTY_STYLE=Q,b.DIRTY_ZINDEX=ve,b.EXCLUDED=Xe,b.Engine=rt,b.SELECT_LAYER=j,b.THREE_LAYERS=A,b.TRAVEL_VALUES=re,b.Tracker=be,b.USER_LAYER=X,b.extractFromStyle=ye,Object.defineProperty(b,Symbol.toStringTag,{value:"Module"})});
@@ -1,6 +1,4 @@
1
1
  import { StyleData } from '@mirage-engine/dom-tracker';
2
2
  import { MeshRegistry } from '../store/MeshRegistry';
3
3
 
4
- import * as THREE from "three";
5
4
  export declare function animateMeshByData(registry: MeshRegistry, data: Map<HTMLElement, StyleData>): void;
6
- export declare function updateFixedMeshesScroll(fixedMeshes: Set<THREE.Mesh>, currentScrollX: number, currentScrollY: number): void;
@@ -38,5 +38,5 @@ export declare class Renderer {
38
38
  private updateMeshLayers;
39
39
  private captureRenderTarget;
40
40
  render(): void;
41
- updateCameraScroll(scrollX: number, scrollY: number): void;
41
+ syncMeshesByDOM(): void;
42
42
  }
@@ -3,6 +3,7 @@ export declare const ATTR_DOM: {
3
3
  readonly KEY: "mirageDom";
4
4
  readonly VALUES: {
5
5
  readonly HIDE: "hide";
6
+ readonly SHOW: "show";
6
7
  };
7
8
  };
8
9
  export declare const TRAVEL_VALUES: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mirage-engine/core",
3
- "version": "0.3.3",
3
+ "version": "0.3.4",
4
4
  "main": "src/index.ts",
5
5
  "types": "src/index.ts",
6
6
  "peerDependencies": {
@@ -13,8 +13,8 @@
13
13
  },
14
14
  "dependencies": {
15
15
  "@types/three": "^0.181.0",
16
- "@mirage-engine/dom-tracker": "0.3.5",
17
- "@mirage-engine/painter": "1.0.2"
16
+ "@mirage-engine/painter": "1.0.2",
17
+ "@mirage-engine/dom-tracker": "0.3.5"
18
18
  },
19
19
  "private": false,
20
20
  "publishConfig": {
@@ -13,96 +13,12 @@ export function animateMeshByData(
13
13
  const mesh = registry.get(element);
14
14
  if (!mesh || !mesh.userData.basePosition) return;
15
15
 
16
- let { x: baseX, y: baseY } = mesh.userData.basePosition;
17
- const { width: baseW, height: baseH } = mesh.userData.baseSize;
18
-
19
- const currentW = styleData.width ?? baseW;
20
- const currentH = styleData.height ?? baseH;
21
- const widthDiff = currentW - baseW;
22
- const heightDiff = currentH - baseH;
23
-
24
- if (
25
- styleData.width !== undefined &&
26
- mesh.userData.originRatioX === undefined &&
27
- Math.abs(widthDiff) > 0.1
28
- ) {
29
- const rect = element.getBoundingClientRect();
30
- const tx = styleData.x ?? 0;
31
- const baseTx = mesh.userData.baseTransform?.x ?? 0;
32
- const scrollOffsetX = mesh.userData.isFixed ? 0 : window.scrollX;
33
- const currentPageX = rect.left + scrollOffsetX - tx + baseTx;
34
- const deltaX = currentPageX - mesh.userData.baseDOM.x;
35
-
36
- let ratioX = -deltaX / widthDiff;
37
- if (Math.abs(ratioX) < 0.05) ratioX = 0.0;
38
- else if (Math.abs(ratioX - 1.0) < 0.05) ratioX = 1.0;
39
- else if (Math.abs(ratioX - 0.5) < 0.05) ratioX = 0.5;
40
-
41
- mesh.userData.originRatioX = ratioX;
42
- }
43
-
44
- if (
45
- styleData.height !== undefined &&
46
- mesh.userData.originRatioY === undefined &&
47
- Math.abs(heightDiff) > 0.1
48
- ) {
49
- const rect = element.getBoundingClientRect();
50
- const ty = styleData.y ?? 0;
51
- const baseTy = mesh.userData.baseTransform?.y ?? 0;
52
- const scrollOffsetY = mesh.userData.isFixed ? 0 : window.scrollY;
53
- const currentPageY = rect.top + scrollOffsetY - ty + baseTy;
54
- const deltaY = currentPageY - mesh.userData.baseDOM.y;
55
-
56
- let ratioY = -deltaY / heightDiff;
57
- if (Math.abs(ratioY) < 0.05) ratioY = 0.0;
58
- else if (Math.abs(ratioY - 1.0) < 0.05) ratioY = 1.0;
59
- else if (Math.abs(ratioY - 0.5) < 0.05) ratioY = 0.5;
60
-
61
- mesh.userData.originRatioY = ratioY;
62
- }
63
-
64
- const ratioX = mesh.userData.originRatioX ?? 0.5;
65
- const ratioY = mesh.userData.originRatioY ?? 0.5;
66
-
67
- const moveX = widthDiff * (0.5 - ratioX);
68
- const moveY = heightDiff * (0.5 - ratioY);
69
-
70
- const baseTx = mesh.userData.baseTransform?.x ?? 0;
71
- const baseTy = mesh.userData.baseTransform?.y ?? 0;
72
-
73
- const deltaTx = (styleData.x ?? baseTx) - baseTx;
74
- const deltaTy = (styleData.y ?? baseTy) - baseTy;
75
-
76
- mesh.position.setX(baseX + moveX + deltaTx);
77
- mesh.position.setY(baseY - (moveY + deltaTy));
78
- mesh.scale.set(currentW, currentH, 1);
79
-
80
16
  Painter.forceUpdateUniforms(mesh.material as THREE.ShaderMaterial, {
81
17
  backgroundColor: styleData.backgroundColor,
82
18
  backgroundImage: styleData.backgroundImage,
83
19
  opacity: styleData.opacity,
84
20
  borderRadius: styleData.borderRadius ?? mesh.userData.baseStyles?.borderRadius,
85
- width: currentW,
86
- height: currentH,
21
+ // width and height are no longer updated here, they are updated in syncMeshesByDOM
87
22
  });
88
23
  });
89
24
  }
90
-
91
- export function updateFixedMeshesScroll(
92
- fixedMeshes: Set<THREE.Mesh>,
93
- currentScrollX: number,
94
- currentScrollY: number,
95
- ) {
96
- fixedMeshes.forEach((mesh) => {
97
- if (mesh.userData.isFixed && mesh.userData.initialScroll && mesh.userData.originalBasePosition) {
98
- const offsetX = currentScrollX - mesh.userData.initialScroll.x;
99
- const offsetY = currentScrollY - mesh.userData.initialScroll.y;
100
-
101
- mesh.userData.basePosition.x = mesh.userData.originalBasePosition.x + offsetX;
102
- mesh.userData.basePosition.y = mesh.userData.originalBasePosition.y - offsetY;
103
-
104
- mesh.position.x = mesh.userData.basePosition.x;
105
- mesh.position.y = mesh.userData.basePosition.y;
106
- }
107
- });
108
- }
@@ -3,7 +3,7 @@ import { Renderer } from "../renderer/Renderer";
3
3
  import { MeshRegistry } from "../store/MeshRegistry";
4
4
  import { extractSceneGraph } from "../dom/Extractor";
5
5
  import { Visibility, USER_LAYER, ATTR_TRAVEL } from "../types";
6
- import { animateMeshByData, updateFixedMeshesScroll } from "../animation/Animator";
6
+ import { animateMeshByData } from "../animation/Animator";
7
7
  import { Tracker } from "@mirage-engine/dom-tracker";
8
8
 
9
9
  export class Syncer {
@@ -52,24 +52,18 @@ export class Syncer {
52
52
  }
53
53
  });
54
54
 
55
- this.tracker.onScrollChange.add((scrollX, scrollY) => {
56
- updateFixedMeshesScroll(this.renderer.fixedMeshes, scrollX, scrollY);
57
- this.renderer.updateCameraScroll(scrollX, scrollY);
58
- });
59
-
60
55
  this.tracker.onStyleChange.add((pendingStyles) => {
61
56
  animateMeshByData(this.registry, pendingStyles);
62
57
  });
63
58
 
64
59
  this.tracker.onRender.add(() => {
60
+ this.renderer.syncMeshesByDOM();
65
61
  this.renderer.render();
66
62
  });
67
63
  }
68
64
 
69
65
  public start() {
70
66
  this.tracker.start();
71
- updateFixedMeshesScroll(this.renderer.fixedMeshes, window.scrollX, window.scrollY);
72
- this.renderer.updateCameraScroll(window.scrollX, window.scrollY);
73
67
  }
74
68
 
75
69
  public stop() {
@@ -316,6 +316,16 @@ export class Renderer {
316
316
  private reconcileNode(node: SceneNode) {
317
317
  let mesh = this.registry.get(node.element) as THREE.Mesh | undefined;
318
318
 
319
+ const currentShaderHash = JSON.stringify(node.shaderHooks || null);
320
+
321
+ if (mesh && mesh.userData.shaderHash !== currentShaderHash) {
322
+ this.scene.remove(mesh);
323
+ mesh.geometry.dispose();
324
+ if (mesh.material instanceof THREE.Material) mesh.material.dispose();
325
+ this.registry.remove(node.element);
326
+ mesh = undefined;
327
+ }
328
+
319
329
  if (!mesh) {
320
330
  const geometry = new THREE.PlaneGeometry(1, 1);
321
331
  const initialTexture = node.isTraveler
@@ -340,6 +350,8 @@ export class Renderer {
340
350
 
341
351
  this.registry.register(node.element, mesh);
342
352
  mesh.userData.baseMaterial = material;
353
+ mesh.userData.domElement = node.element;
354
+ mesh.userData.shaderHash = currentShaderHash;
343
355
  }
344
356
 
345
357
 
@@ -499,7 +511,8 @@ export class Renderer {
499
511
  mesh.scale.set(rect.width, rect.height, 1);
500
512
 
501
513
  mesh.userData.domRect = {
502
- ...rect,
514
+ x: rect.x,
515
+ y: rect.y,
503
516
  width: rect.width,
504
517
  height: rect.height,
505
518
  };
@@ -746,11 +759,72 @@ export class Renderer {
746
759
  this.renderer.render(this.scene, this.camera);
747
760
  }
748
761
 
749
- public updateCameraScroll(scrollX: number, scrollY: number) {
750
- if (this.isViewport) {
751
- this.camera.position.x = scrollX;
752
- this.camera.position.y = -scrollY;
753
- this.camera.updateMatrixWorld();
754
- }
762
+ public syncMeshesByDOM() {
763
+ // If not in viewport mode, we must account for page scroll in absolute positions.
764
+ const targetPageX = this.targetRect.left + window.scrollX;
765
+ const targetPageY = this.targetRect.top + window.scrollY;
766
+
767
+ const pixelRatio = this.renderer.getPixelRatio();
768
+ const canvasWidth = this.renderer.domElement.width / pixelRatio;
769
+ const canvasHeight = this.renderer.domElement.height / pixelRatio;
770
+
771
+ this.scene.children.forEach((child) => {
772
+ const mesh = child as THREE.Mesh;
773
+ if (!mesh.userData || !mesh.userData.domElement) return;
774
+
775
+ const element = mesh.userData.domElement as HTMLElement;
776
+ let rect: DOMRect;
777
+ if (element.nodeType === Node.TEXT_NODE) {
778
+ const range = document.createRange();
779
+ range.selectNode(element);
780
+ rect = range.getBoundingClientRect();
781
+ } else {
782
+ rect = element.getBoundingClientRect();
783
+ }
784
+ const cached = mesh.userData.domRect;
785
+
786
+ // Update if position or size changed by more than 0.5px
787
+ if (
788
+ !cached ||
789
+ Math.abs(rect.x - cached.x) > 0.5 ||
790
+ Math.abs(rect.y - cached.y) > 0.5 ||
791
+ Math.abs(rect.width - cached.width) > 0.5 ||
792
+ Math.abs(rect.height - cached.height) > 0.5
793
+ ) {
794
+ mesh.userData.domRect = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
795
+
796
+ let baseX: number, baseY: number;
797
+ if (this.isViewport) {
798
+ baseX = rect.x - window.innerWidth / 2 + rect.width / 2;
799
+ baseY = -rect.y + window.innerHeight / 2 - rect.height / 2;
800
+ } else {
801
+ const localX = rect.x - targetPageX;
802
+ const localY = rect.y - targetPageY;
803
+ baseX = localX - canvasWidth / 2 + rect.width / 2;
804
+ baseY = -localY + canvasHeight / 2 - rect.height / 2;
805
+ }
806
+
807
+ // Apply new position and scale
808
+ mesh.position.setX(baseX);
809
+ mesh.position.setY(baseY);
810
+ mesh.scale.set(rect.width, rect.height, 1);
811
+
812
+ // Update uniforms so shader-based drawing (like border-radius) doesn't stretch
813
+ if (mesh.material instanceof THREE.ShaderMaterial) {
814
+ Painter.forceUpdateUniforms(mesh.material, {
815
+ width: rect.width,
816
+ height: rect.height,
817
+ });
818
+ }
819
+
820
+ // Update native mesh if exists
821
+ if (mesh.userData.nativeMesh) {
822
+ const nativeMesh = mesh.userData.nativeMesh as THREE.Mesh;
823
+ nativeMesh.position.setX(baseX);
824
+ nativeMesh.position.setY(baseY);
825
+ nativeMesh.scale.set(rect.width, rect.height, 1);
826
+ }
827
+ }
828
+ });
755
829
  }
756
830
  }
@@ -11,6 +11,7 @@ export const ATTR_DOM = {
11
11
  KEY: "mirageDom",
12
12
  VALUES: {
13
13
  HIDE: "hide",
14
+ SHOW: "show",
14
15
  },
15
16
  } as const;
16
17