@vvfx/sdk 0.0.0-alpha.30 → 0.0.0-alpha.31

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.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var t,e=Object.create,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,n=t=>{throw TypeError(t)},c=(t,e)=>{for(var s in e)i(t,s,{get:e[s],enumerable:!0})},h=(t,e,a,n)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of r(e))o.call(t,c)||c===a||i(t,c,{get:()=>e[c],enumerable:!(n=s(e,c))||n.enumerable});return t},p=(t,e,i)=>(h(t,e,"default"),i&&h(i,e,"default")),l=(t,s,r)=>(r=null!=t?e(a(t)):{},h(!s&&t&&t.__esModule?r:i(r,"default",{value:t,enumerable:!0}),t)),m=(t,e,s)=>((t,e,s)=>e in t?i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s)(t,"symbol"!=typeof e?e+"":e,s),d=(t,e,i)=>e.has(t)||n("Cannot "+i),g=(t,e,i)=>(d(t,e,"read from private field"),i?i.call(t):e.get(t)),u=(t,e,i)=>e.has(t)?n("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),f=(t,e,i,s)=>(d(t,e,"write to private field"),s?s.call(t,i):e.set(t,i),i),y={};c(y,{SDK:()=>me,spec:()=>w.spec}),module.exports=(t=y,h(i({},"__esModule",{value:!0}),t));require("@galacean/effects");var w=require("@galacean/effects"),x=(require("@galacean/effects-plugin-rich-text"),require("@galacean/effects-plugin-rich-text")),v=(require("@galacean/effects-plugin-model"),require("@galacean/effects-plugin-multimedia"),require("@galacean/effects-plugin-multimedia")),P=(require("@galacean/effects-plugin-spine"),require("@pixi/app")),D=class{constructor(){m(this,"interactive"),m(this,"type"),m(this,"active"),this.type="null",this.active=!1,this.interactive=!1}},I=1e-6;function b(t,e,i){const s=isNaN(e)?-1/0:e,r=isNaN(i)?1/0:i,a=Math.min(s,r),o=Math.max(s,r);return Math.min(Math.max(t,a),o)}var C=Math.PI/180,E=180/Math.PI;function A(t){return Math.atan2(-t.y,-t.x)+Math.PI}function S(t,e,i=Math.round){if(Number.isInteger(t))return t;const s=Math.pow(10,e);return i(t*s)/s}function z(t,e){return Math.abs(t-e)<I||t===1/0&&e===1/0||t===-1/0&&e===-1/0}function T(t){return isNaN(t)||Math.abs(t)<I}var _=class t extends w.math.Vector2{subtract(t){return this.x-=t.x,this.y-=t.y,this}toViewCoordinate(t,e){return this.x=(this.x+1)/2*t,this.y=(1-(this.y+1)/2)*e,this}clone(){return new t(this.x,this.y)}distanceTo(t){const e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}scaleByCenter(e,i=new t){const s=(new t).subtractVectors(i,this).multiply(e);return(new t).subtractVectors(i,s)}round(t=0){const e=Math.pow(10,t);return this.x=Math.round(this.x*e)/e,this.y=Math.round(this.y*e)/e,this}},M=class t{constructor(t=new _,e=new _){m(this,"start",new _),m(this,"end",new _),this.start.copyFrom(t),this.end.copyFrom(e)}set(t,e){return this.start.copyFrom(t),this.end.copyFrom(e),this}copyFrom(t){return this.start.copyFrom(t.start),this.end.copyFrom(t.end),this}direction(){return(new _).subtractVectors(this.end,this.start).normalize()}getCenter(t=new _){return t.addVectors(this.start,this.end).multiply(.5)}delta(t=new _){return t.subtractVectors(this.end,this.start)}distanceSq(){return this.start.distanceSquared(this.end)}distance(){return this.start.distance(this.end)}at(t,e=new _){return this.delta(e).multiply(t).add(this.start)}closestPointToPointParameter(t,e){const i=new _,s=new _;i.subtractVectors(t,this.start),s.subtractVectors(this.end,this.start);const r=s.dot(s);let a=s.dot(i)/r;return e&&(a=b(a,0,1)),a}closestPointToPoint(t,e,i=new _){const s=this.closestPointToPointParameter(t,e);return this.delta(i).multiply(s).add(this.start)}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return(new t).copyFrom(this)}length(){return(new _).subtractVectors(this.end,this.start).length()}crossWithLine(t){const e=this.delta(),i=t.delta(),s=(new _).subtractVectors(t.start,this.start),r=(new _).subtractVectors(t.end,this.start),a=(new _).subtractVectors(this.start,t.start),o=(new _).subtractVectors(this.end,t.start),n=s.cross(e),c=r.cross(e),h=a.cross(i),p=o.cross(i);return n*c<0&&h*p<0}},V=class t{constructor(t=new _(1/0,1/0),e=new _(-1/0,-1/0)){m(this,"corners",[]),m(this,"min",new _(1/0,1/0)),m(this,"max",new _(-1/0,-1/0)),this.min=t.clone(),this.max=e.clone(),this.isEmpty()?this.corners=[]:this.corners=[t.clone(),new _(e.x,t.y),e.clone(),new _(t.x,e.y)]}set(t,e){return this.min.copyFrom(t),this.max.copyFrom(e),this.corners=[t.clone(),new _(e.x,t.y),e.clone(),new _(t.x,e.y)],this}setFromVec2Array(t){return this.min=(new _).copyFrom(t[0]),this.max=(new _).copyFrom(t[0]),t.forEach(t=>{this.min.min(t),this.max.max(t),this.corners.push(t.clone())}),this}setFromVec2ArrayWithOutCorners(t){return this.min=(new _).copyFrom(t[0]),this.max=(new _).copyFrom(t[0]),t.forEach(t=>{this.min=this.min.min(t),this.max=this.max.max(t)}),this.corners.push(new _(this.min.x,this.min.y)),this.corners.push(new _(this.min.x,this.max.y)),this.corners.push(new _(this.max.x,this.max.y)),this.corners.push(new _(this.max.x,this.min.y)),this}setFromCenterAndSize(t,e){const i=(new _).copyFrom(e).multiply(.5);return this.min.copyFrom(t).subtract(i),this.max.copyFrom(t).add(i),this.corners=[this.min.clone(),new _(this.max.x,this.min.y),this.max.clone(),new _(this.min.x,this.max.y)],this}clone(){return(new t).copyFrom(this)}copyFrom(t){return this.corners=[],this.min.copyFrom(t.min),this.max.copyFrom(t.max),t.corners.forEach(t=>{this.corners.push(t.clone())}),this}makeEmpty(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this.corners=[],this}isEmpty(){return this.max.x<=this.min.x||this.max.y<=this.min.y}getCorners(){const t=[];return this.corners.forEach(e=>{t.push(e.clone())}),t}getCenter(t=new _){return this.isEmpty()?t.set(0,0):t.addVectors(this.min,this.max).multiply(.5)}getSize(t=new _){return this.isEmpty()?t.set(0,0):t.subtractVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.subtract(t),this.max.add(t),this}expandByScalar(t){return this.min.add(-t),this.max.add(t),this}containsPoint(t,e=!0){if(e)return!(t.x<this.min.x||t.x>this.max.x||t.y<this.min.y||t.y>this.max.y);if(this.isEmpty())return!1;for(let e=0;e<this.corners.length;e++){const i=this.corners[e],s=this.corners[(e+1)%4],r=new _(s.x-i.x,s.y-i.y),a=new _(t.x-i.x,t.y-i.y);if(r.cross(a)<0)return!1}return!0}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y}getParameter(t,e=new _){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))}clampPoint(t,e=new _){return e.copyFrom(t).clamp(this.min,this.max)}distanceToPoint(t){return(new _).copyFrom(t).clamp(this.min,this.max).subtract(t).length()}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.min.x>this.max.x||this.min.y>this.max.y?this.makeEmpty():this}union(t){return this.min.min(t.min),this.max.max(t.max),this.corners=[this.min.clone(),new _(this.max.x,this.min.y),this.max.clone(),new _(this.min.x,this.max.y)],this}translate(t){return this.min.add(t),this.max.add(t),this.corners.forEach(e=>{e.add(t)}),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}intersectsBox(t,e=!0){if(e)return!(t.max.x<this.min.x||t.min.x>this.max.x||t.max.y<this.min.y||t.min.y>this.max.y);if(!this.isEmpty())for(let e=0;e<this.corners.length;e++){const i=new M(this.corners[e],this.corners[(e+1)%4]);if(t.containsPoint(this.corners[e],!1))return!0;for(let e=0;e<t.corners.length;e++){const s=new M(t.corners[e],t.corners[(e+1)%4]);if(this.containsPoint(t.corners[e],!1))return!0;if(i.crossWithLine(s))return!0}}for(let e=0;e<t.corners.length;e++){const i=this.containsPoint(t.corners[e],!1),s=t.containsPoint(this.corners[e],!1);if(i||s)return!0}return!1}},k=class t{constructor(t=new _,e=0){m(this,"center"),m(this,"radius"),this.center=t.clone(),this.radius=e}set(t,e){return this.center=(new _).copyFrom(t),this.radius=e,this}clone(){return(new t).copy(this)}copy(t){return this.center.copyFrom(t.center),this.radius=t.radius,this}makeEmpty(){return this.center=new _,this.radius=0,this}isEmpty(){return 0===this.radius}getCenter(t=new _){return t.copyFrom(this.center),t}getRadius(){return this.radius}expandByPoint(t){return this.radius=this.center.distanceTo(t),this}expandByScalar(t){return this.radius+=t,this}containsPoint(t){return this.center.distanceTo(t)<this.radius}containsBox(t){for(let e=0;e<4;e++)if(!this.containsPoint(t.corners[e]))return!1;return!0}intersectsBox(t){for(let e=0;e<4;e++)if(this.containsPoint(t.corners[e]))return!0;return!1}distanceToPoint(t){return this.center.distanceTo(t)-this.radius}},B=class extends w.math.Quaternion{},F=class t extends w.math.Vector3{clone(){return new t(this.x,this.y,this.z)}setFromMatrixColumn(t,e){return this.set(...t.elements.slice(4*e))}applyEuler(t,e){return this.applyQuaternion((new B).setFromEuler(t))}applyQuaternion(e,i=new t){const{x:s,y:r,z:a,w:o}=e,{x:n,y:c,z:h}=this.subtract(i),p=o*n+r*h-a*c,l=o*c+a*n-s*h,m=o*h+s*c-r*n,d=-s*n-r*c-a*h;return this.x=p*o+d*-s+l*-a-m*-r+i.x,this.y=l*o+d*-r+m*-s-p*-a+i.y,this.z=m*o+d*-a+p*-r-l*-s+i.z,this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}applyMatrix(e,i=new t){const s=e.elements,{x:r,y:a,z:o}=this.subtract(i);let n=1/(s[3]*r+s[7]*a+s[11]*o+s[15]);return n=isNaN(n)?1:n,this.x=(s[0]*r+s[4]*a+s[8]*o+s[12])*n+i.x,this.y=(s[1]*r+s[5]*a+s[9]*o+s[13])*n+i.y,this.z=(s[2]*r+s[6]*a+s[10]*o+s[14])*n+i.z,this}},U=class t extends w.math.Matrix4{static fromArray(e,i=0){return(new t).setFromArray(e,i)}clone(){const e=this.elements;return new t(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}compose(t,e,i,s=F.ZERO){const r=this.elements,{x:a,y:o,z:n,w:c}=e,h=-s.x,p=-s.y,l=-s.z,m=a+a,d=o+o,g=n+n,u=a*m,f=a*d,y=a*g,w=o*d,x=o*g,v=n*g,P=c*m,D=c*d,I=c*g,{x:b,y:C,z:E}=i;return r[0]=(1-(w+v))*b,r[1]=(f+I)*b,r[2]=(y-D)*b,r[3]=0,r[4]=(f-I)*C,r[5]=(1-(u+v))*C,r[6]=(x+P)*C,r[7]=0,r[8]=(y+D)*E,r[9]=(x-P)*E,r[10]=(1-(u+w))*E,r[11]=0,r[12]=h*r[0]+p*r[4]+l*r[8]-h+t.x,r[13]=h*r[1]+p*r[5]+l*r[9]-p+t.y,r[14]=h*r[2]+p*r[6]+l*r[10]-l+t.z,this}extractRotation(t){const e=new F,i=t.elements,s=this.elements,r=1/e.setFromMatrixColumn(t,0).length(),a=1/e.setFromMatrixColumn(t,1).length(),o=1/e.setFromMatrixColumn(t,2).length();return s[0]=i[0]*r,s[1]=i[1]*r,s[2]=i[2]*r,s[3]=0,s[4]=i[4]*a,s[5]=i[5]*a,s[6]=i[6]*a,s[7]=0,s[8]=i[8]*o,s[9]=i[9]*o,s[10]=i[10]*o,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,r=t.z,a=Math.cos(i),o=Math.sin(i),n=Math.cos(s),c=Math.sin(s),h=Math.cos(r),p=Math.sin(r);if(t.order===w.math.EulerOrder.XYZ){const t=a*h,i=a*p,s=o*h,r=o*p;e[0]=n*h,e[4]=-n*p,e[8]=c,e[1]=i+s*c,e[5]=t-r*c,e[9]=-o*n,e[2]=r-t*c,e[6]=s+i*c,e[10]=a*n}else if(t.order===w.math.EulerOrder.YXZ){const t=n*h,i=n*p,s=c*h,r=c*p;e[0]=t+r*o,e[4]=s*o-i,e[8]=a*c,e[1]=a*p,e[5]=a*h,e[9]=-o,e[2]=i*o-s,e[6]=r+t*o,e[10]=a*n}else if(t.order===w.math.EulerOrder.ZXY){const t=n*h,i=n*p,s=c*h,r=c*p;e[0]=t-r*o,e[4]=-a*p,e[8]=s+i*o,e[1]=i+s*o,e[5]=a*h,e[9]=r-t*o,e[2]=-a*c,e[6]=o,e[10]=a*n}else if(t.order===w.math.EulerOrder.ZYX){const t=a*h,i=a*p,s=o*h,r=o*p;e[0]=n*h,e[4]=s*c-i,e[8]=t*c+r,e[1]=n*p,e[5]=r*c+t,e[9]=i*c-s,e[2]=-c,e[6]=o*n,e[10]=a*n}else if(t.order===w.math.EulerOrder.YZX){const t=a*n,i=a*c,s=o*n,r=o*c;e[0]=n*h,e[4]=r-t*p,e[8]=s*p+i,e[1]=p,e[5]=a*h,e[9]=-o*h,e[2]=-c*h,e[6]=i*p+s,e[10]=t-r*p}else if(t.order===w.math.EulerOrder.XZY){const t=a*n,i=a*c,s=o*n,r=o*c;e[0]=n*h,e[4]=-p,e[8]=c*h,e[1]=t*p+r,e[5]=a*h,e[9]=i*p-s,e[2]=s*p-i,e[6]=o*h,e[10]=r*p+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}setPosition(t){return this.elements[12]=t.x,this.elements[13]=t.y,this.elements[14]=t.z,this}},R=class extends w.math.Euler{constructor(t=0,e=0,i=0,s=w.math.EulerOrder.XYZ){super(t,e,i,s)}getInvertMatrixByEuler(){return(new U).makeRotationFromEuler(this).invert()}toDegreeVector3(t){return t?t.set(this.x*E,this.y*E,this.z*E):new F(this.x*E,this.y*E,this.z*E)}setFromDegreeVector3(t,e){return this.set(t.x*C,t.y*C,t.z*C,e??this.order)}},W=class t{constructor(t=0,e=new F(0,0,1)){m(this,"distance"),m(this,"normal");const i=e.length();0===i&&(this.normal=new F(0,0,1)),this.distance=t/(i??1),this.normal=e.normalize()}static set(e,i){return new t(e,i)}set(t,e){const i=e.length();return 0===i&&(this.normal=new F(0,0,1)),this.distance=t/i,this.normal=e.normalize(),this}static copy(e){return new t(e.distance,e.normal.clone())}copy(t){return this.distance=t.distance,this.normal.copyFrom(t.normal),this}static setFromNormalAndCoplanarPoint(e,i){const s=-e.dot(i);return new t(s,i)}setFromNormalAndCoplanarPoint(t,e){return this.normal.copyFrom(e),this.distance=-t.dot(this.normal),this}clone(){return new t(this.distance,this.normal.clone())}distanceToPoint(t){return this.normal.dot(t)+this.distance}},G=class t extends w.math.Ray{constructor(t=new F,e=new F(1,0,0)){super(t,e),m(this,"origin"),m(this,"direction"),this.origin=t.clone(),this.direction=e.clone()}clone(){return new t(this.origin,this.direction)}rayCastPlane(t,e){const i=this.distanceToPlane(t);return isNaN(i)||this.at(i),i}at(t){return this.direction.clone().normalize().multiply(t).add(this.origin)}distanceToPlane(t){const e=t.normal.dot(this.direction);if(T(e))return T(t.distanceToPoint(this.origin))?0:NaN;const i=(-this.origin.dot(t.normal)-t.distance)/e;return i>0?i:NaN}},H=class{constructor(t=new G){m(this,"ray"),this.ray=t.clone()}setFromCamera(t,e){const i=e.position,s=new F(t.x,t.y,.5).applyMatrix(e.inverseViewProjectMatrix).subtract(i).normalize();return this.ray.set(i,s),this}rayCastPlane(t){const e=new F,i=this.ray.rayCastPlane(t,e);if(!isNaN(i))return{distance:i,point:this.ray.at(i)}}},N=class extends D{constructor(t){super(),m(this,"defaultInteractive",!0),m(this,"interactive",!0),m(this,"lastPoint",new _),m(this,"SDKUtils"),this.SDKUtils=t,this.type="control"}initialize(){}preparationAction(){}cancelPreparation(){}refreshResults(){}preAction(){}action(t){if(!me.config.gestureHandlerConfig.controlGizmoEnabled)return void console.warn("Control gizmo is not opened, use #SDK.setControlConfig() open this feature.");const{metaKey:e,ctrlKey:i,shiftKey:s}=t;if(0===t.buttons){const{deltaX:r,deltaY:a}=t,o=new _(r,a);e||i?(o.y=b(o.y,-10,10),this.dolly(o.y)):(o.x=s&&0!==o.y?Math.sqrt(o.x**2+o.y**2)*o.y/Math.abs(o.y):o.x,o.y=s?0:o.y,this.pan(o.multiply(-1)))}}endAction(){}interruption(){return this.type}actionKey(){}endActionKey(){}dolly(t){const e=-t*me.config.gestureHandlerConfig.controlGizmoConfig.zoomStep;this.SDKUtils.pageZoom(e)}pan(t){this.SDKUtils.pageMove(t)}getRenderObjects(){return[]}},L=require("@pixi/graphics"),K=class extends D{constructor(t){super(),m(this,"interactive",!0),m(this,"result",{type:"null",box:new V}),m(this,"selectedItemIds",[]),m(this,"cursorPoint",new _),m(this,"startPoint",new _),m(this,"graphics",new L.Graphics),m(this,"pageDataUtils"),m(this,"clearResult",!1),m(this,"type"),this.pageDataUtils=t,this.type="selector"}initialize(){}actionKey(){}endActionKey(){}getRenderObjects(){return me.config.gestureHandlerConfig.selectorGizmoEnabled?this.clearResult?(this.result={type:"null",box:new V},this.clearResult=!1,[]):(this.refreshResults(),[this.graphics]):[]}cancelPreparation(){this.result.type="null",this.pageDataUtils.clearPreSelectedItem()}preparationAction(t){if(this.result.box=new V,!me.config.gestureHandlerConfig.selectorGizmoEnabled)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const e=new _(t.offsetX,t.offsetY);this.selectedItemIds=this.hitTest(e);const i=this.selectedItemIds[0]??"";return i.length&&!this.pageDataUtils.isItemSelected(i)?this.pageDataUtils.addPreSelectedItem(i):this.pageDataUtils.clearPreSelectedItem(),this.type}preAction(t){if(this.pageDataUtils.clearPreSelectedItem(),1===t.buttons)return t.shiftKey||this.pageDataUtils.clearSelectedItems(),0===this.selectedItemIds.length?(this.startPoint=new _(t.clientX,t.clientY),this.cursorPoint=new _(t.offsetX,t.offsetY),this.active=!0,this.type):(this.pageDataUtils.addSelectedItems([this.selectedItemIds[0]]),this.clearResult=!0,"transform")}action(t){const e=(new _).addVectors(this.cursorPoint,(new _).subtractVectors(new _(t.clientX,t.clientY),this.startPoint)),i=(new _).subtractVectors(this.cursorPoint,e),s=(new _).addVectors(this.cursorPoint,e).multiply(.5);i.x=Math.abs(i.x),i.y=Math.abs(i.y);const r=(new V).setFromCenterAndSize(s,i);this.result.type="region",this.result.box=r,this.pageDataUtils.clearSelectedItems();const a=this.pageDataUtils.getPageData().items?.filter(t=>this.pageDataUtils.getItemEditEnable(t.id)),o=[];a?.forEach(t=>{r.intersectsBox(this.pageDataUtils.getViewBoxById(t.id),!1)&&o.push(t.id)}),this.pageDataUtils.addSelectedItems(o)}endAction(){this.active=!1,this.result.type="null"}interruption(){this.active=!1,this.result.type="null"}hitTest(t){const e=this.pageDataUtils.getCurrentComposition();if(!e?.items)return[];const{x:i,y:s}=this.pageDataUtils.getViewportByViewPoint(t),r={ray:new G,regions:[]};try{r.regions=e.hitTest(i,s,!0),r.ray=e.getHitTestRay(i,s)}catch(t){console.warn(t)}return this.reorderHitTestResult(r,e).filter(t=>"extra-camera"!==t&&this.pageDataUtils.getItemEditEnable(t))}reorderHitTestResult(t,e){if(0===t.regions.length||!e)return[];const{ray:i}=t,s=t.regions.reverse(),r=[];return s.forEach(t=>{let s;const a=(t,e)=>{for(const i of t){if(i.getInstanceId()===e&&(s=i),s)return;a(i.children,e)}};if(a(e.items,t.id),void 0===s)return;const o="rootItem"===t.compContent?.name?s.getInstanceId():t.compContent.getInstanceId(),n=i.origin.clone().distance(t.position.clone());if((s.type===w.spec.ItemType.mesh||s.getComponent(w.SpriteComponent)?.renderer?.occlusion||s.getComponent(w.TextComponent)?.renderer?.occlusion||s.getComponent(v.VideoComponent)?.renderer?.occlusion||s.getComponent(x.RichTextComponent)?.renderer?.occlusion)&&r.length>0){let t=!0;r.forEach((e,i)=>{if(t)return n<=e[1]?(r.splice(i,0,[o,n]),void(t=!1)):void(i===r.length-1&&r.push([o,n]))})}else r.push([o,n])}),r.map(t=>t[0])}refreshResults(){const{box:t}=this.result;this.graphics.clear();const e=this.pageDataUtils.getPreSelectedItem(),i=this.pageDataUtils.getViewBoxById(e?.id??""),{regionBoxColor:s,regionBoxAlpha:r,preSelectedWidth:a,preSelectedColor:o,regionWireframeWidth:n,regionWireframeColor:c,regionWireframeAlpha:h}=me.config.gestureHandlerConfig.selectorGizmoConfig;if(i?.isEmpty()||(this.graphics.lineStyle(a,o),this.graphics.drawBox(i)),!t.isEmpty()&&"region"===this.result.type)this.graphics.lineStyle(n,c,h),this.graphics.drawBox(t),this.graphics.beginFill(s,r),this.graphics.fillBox(t),this.graphics.endFill()}},O=require("@pixi/graphics"),j=require("@galacean/effects"),$=class extends D{constructor(t,e){super(),m(this,"type"),m(this,"interactive",!0),m(this,"wireframe"),m(this,"cursorResult",{type:"normal",angle:0}),m(this,"cursorPoint",new _),m(this,"lastPoint",new _),m(this,"rotationAngle",0),m(this,"active",!1),m(this,"enableAdsorption",!0),m(this,"scaleParam"),m(this,"activeType","null"),m(this,"lastWorldPosition",new F),m(this,"pageDataUtils"),m(this,"adsorptionGizmo"),m(this,"graphics",new O.Graphics),this.type="transform",this.pageDataUtils=t,this.adsorptionGizmo=e,this.wireframe={edges:[],anchor:new _,scaleCorners:[],rotationCorners:[],interactive:!0,cornerEnable:!0,directionEnable:!0,box:new V,totalBox:new V,childrenBoxes:[],activeType:"null",interactiveDirection:new _,scaleCorner:new _,scaleEdgeCorners:[]}}initialize(){}actionKey(){}endActionKey(){}getRenderObjects(){return me.config.gestureHandlerConfig.transformGizmoEnabled?(this.refreshRenderObject(),[this.graphics]):[]}cancelPreparation(){this.active=!1,this.wireframe.activeType="null"}preAction(t,e=!1){if(this.active=1===t.buttons,this.lastPoint=new _(t.clientX,t.clientY),this.cursorPoint=new _(t.offsetX,t.offsetY),1!==t.buttons)return;this.active=!0,"null"===this.wireframe.activeType&&(this.wireframe.activeType="translation");const i=this.cursorPoint.clone().subtract(this.pageDataUtils.getViewportLeftTopPosition());return this.initInteractionPlane(i),this.lastWorldPosition=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(i)??new F,this.activeType=e?"null":this.activeType,this.type}preparationAction(t){if(!me.config.gestureHandlerConfig.transformGizmoEnabled)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const e=new _(t.offsetX,t.offsetY),i=this.wireframe;this.refreshTransformType(e);const{interactiveDirection:s}=i;return this.refreshCursorResult(this.activeType,A(s)),this.active="null"!==this.activeType,this.active?this.type:void 0}action(t){if(!me.config.gestureHandlerConfig.transformGizmoEnabled)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");if(!this.active){this.active=!0,this.refreshWireframeBySelectedItems(),this.wireframe.activeType="translation",this.lastPoint.set(t.clientX,t.clientY),this.cursorPoint.set(t.offsetX,t.offsetY);const e=this.cursorPoint.clone().subtract(this.pageDataUtils.getViewportLeftTopPosition());this.initInteractionPlane(e),this.lastWorldPosition=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(e)??new F}const e=new _(t.clientX,t.clientY),i=(new _).subtractVectors(e,this.lastPoint);if(!this.wireframe.interactive)return;const s=this.pageDataUtils.getSelectedItems(),{anchor:r,activeType:a,interactiveDirection:o}=this.wireframe,n=this.pageDataUtils.getPageData();(0,j.assertExist)(n);let c=0;switch(a){case"rotation":{const t=r.clone(),e=new F,a=S(function(t,e){const i=Math.min(Math.max(t.dot(e)/t.length()/e.length(),-1),1);let s=Math.acos(i);return s=t.x*e.y-t.y*e.x>0?s:-s,s}((new _).subtractVectors(this.cursorPoint,t),(new _).subtractVectors(this.cursorPoint.add(i),t))*E,3);e.z=a,this.rotationAngle+=a,c=A(o)+this.rotationAngle*C,s.forEach(t=>{this.pageDataUtils.rotateItem(t.id,e)});break}case"translation":{const t=i.clone();if(this.enableAdsorption){const e=n.items.map(t=>!s.find(e=>e.id===t.id)&&0===s.filter(e=>t.parentId&&t.parentId===e.id).length&&this.pageDataUtils.getItemEditEnable(t.id)?this.pageDataUtils.getViewBoxById(t.id):new V).filter(t=>!t.isEmpty()),i=new _(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);this.adsorptionGizmo.boxTranslationAdsorption(t,this.wireframe.box,e);const r=new _(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);t.add(i).subtract(r)}const e=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint.add(t).clone().subtract(this.pageDataUtils.getViewportLeftTopPosition()));if(e){const t=e.clone().subtract(this.lastWorldPosition);s.forEach(e=>{e.type!==w.spec.ItemType.camera&&this.pageDataUtils.moveItem(e.id,t)}),this.lastWorldPosition.copyFrom(e)}break}case"scale":{this.cursorPoint.add(i);const t=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint.clone().subtract(this.pageDataUtils.getViewportLeftTopPosition()));if(i.length()&&t&&this.scaleParam){const{corner:e,center:i,shift:r,lastScalar:a}=this.scaleParam,o=this.pageDataUtils.getSelectedItems()[0]??void 0,n=this.pageDataUtils.getItemTransformById(o?.id??""),c=(new U).extractRotation(n.matrix).invert(),h=(new F).subtractVectors(e,i).applyMatrix(c),p=h.clone().multiply(a),l=t.subtract(r).subtract(i).applyMatrix(c),m=new F(1,1,1),d=function(t){let e,i=0;return t.forEach((t,s)=>{if(0===s)e=Math.abs(t);else{const r=Math.abs(t);e<r&&(e=r,i=s)}}),i}([z(h.x,0)?1:Math.abs(l.x/h.x),z(h.y,0)?1:Math.abs(l.y/h.y)]),g=l.toArray()[d],u=p.toArray()[d];if(z(a.x,a.y)&&z(a.z,a.x)){const t=z(u,0)?1:Math.abs(g/u);m.set(t,t,t)}else if(0===d){m.x=z(u,0)?1:Math.abs(g/u);const t=h.y*g/h.x;m.y=z(p.y,0)?1:t/p.y;const e=h.z*g/h.x;m.z=z(p.z,0)?1:e/p.z}else if(1===d){m.y=z(u,0)?1:Math.abs(g/u);const t=h.x*g/h.y;m.x=z(p.x,0)?1:t/p.x;const e=h.z*g/h.y;m.z=z(p.z,0)?1:e/p.z}else{m.z=z(u,0)?1:Math.abs(g/u);const t=h.x*g/h.z;m.x=z(p.x,0)?1:t/p.x;const e=h.y*g/h.z;m.y=z(p.y,0)?1:e/p.y}this.scaleParam.lastScalar.multiply(m),s.forEach(t=>{this.pageDataUtils.scaleItem(t.id,m)})}c=A(o);break}}this.refreshCursorResult(a,c),this.lastPoint.copyFrom(e)}endAction(t){this.active=!1;const e=new _(t.clientX,t.clientY),i=(new _).subtractVectors(e,this.lastPoint);this.cursorPoint.add(i);const s=this.wireframe;this.refreshTransformType(this.cursorPoint);const{activeType:r,interactiveDirection:a}=s;this.refreshCursorResult(r,A(a)),this.adsorptionGizmo.clearAbsorptionResult(),this.rotationAngle=0,this.cursorPoint=new _,this.lastPoint=new _}interruption(){this.active=!1,this.cursorResult.type="normal",this.adsorptionGizmo.clearAbsorptionResult()}refreshCursorResult(t,e=0){switch(t){case"scale":this.cursorResult={type:"scale",angle:(e+Math.PI/4)*E};break;case"rotation":this.cursorResult={type:"rotation",angle:(e+Math.PI/4)*E};break;case"translation":case"null":this.cursorResult={type:"normal",angle:0}}}refreshResults(){const t=this.wireframe.activeType;this.refreshWireframeBySelectedItems(),t!==this.wireframe.activeType&&this.refreshCursorResult(this.wireframe.activeType),this.wireframe.box.isEmpty()&&this.adsorptionGizmo.clearAbsorptionResult()}initInteractionPlane(t){const e=this.pageDataUtils.getSelectedItems();switch(this.wireframe.activeType){case"scale":{const i=1==e.length?e[0]:void 0;let s,r,a;if(i){const t=this.pageDataUtils.getItemTransformById(i.id);s=(new F).copyFrom(this.pageDataUtils.getPlayerItemById(i.id).transform.anchor).applyMatrix(t.matrix),r=(new F).setFromMatrixPosition(t.matrix),a=(new R).setFromQuaternion((new B).setFromRotationMatrix(t.matrix))}this.pageDataUtils.interactionUtils.initInteractionPlane(r,a),this.scaleParam={shift:new F,center:new F,corner:new F,lastScalar:new F(1,1,1)},this.scaleParam.center=s??r;const o=this.pageDataUtils.getViewportLeftTopPosition();if(["scale"].includes(this.wireframe.activeType)&&this.wireframe.scaleCorner){const t=this.wireframe.scaleCorner.clone().subtract(o);this.scaleParam.corner=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(t)??new F}this.scaleParam.shift=(this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(t)??new F).subtract(this.scaleParam.corner);break}case"translation":case"rotation":this.pageDataUtils.interactionUtils.initInteractionPlane()}}refreshRenderObject(){this.graphics.clear();const{wireframeAlpha:t,wireframeColor:e,wireframeWidth:i,cornerFillColor:s,cornerLineWidth:r,cornerLineColor:a,cornerLineAlpha:o}=me.config.gestureHandlerConfig.transformGizmoConfig;if(!this.wireframe.box.isEmpty()){this.graphics.lineStyle(i,e,t),this.wireframe.edges.forEach(t=>{this.graphics.drawLine(t)});const n=t=>{t.corners.forEach((e,i)=>{const s=new M(e,t.corners[(i+1)%4]);this.graphics.drawLine(s)})};this.wireframe.childrenBoxes.forEach(t=>{n(t)}),this.wireframe.cornerEnable&&(this.graphics.beginFill(s),this.graphics.lineStyle(r,a,o),this.wireframe.scaleCorners.forEach(t=>{this.graphics.drawCircle(t.center.x,t.center.y,t.radius)}),this.graphics.endFill())}}refreshTransformType(t){this.activeType="null";let e=!0;if(this.wireframe.interactiveDirection=new _,this.wireframe.scaleCorner=void 0,this.wireframe.scaleEdgeCorners=void 0,this.wireframe.cornerEnable&&e&&this.wireframe.totalBox.containsPoint(t)){for(let i=0;i<4;i++){if(this.wireframe.scaleCorners[i].containsPoint(t)){e=!1,this.activeType="scale",this.wireframe.activeType="scale",this.wireframe.scaleCorner=this.wireframe.scaleCorners[i].center.clone(),this.wireframe.interactiveDirection.copyFrom(this.wireframe.scaleCorners[i].center).subtract(this.wireframe.box.getCenter());break}}e&&this.wireframe.box.containsPoint(t,!1)&&(e=!1,this.activeType="translation",this.wireframe.activeType="translation");for(let i=0;i<4;i++){if(this.wireframe.rotationCorners[i].containsPoint(t)&&e){e=!1,this.activeType="rotation",this.wireframe.activeType="rotation",this.wireframe.interactiveDirection.copyFrom(this.wireframe.rotationCorners[i].center).subtract(this.wireframe.box.getCenter());break}}}}refreshWireframeBySelectedItems(){const t=this.pageDataUtils.getSelectedItems(),e=new V;if(this.wireframe.edges=[],this.wireframe.scaleCorners=[],this.wireframe.childrenBoxes=[],this.wireframe.rotationCorners=[],t.length>1)t.forEach(t=>{if(this.pageDataUtils.getItemShow(t.id)){const i=this.pageDataUtils.getViewBoxById(t.id);e.union(i),this.wireframe.childrenBoxes.push((new V).copyFrom(i).expandByScalar(1))}}),this.wireframe.anchor=e.getCenter(),this.wireframe.interactive=!0;else if(1===t.length){const i=t[0];if(this.pageDataUtils.getItemShow(i.id)){const t=this.pageDataUtils.getViewBoxById(i.id);e.copyFrom(t),this.wireframe.anchor=this.pageDataUtils.getItemViewAnchor(i.id)??e.getCenter(),this.wireframe.interactive=i.type!==w.spec.ItemType.mesh&&this.pageDataUtils.getItemEditEnable(i.id)}}const i=e.isEmpty(),s=i?0:1,r=i?0:16;this.wireframe.activeType=t.length?this.wireframe.activeType:"null",this.wireframe.box.copyFrom(e).expandByScalar(s),this.wireframe.totalBox.copyFrom(e).expandByScalar(r);const a=this.wireframe.box.corners;a.forEach((t,e)=>{this.wireframe.edges.push(new M((new _).copyFrom(t),(new _).copyFrom(a[(e+1)%4])))});const{scaleCircleSize:o,rotationCircleSize:n}=me.config.gestureHandlerConfig.transformGizmoConfig;this.wireframe.box.corners.forEach(t=>{this.wireframe.scaleCorners.push(new k(t,o));const e=(new _).subtractVectors(t,this.wireframe.box.getCenter()),i=(new _).copyFrom(this.wireframe.box.getCenter()).add((new _).copyFrom(e).normalize().multiply(e.length()+n-o));this.wireframe.rotationCorners.push(new k(i,n))})}setAdsorptionEnabled(t){this.enableAdsorption=t}},Y=require("@pixi/graphics"),q=class extends D{constructor(){super(),m(this,"interactive",!1),m(this,"results",[]),m(this,"graphics",new Y.Graphics),m(this,"absorptionResult",{}),this.type="adsorption"}initialize(){}preparationAction(){}getCursorState(){}preAction(){}action(){}cancelPreparation(){}actionKey(){}endActionKey(){}endAction(){}interruption(){}boxTranslationAdsorption(t,e,i,s=!0,r=!0){if(this.results=[],!me.config.gestureHandlerConfig.adsorptionGizmoEnabled)return void console.warn("Adsorption gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");if(e.isEmpty())return;const a=new _(this.absorptionResult?.x??0,this.absorptionResult?.y??0).add(t),o=e.clone().translate(a),n=o.getCenter();this.absorptionResult={},i.forEach(t=>{if(t.isEmpty())return;t.corners.forEach(t=>{o.corners.forEach(e=>{this.getPointAbsorption(e,t,s,r)}),this.getPointAbsorption(n,t,s,r)});const e=t.getCenter();this.getPointAbsorption(n,e,s,r),o.corners.forEach(t=>{this.getPointAbsorption(t,e,s,r)})})}pointTranslationAdsorption(t,e,i,s=!0,r=!0){if(this.results=[],!me.config.gestureHandlerConfig.adsorptionGizmoEnabled)return void console.warn("Adsorption is not opened, use #SDK.setAdsorptionConfig() open this feature.");const a=new _(this.absorptionResult?.x??0,this.absorptionResult?.y??0).add(t),o=e.clone().add(a);this.absorptionResult={},i.forEach(t=>{this.getPointAbsorption(o,t,s,r)})}getPointAbsorption(t,e,i=!0,s=!0){i&&Math.abs(t.x-e.x)<me.config.gestureHandlerConfig.adsorptionGizmoConfig.distance&&this.refreshPointAbsorptionResult(t,e,"x"),s&&Math.abs(t.y-e.y)<me.config.gestureHandlerConfig.adsorptionGizmoConfig.distance&&this.refreshPointAbsorptionResult(t,e,"y")}refreshPointAbsorptionResult(t,e,i){const s=t[i]-e[i],r="x"===i?"xPoints":"yPoints";if(this.absorptionResult&&void 0===this.absorptionResult[i])this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}];else if(Math.abs(s)-Math.abs(this.absorptionResult[i]??0)<=.005)if(Math.abs(Math.abs(s)-Math.abs(this.absorptionResult[i]??0))<.05&&s*(this.absorptionResult[i]??0)>0)if(void 0===this.absorptionResult[r])this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}];else{const i=this.absorptionResult[r].filter(e=>e.point.equals(t));void 0===i||0===i.length?this.absorptionResult[r]?.push({point:t,targets:[e]}):i[0]?.targets.push(e)}else this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}]}refreshResults(){if(void 0===this.absorptionResult)return;const{x:t,y:e,xPoints:i,yPoints:s}=this.absorptionResult,r=new _(t??0,e??0);void 0!==t&&void 0!==i&&i.forEach(t=>{const e=t.point.clone().subtract(r),i=e.clone(),s=e.clone();t.targets.forEach(t=>{i.x=t.x,i.y=Math.min(i.y,t.y),s.x=t.x,s.y=Math.max(s.y,t.y)}),this.results.push(new M(i,s))}),void 0!==e&&void 0!==s&&s.forEach(t=>{const e=t.point.clone().subtract(r),i=e.clone(),s=e.clone();t.targets.forEach(t=>{i.y=t.y,i.x=Math.min(i.x,t.x),s.y=t.y,s.x=Math.max(s.x,t.x)}),this.results.push(new M(i,s))})}refreshRenderObject(){this.graphics.clear();const{lineWidth:t,lineColor:e}=me.config.gestureHandlerConfig.adsorptionGizmoConfig;this.results.forEach(i=>{this.graphics.lineStyle(t,e),this.graphics.drawLine(i)})}getRenderObjects(){return me.config.gestureHandlerConfig.adsorptionGizmoEnabled?(this.refreshResults(),this.refreshRenderObject(),[this.graphics]):[]}clearAbsorptionResult(){this.results=[],this.absorptionResult={}}},J={};c(J,{Application:()=>tt.Application,utils:()=>Z});var X={};c(X,{Application:()=>tt.Application,utils:()=>Z});require("@pixi/polyfill");var Z=l(require("@pixi/utils"),1),Q=require("@pixi/interaction"),tt=require("@pixi/app"),et=require("@pixi/core"),it=require("@pixi/loaders"),st=require("@pixi/ticker");p(X,require("@pixi/constants")),p(X,require("@pixi/core")),p(X,require("@pixi/display")),p(X,require("@pixi/graphics")),p(X,require("@pixi/loaders")),p(X,require("@pixi/interaction")),p(X,require("@pixi/math")),p(X,require("@pixi/runner")),p(X,require("@pixi/sprite")),p(X,require("@pixi/text")),p(X,require("@pixi/ticker")),p(X,require("@pixi/settings")),Z.skipHello(),et.Renderer.registerPlugin("interaction",Q.InteractionManager),et.Renderer.registerPlugin("batch",et.BatchRenderer),tt.Application.registerPlugin(st.TickerPlugin),tt.Application.registerPlugin(it.AppLoaderPlugin),X.Graphics.prototype.drawBox=function(t){const e=t.getCorners();this.beginFill();for(let t=0;t<4;t++)this.moveTo(e[t].x,e[t].y),this.lineTo(e[(t+1)%4].x,e[(t+1)%4].y);this.endFill()},X.Graphics.prototype.fillBox=function(t){const e=t.getSize();this.drawRect(t.min.x,t.min.y,e.x,e.y)},X.Graphics.prototype.drawLine=function(t){if(this.beginFill(),t instanceof M)this.moveTo(t.start.x,t.start.y),this.lineTo(t.end.x,t.end.y);else for(let e=0;e<t.length-1;e++)this.moveTo(t[e].x,t[e].y),this.lineTo(t[e+1].x,t[e+1].y);this.endFill()},p(J,X);var rt=class extends D{constructor(t){super(),m(this,"interactive",!1),m(this,"box",new V),m(this,"graphics",new J.Graphics),m(this,"PageDataUtils"),this.PageDataUtils=t,this.type="preference"}initialize(){throw new Error("Method not implemented.")}preparationAction(){}preAction(){}action(){}endAction(){}interruption(){}actionKey(){}endActionKey(){}cancelPreparation(){}refreshResults(){if(this.box=new V,!me.config.gestureHandlerConfig.preferenceGizmoEnabled)return void console.warn("Preference gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const t=this.PageDataUtils.getPageData();(0,w.assertExist)(t);const{container:e}=this.PageDataUtils;if(e){const{zoom:i}=t.property,{offsetWidth:s,offsetHeight:r}=e,a=new _(s,r).multiply(i),o=this.PageDataUtils.getViewportLeftTopPosition().add(a.clone().divide(2));this.box=(new V).setFromCenterAndSize(o,a)}}refreshRenderObjects(){const{boxWidth:t,boxColor:e,markColor:i,markAlpha:s,safeAreaEnabled:r,safeAreaBoxColor:a,safeAreaBoxAlpha:o}=me.config.gestureHandlerConfig.preferenceGizmoConfig;this.graphics=new J.Graphics;const{offsetWidth:n,offsetHeight:c}=this.PageDataUtils.container.parentElement,h=new V(new _(0,0),new _(n,this.box.min.y)),p=new V(new _(0,this.box.min.y),new _(this.box.min.x,c)),l=new V(new _(this.box.min.x,this.box.max.y),new _(n,c)),m=new V(new _(this.box.max.x,this.box.min.y),new _(n,this.box.max.y));if(this.graphics.beginFill(i,s),this.graphics.fillBox(h),this.graphics.fillBox(p),this.graphics.fillBox(l),this.graphics.fillBox(m),this.graphics.endFill(),r){const t=this.PageDataUtils.getPageData();(0,w.assertExist)(t,"You must call SDK#run() first");const{viewProperties:e,activeData:i}=t,s=e[i.view??-1];if(s){const{size:t,safeArea:e,previewSafeAreas:i}=s,[r,n,c,h]=e,p=this.box.getSize(),l=r/t[1]*p.y,m=c/t[0]*p.x,d=h/t[0]*p.x,g=n/t[1]*p.y,{min:u,max:f}=this.box;this.graphics.beginFill(a,o);const y=new V(u,new _(f.x,u.y+l)),w=new V(new _(u.x,u.y+l),new _(u.x+m,f.y)),x=new V(new _(f.x-d,u.y+l),new _(f.x,f.y)),v=new V(new _(u.x+m,f.y-g),new _(f.x-d,f.y));this.graphics.fillBox(y),this.graphics.fillBox(w),this.graphics.fillBox(x),this.graphics.fillBox(v),this.graphics.endFill(),i.forEach(e=>{const{box:[i,s,r,a],color:o}=e,n=this.box.getSize(),c=new _(r/t[0]*n.x,a/t[1]*n.y),h=new _(i/t[0]*n.x+c.x/2,s/t[1]*n.y+c.y/2).add(u),p=(new V).setFromCenterAndSize(h,c),l=o?.[3]??.3,m=o?.slice(0,3)??[255,0,0],d=m[0]<<16|m[1]<<8|m[2];this.graphics.beginFill(d,l),this.graphics.fillBox(p),this.graphics.endFill()})}}this.graphics.lineStyle(t,e),this.graphics.drawBox(this.box)}getRenderObjects(){return me.config.gestureHandlerConfig.preferenceGizmoEnabled?(this.refreshRenderObjects(),[this.graphics]):[]}},at="https://mdn.alipayobjects.com/rms/uri/file/as/0.0.6",ot={normal:{type:"preset",content:"default"},rotation:{type:"svg",content:"default",url:`${at}/icons/cursor-rotate-32.svg`},scale:{type:"svg",content:"default",url:`${at}/icons/cursor-scale-32.svg`}};var nt=class{constructor(t){m(this,"wireframeApplication"),m(this,"gizmos",[]),m(this,"activeGizmo"),m(this,"selectorGizmo"),m(this,"transformGizmo"),m(this,"controlGizmo"),m(this,"preferenceGizmo"),m(this,"spaceClickTime"),m(this,"spaceEmit",!1),m(this,"_ignoreInteraction",!1),m(this,"clickButtons",0),m(this,"container"),m(this,"clickTime",0),m(this,"firstClick",!0),m(this,"dblclickTimeSpan",500),this.gizmos=[];const{width:e,height:i}=t.getBoundingClientRect();this.wireframeApplication=new P.Application({backgroundAlpha:0,width:e,height:i,resolution:1,antialias:!0}),this.container=t,this.wireframeApplication.view.style.position="absolute",this.wireframeApplication.view.id="wireframeApplicationCanvas",t.appendChild(this.wireframeApplication.view),this.wireframeApplication.stage.sortableChildren=!0,this.registerViewEvent(),async function(){await Promise.all(Object.entries(ot).map(([t,e])=>{const{url:i}=e;if(i)return fetch(i).then(t=>t.text()).then(i=>ot[t]={...e,content:i})})).catch(t=>{console.error(t)})}()}set ignoreInteraction(t){t!==this._ignoreInteraction&&(this._ignoreInteraction=t,t&&(this.activeGizmo?.cancelPreparation(),this.activeGizmo=void 0))}get ignoreInteraction(){return this._ignoreInteraction}resize(){this.wireframeApplication&&(this.wireframeApplication.resizeTo=this.container,this.render())}refresh(){this.gizmos.forEach(t=>{t.refreshResults()})}render(){this.refresh(),this.wireframeApplication.stage?.removeChildren();const t=(this.ignoreInteraction?[this.preferenceGizmo]:this.gizmos).flatMap(t=>t.getRenderObjects());this.wireframeApplication.stage.addChild(...t),this.wireframeApplication.render();const e=this.activeGizmo instanceof $?this.activeGizmo.cursorResult:void 0;this.setCursor(e)}init(t){this.gizmos=[],this.controlGizmo=new N(t),this.selectorGizmo=new K(t);const e=new q;this.transformGizmo=new $(t,e),this.preferenceGizmo=new rt(t),this.gizmos.push(this.transformGizmo,this.selectorGizmo,this.controlGizmo,this.preferenceGizmo,e),this.initEvents()}initEvents(){this.onMouseMove=this.onMouseMove.bind(this),this.onMouseUp=this.onMouseUp.bind(this),this.onKeyDown=this.onKeyDown.bind(this),this.onKeyUp=this.onKeyUp.bind(this),document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp)}registerViewEvent(){this.wireframeApplication.view.onmousedown=t=>{this.onMouseDown(t)},this.wireframeApplication.view.onmousemove=t=>{0===t.buttons&&this.onMouseMove(t)},this.wireframeApplication.view.onmouseout=()=>{this.selectorGizmo?.cancelPreparation(),this.render()},this.wireframeApplication.view.onwheel=t=>{this.onWheel(t)}}onMouseDown(t){if(!this.ignoreInteraction){if(this.clickButtons=t.buttons,this.firstClick=!!this.firstClick&&Date.now()-this.clickTime<this.dblclickTimeSpan,this.firstClick){this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()}),this.activeGizmo=void 0;const e=this.selectorGizmo?.preAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===(e??"null")),this.firstClick=!1}else{void 0===this.activeGizmo&&this.gizmos.forEach(e=>{if(!e.interactive||this.activeGizmo)return;const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)});const e=this.activeGizmo?.preAction(t);"selector"!==e&&this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.activeGizmo=this.gizmos.find(t=>t.type===e),this.clickTime=Date.now(),this.firstClick=!0}this.render(),document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("mouseup",this.onMouseUp)}}onMouseMove(t){this.ignoreInteraction||(0!==t.buttons?this.activeGizmo?.action(t):this.spaceEmit||(this.activeGizmo=void 0,this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);"selector"!==i&&this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()})),this.render())}onWheel(t){this.ignoreInteraction||(t.preventDefault(),this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.controlGizmo?.action(t))}onMouseUp(t){if(this.ignoreInteraction)return;const e=this.activeGizmo?.endAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===e),void 0===this.activeGizmo&&1===this.clickButtons&&this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()}),this.clickButtons=0,this.render(),document.removeEventListener("mousemove",this.onMouseMove),document.removeEventListener("mouseup",this.onMouseUp)}onKeyDown(t){if(!this.ignoreInteraction){if("space"!==t.code.toLocaleLowerCase()||this.activeGizmo?.active)this.gizmos.forEach(e=>{e.actionKey(t)});else{if(this.spaceEmit)return;void 0===this.spaceClickTime?this.spaceClickTime=Date.now():Date.now()-this.spaceClickTime>300&&(this.spaceEmit=!0,this.activeGizmo=this.controlGizmo,this.activeGizmo?.actionKey(t))}this.render()}}onKeyUp(t){this.ignoreInteraction||(this.gizmos.forEach(e=>{e.endActionKey(t)}),"space"===t.code.toLocaleLowerCase()&&(this.spaceClickTime=void 0,this.spaceEmit=!1),this.render())}dispose(){this.wireframeApplication.destroy(),this.gizmos=[],this.activeGizmo=void 0}setCursor(t){let e="default";if(t?.type){const i=ot[t.type];if("svg"===i.type){const s=16;e=encodeURIComponent(i.content.replace("rotate(0.00)",`rotate(${t.angle})`)),e=`url("data:image/svg+xml,${e}") ${s} ${s}, auto`}else e=i.content}this.wireframeApplication.view.style.cursor=e}};function ct(t,e){t.includes(e)||t.push(e)}var ht=require("@galacean/effects"),pt=class{constructor(t){m(this,"plane",new W),m(this,"ray",new G),m(this,"viewportParam",{width:0,height:0,viewWidth:0,viewHeight:0,panelWidth:0,panelHeight:0,scale:1,ratio:1,translation:new _,rulerWidth:0}),m(this,"cameraParam",{position:new F,rotation:new F,focusPosition:new F,focusRotation:new F,viewProjectionMatrix:new U,inverseViewProjectionMatrix:new U}),m(this,"pageDataUtils"),this.pageDataUtils=t}refreshViewParam(){const t=this.pageDataUtils.getPageData();(0,ht.assertExist)(t,"You must run SDK first");const e=new _(this.pageDataUtils.container.offsetWidth,this.pageDataUtils.container.offsetHeight),{zoom:i,translation:s}=t.property;this.viewportParam.width=e.x,this.viewportParam.height=e.y,this.viewportParam.viewWidth=e.x,this.viewportParam.viewHeight=e.y,this.viewportParam.panelWidth=e.x,this.viewportParam.panelHeight=e.y,this.viewportParam.scale=i,this.viewportParam.ratio=1,this.viewportParam.translation=new _(...s.map(t=>t/i)),this.viewportParam.rulerWidth=0}refreshCameraParam(){const{player:t}=this.pageDataUtils,e=t?.getCompositions()?.[0]?.camera;if(e){const t=U.fromArray(e.getViewProjectionMatrix().toArray()),i=U.fromArray(e.getViewMatrix().toArray()).invert(),s=new B;i.decompose(this.cameraParam.position,s,new F),this.cameraParam.rotation=(new R).setFromQuaternion(s).toDegreeVector3(),this.cameraParam.focusPosition=new F(...this.cameraParam.position.toVector2().toArray(),this.cameraParam.position.z>0?0:2*this.cameraParam.position.z),this.cameraParam.focusPosition.applyEuler((new R).setFromDegreeVector3(this.cameraParam.rotation.clone()),this.cameraParam.position),this.cameraParam.focusRotation=(new R).setFromQuaternion(s.invert()).toDegreeVector3(),this.cameraParam.viewProjectionMatrix=t,this.cameraParam.inverseViewProjectionMatrix=U.fromArray(e.getInverseViewProjectionMatrix().toArray())}}initInteractionPlane(t,e){t??(t=this.cameraParam.focusPosition),e??(e=(new R).setFromDegreeVector3(this.cameraParam.rotation));const i=new F(0,0,1).applyEuler(e);this.plane.setFromNormalAndCoplanarPoint(t,i)}getWorldSizeByViewSize(t,e=!0,i){const s=e||!i?(new R).setFromDegreeVector3(this.cameraParam.rotation):(new R).setFromQuaternion((new B).setFromRotationMatrix(this.pageDataUtils.getItemTransformById(i.id).matrix)),r=i?(new F).setFromMatrixPosition(this.pageDataUtils.getItemTransformById(i.id).matrix):this.cameraParam.focusPosition,a=this.projectPoint(r.clone()),o=this.getWorldPositionByViewPoint(a.add(t));if(!o)return console.warn("size is out of bounds."),new F(0,0,0);const n=(new R).setFromQuaternion((new B).setFromEuler(s).invert());return(e||!i?o.applyEuler(n,r):o).subtract(r)}projectPoint(t){const{panelWidth:e,panelHeight:i,scale:s}=this.viewportParam,r=this.pageDataUtils.getViewportLeftTopPosition();return(new _).copyFrom(t.applyMatrix(this.cameraParam.viewProjectionMatrix).toVector2()).toViewCoordinate(e*s,i*s).add(r)}getWorldPositionByViewPoint(t){const{position:e,inverseViewProjectionMatrix:i}=this.cameraParam,s=this.getViewPositionByScreenPosition(t),r=(new H).setFromCamera(s,{position:e,inverseViewProjectMatrix:i}).rayCastPlane(this.plane);return r?.point}getViewPositionByScreenPosition(t){const{panelWidth:e,panelHeight:i,scale:s}=this.viewportParam;return new _(t.x/(e*s)*2-1,-t.y/(i*s)*2+1)}getScreenSizeByPixelSize(t){const e=this.viewportParam.width/this.viewportParam.viewWidth,i=t.clone();return i.multiply(e||1),i}getPixelSizeByScreenSize(t){const e=this.viewportParam.viewWidth/this.viewportParam.width,i=t.clone();return i.multiply(e||1),i}},lt=require("@ffmpeg/ffmpeg"),mt=require("@ffmpeg/util");function dt(t,e="asserts failed"){if(!t)throw new Error(e)}function gt(t,e,...i){const s=e.reduce((t,e)=>t?`${t} ${e}`:e,""),r="color: #108ee9;";switch(t){case"error":console.error(`%c[${s}]`,r,...i);break;case"info":console.info(`%c[${s}]`,r,...i);break;case"debug":console.debug(`%c[${s}]`,r,...i);break;case"warn":console.warn(`%c[${s}]`,r,...i);break;default:console.log(`%c[${s}]`,r,...i)}}function ut(t,e,i="application/octet-stream"){const s=new Blob(Array.isArray(t)?t:[t],{type:i}),r=URL.createObjectURL(s),a=document.createElement("a");a.href=r,a.download=e,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(r)}function ft(t,e){if(Object.is(t,e))return!0;if(typeof t!=typeof e)return!1;if(null===t||"object"!=typeof t)return!1;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t instanceof RegExp&&e instanceof RegExp)return t.toString()===e.toString();if(Array.isArray(t)!==Array.isArray(e))return!1;const i=Object.keys(t),s=Object.keys(e);if(i.length!==s.length)return!1;for(const s of i){if(!Object.prototype.hasOwnProperty.call(e,s))return!1;if(!ft(t[s],e[s]))return!1}return!0}var yt={SCRIPT:"https://gw.alipayobjects.com/os/gltf-asset/99531561844014/img2webp.js",WASM:"https://mdn.alipayobjects.com/mars/uri/file/as/0.0.4/wasm/img2webp/img2webp.wasm"},wt={CLASSWORKER:"https://mdn.alipayobjects.com/rms/uri/file/as/ffmpeg/core/0.12.10/dist/worker.js",DEFAULT:{CORE:"https://gw.alipayobjects.com/os/lib/ffmpeg/core/0.12.10/dist/esm/ffmpeg-core.js",WASM:"https://gw.alipayobjects.com/os/lib/ffmpeg/core/0.12.10/dist/esm/ffmpeg-core.wasm"},MT:{CORE:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.js",WASM:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.wasm",WORKER:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.worker.js"}};function xt(t,e,i,s){const r=e.getContext("2d");dt(r),r.clearRect(0,0,e.width,e.height),i&&(r.save(),r.fillStyle=i,r.fillRect(0,0,e.width,e.height),r.restore()),s&&r.drawImage(s,0,0,s.width,s.height,0,0,e.width,e.height),r.drawImage(t,0,0,t.width,t.height,0,0,e.width,e.height)}async function vt(){return new Promise(async(t,e)=>{try{await function(t,e={}){return new Promise((i,s)=>{const r=document.querySelector(`script[src="${t}"]`);if(r)return"true"===r.dataset.loaded?void i(r):(r.addEventListener("load",()=>{i(r)}),void r.addEventListener("error",()=>{s(new Error(`Script already failed: ${t}`))}));const a=document.createElement("script");a.src=t,a.async=!0,Object.keys(e).forEach(t=>{a.setAttribute(t,e[t]??"")}),a.onload=()=>{a.dataset.loaded="true",i(a)},a.onerror=()=>{s(new Error(`Failed to load script: ${t}`))},document.head.appendChild(a)})}(yt.SCRIPT,{crossOrigin:"anonymous"});const e={locateFile:(t,e)=>t.endsWith("createWebPCore.wasm")?yt.WASM:e+t};t(await window.createWebPCore(e))}catch(t){e(t)}})}function Pt(t){for(const e of t.getCompositions())for(const t of e.textures)t.isDestroyed||t.dispose();t.assetManagers=[],t.destroyCurrentCompositions()}var Dt,It,bt,Ct,Et,At,St,zt,Tt,_t,Mt,Vt,kt,Bt,Ft,Ut,Rt,Wt,Gt=class{constructor(t,e,i,s){m(this,"sdk"),m(this,"player"),m(this,"container"),m(this,"emitter"),m(this,"interactionUtils"),this.player=t,this.sdk=s,this.container=e,this.emitter=i}init(){this.interactionUtils=new pt(this)}getPageData(){return this.sdk.pageData}getCurrentComposition(){return this.player.getCompositions()[0]}isItemSelected(t){return!!this.sdk.pageData?.activeData.selectedItems?.find(e=>e===t)}getItemEditEnable(t){const e=this.getViewItemById(t);if(!e||!this.sdk.pageData||this.sdk.pageData.viewProperties[this.sdk.pageData.activeData.view??0]?.ignoreInteraction)return!1;const i=this.sdk.pageData.time,{duration:s,delay:r,endBehavior:a}=e;return i>=r&&(i<r+s||a===w.spec.EndBehavior.restart)}getItemShow(t){const e=this.getViewItemById(t);if(!this.sdk.pageData||!e?.property.visible)return!1;const i=this.sdk.pageData.time,{duration:s,delay:r,endBehavior:a}=e;return i>=r&&(i<r+s||a===w.spec.EndBehavior.restart||a===w.spec.EndBehavior.freeze)}addSelectedItems(t){var e;(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),(e=this.sdk.pageData.activeData).selectedItems??(e.selectedItems=[]),t.forEach(t=>{ct(this.sdk.pageData?.activeData.selectedItems??[],t)}),this.emitter.emit("selectedItemChange",t)}clearSelectedItems(){this.sdk.pageData&&(this.sdk.pageData.activeData.selectedItems=[],this.emitter.emit("selectedItemChange",[]))}getSelectedItems(){const t=this.sdk.pageData?.activeData.selectedItems;return this.sdk.pageData?.items.filter(e=>t?.find(t=>t===e.id))??[]}addPreSelectedItem(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=t,this.emitter.emit("preSelectedItemChange",t)}clearPreSelectedItem(){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=void 0,this.emitter.emit("preSelectedItemChange",void 0)}getPreSelectedItem(){const t=this.getPageData();(0,w.assertExist)(t,"You must call SDK#run() first");const e=t.activeData.preSelectedItem;return e?this.getViewItemById(e):void 0}getViewItemById(t){return this.sdk.pageData?.items.find(e=>e.id===t)}getPlayerSizeByParent(t,e){const[i,s]=t,[r,a]=e;let o=s,n=o/(a||1624)*(r||750);return n>i&&(o=i/n*s,n=i),[n,o]}async loadScene(t){Pt(this.player);const e=this.sdk.pageData?.viewProperties[t];if(!e||!this.sdk.pageData)return void console.warn(`This page does not have ${t} view property.`);const{scene:i,size:s}=e,r=this.container.parentElement?.offsetWidth??300,a=this.container.parentElement?.offsetHeight??300,[o,n]=this.getPlayerSizeByParent([r,a],s);this.container.style.width=`${o}px`,this.container.style.height=`${n}px`,this.sdk.pageData.activeData={view:t,selectedItems:[],preSelectedItem:void 0},this.player.resize();const c=JSON.parse(JSON.stringify(i)),h=await this.player.loadScene(c,{autoplay:!1});this.player.gotoAndStop(this.sdk.pageData.time),this.interactionUtils.refreshViewParam(),this.interactionUtils.refreshCameraParam(),this.sdk.pageData.items=[],this.addViewItemsByItems(this.sdk.pageData.items,h.items),this.emitter.emit("pageDataChange",this.sdk.pageData)}refreshPageTime(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.time=t}pageZoom(t){var e;(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const{zoom:i}=this.sdk.pageData.property;(e=this.sdk.pageData.property).zoom??(e.zoom=1);const s=b(t,-.1,.1),r=S(b(i+s,.3,10),2);this.sdk.pageData.property.zoom=r,this.container.style.scale=`${r}`,this.emitter.emit("zoomChange",r)}setPageZoom(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const e=S(b(t,.3,10),2);this.sdk.pageData.property.zoom=e,this.container.style.scale=`${e}`,this.emitter.emit("zoomChange",t)}refreshInteractionParam(){this.interactionUtils.refreshViewParam(),this.interactionUtils.refreshCameraParam()}pageMove(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const[e,i]=this.sdk.pageData.property.translation??[0,0],s=e+t.x,r=i+t.y;this.sdk.pageData.property.translation=[s,r],this.refreshInteractionParam(),this.container.style.translate=`${s}px ${r}px`,this.emitter.emit("pageDataChange",this.sdk.pageData)}rotateItem(t,e){const i=this.getPlayerItemById(t);i&&(i.rotate(...e.toArray()),this.transformSceneItem(t,"rotation",e.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"rotation"}))}moveItem(t,e){const i=this.getPlayerItemById(t);if(i){const s=(new U).copyFrom(i.transform.getParentMatrix()??new U);s.setPosition(new F);const r=e.clone().applyMatrix(s.invert());i.translate(...r.toArray()),i.transform.updateLocalMatrix(),this.transformSceneItem(t,"position",r.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"translation"})}}scaleItem(t,e){const i=this.getPlayerItemById(t);i&&(i.scale(...e.toArray()),this.transformSceneItem(t,"scale",e.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"size"}))}getItemTransformById(t){const e={matrix:new U,parentMatrix:new U},i=this.getPlayerItemById(t);if(void 0!==i?.transform){i.transform.updateLocalMatrix();const t=U.fromArray(i.composition?.transform.getWorldMatrix().elements??[]).invert();e.matrix=t.clone().multiply(U.fromArray(i.transform.getWorldMatrix().elements)),e.parentMatrix=t.clone().multiply(U.fromArray(i.transform.parentTransform?.getWorldMatrix().elements??(new U).toArray()))}return e}addViewItemsByItems(t,e,i){const s=e=>{e.forEach(e=>{t.find(t=>t.id===e.getInstanceId())||t.push(this.createViewItemByPlayerItem(e,i))})};for(const i of e)me.config.pageConfig.filterItemNames.includes(i.name)||(s([i]),this.addViewItemsByItems(t,i.children,i.getInstanceId()))}createViewItemByPlayerItem(t,e){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const{transform:i,composition:s,isVisible:r}=t;i.updateLocalMatrix();const a=(new U).copyFrom(s?.transform.getWorldMatrix()??(new U).identity()).invert().multiply(i.getWorldMatrix()),o=new F,n=new B,c=new F;a.decompose(o,n,c);const h=(new R).setFromQuaternion(n);h.x=Number.isNaN(h.x)?0:h.x,h.y=Number.isNaN(h.y)?0:h.y,h.z=Number.isNaN(h.z)?0:h.z;const p=o.toArray().map(t=>S(t,2)),l=h.toArray().map(t=>S(t,2)),m=c.toArray().map(t=>S(t,2)),d=i.size.toArray(),g={position:p,rotation:l,size:this.getPixelSizeByWorldSize([m[0]*d[0],m[1]*d[1],m[2]],t).map(t=>S(t,2)),visible:r,keyPropertyEditing:!1};switch(t.type){case w.spec.ItemType.sprite:{const e=this.getActiveScene()?.scene;if(e){e.components.filter(e=>e.item.id===t.getInstanceId()).forEach(t=>{if(g.keyPropertyEditing||!("renderer"in t)||!("texture"in t.renderer)||!t.renderer.texture)return;const i=e.textures?.find(e=>e.id===t.renderer.texture.id);if(i&&"source"in i&&i.source){const t=e?.images.find(t=>t.id===i.source.id);g.keyPropertyEditing=!!t?.template;const s=t?.url??"";s&&Object.assign(g,{image:s})}})}break}case w.spec.ItemType.text:case w.spec.ItemType.richtext:{const e=this.getActiveScene()?.scene;if(g.keyPropertyEditing=!0,e){e.components.filter(e=>e.item.id===t.getInstanceId()).forEach(t=>{if(![w.spec.DataType.TextComponent,w.spec.DataType.RichTextComponent].includes(t.dataType))return;const{textAlign:e,textColor:i,text:s,fontWeight:r,fontFamily:a}=t.options;Object.assign(g,{alignment:e,color:i,weight:r,text:s,font:a})})}break}}return{id:t.getInstanceId(),name:t.name,parentId:t.parentId??e,children:[],type:t.type,duration:t.duration,delay:t.defination.delay,endBehavior:t.endBehavior,property:g}}getViewBoxById(t){const e=new V,i=this.getPlayerItemById(t),s=this.getChildrenPlayerItems(i);return i&&s?this.getViewBoxByPlayerItem(i,s):e}getItemViewAnchor(t){const e=this.getPlayerItemById(t);if(e?.transform?.anchor){const t=(new F).copyFrom(e.transform.anchor).applyMatrix((new U).copyFrom(e.transform.getWorldMatrix()));return this.interactionUtils.projectPoint(t).round(2)}}getChildrenPlayerItems(t){const e=[];return t?(e.push(...this.player.getCompositions()[0].items.filter(e=>e.parentId===t.getInstanceId())),e.push(...e.flatMap(t=>this.getChildrenPlayerItems(t))),e):[]}getChildrenSceneItemIds(t,e){const i=[];return i.push(...e.items.filter(e=>e.parentId===t).map(t=>t.id)),i.push(...i.flatMap(t=>this.getChildrenSceneItemIds(t,e))),i}getViewBoxByPlayerItem(t,e){const i=new V;switch(t.type){case w.spec.ItemType.sprite:case w.spec.ItemType.plugin:case w.spec.ItemType.video:case w.spec.ItemType.richtext:case w.spec.ItemType.text:case w.spec.ItemType.shape:{const{transform:s,composition:r}=t;s.updateLocalMatrix();const{size:a}=s,o=(new U).copyFrom(r?.transform.getWorldMatrix()??new U).invert().multiply(s.getWorldMatrix()),{x:n,y:c}=a.clone().divide(2),h=new F(n,c,0).applyMatrix(o),p=new F(n,-c,0).applyMatrix(o),l=new F(-n,-c,0).applyMatrix(o),m=new F(-n,c,0).applyMatrix(o),d=this.interactionUtils.projectPoint(h).round(2),g=this.interactionUtils.projectPoint(p).round(2),u=this.interactionUtils.projectPoint(l).round(2),f=this.interactionUtils.projectPoint(m).round(2);i.setFromVec2Array([d,g,u,f]);const y=e?.map(t=>this.getViewBoxById(t.getInstanceId()));y&&y.map(t=>i.union(t));break}case w.spec.ItemType.null:{const t=e?.map(t=>this.getViewBoxById(t.getInstanceId()));t&&t.map(t=>i.union(t));break}}return i}getViewportLeftTopPosition(){if(!this.sdk.pageData)return new _;const{zoom:t,translation:e}=this.sdk.pageData.property,{offsetWidth:i,offsetHeight:s}=this.container.parentElement,{offsetWidth:r,offsetHeight:a}=this.container,o=new _(i,s),n=new _(r,a).multiply(t);return o.clone().divide(2).subtract(n.clone().divide(2)).add(e)}getContainerPosition(){const{offsetWidth:t,offsetHeight:e}=this.container.parentElement;return new _(t/2,e/2).add(new _(...this.sdk.pageData?.property.translation??[0,0]))}getViewportByViewPoint(t){if(!this.sdk.pageData)return t;const{zoom:e}=this.sdk.pageData.property,{offsetWidth:i,offsetHeight:s}=this.container,r=new _(i,s).multiply(e),a=this.getViewportLeftTopPosition(),o=t.clone().subtract(a);return new _(o.x/r.x*2-1,1-o.y/r.y*2)}getActiveScene(){return this.sdk.pageData?.viewProperties[this.sdk.pageData?.activeData.view??-1]}async changeItemProperty(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const e=this.getViewItemById(t.itemId),i=this.getPlayerItemById(t.itemId);if(e&&i)if(t.propertyName in e.property){switch(t.propertyName){case"alignment":[w.spec.TextAlignment.left,w.spec.TextAlignment.middle,w.spec.TextAlignment.right].includes(t.propertyValue)&&i.getComponent(w.TextComponent).setTextAlign(t.propertyValue);break;case"color":Array.isArray(t.propertyValue)&&4===t.propertyValue.length&&(console.log(t.propertyValue),i.getComponent(w.TextComponent).setTextColor(t.propertyValue));break;case"font":if("string"==typeof t.propertyValue){const e=t.propertyValue.split("/"),s=e[e.length-1]?.split(".")[0],r=this.player.getAssetManager()[0];await r.processFontURL([{fontURL:t.propertyValue,fontFamily:s}]),s&&i.getComponent(w.TextComponent).setFontFamily(s)}break;case"text":"string"==typeof t.propertyValue&&i.getComponent(w.TextComponent).setText(t.propertyValue);break;case"weight":[w.spec.TextWeight.normal,w.spec.TextWeight.bold,w.spec.TextWeight.lighter].includes(t.propertyValue)&&i.getComponent(w.TextComponent).setFontWeight(t.propertyValue);break;case"image":"string"==typeof t.propertyValue&&i.getComponent(w.SpriteComponent).setTexture(await w.Texture.fromImage(t.propertyValue,this.player.renderer.engine));break;case"position":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const i=t.propertyValue.map((t,i)=>t-(e.property.position[i]??0));this.moveItem(t.itemId,new F(...i))}break;case"rotation":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const i=t.propertyValue.map((t,i)=>t-(e.property.rotation[i]??0));this.rotateItem(t.itemId,new F(...i).negate())}break;case"size":if(Array.isArray(t.propertyValue)&&2===t.propertyValue.length){const i=t.propertyValue.map(t=>0===t||null===t?1:t),s=e.property.size.map(t=>t||1),r=i.map((t,e)=>t/s[e]);this.scaleItem(t.itemId,new F(...r,1))}break;case"visible":if("boolean"==typeof t.propertyValue&&(i.setVisible(t.propertyValue),me.config.pageConfig.groupVisible)){this.getChildrenPlayerItems(i).forEach(e=>{e.setVisible(t.propertyValue)})}}["position","rotation","size"].includes(t.propertyName)||this.player.gotoAndStop(this.sdk.pageData.time),this.changeViewItemProperty(t),this.refreshViewItem(t.itemId)}else console.warn(`Item does not have property ${t.propertyName}.`);else console.warn(`Id ${t.itemId} is not a item id.`)}changeViewItemProperty(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.viewProperties.forEach((e,i)=>{if(!this.sdk.pageData?.property.asyncMode&&i!==this.sdk.pageData?.activeData.view)return;const{scene:s}=e;switch(t.propertyName){case"position":case"rotation":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const e=this.sdk.pageData.items.find(e=>e.id===t.itemId),i=e?.property[t.propertyName],r=t.propertyValue.map((t,e)=>t-(i?.[e]??0));this.changeSceneItemProperty(s,{...t,propertyValue:r})}break;case"size":if(Array.isArray(t.propertyValue)&&2===t.propertyValue.length){const e=this.sdk.pageData.items.find(e=>e.id===t.itemId),i=e?.property[t.propertyName],r=t.propertyValue.map((t,e)=>t/(i?.[e]??0));this.changeSceneItemProperty(s,{...t,propertyValue:r})}break;default:this.changeSceneItemProperty(s,t)}})}changeSceneItemProperty(t,e){switch(e.propertyName){case"alignment":if([w.spec.TextAlignment.left,w.spec.TextAlignment.middle,w.spec.TextAlignment.right].includes(e.propertyValue)){const i=t.components.find(t=>t.item.id===e.itemId&&[w.spec.DataType.TextComponent,w.spec.DataType.RichTextComponent].includes(t.dataType));i?.options&&"textAlign"in i.options&&(console.log(e.propertyValue),i.options.textAlign=e.propertyValue)}break;case"color":if(Array.isArray(e.propertyValue)&&4===e.propertyValue.length){const i=t.components.find(t=>t.item.id===e.itemId&&[w.spec.DataType.TextComponent,w.spec.DataType.RichTextComponent].includes(t.dataType));i?.options&&(i.options.textColor=[...e.propertyValue])}break;case"font":if("string"==typeof e.propertyValue){const i=e.propertyValue.split("/"),s=i[i.length-1]?.split(".")[0],r=t.fonts?.find(t=>"family"in t&&t.family===s||"fontFamily"in t&&t.fontFamily===s);!r&&t.fonts&&s&&t.fonts.push({fontFamily:s,fontURL:e.propertyValue});const a=t.components.find(t=>t.item.id===e.itemId&&[w.spec.DataType.TextComponent,w.spec.DataType.RichTextComponent].includes(t.dataType));a?.options&&(a.options.fontFamily=s)}break;case"text":if("string"==typeof e.propertyValue){const i=t.components.find(t=>t.item.id===e.itemId&&[w.spec.DataType.TextComponent,w.spec.DataType.RichTextComponent].includes(t.dataType));i?.options&&(i.options.text=e.propertyValue)}break;case"weight":if("string"==typeof e.propertyValue){const i=t.components.find(t=>t.item.id===e.itemId&&[w.spec.DataType.TextComponent,w.spec.DataType.RichTextComponent].includes(t.dataType));i?.options&&(i.options.fontWeight=e.propertyValue)}break;case"image":if("string"==typeof e.propertyValue){t.components.filter(t=>t.item.id===e.itemId).forEach(i=>{if(!("renderer"in i))return;const s=t.textures?.find(t=>t.id===i.renderer.texture.id);if(s&&"source"in s&&s.source){const i=t?.images.find(t=>t.id===s.source.id);i?.url&&i?.webp&&(i.url=e.propertyValue,i.webp=e.propertyValue),i&&"template"in i&&i.template.background&&(i.template.background.url=e.propertyValue)}})}break;case"position":if(Array.isArray(e.propertyValue)&&3===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.position.x+=e.propertyValue[0],i.transform.position.y+=e.propertyValue[1],i.transform.position.z+=e.propertyValue[2])}break;case"rotation":if(Array.isArray(e.propertyValue)&&3===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.eulerHint.x+=e.propertyValue[0],i.transform.eulerHint.y+=e.propertyValue[1],i.transform.eulerHint.z+=e.propertyValue[2])}break;case"size":if(Array.isArray(e.propertyValue)&&2===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.scale.x*=e.propertyValue[0],i.transform.scale.y*=e.propertyValue[1])}break;case"visible":{const i=t.items.find(t=>t.id===e.itemId);if(i&&(i.visible=e.propertyValue,me.config.pageConfig.groupVisible)){this.getChildrenSceneItemIds(e.itemId,t).forEach(i=>{const s=t.items.find(t=>t.id===i);s&&(s.visible=e.propertyValue)})}break}}}transformSceneItem(t,e,i){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.viewProperties.forEach((s,r)=>{if(!this.sdk.pageData?.property.asyncMode&&r!==this.sdk.pageData?.activeData.view)return;const{scene:a}=s;switch(e){case"position":if(Array.isArray(i)&&3===i.length){const e=a.items.find(e=>e.id===t);e?.transform&&(e.transform.position.x+=i[0],e.transform.position.y+=i[1],e.transform.position.z+=i[2])}break;case"rotation":if(Array.isArray(i)&&3===i.length){const e=a.items.find(e=>e.id===t);e?.transform&&(e.transform.eulerHint.x+=i[0],e.transform.eulerHint.y+=i[1],e.transform.eulerHint.z+=i[2])}break;case"scale":if(Array.isArray(i)&&3===i.length){const e=a.items.find(e=>e.id===t);e?.transform&&(e.transform.scale.x*=i[0],e.transform.scale.y*=i[1],e.transform.scale.z*=i[2])}}})}refreshViewItem(t){const e=this.sdk.pageData;(0,w.assertExist)(e,"You must call SDK#run() first");const i=e.items.findIndex(e=>e.id===t);if(i<0)return void console.log(`item ${t} is not existed.`);const s=e.items[i],r=this.getPlayerItemById(t);r&&s&&(e.items[i]=this.createViewItemByPlayerItem(r,s.parentId))}getPlayerItemById(t){return this.player.getCompositions()[0]?.items.find(e=>e.getInstanceId()===t)}getPixelSizeByWorldSize(t,e){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const i=[0,0],s=e.composition?.camera,r=this.sdk.pageData.viewProperties[this.sdk.pageData.activeData.view??0]?.size;if(s&&r){const{z:a}=e.transform.getWorldPosition(),{x:o,y:n}=s.getInverseVPRatio(a);i[0]=Math.abs(t[0]*r[0]/o/2),i[1]=Math.abs(t[1]*r[1]/n/-2)}else console.warn("camera is not existed.");return i}},Ht=l(require("jszip"),1),Nt=l(require("jszip"),1),Lt="ready",Kt="executable",Ot="dispose",jt={APNG:"APNG",MP4:"MP4",WebM:"WebM",Images:"Images",WebP:"WebP",GIF:"GIF",AlphaMaskVideo:"AlphaMaskVideo"},$t="idle",Yt="convertImage",qt="transcoding",Jt="audio",Xt="jpeg",Zt="webp",Qt="png",te=(jt.MP4,jt.WebP,jt.APNG,jt.GIF,jt.AlphaMaskVideo,jt.Images,jt.MP4,jt.WebP,jt.APNG,jt.GIF,jt.AlphaMaskVideo,jt.Images,"default"),ee="exporting",ie="success",se="error",re=class{constructor(t){m(this,"sampleRate"),m(this,"duration"),m(this,"channels");const{sampleRate:e=44100,duration:i=1,channels:s=2}=t??{};this.sampleRate=e,this.duration=i,this.channels=s}getBuffer(){const t=this.sampleRate*this.duration*this.channels*2,e=44+t,i=new ArrayBuffer(e),s=new DataView(i);let r=0;const a=t=>{for(let e=0;e<t.length;e++)s.setUint8(r++,t.charCodeAt(e))},o=t=>{s.setUint32(r,t,!0),r+=4},n=t=>{s.setUint16(r,t,!0),r+=2};a("RIFF"),o(e-8),a("WAVE"),a("fmt "),o(16),n(1),n(this.channels),o(this.sampleRate),o(this.sampleRate*this.channels*2),n(2*this.channels),n(16),a("data"),o(t);for(let e=0;e<t;e++)s.setUint8(r++,0);return new Uint8Array(i)}},ae=["@vvfx/sdk","exporter"],oe=class extends w.EventEmitter{constructor(t){super(),m(this,"status",Lt),m(this,"stage",$t),m(this,"mediaType"),m(this,"loggerInTranscoding"),m(this,"multiThreading"),m(this,"extraCanvas"),m(this,"player"),u(this,Dt,0),u(this,It),u(this,bt),u(this,Ct),u(this,Et),u(this,At,[]),u(this,St),u(this,zt),u(this,Tt,[]),u(this,_t,0),u(this,Mt),u(this,Vt,[]),u(this,kt,0),u(this,Bt,0),u(this,Ft,0),u(this,Ut,0),u(this,Rt,[]),u(this,Wt,!0);const{mediaType:e,extraCanvas:i,loggerInTranscoding:s,multiThreading:r}=t;this.mediaType=e,this.loggerInTranscoding=s??!1,this.multiThreading=r??!1,this.extraCanvas=i??void 0,this.onInit()}get canceled(){return this.status===Ot}get config(){const t=this.player?.getCompositions()??[],e=t?.[0],i=e?.name??(new Date).getTime().toString(),s=e?.getDuration()??0,r=e?.startTime??0,a=g(this,Mt)?.time;return{name:i,startTime:r,oldTotalTime:s,newTotalTime:a,fps:g(this,Mt)?.fps??30,backgroundColor:g(this,Mt)?.backgroundColor??"#000000",loop:g(this,Mt)?.loop??!0,audioEnable:g(this,Mt)?.audioEnable??!1}}get progress(){const t=g(this,Bt)||1,e=g(this,Ft)||1,i=Math.min(t/e,1),s=Math.min(g(this,kt),t)/t*.4,r=Math.min(g(this,Ut),t)/t*.6,a=Math.min(s+r,1);g(this,Vt)[g(this,_t)]=i;const o=g(this,Vt).reduce((t,e,i)=>i<g(this,_t)?t+(e||0):t,0)+a*i;return Math.min((n=o,Math.round(100*n)/100),1);var n}get transImageType(){return this.mediaType===jt.MP4?Xt:this.mediaType===jt.WebP?Zt:Qt}async onInit(){try{gt("log",[...ae,"ready"],"starting"),this.status=Lt,await this.loadHelper(this.mediaType),this.status=Kt,gt("log",[...ae,"ready"],"success"),this.emit("ready",this.mediaType)}catch(t){this.status=Ot,this.onError(t)}finally{return this.status}}onReset(){this.stage=$t,window.cancelAnimationFrame(g(this,Dt)),f(this,Dt,0),this.player?.pause(),this.clearTaskInfo(),this.setProgress()}onError(t){gt("log",[...ae,"error"],t),this.onFinish(!1,g(this,Rt)),this.emit("error",t),this.dispose()}onFinish(t,e){gt("log",[...ae,"finish"],t?"success":"failed"),this.emit("progress",1),this.emit("finish",t,e)}async loadHelper(t){const e="WebP"===t&&!g(this,Ct),i=[jt.MP4,jt.APNG,jt.GIF,jt.AlphaMaskVideo].includes(t)&&!g(this,bt);e&&f(this,Ct,await vt()),i&&(f(this,bt,await async function(t){const{multiThreading:e}=t??{},i=new lt.FFmpeg,s=!!e,r={classWorkerURL:await(0,mt.toBlobURL)(wt.CLASSWORKER,"text/javascript"),coreURL:"",wasmURL:""};return s?(r.coreURL=await(0,mt.toBlobURL)(wt.MT.CORE,"text/javascript"),r.wasmURL=await(0,mt.toBlobURL)(wt.MT.WASM,"application/wasm"),r.workerURL=await(0,mt.toBlobURL)(wt.MT.WORKER,"text/javascript")):(r.coreURL=await(0,mt.toBlobURL)(wt.DEFAULT.CORE,"text/javascript"),r.wasmURL=await(0,mt.toBlobURL)(wt.DEFAULT.WASM,"application/wasm")),await i.load(r),i}({multiThreading:this.multiThreading})),g(this,bt).on("log",({message:t})=>{if(this.loggerInTranscoding&&gt("log",[...ae,"transcoding log"],t),this.canceled||this.stage!==qt)return;const e=/frame=\s*(\d+)/.exec(t);if(e?.[1]){const t=Number(e[1]);this.setProgress({currentTaskInTranscodingFrameIndex:t})}}))}getAllTaskFrames(t){return t.reduce((t,e)=>{const{scene:i,fps:s}=e,r=i.compositions?.[0]?.duration??0;return t+Math.round(r*(s??30))},0)}setProgress(t){void 0!==t?.completedTaskPercentArray&&f(this,Vt,t.completedTaskPercentArray),void 0!==t?.currentTaskFrameIndex&&f(this,kt,t.currentTaskFrameIndex),void 0!==t?.currentTaskTotalFrames&&f(this,Bt,t.currentTaskTotalFrames),void 0!==t?.currentTaskInTranscodingFrameIndex&&f(this,Ut,t.currentTaskInTranscodingFrameIndex),void 0!==t?.allTaskFrames&&f(this,Ft,t.allTaskFrames),this.emit("progress",this.progress)}forwardPlayerTime(t,e=!1){(0,w.assertExist)(this.player);const{oldTotalTime:i,startTime:s}=this.config;(0,w.assertExist)(i);const r=1e3*i-1e3*i%15;return t=Math.min(t,r/1e3),e?this.player.gotoAndPlay(t-s):this.player.gotoAndStop(t-s),t}getWavAudio(t){f(this,St,new re),g(this,bt)?g(this,bt).writeFile(t,g(this,St).getBuffer()):gt("log",[...ae,"getWavAudio"],"ffmpegCore is not ready")}async getImagesZip(t,e){const i=new Nt.default,s=i.folder(t);return(0,w.assertExist)(s),g(this,Tt).forEach((t,i)=>{s.file(t,e[i])}),i.generateAsync({type:"arraybuffer"})}getWebP(){(0,w.assertExist)(g(this,Ct));const t=Math.round(1e3/this.config.fps/1),e="out.webp",i=`${g(this,Tt).join(` -d ${t} `)} -d ${t} -o ${e} -loop ${this.config.loop?0:1}`.split(" "),s=g(this,Ct).cwrap("main","string",["number","number"]),[r,a]=function(t,e){const i=t._malloc(e.length*Uint32Array.BYTES_PER_ELEMENT);return e.forEach((e,s)=>{const r=t._malloc(e.length+1);t.writeAsciiToMemory(e,r),t.setValue(i+Uint32Array.BYTES_PER_ELEMENT*s,r,"i32")}),[e.length,i]}(g(this,Ct),i);dt(r&&a,"getWebP has error"),s(r,a);const o=g(this,Ct).FS.readFile(e);return g(this,Tt).forEach(t=>{g(this,Ct)?.FS.unlink(t)}),o}async getAPNG(){(0,w.assertExist)(g(this,bt));this.stage=qt;const t="export.apng";if(0!==await g(this,bt).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-plays",this.config.loop?"0":"1","-y",t]))throw new Error("the command executed by ffmpeg to generate a apng failed.");return t}async getGIF(){(0,w.assertExist)(g(this,bt));this.stage=qt;const t="export.gif";if(0!==await g(this,bt).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-loop",this.config.loop?"0":"-1","-vf","scale=-1:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse","-y",t]))throw new Error("the command executed by ffmpeg to generate a gif failed.");return t}async getMP4(t,e){(0,w.assertExist)(g(this,bt));this.stage=qt;const i="export.mp4";let s;const r=e?",setpts=PTS/"+Math.round(t/e*100)/100:"",a=e??t;this.config.audioEnable&&!g(this,St)&&(f(this,zt,"audio.wav"),this.getWavAudio(g(this,zt)));if(0!==await g(this,bt).exec(["-framerate",String(this.config.fps),"-start_number",String(1),"-i",`image-%4d.${this.transImageType}`,"-c:v","libx264","-crf","23","-pix_fmt","yuv420p","-vf",`pad=ceil(iw/2)*2:ceil(ih/2)*2${r}`,"-y",i]))throw new Error("the command executed by ffmpeg to generate a mp4 failed.");if(g(this,zt)&&g(this,St)){this.stage=Jt,s="export-with-audio.mp4";if(0!==await g(this,bt).exec(["-i",i,"-i",g(this,zt),"-c:v","copy","-c:a","aac","-t",`${a}`,"-y",s]))throw new Error("the command executed by ffmpeg to generate a audio of video failed.")}return s&&g(this,bt).deleteFile(i).catch(()=>{gt("log",[...ae,"ffmpeg delete file error"])}),s??i}async getAlphaMaskVideo(t,e){(0,w.assertExist)(g(this,bt));this.stage=qt;const i="export.mp4",s=e?",setpts=PTS/"+Math.round(t/e*100)/100:"";return await g(this,bt).exec(["-framerate",String(this.config.fps),"-start_number",String(1),"-i",`image-%4d.${this.transImageType}`,"-c:v","libx264","-crf","23","-pix_fmt","yuv420p","-vf",`pad=ceil(iw/2)*2:ceil(ih/2)*2${s}`,"-y",i]),i}async getVideoByType(t,e){(0,w.assertExist)(g(this,bt));const i=this.mediaType===jt.APNG,s=this.mediaType===jt.GIF,r=this.mediaType===jt.AlphaMaskVideo,a=this.mediaType===jt.MP4;let o="";try{i&&(o=await this.getAPNG()),s&&(o=await this.getGIF()),a&&(o=await this.getMP4(t,e)),r&&(o=await this.getAlphaMaskVideo(t,e)),this.stage=$t}catch(t){throw t}finally{for(const t of g(this,Tt))t&&g(this,bt).deleteFile(t)}let n=null;try{(0,w.assertExist)(o);const t=await g(this,bt).readFile(o);n="string"==typeof t?(new TextEncoder).encode(t):new Uint8Array(t)}finally{g(this,bt).deleteFile(o).catch(()=>{gt("log",[...ae,"ffmpeg delete file error"])})}return n}onRecordWebM(t){const e=new MediaRecorder(t.captureStream(this.config.fps),{mimeType:"video/webm;codecs=vp9"});f(this,Et,e),g(this,Et).start(0);const i=[];g(this,Et).ondataavailable=t=>{t.data.size>0&&i.push(t.data)},f(this,At,i)}async onExportImageFrame(t){try{if(this.canceled)return;const{canvas:s,imageBuffers:r,startTime:a,oldTotalTime:o,newTotalTime:n}=t;(0,w.assertExist)(this.player),(0,w.assertExist)(g(this,It));const c=g(this,kt)+1;this.stage=Yt,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:c}),this.loggerInTranscoding&&gt("log",[...ae,"converting log"],`converting ${c} frame image`),c>=1&&this.forwardPlayerTime(c/this.config.fps+a),xt(g(this,It),s,this.config.backgroundColor);let h=s;this.mediaType===jt.AlphaMaskVideo&&((0,w.assertExist)(this.extraCanvas),function(t,e){e.width=2*t.width,e.height=t.height;const i=t.getContext("2d");if(!i)throw new Error("inputCtx is null");const s=e.getContext("2d");if(!s)throw new Error("ctx is null");s.clearRect(0,0,e.width,e.height);const r=i.getImageData(0,0,t.width,t.height),a=i.getImageData(0,0,t.width,t.height),o=r.data;for(let t=0;t<o.length;t+=4){const e=Math.max(0,(o[t+3]??0)-5)/250*255;e<=0?(o[t]=0,o[t+1]=0,o[t+2]=0,o[t+3]=255):(o[t]=(o[t]??0)*e/255,o[t+1]=(o[t+1]??0)*e/255,o[t+2]=(o[t+2]??0)*e/255,o[t+3]=255)}s.putImageData(r,0,0);const n=a.data;for(let t=0;t<n.length;t+=4){const e=Math.max(0,(n[t+3]??0)-5)/250*255;n[t]=e,n[t+1]=e,n[t+2]=e,n[t+3]=255}s.putImageData(a,t.width,0)}(s,this.extraCanvas),h=this.extraCanvas);const p=await async function(t,e,i){return new Promise((s,r)=>{t.toBlob(t=>{t?s(t.arrayBuffer()):r("toBlob failed")},e,i)})}(h,`image/${this.transImageType}`,1),l=`image-${e=c,i=4,String(e).padStart(i,"0")}.${this.transImageType}`;this.mediaType===jt.Images?r.push(p):this.mediaType===jt.WebP?((0,w.assertExist)(g(this,Ct)),g(this,Ct).FS.writeFile(l,new Uint8Array(p))):((0,w.assertExist)(g(this,bt)),await g(this,bt).writeFile(l,new Uint8Array(p))),g(this,Tt).push(l);if(c===g(this,Bt)){this.player?.pause(),await new Promise(t=>{window.requestAnimationFrame(t)});let t=null;"Images"===this.mediaType?t=await this.getImagesZip(this.config.name,r):"WebP"===this.mediaType?t=this.getWebP():[jt.MP4,jt.APNG,jt.GIF,jt.AlphaMaskVideo].includes(this.mediaType)&&(t=await this.getVideoByType(o,n)??null),t&&(gt("log",[...ae,"done"],"success"),this.emit("done",g(this,Mt),!0,t))}else f(this,Dt,window.requestAnimationFrame(()=>{this.canceled||this.onExportImageFrame({canvas:s,imageBuffers:r,startTime:a,oldTotalTime:o,newTotalTime:n})}))}catch(t){gt("log",[...ae,"onExportImageFrame","failed"],t),this.emit("done",g(this,Mt),!1)}var e,i}async onExportWebMFrame(t){try{if(this.canceled)return;(0,w.assertExist)(this.player),(0,w.assertExist)(g(this,It));const e=g(this,kt)+1;if(this.stage=Yt,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:e}),this.loggerInTranscoding&&gt("log",[...ae,"converting log"],`converting ${e} frame image`),xt(g(this,It),t,this.config.backgroundColor),1===e&&(this.player.play(),this.onRecordWebM(t)),e<g(this,Bt))f(this,Dt,window.requestAnimationFrame(()=>{this.canceled||this.onExportWebMFrame(t)}));else{this.player?.pause(),g(this,Et)?.stop();const t=new Blob(g(this,At),{type:"video/webm"}),e=await t.arrayBuffer();gt("log",[...ae,"done"],"success"),this.emit("done",g(this,Mt),!0,e)}}catch(t){gt("log",[...ae,"done"],"failed",t),this.emit("done",g(this,Mt),!1)}}async runTask(t){try{if(this.canceled)return;(0,w.assertExist)(this.player),(0,w.assertExist)(g(this,It));const{size:e,startTime:i,containerCanvas:s}=t,{oldTotalTime:r,newTotalTime:a}=this.config,[o,n]=e;if(g(this,It).width=o,g(this,It).height=n,s.width=o,s.height=n,this.player.resize(),f(this,Tt,[]),[jt.MP4,jt.APNG,jt.Images,jt.WebP,jt.GIF,jt.AlphaMaskVideo].includes(this.mediaType)){const t={canvas:s,imageBuffers:[],startTime:i,oldTotalTime:r,newTotalTime:a};await this.onExportImageFrame(t)}else"WebM"===this.mediaType&&await this.onExportWebMFrame(s)}catch(t){gt("log",[...ae,"run task error"],t),this.emit("done",g(this,Mt),!1)}}clearTaskInfo(){f(this,_t,0),f(this,Mt,void 0),f(this,Vt,[]),f(this,kt,0),f(this,Bt,0),f(this,Ft,0),f(this,Ut,0),f(this,Rt,[]),f(this,Wt,!0)}clearFFMpegCore(){if(g(this,bt)){for(const t of g(this,Tt))t&&g(this,bt).deleteFile(t);f(this,Tt,[]),g(this,bt).terminate(),f(this,bt,void 0)}}clearImage2WebPCore(){g(this,Ct)&&(g(this,Ct).FS.quit(),f(this,Ct,void 0))}clearMediaRecorder(){g(this,Et)&&(g(this,Et).stop(),f(this,Et,void 0)),f(this,At,[])}clearAllListeners(){for(const t of this.getListeners("ready"))this.off("ready",t);for(const t of this.getListeners("progress"))this.off("progress",t);for(const t of this.getListeners("done"))this.off("done",t);for(const t of this.getListeners("finish"))this.off("finish",t);for(const t of this.getListeners("error"))this.off("error",t)}onCancel(){this.canceled||(this.onFinish(!1,g(this,Rt)),this.status=Ot,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),gt("log",ae,"canceled"))}async onExport(t){const e=t.length;try{if(this.status===Lt)return gt("log",[...ae],"readying"),void this.on("ready",()=>{this.onExport(t)});if(this.status===Ot){if(await this.onInit()===Ot)throw new Error("init environment failed")}if(this.clearTaskInfo(),!g(this,It)){const t=document.createElement("canvas");t.dataset.key="player-canvas",f(this,It,t)}this.player||(this.player=new w.Player({canvas:g(this,It),pixelRatio:1,transparentBackground:!0,renderOptions:{willCaptureImage:!0}}),this.player.on("rendererror",t=>{this.onError(t)}),this.player.on("webglcontextlost",t=>{this.onError(t)}));let e=null;e??(e=document.querySelector('canvas[data-key="container-canvas"]')),e??(e=document.createElement("canvas")),e.dataset.key="container-canvas",e.style.display="none",this.setProgress({allTaskFrames:this.getAllTaskFrames(t)});const i=[];let s=!0;for(const[r,a]of t.entries()){if(this.canceled){s=!1;break}f(this,_t,r),f(this,Mt,a);const{size:t,scene:o}=a;await new Promise(async n=>{try{if(!this.player)throw new Error("player not found");gt("log",[...ae,"export"],"start",a),Pt(this.player),await this.player.loadScene(o,{env:"editor",autoplay:!1});const c=this.config.oldTotalTime,h=0;this.player.pause(),this.setProgress({currentTaskFrameIndex:0,currentTaskTotalFrames:Math.round(c*this.config.fps)});const p=(t,e,a)=>{this.off("done",p),e&&a?i[r]=a:s=!1,n()};this.on("done",p);const l={size:t,startTime:h,containerCanvas:e};await this.runTask(l)}catch(t){gt("log",[...ae,"export error"],t),s=!1,n()}})}f(this,Rt,i),f(this,Wt,s)}catch(t){this.onError(t),f(this,Wt,!1)}e>=1&&g(this,Wt)?this.onFinish(!0,g(this,Rt)):this.onFinish(!1,g(this,Rt))}dispose(){this.status=Ot,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),this.player?.dispose(),this.player=void 0,g(this,It)?.remove(),f(this,It,void 0),f(this,zt,void 0),f(this,St,void 0)}};Dt=new WeakMap,It=new WeakMap,bt=new WeakMap,Ct=new WeakMap,Et=new WeakMap,At=new WeakMap,St=new WeakMap,zt=new WeakMap,Tt=new WeakMap,_t=new WeakMap,Mt=new WeakMap,Vt=new WeakMap,kt=new WeakMap,Bt=new WeakMap,Ft=new WeakMap,Ut=new WeakMap,Rt=new WeakMap,Wt=new WeakMap;var ne=class extends w.EventEmitter{constructor(t){super(),m(this,"_config"),m(this,"_status",te),m(this,"_exportMedia"),this._config=t,this._exportMedia=new oe(t)}get status(){return this._status}onExportMP4(t,e){const i=t[0]?.folderName,s=new Ht.default;e.forEach((e,i)=>{if(!e)return;const{name:r}=t[i]??{};r&&s.file(`${r}.mp4`,e)}),s.generateAsync({type:"blob"}).then(t=>{ut(t,`${i}.zip`,"application/zip")}).catch(t=>{gt("error",["@vvfx/sdk"],"export mp4 is error",t)})}onExportGIF(t,e){const i=t[0]?.folderName,s=new Ht.default;e.forEach((e,i)=>{if(!e)return;const{name:r}=t[i]??{};r&&s.file(`${r}.gif`,e)}),s.generateAsync({type:"blob"}).then(t=>{ut(t,`${i}.zip`,"application/zip")}).catch(t=>{gt("error",["@vvfx/sdk"],"export gif is error",t)})}onExportImages(t,e){const i=t[0]?.folderName,s=new Ht.default;e.forEach((e,i)=>{if(!e)return;const{name:r}=t[i]??{};r&&s.file(`${r}.zip`,e)}),s.generateAsync({type:"blob"}).then(t=>{ut(t,`${i}.zip`,"application/zip")}).catch(t=>{gt("error",["@vvfx/sdk"],"export Images is error",t)})}onExportProgress(t){this.emit("progress",t)}onExportDone(t,e,i){this.emit("done",t,e,i)}onExportError(t){this._status=se,gt("error",["@vvfx/sdk"],"export is error",t)}onExport(t){this._status=ee,this._exportMedia.onExport(t),this._exportMedia.on("progress",this.onExportProgress.bind(this)),this._exportMedia.on("done",this.onExportDone.bind(this)),this._exportMedia.once("finish",(e,i)=>{this._status=e?ie:se,this.emit("complete",e),i&&0!==i.length&&(this._config.mediaType===jt.MP4?this.onExportMP4(t,i):this._config.mediaType===jt.GIF?this.onExportGIF(t,i):this._config.mediaType===jt.Images&&this.onExportImages(t,i))}),this._exportMedia.on("error",this.onExportError.bind(this))}onCancel(){this._status=se,this._exportMedia.onCancel(),this.emit("complete",!1)}dispose(){this._exportMedia.dispose()}},ce=class{constructor(){m(this,"enabled",!0),m(this,"_player"),m(this,"_container"),this._container=document.createElement("canvas"),this._player=new w.Player({canvas:this._container,manualRender:!0,renderOptions:{willCaptureImage:!0}})}async generate(t,e,i,s,r){if(!this.enabled)return void console.warn("Screen shot is not opened, use #SDK.setConfig() open this feature.");const[a,o]=e;this._container.width=a,this._container.height=o,this._player.resize();const n=JSON.parse(JSON.stringify(t));await this._player.loadScene(n,{reusable:!0,autoplay:!1}),this._player.gotoAndStop(s);const[c,h]=i,p=document.createElement("canvas");p.width=c,p.height=h;const l=p.getContext("2d");l&&(l.fillStyle="rgba(255, 255, 255, 1)",l.fillRect(0,0,c,h),this.drawImageCover(l,this._player.canvas,0,0,c,h,.5,.5));const m=p.toDataURL("image/png");return Pt(this._player),m}dispose(){this._player.dispose()}drawImageCover(t,e,i,s,r,a,o,n,c){2===arguments.length&&(i=s=0,r=t.canvas.width,a=t.canvas.height),o="number"==typeof o?b(o,0,1):.5,n="number"==typeof n?b(n,0,1):.5,c??(c={left:0,top:0,width:e instanceof HTMLVideoElement?e.videoWidth:e.width,height:e instanceof HTMLVideoElement?e.videoHeight:e.height});const h=c.width,p=c.height,l=Math.min(r/h,a/p);let m=h*l,d=p*l,g=1;m<r&&(g=r/m),Math.abs(g-1)<1e-14&&d<a&&(g=a/d),m*=g,d*=g;const u=Math.max(h/(m/r),0),f=Math.max(p/(d/a),0),y=Math.min((h-u)*o,h),w=Math.min((p-f)*n,p);t.drawImage(e,y+c.left,w+c.top,u,f,i,s,r,a)}},he={topAdsorption:"T",leftAdsorption:"L",rightAdsorption:"R",bottomAdsorption:"B",centerAdsorption:"C",bottomCenterAdsorption:"BC"},pe=class{constructor(t){m(this,"_player"),m(this,"_container"),m(this,"size",[0,0]),m(this,"_pageDataUtils"),this._container=document.createElement("canvas"),this._player=new w.Player({canvas:this._container,manualRender:!0}),this._pageDataUtils=t}async adjustment(t,e,i,s,r,a){if(!me.config.sizeAdaptConfig.enabled)return console.warn("Size adapt is not opened, use #SDK.setConfig() open this feature."),t;this._player??(this._player=new w.Player({canvas:this._container,manualRender:!0})),r??(r=[0,0,0,0]),a??(a=i[0]<i[1]?"y":"x"),this.size=[...s],this._container.width=this.size[0],this._container.height=this.size[1],Pt(this._player),this._player.resize();const o=JSON.parse(JSON.stringify(t));await this._player.loadScene(o,{reusable:!0,autoplay:!1}),this._player.gotoAndStop(e);const n=this._player.getCompositions()[0];if(n){const[e,o]=s,c=i[0]/i[1],h=e/o;c>h&&this.keepDistribute(t,n,h/c,s);const[p,l,m,d]=r,g=e-m-d,u=o-p-l,f=[(m-d)/2,(p-l)/2],y=(new V).setFromCenterAndSize(new _(e,o).divide(2),new _(e,o)),w=(new V).setFromCenterAndSize(new _(e,o).divide(2).add(new _(...f)),new _(g,u));this.keepAdsorption("topAdsorption",t,n,f,y,w,a),this.keepAdsorption("bottomAdsorption",t,n,f,y,w,a),this.keepAdsorption("leftAdsorption",t,n,f,y,w,a),this.keepAdsorption("rightAdsorption",t,n,f,y,w,a),this.keepAdsorption("centerAdsorption",t,n,f,y,w,a),this.keepDoubleAdsorption("bottomCenterAdsorption",t,n,f,y,w)}return t}keepDistribute(t,e,i,s){const r=t=>{const i=(new U).copyFrom(e.camera.getViewProjectionMatrix());return(new _).copyFrom(t.applyMatrix(i).toVector2()).toViewCoordinate(s[0],s[1])};["topAdsorption","centerAdsorption","bottomAdsorption"].forEach(a=>{e.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===he[a]&&!t.parentId).forEach(a=>{const o=e.items.filter(t=>t.parentId===a.getInstanceId()),n=o.find(t=>"check-area"===t.name),c=n?this.getViewBoxByHeadlessPlayerItem(n,[],r):this.getViewBoxByHeadlessPlayerItem(a,o,r),h=a.transform.position.clone(),p=c.getCenter(),l=new _(...s.map(t=>t/2)),m=p.y-l.y;((t,i,r)=>{const{z:a}=t.transform.getWorldPosition(),{x:o,y:n}=e.camera.getInverseVPRatio(a);t.transform.translate(2*i*o/s[0],-2*r*n/s[1],0)})(a,0,m/i-m),a.transform.updateLocalMatrix();const d=a.transform.position.clone().subtract(h).toArray();this._pageDataUtils.changeSceneItemProperty(t,{itemId:a.getInstanceId(),type:a.type,propertyName:"position",propertyValue:d})})})}keepAdsorption(t,e,i,s,r,a,o){const{x:n,y:c}=r.getSize(),h=(t,e,s)=>{const{z:r}=t.transform.getWorldPosition(),{x:a,y:o}=i.camera.getInverseVPRatio(r);t.transform.translate(2*e*a/n,-2*s*o/c,0)},p=t=>{const e=(new U).copyFrom(i.camera.getViewProjectionMatrix());return(new _).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(n,c)},l=he[t];i.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===l&&!t.parentId).forEach(r=>{const n=i.items.filter(t=>t.parentId===r.getInstanceId()),c=n.find(t=>"check-area"===t.name),l=r.transform.position.clone(),m=["leftAdsorption","rightAdsorption"].includes(t)?"x":"y",d=["leftAdsorption","topAdsorption"].includes(t)?1:-1,g=["leftAdsorption","topAdsorption"].includes(t)?"min":"max",u=["leftAdsorption","topAdsorption"].includes(t)?"max":"min",f=3===r.name.split("-").length,y=Number(r.name.split("-")[1]),w=new _,x=[1,1],v=c?this.getViewBoxByHeadlessPlayerItem(c,[],p):this.getViewBoxByHeadlessPlayerItem(r,n,p);h(r,...s),v.getSize().x>a.getSize().x&&(x[0]=a.getSize().x/v.getSize().x,x[1]=a.getSize().x/v.getSize().x,r.scale(...x,1)),r.transform.updateLocalMatrix();const P=c?this.getViewBoxByHeadlessPlayerItem(c,[],p):this.getViewBoxByHeadlessPlayerItem(r,n,p),D=new _;if(!a.containsBox(P)){const{min:t,max:e}=P,{min:i,max:s}=a;D.x+=t.x<i.x?i.x-t.x:0,D.x+=e.x>s.x?s.x-e.x:0,D.y+=t.y<i.y?i.y-t.y:0,D.y+=e.y>s.y?s.y-e.y:0,h(r,...D.toArray()),r.transform.updateLocalMatrix()}const I=c?this.getViewBoxByHeadlessPlayerItem(c,[],p):this.getViewBoxByHeadlessPlayerItem(r,n,p);if(!Number.isNaN(y)&&f)if("centerAdsorption"!==t){const t=Math.abs(I[u][m]-a[g][m]),e=a.getSize()[m]*y;t>e&&(w[m]=(e-t)*d,h(r,...w.toArray()),r.transform.updateLocalMatrix())}else{const t=I.getSize()[o],e=a.getSize()[o];if(t/e>y){const i=e*y/t;r.scale(i,i,1),x[0]*=i,x[1]*=i}}const b=c?this.getViewBoxByHeadlessPlayerItem(c,[],p):this.getViewBoxByHeadlessPlayerItem(r,n,p),C=i.items.filter(t=>"T"===t.name.split("-")[0]?.toLocaleUpperCase()&&!t.parentId),E=new V;if(C.forEach(t=>{const e=i.items.filter(e=>e.parentId===t.getInstanceId()),s=e.find(t=>"check-area"===t.name),r=s?this.getViewBoxByHeadlessPlayerItem(s,[],p):this.getViewBoxByHeadlessPlayerItem(t,e,p);E.union(r)}),!E.isEmpty()&&E.max.y>b.min.y)if("centerAdsorption"===t){const t=E.max.y-b.min.y;h(r,0,t),r.transform.updateLocalMatrix()}else if(["leftAdsorption","rightAdsorption"].includes(t)){const t=b.getSize().y,e=a.getSize().y-(E.max.y-a.min.y);let i=E.max.y-b.min.y;if(t>e){const s=e/t;x[0]*=s,x[1]*=s,r.scale(s,s,1),r.transform.updateLocalMatrix(),i-=(t-e)/2}h(r,0,i),r.transform.updateLocalMatrix()}const A=r.transform.position.clone().subtract(l).toArray();this._pageDataUtils.changeSceneItemProperty(e,{itemId:r.getInstanceId(),type:r.type,propertyName:"position",propertyValue:A}),this._pageDataUtils.changeSceneItemProperty(e,{itemId:r.getInstanceId(),type:r.type,propertyName:"size",propertyValue:x})})}keepDoubleAdsorption(t,e,i,s,r,a){const{x:o,y:n}=r.getSize(),c=(t,e,s)=>{const{z:r}=t.transform.getWorldPosition(),{x:a,y:c}=i.camera.getInverseVPRatio(r);t.transform.translate(2*e*a/o,-2*s*c/n,0)},h=t=>{const e=(new U).copyFrom(i.camera.getViewProjectionMatrix());return(new _).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(o,n)},p=he[t];i.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===p&&!t.parentId).forEach(t=>{const r=i.items.filter(e=>e.parentId===t.getInstanceId()),o=r.find(t=>"check-area"===t.name),n=t.transform.position.clone(),p=3===t.name.split("-").length,l=Number(t.name.split("-")[1]),m=[1,1],d=o?this.getViewBoxByHeadlessPlayerItem(o,[],h):this.getViewBoxByHeadlessPlayerItem(t,r,h);c(t,...s),d.getSize().x>a.getSize().x&&(m[0]=a.getSize().x/d.getSize().x,m[1]=a.getSize().x/d.getSize().x,t.scale(...m,1)),t.transform.updateLocalMatrix();const g=o?this.getViewBoxByHeadlessPlayerItem(o,[],h):this.getViewBoxByHeadlessPlayerItem(t,r,h);if(!Number.isNaN(l)&&p){const e=g.getSize().y,i=a.getSize().y;if(e/i>l){const s=i*l/e;t.scale(s,s,1),m[0]*=s,m[1]*=s}}const u=o?this.getViewBoxByHeadlessPlayerItem(o,[],h):this.getViewBoxByHeadlessPlayerItem(t,r,h),f=new _;if(!a.containsBox(u)){const{min:e,max:i}=u,{min:s,max:r}=a;f.x+=e.x<s.x?s.x-e.x:0,f.x+=i.x>r.x?r.x-i.x:0,f.y+=e.y<s.y?s.y-e.y:0,f.y+=i.y>r.y?r.y-i.y:0,c(t,...f.toArray()),t.transform.updateLocalMatrix()}const y=t.transform.position.clone().subtract(n).toArray();this._pageDataUtils.changeSceneItemProperty(e,{itemId:t.getInstanceId(),type:t.type,propertyName:"position",propertyValue:y}),this._pageDataUtils.changeSceneItemProperty(e,{itemId:t.getInstanceId(),type:t.type,propertyName:"size",propertyValue:m})})}getViewBoxByHeadlessPlayerItem(t,e,i){const s=new V,{transform:r,composition:a}=t;switch(t.type){case w.spec.ItemType.sprite:case w.spec.ItemType.plugin:case w.spec.ItemType.video:case w.spec.ItemType.richtext:case w.spec.ItemType.text:case w.spec.ItemType.shape:{r.setValid(!0),r.updateLocalMatrix();const{size:t}=r,o=(new U).copyFrom(a?.transform.getWorldMatrix()??new U).invert().multiply(r.getWorldMatrix()),{x:n,y:c}=t.clone().divide(2),h=new F(n,c,0).applyMatrix(o),p=new F(n,-c,0).applyMatrix(o),l=new F(-n,-c,0).applyMatrix(o),m=new F(-n,c,0).applyMatrix(o),d=i(h).round(2),g=i(p).round(2),u=i(l).round(2),f=i(m).round(2);s.setFromVec2Array([d,g,u,f]);const y=e?.map(t=>{const e=a?.items.filter(e=>e.parentId===t.getInstanceId())??[];return this.getViewBoxByHeadlessPlayerItem(t,e,i)});y&&y.map(t=>s.union(t));break}case w.spec.ItemType.null:{const t=e?.map(t=>{const e=a?.items.filter(e=>e.parentId===t.getInstanceId())??[];return this.getViewBoxByHeadlessPlayerItem(t,e,i)});t&&t.map(t=>s.union(t));break}}return s}dispose(){this._player?.dispose()}},le=class t{constructor(e){m(this,"_eventEmitter",new w.EventEmitter),m(this,"_pageData"),m(this,"_screenShot"),m(this,"_exporter"),m(this,"_pageDataUtils"),m(this,"_sizeAdapt"),m(this,"_gestureHandler"),m(this,"disposables",[]),m(this,"_isSwitchScene",!1),m(this,"player"),m(this,"_playerContainer"),m(this,"on",this._eventEmitter.on);const[i,s]=[e.offsetWidth,e.offsetHeight],r=document.createElement("div");r.id="player-container",r.style.width=`${i}px`,r.style.height=`${s}px`,r.style.position="absolute",r.style.backgroundRepeat="no-repeat",r.style.backgroundPosition="center center",e.appendChild(r),this._playerContainer=r,this.player=new w.Player({container:r,interactive:!0,pixelRatio:window.devicePixelRatio||1}),this.player.on("update",()=>{if((0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._isSwitchScene)return;const t=this.player.getCompositions()[0]?.time;if(this._pageData.playing)if(void 0!==t)this._pageData.time===t&&this.player.pause(),this._pageData.time=t,this._pageDataUtils.refreshPageTime(t);else{this._pageData.playing=!1,this.setPlayProgress(100);const t=this._pageData.viewProperties[this._pageData.activeData.view??0]?.scene,e=t?.compositions.find(e=>e.id===t.compositionId);this._pageData.time=e?.duration??2,this._pageDataUtils.refreshPageTime(this._pageData.time)}this._eventEmitter.emit("progress",{duration:this.player.getCompositions()[0]?.getDuration()??2,time:this._pageData.time,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!this._pageData.playing})}),this._eventEmitter.on("pageDataChange",t=>{this._pageData=t,this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("zoomChange",t=>{(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.property.zoom=t,this._pageDataUtils.refreshInteractionParam(),this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("selectedItemChange",t=>{(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems=[...t],this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("preSelectedItemChange",t=>{(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t,this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("selectedViewChange",t=>{(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.view=t;const e=this._pageData.viewProperties[t];this._gestureHandler.ignoreInteraction=!!e?.ignoreInteraction}),this._eventEmitter.on("sdkConfigChange",(t,e)=>{this._exporter&&!ft(t.exportVideoConfig,e.exportVideoConfig)&&(this._exporter.dispose(),this.initExporter(e.exportVideoConfig))}),this._pageDataUtils=new Gt(this.player,r,this._eventEmitter,this),this.initExporter(t.config.exportVideoConfig),this._gestureHandler=new nt(e),this._gestureHandler.registerViewEvent(),this._screenShot=new ce,this._sizeAdapt=new pe(this._pageDataUtils);const a=new ResizeObserver(()=>{const t=[e.offsetWidth,e.offsetHeight],i=this._pageData?.viewProperties[this._pageData.activeData.view??0];if(!i)return;const{size:s}=i,[r,a]=this._pageDataUtils.getPlayerSizeByParent(t,s);this._playerContainer.style.width=`${r}px`,this._playerContainer.style.height=`${a}px`,this.player.resize(),this._gestureHandler.resize()});a.observe(e),this.disposables.push(()=>{a.disconnect()})}get pageData(){return this._pageData}get exportStatus(){return this?._exporter?.status}get exportOptions(){if(!this.pageData)return[];const t=this.pageData.viewProperties.filter(t=>!t.ignoreInteraction),e=t[0]?.scene?.compositions?.[0]?.name??"videos",i=[];return t.map((t,s)=>{const{size:r,scene:a,export:{name:o,time:n,audioEnable:c,fps:h}}=t,p=r?.[0]&&r?.[1]?` (${s+1})_${r[0]}×${r[1]}`:` (${s+1})`;let l="";return l=o?function(t,e){if(!e.includes(t))return t;let i=1,s=`${t} (${i})`;for(;e.includes(s);)i++,s=`${t} (${i})`;return s}(o,i):`${e}${p}`,i.push(l),{folderName:e,name:l,size:r,fps:h,scene:JSON.parse(JSON.stringify(a)),time:n,audioEnable:c}})}dispose(){this.player?.dispose(),this._screenShot?.dispose(),this._pageData=void 0,this._playerContainer.remove(),this?._exporter?.dispose(),this._screenShot.dispose(),this._gestureHandler.dispose(),this.disposables.forEach(t=>{t()})}async getInitParam(t){const e=JSON.parse(JSON.stringify(t));if("string"==typeof e.scene)try{const t=await fetch(e.scene,{mode:"cors",credentials:"omit",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}, statusText: ${t.statusText}`);const i=await t.json();return{...e,scene:i}}catch(t){throw new Error(`Failed to fetch scene data from ${e.scene}: ${t instanceof Error?t.message:String(t)}`)}return{...e,scene:e.scene}}initExporter(t){this._exporter=new ne(t),this._exporter.on("progress",t=>{this._eventEmitter.emit("exportProgress",t)}),this._exporter.on("done",(t,e,i)=>{this._eventEmitter.emit("exportDone",t,e,i)}),this._exporter.on("complete",t=>{this._eventEmitter.emit("exportComplete",t)})}async initSDK(e){var i;const{scene:s,viewParams:r,options:a}=e,o=[];if(t.config.pageConfig.staticPreview){const t=JSON.parse(JSON.stringify(s)),e=t.compositions.find(e=>e.id===t.compositionId)??t.compositions[0];if(e){const[i,s]=e.previewSize??[1080,1920],r=e.duration??0;o.push({size:[i,s],safeArea:[0,0,0,0],previewSafeAreas:[],id:0,scene:t,ignoreInteraction:!0,export:{time:r,fileSizeLimit:1,audioEnable:!1}})}}for(let e=0;e<r.length;e++){const a=r[e];if(!a)continue;let n=JSON.parse(JSON.stringify(s));const c=n.compositions.find(t=>t.id===n.compositionId)??n.compositions[0];(0,w.assertExist)(c);const h=c.previewSize??[750,1624],p=h,[l,m]=a.size??h;c.previewSize=[l,m];const d=c.duration??0,g=a.safeArea??[0,0,0,0];t.config.sizeAdaptConfig.enabled&&(n=await this._sizeAdapt.adjustment(n,d,p,[l,m],g,a.adaptionDirection)),(i=a.export).time??(i.time=d),o.push({...a,size:h,safeArea:g,previewSafeAreas:[...a.previewSafeAreas??[]],id:e+1,scene:n,ignoreInteraction:!1})}const n=o[0]?.scene;if(!n)return void console.warn("SDK need a view property at least.");const c=n.compositions.find(t=>t.id===n.compositionId)??n.compositions[0],h={...a,zoom:1,translation:[0,0],asyncMode:a.asyncMode??!1},p=(c?.duration??0)-.1;this._pageData={scene:JSON.parse(JSON.stringify(s)),time:p,property:h,activeData:{selectedItems:[]},items:[],viewProperties:o,playing:!1},this._pageDataUtils.init(),this._gestureHandler.init(this._pageDataUtils),this._gestureHandler.ignoreInteraction=!!o[0]?.ignoreInteraction,t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaEnabled=h.safeAreaPreview,this._eventEmitter.emit("progress",{duration:p,time:p,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!this._pageData.playing}),await this._pageDataUtils.loadScene(0),this._pageDataUtils.refreshPageTime(p)}async run(t){const e=await this.getInitParam(t);await this.initSDK(e),this._eventEmitter.emit("pageDataChange",this.getPageData())}getPageData(){return JSON.parse(JSON.stringify(this._pageData))}getActiveItems(){return(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems}setPreSelectedItem(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t}getPreSelectedItem(){return(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem??""}setSelectedItems(t){this._pageDataUtils.clearPreSelectedItem(),this._pageDataUtils.clearSelectedItems(),this._pageDataUtils.addSelectedItems([...t])}getItemProperty(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const e=this._pageData.items.find(e=>e.id===t.itemId);if(e&&e.type===t.type)return{type:e.type,property:e.property}}getItemPropertyValue(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const e=this.getItemProperty(t)?.property?.[t.propertyName];return e}async setItemPropertyValue(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const e=this._pageData.viewProperties[this._pageData.activeData.view??0]?.ignoreInteraction;e?console.warn("Static scene cannot change."):(await this._pageDataUtils.changeItemProperty(t),this._gestureHandler.refresh(),this._gestureHandler.render(),this._eventEmitter.emit("pageDataChange",this.getPageData()))}async generateScreenShot(t,e=[300,400],i){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const s=this.pageData?.viewProperties?.[t];if(!s)return"";const{scene:r,size:[a,o]}=s,n=r.compositionId,c=r.compositions.find(t=>t.id===n);i??(i=c?.duration??0);const h=JSON.parse(JSON.stringify(r));return await this._screenShot.generate(h,[a,o],e,i)}async switchScene(t){if((0,w.assertExist)(this._pageData,"You must call SDK#run() first"),t===this._pageData.activeData.view)return;this._isSwitchScene=!0;if(this._pageData.viewProperties[t]){const e=this._pageData.playing;this._pageData.activeData={view:t,selectedItems:[],preSelectedItem:void 0},await this._pageDataUtils.loadScene(t),e&&(this._pageData.playing=e,this.player.gotoAndPlay(this._pageData.time))}else console.warn("target scene does not exist.");this._eventEmitter.emit("selectedViewChange",t),this._eventEmitter.emit("pageDataChange",this.getPageData()),this._isSwitchScene=!1}getConfig(){return(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),{safeAreaPreview:this._pageData.property.safeAreaPreview,zoom:this._pageData.property.zoom,adsorption:this._pageData.property.adsorption,asyncMode:this._pageData.property.asyncMode}}setConfig(e){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const{adsorption:i,safeAreaPreview:s,zoom:r}=this._pageData.property;this._pageData.property={...this._pageData.property,...e},this._pageData.property.zoom!==r&&this._pageDataUtils.setPageZoom(this._pageData.property.zoom),i!==e.adsorption&&(t.config.gestureHandlerConfig.adsorptionGizmoEnabled=e.adsorption),s!==e.safeAreaPreview&&(t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaEnabled=e.safeAreaPreview),this._gestureHandler.refresh(),this._gestureHandler.render()}async setPlayProgress(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const e=(this.player.getCompositions()[0]?.getDuration()??2)*t/100;this._pageData.time=e;!this.player.getCompositions().length&&(Pt(this.player),await this._pageDataUtils.loadScene(this._pageData.activeData.view??0));this._pageData.playing?this.player.gotoAndPlay(e):(this.player.gotoAndStop(e),this._eventEmitter.emit("progress",{duration:this.player.getCompositions()[0]?.getDuration()??2,time:e,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!0})),this._pageDataUtils.refreshPageTime(e)}getViewItems(){return this.getPageData()?.items??[]}async setPlayState(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const e="play"===t;if(this._pageData.playing!==e){if(this._pageData.playing=e,this._gestureHandler.ignoreInteraction=e,e){const t=this.player.getCompositions();await this.player.loadScene(this._pageData.viewProperties[this._pageData.activeData.view].scene,{autoplay:!1}),this.player.gotoAndPlay(this._pageData.time),this.destroyCompositions(t)}else this.player.gotoAndStop(this._pageData.time);this._gestureHandler.refresh(),this._gestureHandler.render()}}getViewThumbnail(){return(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.viewProperties.map(t=>({id:t.id,thumbnail:this.generateScreenShot(t.id)}))}getViewScene(){return(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.viewProperties.map(t=>({id:t.id,thumbnail:t.scene}))}destroyCompositions(t){t.forEach(t=>{t.dispose();const e=this.player.getCompositions(),i=e.indexOf(t);i>-1&&e.splice(i,1)})}onExport(){t.config.exportVideoConfig.enabled&&((0,w.assertExist)(this.pageData,"You must call SDK#run() first"),(0,w.assertExist)(this._exporter,"You must init exporter first"),this._exporter.onExport(this.exportOptions))}cancelExport(){(0,w.assertExist)(this._exporter,"You must init exporter first"),this._exporter.onCancel()}async loadPageData(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData={view:this._pageData.viewProperties.length,selectedItems:[],preSelectedItem:void 0},this._pageData.viewProperties.push(...t.viewProperties),this._pageDataUtils.init(),this._gestureHandler.init(this._pageDataUtils),await this._pageDataUtils.loadScene(this.pageData?.activeData.view??0),this._eventEmitter.emit("pageDataChange",this.getPageData())}async runByPageData(t){const e=JSON.parse(JSON.stringify(t));e.property.zoom=1,e.property.translation=[0,0],this._pageData=e,this._pageDataUtils.init(),this._gestureHandler.init(this._pageDataUtils),await this._pageDataUtils.loadScene(this.pageData?.activeData.view??0),this._pageDataUtils.refreshPageTime(this._pageData.time),this._eventEmitter.emit("pageDataChange",this.getPageData())}async reloadPageDataByScene(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");let e=JSON.parse(JSON.stringify(t));if("string"==typeof e)try{const t=await fetch(e,{mode:"cors",credentials:"omit",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}, statusText: ${t.statusText}`);e=await t.json()}catch(t){throw new Error(`Failed to fetch scene data from ${e}: ${t instanceof Error?t.message:String(t)}`)}this._pageData.time=e.compositions.find(t=>t.id===e.compositionId)?.duration??2,this._pageData.viewProperties.forEach(t=>{t.scene=JSON.parse(JSON.stringify(e))}),this._pageDataUtils.init(),this._gestureHandler.init(this._pageDataUtils),await this._pageDataUtils.loadScene(this._pageData.activeData.view??0),this._eventEmitter.emit("progress",{duration:this.player.getCompositions()[0]?.getDuration()??2,time:this._pageData.time,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!this._pageData.playing})}async addViewParams(e){var i;(0,w.assertExist)(this._pageData);const s=[],r=this._pageData.viewProperties[this._pageData.viewProperties.length-1]?.id??this._pageData.viewProperties.length-1;for(let a=0;a<e.length;a++){const o=e[a];if(!o)continue;let n=JSON.parse(JSON.stringify(this._pageData.scene));const c=n.compositions.find(t=>t.id===n.compositionId)??n.compositions[0];(0,w.assertExist)(c);const{previewSize:h=[750,1624]}=c,p=h,[l,m]=o.size??h;c.previewSize=[l,m];const d=c.duration??0,g=o.safeArea??[0,0,0,0];t.config.sizeAdaptConfig.enabled&&(n=await this._sizeAdapt.adjustment(n,d,p,[l,m],g,o.adaptionDirection)),(i=o.export).time??(i.time=d),s.push({...o,size:h,safeArea:g,previewSafeAreas:[...o.previewSafeAreas??[]],id:r+1+a,scene:n,ignoreInteraction:!1})}this._pageData.viewProperties.push(...s),this._eventEmitter.emit("pageDataChange",this.getPageData())}async deleteViewParams(t){t.sort((t,e)=>t-e);for(let e=0;e<t.length;e++){const i=t[e];(0,w.assertExist)(this._pageData);const s=i-e,r=this._pageData.viewProperties.findIndex(t=>t.id===s);if(!1!==this._pageData.viewProperties[r]?.ignoreInteraction)return void console.warn("target view ignore interaction, it can not be deleted.");this._pageData.viewProperties.splice(r,1);const a=this._pageData.activeData.view??0;s===a?await this._pageDataUtils.loadScene(a):s<a&&(this._pageData.activeData.view=a-1,await this._pageDataUtils.loadScene(this._pageData.activeData.view)),this._pageData.viewProperties.forEach(t=>{t.id>s&&(t.id-=1)})}this._eventEmitter.emit("pageDataChange",this.getPageData())}setExportParam(t,e){(0,w.assertExist)(this._pageData),this._pageData.viewProperties.forEach(i=>{void 0!==e&&i.id!==e||(i.export=t)})}setPageZoom(t){(0,w.assertExist)(this._pageData),this._pageData.property.zoom=t,this._pageDataUtils.setPageZoom(this._pageData.property.zoom),this._gestureHandler.refresh(),this._gestureHandler.render()}setStaticPreviewEnabled(e){t.config.pageConfig.staticPreview=e}setStaticPreviewName(e){t.config.pageConfig.staticPreviewName=e}setAsyncEnabled(e){t.config.pageConfig.asncMode=e}setGroupVisibleEnabled(e){t.config.pageConfig.groupVisible=e}addFilterItemNames(e){"string"==typeof e?ct(t.config.pageConfig.filterItemNames,e):e.forEach(e=>{ct(t.config.pageConfig.filterItemNames,e)})}setPreferenceBackgroundColor(e){t.config.gestureHandlerConfig.preferenceGizmoConfig.markColor=e[0]<<16|e[1]<<8|e[2],t.config.gestureHandlerConfig.preferenceGizmoConfig.markAlpha=e[3]??.3,this._gestureHandler.refresh(),this._gestureHandler.render()}setSafeAreaColor(e){t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaBoxColor=e[0]<<16|e[1]<<8|e[2],t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaBoxAlpha=e[3]??.3,this._gestureHandler.refresh(),this._gestureHandler.render()}setSizeAdaptEnabled(e){t.config.sizeAdaptConfig.enabled=e}setScreenShotEnabled(e){t.config.screenShotConfig.enabled=e}setExportVideoEnabled(e){t.config.exportVideoConfig.enabled=e}setSelectorGizmoPreSelectConfig(e,i){void 0!==e&&(t.config.gestureHandlerConfig.selectorGizmoConfig.preSelectedColor=e),void 0!==i&&(t.config.gestureHandlerConfig.selectorGizmoConfig.preSelectedWidth=i),this._gestureHandler.refresh(),this._gestureHandler.render()}setTranformGizmoWireframeConfig(e){void 0!==e.wireframeAlpha&&(t.config.gestureHandlerConfig.transformGizmoConfig.wireframeAlpha=e.wireframeAlpha),void 0!==e.wireframeColor&&(t.config.gestureHandlerConfig.transformGizmoConfig.wireframeColor=e.wireframeColor),void 0!==e.wireframeWidth&&(t.config.gestureHandlerConfig.transformGizmoConfig.wireframeWidth=e.wireframeWidth),this._gestureHandler.refresh(),this._gestureHandler.render()}getSDKConfig(){return t.config}setSDKConfig(e){const i=Object.assign({},t.config);this._eventEmitter.emit("sdkConfigChange",i,e),t.config=e}};m(le,"config",{pageConfig:{asncMode:!1,staticPreview:!0,staticPreviewName:"标准模板",filterItemNames:["check-area","ModelPluginItem"],groupVisible:!0},screenShotConfig:{enabled:!0},exportVideoConfig:{enabled:!0,mediaType:"MP4",loggerInTranscoding:!1},sizeAdaptConfig:{enabled:!0},gestureHandlerConfig:{enabled:!0,adsorptionGizmoEnabled:!0,adsorptionGizmoConfig:{lineWidth:2,lineColor:37375,distance:6},controlGizmoEnabled:!0,controlGizmoConfig:{zoomStep:.01},preferenceGizmoEnabled:!0,preferenceGizmoConfig:{boxColor:16711680,boxWidth:1,markColor:0,markAlpha:.17,safeAreaEnabled:!0,safeAreaBoxColor:65280,safeAreaBoxAlpha:.3},selectorGizmoEnabled:!0,selectorGizmoConfig:{preSelectedWidth:3,preSelectedColor:15425024,regionBoxColor:16777215,regionBoxAlpha:.17,regionWireframeColor:16777215,regionWireframeAlpha:.78,regionWireframeWidth:1},transformGizmoEnabled:!0,transformGizmoConfig:{wireframeColor:16711680,wireframeAlpha:1,wireframeWidth:1.5,cornerFillColor:16777215,cornerLineColor:0,cornerLineWidth:1,cornerLineAlpha:.3,scaleCircleSize:4,rotationCircleSize:8}}});var me=le;
1
+ "use strict";var t,e=Object.create,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,n=t=>{throw TypeError(t)},c=(t,e)=>{for(var s in e)i(t,s,{get:e[s],enumerable:!0})},h=(t,e,a,n)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of r(e))o.call(t,c)||c===a||i(t,c,{get:()=>e[c],enumerable:!(n=s(e,c))||n.enumerable});return t},p=(t,e,i)=>(h(t,e,"default"),i&&h(i,e,"default")),l=(t,s,r)=>(r=null!=t?e(a(t)):{},h(!s&&t&&t.__esModule?r:i(r,"default",{value:t,enumerable:!0}),t)),m=(t,e,s)=>((t,e,s)=>e in t?i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s)(t,"symbol"!=typeof e?e+"":e,s),d=(t,e,i)=>e.has(t)||n("Cannot "+i),g=(t,e,i)=>(d(t,e,"read from private field"),i?i.call(t):e.get(t)),u=(t,e,i)=>e.has(t)?n("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),f=(t,e,i,s)=>(d(t,e,"write to private field"),s?s.call(t,i):e.set(t,i),i),y={};c(y,{SDK:()=>me,spec:()=>w.spec}),module.exports=(t=y,h(i({},"__esModule",{value:!0}),t));require("@galacean/effects");var w=require("@galacean/effects"),x=(require("@galacean/effects-plugin-rich-text"),require("@galacean/effects-plugin-rich-text")),v=(require("@galacean/effects-plugin-model"),require("@galacean/effects-plugin-multimedia"),require("@galacean/effects-plugin-multimedia")),P=(require("@galacean/effects-plugin-spine"),require("@pixi/app")),D=class{constructor(){m(this,"interactive"),m(this,"type"),m(this,"active"),this.type="null",this.active=!1,this.interactive=!1}},I=1e-6;function b(t,e,i){const s=isNaN(e)?-1/0:e,r=isNaN(i)?1/0:i,a=Math.min(s,r),o=Math.max(s,r);return Math.min(Math.max(t,a),o)}var C=Math.PI/180,E=180/Math.PI;function A(t){return Math.atan2(-t.y,-t.x)+Math.PI}function S(t,e,i=Math.round){if(Number.isInteger(t))return t;const s=Math.pow(10,e);return i(t*s)/s}function z(t,e){return Math.abs(t-e)<I||t===1/0&&e===1/0||t===-1/0&&e===-1/0}function T(t){return isNaN(t)||Math.abs(t)<I}var _=class t extends w.math.Vector2{subtract(t){return this.x-=t.x,this.y-=t.y,this}toViewCoordinate(t,e){return this.x=(this.x+1)/2*t,this.y=(1-(this.y+1)/2)*e,this}clone(){return new t(this.x,this.y)}distanceTo(t){const e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}scaleByCenter(e,i=new t){const s=(new t).subtractVectors(i,this).multiply(e);return(new t).subtractVectors(i,s)}round(t=0){const e=Math.pow(10,t);return this.x=Math.round(this.x*e)/e,this.y=Math.round(this.y*e)/e,this}},M=class t{constructor(t=new _,e=new _){m(this,"start",new _),m(this,"end",new _),this.start.copyFrom(t),this.end.copyFrom(e)}set(t,e){return this.start.copyFrom(t),this.end.copyFrom(e),this}copyFrom(t){return this.start.copyFrom(t.start),this.end.copyFrom(t.end),this}direction(){return(new _).subtractVectors(this.end,this.start).normalize()}getCenter(t=new _){return t.addVectors(this.start,this.end).multiply(.5)}delta(t=new _){return t.subtractVectors(this.end,this.start)}distanceSq(){return this.start.distanceSquared(this.end)}distance(){return this.start.distance(this.end)}at(t,e=new _){return this.delta(e).multiply(t).add(this.start)}closestPointToPointParameter(t,e){const i=new _,s=new _;i.subtractVectors(t,this.start),s.subtractVectors(this.end,this.start);const r=s.dot(s);let a=s.dot(i)/r;return e&&(a=b(a,0,1)),a}closestPointToPoint(t,e,i=new _){const s=this.closestPointToPointParameter(t,e);return this.delta(i).multiply(s).add(this.start)}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return(new t).copyFrom(this)}length(){return(new _).subtractVectors(this.end,this.start).length()}crossWithLine(t){const e=this.delta(),i=t.delta(),s=(new _).subtractVectors(t.start,this.start),r=(new _).subtractVectors(t.end,this.start),a=(new _).subtractVectors(this.start,t.start),o=(new _).subtractVectors(this.end,t.start),n=s.cross(e),c=r.cross(e),h=a.cross(i),p=o.cross(i);return n*c<0&&h*p<0}},V=class t{constructor(t=new _(1/0,1/0),e=new _(-1/0,-1/0)){m(this,"corners",[]),m(this,"min",new _(1/0,1/0)),m(this,"max",new _(-1/0,-1/0)),this.min=t.clone(),this.max=e.clone(),this.isEmpty()?this.corners=[]:this.corners=[t.clone(),new _(e.x,t.y),e.clone(),new _(t.x,e.y)]}set(t,e){return this.min.copyFrom(t),this.max.copyFrom(e),this.corners=[t.clone(),new _(e.x,t.y),e.clone(),new _(t.x,e.y)],this}setFromVec2Array(t){return this.min=(new _).copyFrom(t[0]),this.max=(new _).copyFrom(t[0]),t.forEach(t=>{this.min.min(t),this.max.max(t),this.corners.push(t.clone())}),this}setFromVec2ArrayWithOutCorners(t){return this.min=(new _).copyFrom(t[0]),this.max=(new _).copyFrom(t[0]),t.forEach(t=>{this.min=this.min.min(t),this.max=this.max.max(t)}),this.corners.push(new _(this.min.x,this.min.y)),this.corners.push(new _(this.min.x,this.max.y)),this.corners.push(new _(this.max.x,this.max.y)),this.corners.push(new _(this.max.x,this.min.y)),this}setFromCenterAndSize(t,e){const i=(new _).copyFrom(e).multiply(.5);return this.min.copyFrom(t).subtract(i),this.max.copyFrom(t).add(i),this.corners=[this.min.clone(),new _(this.max.x,this.min.y),this.max.clone(),new _(this.min.x,this.max.y)],this}clone(){return(new t).copyFrom(this)}copyFrom(t){return this.corners=[],this.min.copyFrom(t.min),this.max.copyFrom(t.max),t.corners.forEach(t=>{this.corners.push(t.clone())}),this}makeEmpty(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this.corners=[],this}isEmpty(){return this.max.x<=this.min.x||this.max.y<=this.min.y}getCorners(){const t=[];return this.corners.forEach(e=>{t.push(e.clone())}),t}getCenter(t=new _){return this.isEmpty()?t.set(0,0):t.addVectors(this.min,this.max).multiply(.5)}getSize(t=new _){return this.isEmpty()?t.set(0,0):t.subtractVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.subtract(t),this.max.add(t),this}expandByScalar(t){return this.min.add(-t),this.max.add(t),this}containsPoint(t,e=!0){if(e)return!(t.x<this.min.x||t.x>this.max.x||t.y<this.min.y||t.y>this.max.y);if(this.isEmpty())return!1;for(let e=0;e<this.corners.length;e++){const i=this.corners[e],s=this.corners[(e+1)%4],r=new _(s.x-i.x,s.y-i.y),a=new _(t.x-i.x,t.y-i.y);if(r.cross(a)<0)return!1}return!0}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y}getParameter(t,e=new _){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))}clampPoint(t,e=new _){return e.copyFrom(t).clamp(this.min,this.max)}distanceToPoint(t){return(new _).copyFrom(t).clamp(this.min,this.max).subtract(t).length()}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.min.x>this.max.x||this.min.y>this.max.y?this.makeEmpty():this}union(t){return this.min.min(t.min),this.max.max(t.max),this.corners=[this.min.clone(),new _(this.max.x,this.min.y),this.max.clone(),new _(this.min.x,this.max.y)],this}translate(t){return this.min.add(t),this.max.add(t),this.corners.forEach(e=>{e.add(t)}),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}intersectsBox(t,e=!0){if(e)return!(t.max.x<this.min.x||t.min.x>this.max.x||t.max.y<this.min.y||t.min.y>this.max.y);if(!this.isEmpty())for(let e=0;e<this.corners.length;e++){const i=new M(this.corners[e],this.corners[(e+1)%4]);if(t.containsPoint(this.corners[e],!1))return!0;for(let e=0;e<t.corners.length;e++){const s=new M(t.corners[e],t.corners[(e+1)%4]);if(this.containsPoint(t.corners[e],!1))return!0;if(i.crossWithLine(s))return!0}}for(let e=0;e<t.corners.length;e++){const i=this.containsPoint(t.corners[e],!1),s=t.containsPoint(this.corners[e],!1);if(i||s)return!0}return!1}},k=class t{constructor(t=new _,e=0){m(this,"center"),m(this,"radius"),this.center=t.clone(),this.radius=e}set(t,e){return this.center=(new _).copyFrom(t),this.radius=e,this}clone(){return(new t).copy(this)}copy(t){return this.center.copyFrom(t.center),this.radius=t.radius,this}makeEmpty(){return this.center=new _,this.radius=0,this}isEmpty(){return 0===this.radius}getCenter(t=new _){return t.copyFrom(this.center),t}getRadius(){return this.radius}expandByPoint(t){return this.radius=this.center.distanceTo(t),this}expandByScalar(t){return this.radius+=t,this}containsPoint(t){return this.center.distanceTo(t)<this.radius}containsBox(t){for(let e=0;e<4;e++)if(!this.containsPoint(t.corners[e]))return!1;return!0}intersectsBox(t){for(let e=0;e<4;e++)if(this.containsPoint(t.corners[e]))return!0;return!1}distanceToPoint(t){return this.center.distanceTo(t)-this.radius}},B=class extends w.math.Quaternion{},F=class t extends w.math.Vector3{clone(){return new t(this.x,this.y,this.z)}setFromMatrixColumn(t,e){return this.set(...t.elements.slice(4*e))}applyEuler(t,e){return this.applyQuaternion((new B).setFromEuler(t))}applyQuaternion(e,i=new t){const{x:s,y:r,z:a,w:o}=e,{x:n,y:c,z:h}=this.subtract(i),p=o*n+r*h-a*c,l=o*c+a*n-s*h,m=o*h+s*c-r*n,d=-s*n-r*c-a*h;return this.x=p*o+d*-s+l*-a-m*-r+i.x,this.y=l*o+d*-r+m*-s-p*-a+i.y,this.z=m*o+d*-a+p*-r-l*-s+i.z,this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}applyMatrix(e,i=new t){const s=e.elements,{x:r,y:a,z:o}=this.subtract(i);let n=1/(s[3]*r+s[7]*a+s[11]*o+s[15]);return n=isNaN(n)?1:n,this.x=(s[0]*r+s[4]*a+s[8]*o+s[12])*n+i.x,this.y=(s[1]*r+s[5]*a+s[9]*o+s[13])*n+i.y,this.z=(s[2]*r+s[6]*a+s[10]*o+s[14])*n+i.z,this}},U=class t extends w.math.Matrix4{static fromArray(e,i=0){return(new t).setFromArray(e,i)}clone(){const e=this.elements;return new t(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}compose(t,e,i,s=F.ZERO){const r=this.elements,{x:a,y:o,z:n,w:c}=e,h=-s.x,p=-s.y,l=-s.z,m=a+a,d=o+o,g=n+n,u=a*m,f=a*d,y=a*g,w=o*d,x=o*g,v=n*g,P=c*m,D=c*d,I=c*g,{x:b,y:C,z:E}=i;return r[0]=(1-(w+v))*b,r[1]=(f+I)*b,r[2]=(y-D)*b,r[3]=0,r[4]=(f-I)*C,r[5]=(1-(u+v))*C,r[6]=(x+P)*C,r[7]=0,r[8]=(y+D)*E,r[9]=(x-P)*E,r[10]=(1-(u+w))*E,r[11]=0,r[12]=h*r[0]+p*r[4]+l*r[8]-h+t.x,r[13]=h*r[1]+p*r[5]+l*r[9]-p+t.y,r[14]=h*r[2]+p*r[6]+l*r[10]-l+t.z,this}extractRotation(t){const e=new F,i=t.elements,s=this.elements,r=1/e.setFromMatrixColumn(t,0).length(),a=1/e.setFromMatrixColumn(t,1).length(),o=1/e.setFromMatrixColumn(t,2).length();return s[0]=i[0]*r,s[1]=i[1]*r,s[2]=i[2]*r,s[3]=0,s[4]=i[4]*a,s[5]=i[5]*a,s[6]=i[6]*a,s[7]=0,s[8]=i[8]*o,s[9]=i[9]*o,s[10]=i[10]*o,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,r=t.z,a=Math.cos(i),o=Math.sin(i),n=Math.cos(s),c=Math.sin(s),h=Math.cos(r),p=Math.sin(r);if(t.order===w.math.EulerOrder.XYZ){const t=a*h,i=a*p,s=o*h,r=o*p;e[0]=n*h,e[4]=-n*p,e[8]=c,e[1]=i+s*c,e[5]=t-r*c,e[9]=-o*n,e[2]=r-t*c,e[6]=s+i*c,e[10]=a*n}else if(t.order===w.math.EulerOrder.YXZ){const t=n*h,i=n*p,s=c*h,r=c*p;e[0]=t+r*o,e[4]=s*o-i,e[8]=a*c,e[1]=a*p,e[5]=a*h,e[9]=-o,e[2]=i*o-s,e[6]=r+t*o,e[10]=a*n}else if(t.order===w.math.EulerOrder.ZXY){const t=n*h,i=n*p,s=c*h,r=c*p;e[0]=t-r*o,e[4]=-a*p,e[8]=s+i*o,e[1]=i+s*o,e[5]=a*h,e[9]=r-t*o,e[2]=-a*c,e[6]=o,e[10]=a*n}else if(t.order===w.math.EulerOrder.ZYX){const t=a*h,i=a*p,s=o*h,r=o*p;e[0]=n*h,e[4]=s*c-i,e[8]=t*c+r,e[1]=n*p,e[5]=r*c+t,e[9]=i*c-s,e[2]=-c,e[6]=o*n,e[10]=a*n}else if(t.order===w.math.EulerOrder.YZX){const t=a*n,i=a*c,s=o*n,r=o*c;e[0]=n*h,e[4]=r-t*p,e[8]=s*p+i,e[1]=p,e[5]=a*h,e[9]=-o*h,e[2]=-c*h,e[6]=i*p+s,e[10]=t-r*p}else if(t.order===w.math.EulerOrder.XZY){const t=a*n,i=a*c,s=o*n,r=o*c;e[0]=n*h,e[4]=-p,e[8]=c*h,e[1]=t*p+r,e[5]=a*h,e[9]=i*p-s,e[2]=s*p-i,e[6]=o*h,e[10]=r*p+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}setPosition(t){return this.elements[12]=t.x,this.elements[13]=t.y,this.elements[14]=t.z,this}},R=class extends w.math.Euler{constructor(t=0,e=0,i=0,s=w.math.EulerOrder.XYZ){super(t,e,i,s)}getInvertMatrixByEuler(){return(new U).makeRotationFromEuler(this).invert()}toDegreeVector3(t){return t?t.set(this.x*E,this.y*E,this.z*E):new F(this.x*E,this.y*E,this.z*E)}setFromDegreeVector3(t,e){return this.set(t.x*C,t.y*C,t.z*C,e??this.order)}},W=class t{constructor(t=0,e=new F(0,0,1)){m(this,"distance"),m(this,"normal");const i=e.length();0===i&&(this.normal=new F(0,0,1)),this.distance=t/(i??1),this.normal=e.normalize()}static set(e,i){return new t(e,i)}set(t,e){const i=e.length();return 0===i&&(this.normal=new F(0,0,1)),this.distance=t/i,this.normal=e.normalize(),this}static copy(e){return new t(e.distance,e.normal.clone())}copy(t){return this.distance=t.distance,this.normal.copyFrom(t.normal),this}static setFromNormalAndCoplanarPoint(e,i){const s=-e.dot(i);return new t(s,i)}setFromNormalAndCoplanarPoint(t,e){return this.normal.copyFrom(e),this.distance=-t.dot(this.normal),this}clone(){return new t(this.distance,this.normal.clone())}distanceToPoint(t){return this.normal.dot(t)+this.distance}},G=class t extends w.math.Ray{constructor(t=new F,e=new F(1,0,0)){super(t,e),m(this,"origin"),m(this,"direction"),this.origin=t.clone(),this.direction=e.clone()}clone(){return new t(this.origin,this.direction)}rayCastPlane(t,e){const i=this.distanceToPlane(t);return isNaN(i)||this.at(i),i}at(t){return this.direction.clone().normalize().multiply(t).add(this.origin)}distanceToPlane(t){const e=t.normal.dot(this.direction);if(T(e))return T(t.distanceToPoint(this.origin))?0:NaN;const i=(-this.origin.dot(t.normal)-t.distance)/e;return i>0?i:NaN}},H=class{constructor(t=new G){m(this,"ray"),this.ray=t.clone()}setFromCamera(t,e){const i=e.position,s=new F(t.x,t.y,.5).applyMatrix(e.inverseViewProjectMatrix).subtract(i).normalize();return this.ray.set(i,s),this}rayCastPlane(t){const e=new F,i=this.ray.rayCastPlane(t,e);if(!isNaN(i))return{distance:i,point:this.ray.at(i)}}},N=class extends D{constructor(t){super(),m(this,"defaultInteractive",!0),m(this,"interactive",!0),m(this,"lastPoint",new _),m(this,"SDKUtils"),this.SDKUtils=t,this.type="control"}initialize(){}preparationAction(){}cancelPreparation(){}refreshResults(){}preAction(){}action(t){if(!me.config.gestureHandlerConfig.controlGizmoEnabled)return void console.warn("Control gizmo is not opened, use #SDK.setControlConfig() open this feature.");const{metaKey:e,ctrlKey:i,shiftKey:s}=t;if(0===t.buttons){const{deltaX:r,deltaY:a}=t,o=new _(r,a);e||i?(o.y=b(o.y,-10,10),this.dolly(o.y)):(o.x=s&&0!==o.y?Math.sqrt(o.x**2+o.y**2)*o.y/Math.abs(o.y):o.x,o.y=s?0:o.y,this.pan(o.multiply(-1)))}}endAction(){}interruption(){return this.type}actionKey(){}endActionKey(){}dolly(t){const e=-t*me.config.gestureHandlerConfig.controlGizmoConfig.zoomStep;this.SDKUtils.pageZoom(e)}pan(t){this.SDKUtils.pageMove(t)}getRenderObjects(){return[]}},L=require("@pixi/graphics"),K=class extends D{constructor(t){super(),m(this,"interactive",!0),m(this,"result",{type:"null",box:new V}),m(this,"selectedItemIds",[]),m(this,"cursorPoint",new _),m(this,"startPoint",new _),m(this,"graphics",new L.Graphics),m(this,"pageDataUtils"),m(this,"clearResult",!1),m(this,"type"),this.pageDataUtils=t,this.type="selector"}initialize(){}actionKey(){}endActionKey(){}getRenderObjects(){return me.config.gestureHandlerConfig.selectorGizmoEnabled?this.clearResult?(this.result={type:"null",box:new V},this.clearResult=!1,[]):(this.refreshResults(),[this.graphics]):[]}cancelPreparation(){this.result.type="null",this.pageDataUtils.clearPreSelectedItem()}preparationAction(t){if(this.result.box=new V,!me.config.gestureHandlerConfig.selectorGizmoEnabled)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const e=new _(t.offsetX,t.offsetY);this.selectedItemIds=this.hitTest(e);const i=this.selectedItemIds[0]??"";return i.length&&!this.pageDataUtils.isItemSelected(i)?this.pageDataUtils.addPreSelectedItem(i):this.pageDataUtils.clearPreSelectedItem(),this.type}preAction(t){if(this.pageDataUtils.clearPreSelectedItem(),1===t.buttons)return t.shiftKey||this.pageDataUtils.clearSelectedItems(),0===this.selectedItemIds.length?(this.startPoint=new _(t.clientX,t.clientY),this.cursorPoint=new _(t.offsetX,t.offsetY),this.active=!0,this.type):(this.pageDataUtils.addSelectedItems([this.selectedItemIds[0]]),this.clearResult=!0,"transform")}action(t){const e=(new _).addVectors(this.cursorPoint,(new _).subtractVectors(new _(t.clientX,t.clientY),this.startPoint)),i=(new _).subtractVectors(this.cursorPoint,e),s=(new _).addVectors(this.cursorPoint,e).multiply(.5);i.x=Math.abs(i.x),i.y=Math.abs(i.y);const r=(new V).setFromCenterAndSize(s,i);this.result.type="region",this.result.box=r,this.pageDataUtils.clearSelectedItems();const a=this.pageDataUtils.getPageData().items?.filter(t=>this.pageDataUtils.getItemEditEnable(t.id)),o=[];a?.forEach(t=>{r.intersectsBox(this.pageDataUtils.getViewBoxById(t.id),!1)&&o.push(t.id)}),this.pageDataUtils.addSelectedItems(o)}endAction(){this.active=!1,this.result.type="null"}interruption(){this.active=!1,this.result.type="null"}hitTest(t){const e=this.pageDataUtils.getCurrentComposition();if(!e?.items)return[];const{x:i,y:s}=this.pageDataUtils.getViewportByViewPoint(t),r={ray:new G,regions:[]};try{r.regions=e.hitTest(i,s,!0),r.ray=e.getHitTestRay(i,s)}catch(t){console.warn(t)}return this.reorderHitTestResult(r,e).filter(t=>"extra-camera"!==t&&this.pageDataUtils.getItemEditEnable(t))}reorderHitTestResult(t,e){if(0===t.regions.length||!e)return[];const{ray:i}=t,s=t.regions.reverse(),r=[];return s.forEach(t=>{let s;const a=(t,e)=>{for(const i of t){if(i.getInstanceId()===e&&(s=i),s)return;a(i.children,e)}};if(a(e.items,t.id),void 0===s)return;const o="rootItem"===t.compContent?.name?s.getInstanceId():t.compContent.getInstanceId(),n=i.origin.clone().distance(t.position.clone());if((s.type===w.spec.ItemType.mesh||s.getComponent(w.SpriteComponent)?.renderer?.occlusion||s.getComponent(w.TextComponent)?.renderer?.occlusion||s.getComponent(v.VideoComponent)?.renderer?.occlusion||s.getComponent(x.RichTextComponent)?.renderer?.occlusion)&&r.length>0){let t=!0;r.forEach((e,i)=>{if(t)return n<=e[1]?(r.splice(i,0,[o,n]),void(t=!1)):void(i===r.length-1&&r.push([o,n]))})}else r.push([o,n])}),r.map(t=>t[0])}refreshResults(){const{box:t}=this.result;this.graphics.clear();const e=this.pageDataUtils.getPreSelectedItem(),i=this.pageDataUtils.getViewBoxById(e?.id??""),{regionBoxColor:s,regionBoxAlpha:r,preSelectedWidth:a,preSelectedColor:o,regionWireframeWidth:n,regionWireframeColor:c,regionWireframeAlpha:h}=me.config.gestureHandlerConfig.selectorGizmoConfig;if(i?.isEmpty()||(this.graphics.lineStyle(a,o),this.graphics.drawBox(i)),!t.isEmpty()&&"region"===this.result.type)this.graphics.lineStyle(n,c,h),this.graphics.drawBox(t),this.graphics.beginFill(s,r),this.graphics.fillBox(t),this.graphics.endFill()}},O=require("@pixi/graphics"),j=require("@galacean/effects"),$=class extends D{constructor(t,e){super(),m(this,"type"),m(this,"interactive",!0),m(this,"wireframe"),m(this,"cursorResult",{type:"normal",angle:0}),m(this,"cursorPoint",new _),m(this,"lastPoint",new _),m(this,"rotationAngle",0),m(this,"active",!1),m(this,"enableAdsorption",!0),m(this,"scaleParam"),m(this,"activeType","null"),m(this,"lastWorldPosition",new F),m(this,"pageDataUtils"),m(this,"adsorptionGizmo"),m(this,"graphics",new O.Graphics),this.type="transform",this.pageDataUtils=t,this.adsorptionGizmo=e,this.wireframe={edges:[],anchor:new _,scaleCorners:[],rotationCorners:[],interactive:!0,cornerEnable:!0,directionEnable:!0,box:new V,totalBox:new V,childrenBoxes:[],activeType:"null",interactiveDirection:new _,scaleCorner:new _,scaleEdgeCorners:[]}}initialize(){}actionKey(){}endActionKey(){}getRenderObjects(){return me.config.gestureHandlerConfig.transformGizmoEnabled?(this.refreshRenderObject(),[this.graphics]):[]}cancelPreparation(){this.active=!1,this.wireframe.activeType="null"}preAction(t,e=!1){if(this.active=1===t.buttons,this.lastPoint=new _(t.clientX,t.clientY),this.cursorPoint=new _(t.offsetX,t.offsetY),1!==t.buttons)return;this.active=!0,"null"===this.wireframe.activeType&&(this.wireframe.activeType="translation");const i=this.cursorPoint.clone().subtract(this.pageDataUtils.getViewportLeftTopPosition());return this.initInteractionPlane(i),this.lastWorldPosition=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(i)??new F,this.activeType=e?"null":this.activeType,this.type}preparationAction(t){if(!me.config.gestureHandlerConfig.transformGizmoEnabled)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const e=new _(t.offsetX,t.offsetY),i=this.wireframe;this.refreshTransformType(e);const{interactiveDirection:s}=i;return this.refreshCursorResult(this.activeType,A(s)),this.active="null"!==this.activeType,this.active?this.type:void 0}action(t){if(!me.config.gestureHandlerConfig.transformGizmoEnabled)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");if(!this.active){this.active=!0,this.refreshWireframeBySelectedItems(),this.wireframe.activeType="translation",this.lastPoint.set(t.clientX,t.clientY),this.cursorPoint.set(t.offsetX,t.offsetY);const e=this.cursorPoint.clone().subtract(this.pageDataUtils.getViewportLeftTopPosition());this.initInteractionPlane(e),this.lastWorldPosition=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(e)??new F}const e=new _(t.clientX,t.clientY),i=(new _).subtractVectors(e,this.lastPoint);if(!this.wireframe.interactive)return;const s=this.pageDataUtils.getSelectedItems(),{anchor:r,activeType:a,interactiveDirection:o}=this.wireframe,n=this.pageDataUtils.getPageData();(0,j.assertExist)(n);let c=0;switch(a){case"rotation":{const t=r.clone(),e=new F,a=S(function(t,e){const i=Math.min(Math.max(t.dot(e)/t.length()/e.length(),-1),1);let s=Math.acos(i);return s=t.x*e.y-t.y*e.x>0?s:-s,s}((new _).subtractVectors(this.cursorPoint,t),(new _).subtractVectors(this.cursorPoint.add(i),t))*E,3);e.z=a,this.rotationAngle+=a,c=A(o)+this.rotationAngle*C,s.forEach(t=>{this.pageDataUtils.rotateItem(t.id,e)});break}case"translation":{const t=i.clone();if(this.enableAdsorption){const e=n.items.map(t=>!s.find(e=>e.id===t.id)&&0===s.filter(e=>t.parentId&&t.parentId===e.id).length&&this.pageDataUtils.getItemEditEnable(t.id)?this.pageDataUtils.getViewBoxById(t.id):new V).filter(t=>!t.isEmpty()),i=new _(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);this.adsorptionGizmo.boxTranslationAdsorption(t,this.wireframe.box,e);const r=new _(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);t.add(i).subtract(r)}const e=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint.add(t).clone().subtract(this.pageDataUtils.getViewportLeftTopPosition()));if(e){const t=e.clone().subtract(this.lastWorldPosition);s.forEach(e=>{e.type!==w.spec.ItemType.camera&&this.pageDataUtils.moveItem(e.id,t)}),this.lastWorldPosition.copyFrom(e)}break}case"scale":{this.cursorPoint.add(i);const t=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint.clone().subtract(this.pageDataUtils.getViewportLeftTopPosition()));if(i.length()&&t&&this.scaleParam){const{corner:e,center:i,shift:r,lastScalar:a}=this.scaleParam,o=this.pageDataUtils.getSelectedItems()[0]??void 0,n=this.pageDataUtils.getItemTransformById(o?.id??""),c=(new U).extractRotation(n.matrix).invert(),h=(new F).subtractVectors(e,i).applyMatrix(c),p=h.clone().multiply(a),l=t.subtract(r).subtract(i).applyMatrix(c),m=new F(1,1,1),d=function(t){let e,i=0;return t.forEach((t,s)=>{if(0===s)e=Math.abs(t);else{const r=Math.abs(t);e<r&&(e=r,i=s)}}),i}([z(h.x,0)?1:Math.abs(l.x/h.x),z(h.y,0)?1:Math.abs(l.y/h.y)]),g=l.toArray()[d],u=p.toArray()[d];if(z(a.x,a.y)&&z(a.z,a.x)){const t=z(u,0)?1:Math.abs(g/u);m.set(t,t,t)}else if(0===d){m.x=z(u,0)?1:Math.abs(g/u);const t=h.y*g/h.x;m.y=z(p.y,0)?1:t/p.y;const e=h.z*g/h.x;m.z=z(p.z,0)?1:e/p.z}else if(1===d){m.y=z(u,0)?1:Math.abs(g/u);const t=h.x*g/h.y;m.x=z(p.x,0)?1:t/p.x;const e=h.z*g/h.y;m.z=z(p.z,0)?1:e/p.z}else{m.z=z(u,0)?1:Math.abs(g/u);const t=h.x*g/h.z;m.x=z(p.x,0)?1:t/p.x;const e=h.y*g/h.z;m.y=z(p.y,0)?1:e/p.y}this.scaleParam.lastScalar.multiply(m),s.forEach(t=>{this.pageDataUtils.scaleItem(t.id,m)})}c=A(o);break}}this.refreshCursorResult(a,c),this.lastPoint.copyFrom(e)}endAction(t){this.active=!1;const e=new _(t.clientX,t.clientY),i=(new _).subtractVectors(e,this.lastPoint);this.cursorPoint.add(i);const s=this.wireframe;this.refreshTransformType(this.cursorPoint);const{activeType:r,interactiveDirection:a}=s;this.refreshCursorResult(r,A(a)),this.adsorptionGizmo.clearAbsorptionResult(),this.rotationAngle=0,this.cursorPoint=new _,this.lastPoint=new _}interruption(){this.active=!1,this.cursorResult.type="normal",this.adsorptionGizmo.clearAbsorptionResult()}refreshCursorResult(t,e=0){switch(t){case"scale":this.cursorResult={type:"scale",angle:(e+Math.PI/4)*E};break;case"rotation":this.cursorResult={type:"rotation",angle:(e+Math.PI/4)*E};break;case"translation":case"null":this.cursorResult={type:"normal",angle:0}}}refreshResults(){const t=this.wireframe.activeType;this.refreshWireframeBySelectedItems(),t!==this.wireframe.activeType&&this.refreshCursorResult(this.wireframe.activeType),this.wireframe.box.isEmpty()&&this.adsorptionGizmo.clearAbsorptionResult()}initInteractionPlane(t){const e=this.pageDataUtils.getSelectedItems();switch(this.wireframe.activeType){case"scale":{const i=1==e.length?e[0]:void 0;let s,r,a;if(i){const t=this.pageDataUtils.getItemTransformById(i.id);s=(new F).copyFrom(this.pageDataUtils.getPlayerItemById(i.id).transform.anchor).applyMatrix(t.matrix),r=(new F).setFromMatrixPosition(t.matrix),a=(new R).setFromQuaternion((new B).setFromRotationMatrix(t.matrix))}this.pageDataUtils.interactionUtils.initInteractionPlane(r,a),this.scaleParam={shift:new F,center:new F,corner:new F,lastScalar:new F(1,1,1)},this.scaleParam.center=s??r;const o=this.pageDataUtils.getViewportLeftTopPosition();if(["scale"].includes(this.wireframe.activeType)&&this.wireframe.scaleCorner){const t=this.wireframe.scaleCorner.clone().subtract(o);this.scaleParam.corner=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(t)??new F}this.scaleParam.shift=(this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(t)??new F).subtract(this.scaleParam.corner);break}case"translation":case"rotation":this.pageDataUtils.interactionUtils.initInteractionPlane()}}refreshRenderObject(){this.graphics.clear();const{wireframeAlpha:t,wireframeColor:e,wireframeWidth:i,cornerFillColor:s,cornerLineWidth:r,cornerLineColor:a,cornerLineAlpha:o}=me.config.gestureHandlerConfig.transformGizmoConfig;if(!this.wireframe.box.isEmpty()){this.graphics.lineStyle(i,e,t),this.wireframe.edges.forEach(t=>{this.graphics.drawLine(t)});const n=t=>{t.corners.forEach((e,i)=>{const s=new M(e,t.corners[(i+1)%4]);this.graphics.drawLine(s)})};this.wireframe.childrenBoxes.forEach(t=>{n(t)}),this.wireframe.cornerEnable&&(this.graphics.beginFill(s),this.graphics.lineStyle(r,a,o),this.wireframe.scaleCorners.forEach(t=>{this.graphics.drawCircle(t.center.x,t.center.y,t.radius)}),this.graphics.endFill())}}refreshTransformType(t){this.activeType="null";let e=!0;if(this.wireframe.interactiveDirection=new _,this.wireframe.scaleCorner=void 0,this.wireframe.scaleEdgeCorners=void 0,this.wireframe.cornerEnable&&e&&this.wireframe.totalBox.containsPoint(t)){for(let i=0;i<4;i++){if(this.wireframe.scaleCorners[i].containsPoint(t)){e=!1,this.activeType="scale",this.wireframe.activeType="scale",this.wireframe.scaleCorner=this.wireframe.scaleCorners[i].center.clone(),this.wireframe.interactiveDirection.copyFrom(this.wireframe.scaleCorners[i].center).subtract(this.wireframe.box.getCenter());break}}e&&this.wireframe.box.containsPoint(t,!1)&&(e=!1,this.activeType="translation",this.wireframe.activeType="translation");for(let i=0;i<4;i++){if(this.wireframe.rotationCorners[i].containsPoint(t)&&e){e=!1,this.activeType="rotation",this.wireframe.activeType="rotation",this.wireframe.interactiveDirection.copyFrom(this.wireframe.rotationCorners[i].center).subtract(this.wireframe.box.getCenter());break}}}}refreshWireframeBySelectedItems(){const t=this.pageDataUtils.getSelectedItems(),e=new V;if(this.wireframe.edges=[],this.wireframe.scaleCorners=[],this.wireframe.childrenBoxes=[],this.wireframe.rotationCorners=[],t.length>1)t.forEach(t=>{if(this.pageDataUtils.getItemShow(t.id)){const i=this.pageDataUtils.getViewBoxById(t.id);e.union(i),this.wireframe.childrenBoxes.push((new V).copyFrom(i).expandByScalar(1))}}),this.wireframe.anchor=e.getCenter(),this.wireframe.interactive=!0;else if(1===t.length){const i=t[0];if(this.pageDataUtils.getItemShow(i.id)){const t=this.pageDataUtils.getViewBoxById(i.id);e.copyFrom(t),this.wireframe.anchor=this.pageDataUtils.getItemViewAnchor(i.id)??e.getCenter(),this.wireframe.interactive=i.type!==w.spec.ItemType.mesh&&this.pageDataUtils.getItemEditEnable(i.id)}}const i=e.isEmpty(),s=i?0:1,r=i?0:16;this.wireframe.activeType=t.length?this.wireframe.activeType:"null",this.wireframe.box.copyFrom(e).expandByScalar(s),this.wireframe.totalBox.copyFrom(e).expandByScalar(r);const a=this.wireframe.box.corners;a.forEach((t,e)=>{this.wireframe.edges.push(new M((new _).copyFrom(t),(new _).copyFrom(a[(e+1)%4])))});const{scaleCircleSize:o,rotationCircleSize:n}=me.config.gestureHandlerConfig.transformGizmoConfig;this.wireframe.box.corners.forEach(t=>{this.wireframe.scaleCorners.push(new k(t,o));const e=(new _).subtractVectors(t,this.wireframe.box.getCenter()),i=(new _).copyFrom(this.wireframe.box.getCenter()).add((new _).copyFrom(e).normalize().multiply(e.length()+n-o));this.wireframe.rotationCorners.push(new k(i,n))})}setAdsorptionEnabled(t){this.enableAdsorption=t}},Y=require("@pixi/graphics"),q=class extends D{constructor(){super(),m(this,"interactive",!1),m(this,"results",[]),m(this,"graphics",new Y.Graphics),m(this,"absorptionResult",{}),this.type="adsorption"}initialize(){}preparationAction(){}getCursorState(){}preAction(){}action(){}cancelPreparation(){}actionKey(){}endActionKey(){}endAction(){}interruption(){}boxTranslationAdsorption(t,e,i,s=!0,r=!0){if(this.results=[],!me.config.gestureHandlerConfig.adsorptionGizmoEnabled)return void console.warn("Adsorption gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");if(e.isEmpty())return;const a=new _(this.absorptionResult?.x??0,this.absorptionResult?.y??0).add(t),o=e.clone().translate(a),n=o.getCenter();this.absorptionResult={},i.forEach(t=>{if(t.isEmpty())return;t.corners.forEach(t=>{o.corners.forEach(e=>{this.getPointAbsorption(e,t,s,r)}),this.getPointAbsorption(n,t,s,r)});const e=t.getCenter();this.getPointAbsorption(n,e,s,r),o.corners.forEach(t=>{this.getPointAbsorption(t,e,s,r)})})}pointTranslationAdsorption(t,e,i,s=!0,r=!0){if(this.results=[],!me.config.gestureHandlerConfig.adsorptionGizmoEnabled)return void console.warn("Adsorption is not opened, use #SDK.setAdsorptionConfig() open this feature.");const a=new _(this.absorptionResult?.x??0,this.absorptionResult?.y??0).add(t),o=e.clone().add(a);this.absorptionResult={},i.forEach(t=>{this.getPointAbsorption(o,t,s,r)})}getPointAbsorption(t,e,i=!0,s=!0){i&&Math.abs(t.x-e.x)<me.config.gestureHandlerConfig.adsorptionGizmoConfig.distance&&this.refreshPointAbsorptionResult(t,e,"x"),s&&Math.abs(t.y-e.y)<me.config.gestureHandlerConfig.adsorptionGizmoConfig.distance&&this.refreshPointAbsorptionResult(t,e,"y")}refreshPointAbsorptionResult(t,e,i){const s=t[i]-e[i],r="x"===i?"xPoints":"yPoints";if(this.absorptionResult&&void 0===this.absorptionResult[i])this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}];else if(Math.abs(s)-Math.abs(this.absorptionResult[i]??0)<=.005)if(Math.abs(Math.abs(s)-Math.abs(this.absorptionResult[i]??0))<.05&&s*(this.absorptionResult[i]??0)>0)if(void 0===this.absorptionResult[r])this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}];else{const i=this.absorptionResult[r].filter(e=>e.point.equals(t));void 0===i||0===i.length?this.absorptionResult[r]?.push({point:t,targets:[e]}):i[0]?.targets.push(e)}else this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}]}refreshResults(){if(void 0===this.absorptionResult)return;const{x:t,y:e,xPoints:i,yPoints:s}=this.absorptionResult,r=new _(t??0,e??0);void 0!==t&&void 0!==i&&i.forEach(t=>{const e=t.point.clone().subtract(r),i=e.clone(),s=e.clone();t.targets.forEach(t=>{i.x=t.x,i.y=Math.min(i.y,t.y),s.x=t.x,s.y=Math.max(s.y,t.y)}),this.results.push(new M(i,s))}),void 0!==e&&void 0!==s&&s.forEach(t=>{const e=t.point.clone().subtract(r),i=e.clone(),s=e.clone();t.targets.forEach(t=>{i.y=t.y,i.x=Math.min(i.x,t.x),s.y=t.y,s.x=Math.max(s.x,t.x)}),this.results.push(new M(i,s))})}refreshRenderObject(){this.graphics.clear();const{lineWidth:t,lineColor:e}=me.config.gestureHandlerConfig.adsorptionGizmoConfig;this.results.forEach(i=>{this.graphics.lineStyle(t,e),this.graphics.drawLine(i)})}getRenderObjects(){return me.config.gestureHandlerConfig.adsorptionGizmoEnabled?(this.refreshResults(),this.refreshRenderObject(),[this.graphics]):[]}clearAbsorptionResult(){this.results=[],this.absorptionResult={}}},J={};c(J,{Application:()=>tt.Application,utils:()=>Z});var X={};c(X,{Application:()=>tt.Application,utils:()=>Z});require("@pixi/polyfill");var Z=l(require("@pixi/utils"),1),Q=require("@pixi/interaction"),tt=require("@pixi/app"),et=require("@pixi/core"),it=require("@pixi/loaders"),st=require("@pixi/ticker");p(X,require("@pixi/constants")),p(X,require("@pixi/core")),p(X,require("@pixi/display")),p(X,require("@pixi/graphics")),p(X,require("@pixi/loaders")),p(X,require("@pixi/interaction")),p(X,require("@pixi/math")),p(X,require("@pixi/runner")),p(X,require("@pixi/sprite")),p(X,require("@pixi/text")),p(X,require("@pixi/ticker")),p(X,require("@pixi/settings")),Z.skipHello(),et.Renderer.registerPlugin("interaction",Q.InteractionManager),et.Renderer.registerPlugin("batch",et.BatchRenderer),tt.Application.registerPlugin(st.TickerPlugin),tt.Application.registerPlugin(it.AppLoaderPlugin),X.Graphics.prototype.drawBox=function(t){const e=t.getCorners();this.beginFill();for(let t=0;t<4;t++)this.moveTo(e[t].x,e[t].y),this.lineTo(e[(t+1)%4].x,e[(t+1)%4].y);this.endFill()},X.Graphics.prototype.fillBox=function(t){const e=t.getSize();this.drawRect(t.min.x,t.min.y,e.x,e.y)},X.Graphics.prototype.drawLine=function(t){if(this.beginFill(),t instanceof M)this.moveTo(t.start.x,t.start.y),this.lineTo(t.end.x,t.end.y);else for(let e=0;e<t.length-1;e++)this.moveTo(t[e].x,t[e].y),this.lineTo(t[e+1].x,t[e+1].y);this.endFill()},p(J,X);var rt=class extends D{constructor(t){super(),m(this,"interactive",!1),m(this,"box",new V),m(this,"graphics",new J.Graphics),m(this,"PageDataUtils"),this.PageDataUtils=t,this.type="preference"}initialize(){throw new Error("Method not implemented.")}preparationAction(){}preAction(){}action(){}endAction(){}interruption(){}actionKey(){}endActionKey(){}cancelPreparation(){}refreshResults(){if(this.box=new V,!me.config.gestureHandlerConfig.preferenceGizmoEnabled)return void console.warn("Preference gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const t=this.PageDataUtils.getPageData();(0,w.assertExist)(t);const{container:e}=this.PageDataUtils;if(e){const{zoom:i}=t.property,{offsetWidth:s,offsetHeight:r}=e,a=new _(s,r).multiply(i),o=this.PageDataUtils.getViewportLeftTopPosition().add(a.clone().divide(2));this.box=(new V).setFromCenterAndSize(o,a)}}refreshRenderObjects(){const{boxWidth:t,boxColor:e,markColor:i,markAlpha:s,safeAreaEnabled:r,safeAreaBoxColor:a,safeAreaBoxAlpha:o}=me.config.gestureHandlerConfig.preferenceGizmoConfig;this.graphics=new J.Graphics;const{offsetWidth:n,offsetHeight:c}=this.PageDataUtils.container.parentElement,h=new V(new _(0,0),new _(n,this.box.min.y)),p=new V(new _(0,this.box.min.y),new _(this.box.min.x,c)),l=new V(new _(this.box.min.x,this.box.max.y),new _(n,c)),m=new V(new _(this.box.max.x,this.box.min.y),new _(n,this.box.max.y));if(this.graphics.beginFill(i,s),this.graphics.fillBox(h),this.graphics.fillBox(p),this.graphics.fillBox(l),this.graphics.fillBox(m),this.graphics.endFill(),r){const t=this.PageDataUtils.getPageData();(0,w.assertExist)(t,"You must call SDK#run() first");const{viewProperties:e,activeData:i}=t,s=e[i.view??-1];if(s){const{size:t,safeArea:e,previewSafeAreas:i}=s,[r,n,c,h]=e,p=this.box.getSize(),l=r/t[1]*p.y,m=c/t[0]*p.x,d=h/t[0]*p.x,g=n/t[1]*p.y,{min:u,max:f}=this.box;this.graphics.beginFill(a,o);const y=new V(u,new _(f.x,u.y+l)),w=new V(new _(u.x,u.y+l),new _(u.x+m,f.y)),x=new V(new _(f.x-d,u.y+l),new _(f.x,f.y)),v=new V(new _(u.x+m,f.y-g),new _(f.x-d,f.y));this.graphics.fillBox(y),this.graphics.fillBox(w),this.graphics.fillBox(x),this.graphics.fillBox(v),this.graphics.endFill(),i.forEach(e=>{const{box:[i,s,r,a],color:o}=e,n=this.box.getSize(),c=new _(r/t[0]*n.x,a/t[1]*n.y),h=new _(i/t[0]*n.x+c.x/2,s/t[1]*n.y+c.y/2).add(u),p=(new V).setFromCenterAndSize(h,c),l=o?.[3]??.3,m=o?.slice(0,3)??[255,0,0],d=m[0]<<16|m[1]<<8|m[2];this.graphics.beginFill(d,l),this.graphics.fillBox(p),this.graphics.endFill()})}}this.graphics.lineStyle(t,e),this.graphics.drawBox(this.box)}getRenderObjects(){return me.config.gestureHandlerConfig.preferenceGizmoEnabled?(this.refreshRenderObjects(),[this.graphics]):[]}},at="https://mdn.alipayobjects.com/rms/uri/file/as/0.0.6",ot={normal:{type:"preset",content:"default"},rotation:{type:"svg",content:"default",url:`${at}/icons/cursor-rotate-32.svg`},scale:{type:"svg",content:"default",url:`${at}/icons/cursor-scale-32.svg`}};var nt=class{constructor(t){m(this,"wireframeApplication"),m(this,"gizmos",[]),m(this,"activeGizmo"),m(this,"selectorGizmo"),m(this,"transformGizmo"),m(this,"controlGizmo"),m(this,"preferenceGizmo"),m(this,"spaceClickTime"),m(this,"spaceEmit",!1),m(this,"_ignoreInteraction",!1),m(this,"clickButtons",0),m(this,"container"),m(this,"clickTime",0),m(this,"firstClick",!0),m(this,"dblclickTimeSpan",500),this.gizmos=[];const{width:e,height:i}=t.getBoundingClientRect();this.wireframeApplication=new P.Application({backgroundAlpha:0,width:e,height:i,resolution:1,antialias:!0}),this.container=t,this.wireframeApplication.view.style.position="absolute",this.wireframeApplication.view.id="wireframeApplicationCanvas",t.appendChild(this.wireframeApplication.view),this.wireframeApplication.stage.sortableChildren=!0,this.registerViewEvent(),async function(){await Promise.all(Object.entries(ot).map(([t,e])=>{const{url:i}=e;if(i)return fetch(i).then(t=>t.text()).then(i=>ot[t]={...e,content:i})})).catch(t=>{console.error(t)})}()}set ignoreInteraction(t){t!==this._ignoreInteraction&&(this._ignoreInteraction=t,t&&(this.activeGizmo?.cancelPreparation(),this.activeGizmo=void 0))}get ignoreInteraction(){return this._ignoreInteraction}resize(){this.wireframeApplication&&(this.wireframeApplication.resizeTo=this.container,this.render())}refresh(){this.gizmos.forEach(t=>{t.refreshResults()})}render(){this.refresh(),this.wireframeApplication.stage?.removeChildren();const t=(this.ignoreInteraction?[this.preferenceGizmo]:this.gizmos).flatMap(t=>t.getRenderObjects());this.wireframeApplication.stage.addChild(...t),this.wireframeApplication.render();const e=this.activeGizmo instanceof $?this.activeGizmo.cursorResult:void 0;this.setCursor(e)}init(t){this.gizmos=[],this.controlGizmo=new N(t),this.selectorGizmo=new K(t);const e=new q;this.transformGizmo=new $(t,e),this.preferenceGizmo=new rt(t),this.gizmos.push(this.transformGizmo,this.selectorGizmo,this.controlGizmo,this.preferenceGizmo,e),this.initEvents()}initEvents(){this.onMouseMove=this.onMouseMove.bind(this),this.onMouseUp=this.onMouseUp.bind(this),this.onKeyDown=this.onKeyDown.bind(this),this.onKeyUp=this.onKeyUp.bind(this),document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp)}registerViewEvent(){this.wireframeApplication.view.onmousedown=t=>{this.onMouseDown(t)},this.wireframeApplication.view.onmousemove=t=>{0===t.buttons&&this.onMouseMove(t)},this.wireframeApplication.view.onmouseout=()=>{this.selectorGizmo?.cancelPreparation(),this.render()},this.wireframeApplication.view.onwheel=t=>{this.onWheel(t)}}onMouseDown(t){if(!this.ignoreInteraction){if(this.clickButtons=t.buttons,this.firstClick=!!this.firstClick&&Date.now()-this.clickTime<this.dblclickTimeSpan,this.firstClick){this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()}),this.activeGizmo=void 0;const e=this.selectorGizmo?.preAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===(e??"null")),this.firstClick=!1}else{void 0===this.activeGizmo&&this.gizmos.forEach(e=>{if(!e.interactive||this.activeGizmo)return;const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)});const e=this.activeGizmo?.preAction(t);"selector"!==e&&this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.activeGizmo=this.gizmos.find(t=>t.type===e),this.clickTime=Date.now(),this.firstClick=!0}this.render(),document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("mouseup",this.onMouseUp)}}onMouseMove(t){this.ignoreInteraction||(0!==t.buttons?this.activeGizmo?.action(t):this.spaceEmit||(this.activeGizmo=void 0,this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);"selector"!==i&&this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()})),this.render())}onWheel(t){this.ignoreInteraction||(t.preventDefault(),this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.controlGizmo?.action(t))}onMouseUp(t){if(this.ignoreInteraction)return;const e=this.activeGizmo?.endAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===e),void 0===this.activeGizmo&&1===this.clickButtons&&this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()}),this.clickButtons=0,this.render(),document.removeEventListener("mousemove",this.onMouseMove),document.removeEventListener("mouseup",this.onMouseUp)}onKeyDown(t){if(!this.ignoreInteraction){if("space"!==t.code.toLocaleLowerCase()||this.activeGizmo?.active)this.gizmos.forEach(e=>{e.actionKey(t)});else{if(this.spaceEmit)return;void 0===this.spaceClickTime?this.spaceClickTime=Date.now():Date.now()-this.spaceClickTime>300&&(this.spaceEmit=!0,this.activeGizmo=this.controlGizmo,this.activeGizmo?.actionKey(t))}this.render()}}onKeyUp(t){this.ignoreInteraction||(this.gizmos.forEach(e=>{e.endActionKey(t)}),"space"===t.code.toLocaleLowerCase()&&(this.spaceClickTime=void 0,this.spaceEmit=!1),this.render())}dispose(){this.wireframeApplication.destroy(),this.gizmos=[],this.activeGizmo=void 0}setCursor(t){let e="default";if(t?.type){const i=ot[t.type];if("svg"===i.type){const s=16;e=encodeURIComponent(i.content.replace("rotate(0.00)",`rotate(${t.angle})`)),e=`url("data:image/svg+xml,${e}") ${s} ${s}, auto`}else e=i.content}this.wireframeApplication.view.style.cursor=e}};function ct(t,e){t.includes(e)||t.push(e)}var ht=require("@galacean/effects"),pt=class{constructor(t){m(this,"plane",new W),m(this,"ray",new G),m(this,"viewportParam",{width:0,height:0,viewWidth:0,viewHeight:0,panelWidth:0,panelHeight:0,scale:1,ratio:1,translation:new _,rulerWidth:0}),m(this,"cameraParam",{position:new F,rotation:new F,focusPosition:new F,focusRotation:new F,viewProjectionMatrix:new U,inverseViewProjectionMatrix:new U}),m(this,"pageDataUtils"),this.pageDataUtils=t}refreshViewParam(){const t=this.pageDataUtils.getPageData();(0,ht.assertExist)(t,"You must run SDK first");const e=new _(this.pageDataUtils.container.offsetWidth,this.pageDataUtils.container.offsetHeight),{zoom:i,translation:s}=t.property;this.viewportParam.width=e.x,this.viewportParam.height=e.y,this.viewportParam.viewWidth=e.x,this.viewportParam.viewHeight=e.y,this.viewportParam.panelWidth=e.x,this.viewportParam.panelHeight=e.y,this.viewportParam.scale=i,this.viewportParam.ratio=1,this.viewportParam.translation=new _(...s.map(t=>t/i)),this.viewportParam.rulerWidth=0}refreshCameraParam(){const{player:t}=this.pageDataUtils,e=t?.getCompositions()?.[0]?.camera;if(e){const t=U.fromArray(e.getViewProjectionMatrix().toArray()),i=U.fromArray(e.getViewMatrix().toArray()).invert(),s=new B;i.decompose(this.cameraParam.position,s,new F),this.cameraParam.rotation=(new R).setFromQuaternion(s).toDegreeVector3(),this.cameraParam.focusPosition=new F(...this.cameraParam.position.toVector2().toArray(),this.cameraParam.position.z>0?0:2*this.cameraParam.position.z),this.cameraParam.focusPosition.applyEuler((new R).setFromDegreeVector3(this.cameraParam.rotation.clone()),this.cameraParam.position),this.cameraParam.focusRotation=(new R).setFromQuaternion(s.invert()).toDegreeVector3(),this.cameraParam.viewProjectionMatrix=t,this.cameraParam.inverseViewProjectionMatrix=U.fromArray(e.getInverseViewProjectionMatrix().toArray())}}initInteractionPlane(t,e){t??(t=this.cameraParam.focusPosition),e??(e=(new R).setFromDegreeVector3(this.cameraParam.rotation));const i=new F(0,0,1).applyEuler(e);this.plane.setFromNormalAndCoplanarPoint(t,i)}getWorldSizeByViewSize(t,e=!0,i){const s=e||!i?(new R).setFromDegreeVector3(this.cameraParam.rotation):(new R).setFromQuaternion((new B).setFromRotationMatrix(this.pageDataUtils.getItemTransformById(i.id).matrix)),r=i?(new F).setFromMatrixPosition(this.pageDataUtils.getItemTransformById(i.id).matrix):this.cameraParam.focusPosition,a=this.projectPoint(r.clone()),o=this.getWorldPositionByViewPoint(a.add(t));if(!o)return console.warn("size is out of bounds."),new F(0,0,0);const n=(new R).setFromQuaternion((new B).setFromEuler(s).invert());return(e||!i?o.applyEuler(n,r):o).subtract(r)}projectPoint(t){const{panelWidth:e,panelHeight:i,scale:s}=this.viewportParam,r=this.pageDataUtils.getViewportLeftTopPosition();return(new _).copyFrom(t.applyMatrix(this.cameraParam.viewProjectionMatrix).toVector2()).toViewCoordinate(e*s,i*s).add(r)}getWorldPositionByViewPoint(t){const{position:e,inverseViewProjectionMatrix:i}=this.cameraParam,s=this.getViewPositionByScreenPosition(t),r=(new H).setFromCamera(s,{position:e,inverseViewProjectMatrix:i}).rayCastPlane(this.plane);return r?.point}getViewPositionByScreenPosition(t){const{panelWidth:e,panelHeight:i,scale:s}=this.viewportParam;return new _(t.x/(e*s)*2-1,-t.y/(i*s)*2+1)}getScreenSizeByPixelSize(t){const e=this.viewportParam.width/this.viewportParam.viewWidth,i=t.clone();return i.multiply(e||1),i}getPixelSizeByScreenSize(t){const e=this.viewportParam.viewWidth/this.viewportParam.width,i=t.clone();return i.multiply(e||1),i}},lt=require("@ffmpeg/ffmpeg"),mt=require("@ffmpeg/util");function dt(t,e="asserts failed"){if(!t)throw new Error(e)}function gt(t,e,...i){const s=e.reduce((t,e)=>t?`${t} ${e}`:e,""),r="color: #108ee9;";switch(t){case"error":console.error(`%c[${s}]`,r,...i);break;case"info":console.info(`%c[${s}]`,r,...i);break;case"debug":console.debug(`%c[${s}]`,r,...i);break;case"warn":console.warn(`%c[${s}]`,r,...i);break;default:console.log(`%c[${s}]`,r,...i)}}function ut(t,e,i="application/octet-stream"){const s=new Blob(Array.isArray(t)?t:[t],{type:i}),r=URL.createObjectURL(s),a=document.createElement("a");a.href=r,a.download=e,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(r)}function ft(t,e){if(Object.is(t,e))return!0;if(typeof t!=typeof e)return!1;if(null===t||"object"!=typeof t)return!1;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t instanceof RegExp&&e instanceof RegExp)return t.toString()===e.toString();if(Array.isArray(t)!==Array.isArray(e))return!1;const i=Object.keys(t),s=Object.keys(e);if(i.length!==s.length)return!1;for(const s of i){if(!Object.prototype.hasOwnProperty.call(e,s))return!1;if(!ft(t[s],e[s]))return!1}return!0}var yt={SCRIPT:"https://gw.alipayobjects.com/os/gltf-asset/99531561844014/img2webp.js",WASM:"https://mdn.alipayobjects.com/mars/uri/file/as/0.0.4/wasm/img2webp/img2webp.wasm"},wt={CLASSWORKER:"https://mdn.alipayobjects.com/rms/uri/file/as/ffmpeg/core/0.12.10/dist/worker.js",DEFAULT:{CORE:"https://gw.alipayobjects.com/os/lib/ffmpeg/core/0.12.10/dist/esm/ffmpeg-core.js",WASM:"https://gw.alipayobjects.com/os/lib/ffmpeg/core/0.12.10/dist/esm/ffmpeg-core.wasm"},MT:{CORE:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.js",WASM:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.wasm",WORKER:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.worker.js"}};function xt(t,e,i,s){const r=e.getContext("2d");dt(r),r.clearRect(0,0,e.width,e.height),i&&(r.save(),r.fillStyle=i,r.fillRect(0,0,e.width,e.height),r.restore()),s&&r.drawImage(s,0,0,s.width,s.height,0,0,e.width,e.height),r.drawImage(t,0,0,t.width,t.height,0,0,e.width,e.height)}async function vt(){return new Promise(async(t,e)=>{try{await function(t,e={}){return new Promise((i,s)=>{const r=document.querySelector(`script[src="${t}"]`);if(r)return"true"===r.dataset.loaded?void i(r):(r.addEventListener("load",()=>{i(r)}),void r.addEventListener("error",()=>{s(new Error(`Script already failed: ${t}`))}));const a=document.createElement("script");a.src=t,a.async=!0,Object.keys(e).forEach(t=>{a.setAttribute(t,e[t]??"")}),a.onload=()=>{a.dataset.loaded="true",i(a)},a.onerror=()=>{s(new Error(`Failed to load script: ${t}`))},document.head.appendChild(a)})}(yt.SCRIPT,{crossOrigin:"anonymous"});const e={locateFile:(t,e)=>t.endsWith("createWebPCore.wasm")?yt.WASM:e+t};t(await window.createWebPCore(e))}catch(t){e(t)}})}function Pt(t){for(const e of t.getCompositions())for(const t of e.textures)t.isDestroyed||t.dispose();t.assetManagers=[],t.destroyCurrentCompositions()}var Dt,It,bt,Ct,Et,At,St,zt,Tt,_t,Mt,Vt,kt,Bt,Ft,Ut,Rt,Wt,Gt=class{constructor(t,e,i,s){m(this,"sdk"),m(this,"player"),m(this,"container"),m(this,"emitter"),m(this,"interactionUtils"),this.player=t,this.sdk=s,this.container=e,this.emitter=i}init(){this.interactionUtils=new pt(this)}getPageData(){return this.sdk.pageData}getCurrentComposition(){return this.player.getCompositions()[0]}isItemSelected(t){return!!this.sdk.pageData?.activeData.selectedItems?.find(e=>e===t)}getItemEditEnable(t){const e=this.getViewItemById(t);if(!e||!this.sdk.pageData||this.sdk.pageData.viewProperties[this.sdk.pageData.activeData.view??0]?.ignoreInteraction)return!1;const i=this.sdk.pageData.time,{duration:s,delay:r,endBehavior:a}=e;return i>=r&&(i<r+s||a===w.spec.EndBehavior.restart)}getItemShow(t){const e=this.getViewItemById(t);if(!this.sdk.pageData||!e?.property.visible)return!1;const i=this.sdk.pageData.time,{duration:s,delay:r,endBehavior:a}=e;return i>=r&&(i<r+s||a===w.spec.EndBehavior.restart||a===w.spec.EndBehavior.freeze)}addSelectedItems(t){var e;(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),(e=this.sdk.pageData.activeData).selectedItems??(e.selectedItems=[]),t.forEach(t=>{ct(this.sdk.pageData?.activeData.selectedItems??[],t)}),this.emitter.emit("selectedItemChange",t)}clearSelectedItems(){this.sdk.pageData&&(this.sdk.pageData.activeData.selectedItems=[],this.emitter.emit("selectedItemChange",[]))}getSelectedItems(){const t=this.sdk.pageData?.activeData.selectedItems;return this.sdk.pageData?.items.filter(e=>t?.find(t=>t===e.id))??[]}addPreSelectedItem(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=t,this.emitter.emit("preSelectedItemChange",t)}clearPreSelectedItem(){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=void 0,this.emitter.emit("preSelectedItemChange",void 0)}getPreSelectedItem(){const t=this.getPageData();(0,w.assertExist)(t,"You must call SDK#run() first");const e=t.activeData.preSelectedItem;return e?this.getViewItemById(e):void 0}getViewItemById(t){return this.sdk.pageData?.items.find(e=>e.id===t)}getPlayerSizeByParent(t,e){const[i,s]=t,[r,a]=e;let o=s,n=o/(a||1624)*(r||750);return n>i&&(o=i/n*s,n=i),[n,o]}async loadScene(t){Pt(this.player);const e=this.sdk.pageData?.viewProperties[t];if(!e||!this.sdk.pageData)return void console.warn(`This page does not have ${t} view property.`);const{scene:i,size:s}=e,r=this.container.parentElement?.offsetWidth??300,a=this.container.parentElement?.offsetHeight??300,[o,n]=this.getPlayerSizeByParent([r,a],s);this.container.style.width=`${o}px`,this.container.style.height=`${n}px`,this.sdk.pageData.activeData={view:t,selectedItems:[],preSelectedItem:void 0},this.player.resize();const c=JSON.parse(JSON.stringify(i)),h=await this.player.loadScene(c,{autoplay:!1});this.player.gotoAndStop(this.sdk.pageData.time),this.interactionUtils.refreshViewParam(),this.interactionUtils.refreshCameraParam(),this.sdk.pageData.items=[],this.addViewItemsByItems(this.sdk.pageData.items,h.items),this.emitter.emit("pageDataChange",this.sdk.pageData)}refreshPageTime(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.time=t}pageZoom(t){var e;(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const{zoom:i}=this.sdk.pageData.property;(e=this.sdk.pageData.property).zoom??(e.zoom=1);const s=b(t,-.1,.1),r=S(b(i+s,.3,10),2);this.sdk.pageData.property.zoom=r,this.container.style.scale=`${r}`,this.emitter.emit("zoomChange",r)}setPageZoom(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const e=S(b(t,.3,10),2);this.sdk.pageData.property.zoom=e,this.container.style.scale=`${e}`,this.emitter.emit("zoomChange",t)}refreshInteractionParam(){this.interactionUtils.refreshViewParam(),this.interactionUtils.refreshCameraParam()}pageMove(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const[e,i]=this.sdk.pageData.property.translation??[0,0],s=e+t.x,r=i+t.y;this.sdk.pageData.property.translation=[s,r],this.refreshInteractionParam(),this.container.style.translate=`${s}px ${r}px`,this.emitter.emit("pageDataChange",this.sdk.pageData)}rotateItem(t,e){const i=this.getPlayerItemById(t);i&&(i.rotate(...e.toArray()),this.transformSceneItem(t,"rotation",e.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"rotation"}))}moveItem(t,e){const i=this.getPlayerItemById(t);if(i){const s=(new U).copyFrom(i.transform.getParentMatrix()??new U);s.setPosition(new F);const r=e.clone().applyMatrix(s.invert());i.translate(...r.toArray()),i.transform.updateLocalMatrix(),this.transformSceneItem(t,"position",r.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"translation"})}}scaleItem(t,e){const i=this.getPlayerItemById(t);i&&(i.scale(...e.toArray()),this.transformSceneItem(t,"scale",e.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"size"}))}getItemTransformById(t){const e={matrix:new U,parentMatrix:new U},i=this.getPlayerItemById(t);if(void 0!==i?.transform){i.transform.updateLocalMatrix();const t=U.fromArray(i.composition?.transform.getWorldMatrix().elements??[]).invert();e.matrix=t.clone().multiply(U.fromArray(i.transform.getWorldMatrix().elements)),e.parentMatrix=t.clone().multiply(U.fromArray(i.transform.parentTransform?.getWorldMatrix().elements??(new U).toArray()))}return e}addViewItemsByItems(t,e,i){const s=e=>{e.forEach(e=>{t.find(t=>t.id===e.getInstanceId())||t.push(this.createViewItemByPlayerItem(e,i))})};for(const i of e)me.config.pageConfig.filterItemNames.includes(i.name)||(s([i]),this.addViewItemsByItems(t,i.children,i.getInstanceId()))}createViewItemByPlayerItem(t,e){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const{transform:i,composition:s,isVisible:r}=t;i.updateLocalMatrix();const a=(new U).copyFrom(s?.transform.getWorldMatrix()??(new U).identity()).invert().multiply(i.getWorldMatrix()),o=new F,n=new B,c=new F;a.decompose(o,n,c);const h=(new R).setFromQuaternion(n);h.x=Number.isNaN(h.x)?0:h.x,h.y=Number.isNaN(h.y)?0:h.y,h.z=Number.isNaN(h.z)?0:h.z;const p=o.toArray().map(t=>S(t,2)),l=h.toArray().map(t=>S(t,2)),m=c.toArray().map(t=>S(t,2)),d=i.size.toArray(),g={position:p,rotation:l,size:this.getPixelSizeByWorldSize([m[0]*d[0],m[1]*d[1],m[2]],t).map(t=>S(t,2)),visible:r,keyPropertyEditing:!1};switch(t.type){case w.spec.ItemType.sprite:{const e=this.getActiveScene()?.scene;if(e){e.components.filter(e=>e.item.id===t.getInstanceId()).forEach(t=>{if(g.keyPropertyEditing||!("renderer"in t)||!("texture"in t.renderer)||!t.renderer.texture)return;const i=e.textures?.find(e=>e.id===t.renderer.texture.id);if(i&&"source"in i&&i.source){const t=e?.images.find(t=>t.id===i.source.id);g.keyPropertyEditing=!!t?.template;const s=t?.url??"";s&&Object.assign(g,{image:s})}})}break}case w.spec.ItemType.text:case w.spec.ItemType.richtext:{const e=this.getActiveScene()?.scene;if(g.keyPropertyEditing=!0,e){e.components.filter(e=>e.item.id===t.getInstanceId()).forEach(t=>{if(![w.spec.DataType.TextComponent,w.spec.DataType.RichTextComponent].includes(t.dataType))return;const{textAlign:e,textColor:i,text:s,fontWeight:r,fontFamily:a}=t.options;Object.assign(g,{alignment:e,color:i,weight:r,text:s,font:a})})}break}}return{id:t.getInstanceId(),name:t.name,parentId:t.parentId??e,children:[],type:t.type,duration:t.duration,delay:t.defination.delay,endBehavior:t.endBehavior,property:g}}getViewBoxById(t){const e=new V,i=this.getPlayerItemById(t),s=this.getChildrenPlayerItems(i);return i&&s?this.getViewBoxByPlayerItem(i,s):e}getItemViewAnchor(t){const e=this.getPlayerItemById(t);if(e?.transform?.anchor){const t=(new F).copyFrom(e.transform.anchor).applyMatrix((new U).copyFrom(e.transform.getWorldMatrix()));return this.interactionUtils.projectPoint(t).round(2)}}getChildrenPlayerItems(t){const e=[];return t?(e.push(...this.player.getCompositions()[0].items.filter(e=>e.parentId===t.getInstanceId())),e.push(...e.flatMap(t=>this.getChildrenPlayerItems(t))),e):[]}getChildrenSceneItemIds(t,e){const i=[];return i.push(...e.items.filter(e=>e.parentId===t).map(t=>t.id)),i.push(...i.flatMap(t=>this.getChildrenSceneItemIds(t,e))),i}getViewBoxByPlayerItem(t,e){const i=new V;switch(t.type){case w.spec.ItemType.sprite:case w.spec.ItemType.plugin:case w.spec.ItemType.video:case w.spec.ItemType.richtext:case w.spec.ItemType.text:case w.spec.ItemType.shape:{const{transform:s,composition:r}=t;s.updateLocalMatrix();const{size:a}=s,o=(new U).copyFrom(r?.transform.getWorldMatrix()??new U).invert().multiply(s.getWorldMatrix()),{x:n,y:c}=a.clone().divide(2),h=new F(n,c,0).applyMatrix(o),p=new F(n,-c,0).applyMatrix(o),l=new F(-n,-c,0).applyMatrix(o),m=new F(-n,c,0).applyMatrix(o),d=this.interactionUtils.projectPoint(h).round(2),g=this.interactionUtils.projectPoint(p).round(2),u=this.interactionUtils.projectPoint(l).round(2),f=this.interactionUtils.projectPoint(m).round(2);i.setFromVec2Array([d,g,u,f]);const y=e?.map(t=>this.getViewBoxById(t.getInstanceId()));y&&y.map(t=>i.union(t));break}case w.spec.ItemType.null:{const t=e?.map(t=>this.getViewBoxById(t.getInstanceId()));t&&t.map(t=>i.union(t));break}}return i}getViewportLeftTopPosition(){if(!this.sdk.pageData)return new _;const{zoom:t,translation:e}=this.sdk.pageData.property,{offsetWidth:i,offsetHeight:s}=this.container.parentElement,{offsetWidth:r,offsetHeight:a}=this.container,o=new _(i,s),n=new _(r,a).multiply(t);return o.clone().divide(2).subtract(n.clone().divide(2)).add(e)}getContainerPosition(){const{offsetWidth:t,offsetHeight:e}=this.container.parentElement;return new _(t/2,e/2).add(new _(...this.sdk.pageData?.property.translation??[0,0]))}getViewportByViewPoint(t){if(!this.sdk.pageData)return t;const{zoom:e}=this.sdk.pageData.property,{offsetWidth:i,offsetHeight:s}=this.container,r=new _(i,s).multiply(e),a=this.getViewportLeftTopPosition(),o=t.clone().subtract(a);return new _(o.x/r.x*2-1,1-o.y/r.y*2)}getActiveScene(){return this.sdk.pageData?.viewProperties[this.sdk.pageData?.activeData.view??-1]}async changeItemProperty(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const e=this.getViewItemById(t.itemId),i=this.getPlayerItemById(t.itemId);if(e&&i)if(t.propertyName in e.property){switch(t.propertyName){case"alignment":[w.spec.TextAlignment.left,w.spec.TextAlignment.middle,w.spec.TextAlignment.right].includes(t.propertyValue)&&i.getComponent(w.TextComponent).setTextAlign(t.propertyValue);break;case"color":Array.isArray(t.propertyValue)&&4===t.propertyValue.length&&(console.log(t.propertyValue),i.getComponent(w.TextComponent).setTextColor(t.propertyValue));break;case"font":if("string"==typeof t.propertyValue){const e=t.propertyValue.split("/"),s=e[e.length-1]?.split(".")[0],r=this.player.getAssetManager()[0];await r.processFontURL([{fontURL:t.propertyValue,fontFamily:s}]),s&&i.getComponent(w.TextComponent).setFontFamily(s)}break;case"text":"string"==typeof t.propertyValue&&i.getComponent(w.TextComponent).setText(t.propertyValue);break;case"weight":[w.spec.TextWeight.normal,w.spec.TextWeight.bold,w.spec.TextWeight.lighter].includes(t.propertyValue)&&i.getComponent(w.TextComponent).setFontWeight(t.propertyValue);break;case"image":"string"==typeof t.propertyValue&&i.getComponent(w.SpriteComponent).setTexture(await w.Texture.fromImage(t.propertyValue,this.player.renderer.engine));break;case"position":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const i=t.propertyValue.map((t,i)=>t-(e.property.position[i]??0));this.moveItem(t.itemId,new F(...i))}break;case"rotation":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const i=t.propertyValue.map((t,i)=>t-(e.property.rotation[i]??0));this.rotateItem(t.itemId,new F(...i).negate())}break;case"size":if(Array.isArray(t.propertyValue)&&2===t.propertyValue.length){const i=t.propertyValue.map(t=>0===t||null===t?1:t),s=e.property.size.map(t=>t||1),r=i.map((t,e)=>t/s[e]);this.scaleItem(t.itemId,new F(...r,1))}break;case"visible":if("boolean"==typeof t.propertyValue&&(i.setVisible(t.propertyValue),me.config.pageConfig.groupVisible)){this.getChildrenPlayerItems(i).forEach(e=>{e.setVisible(t.propertyValue)})}}["position","rotation","size"].includes(t.propertyName)||this.player.gotoAndStop(this.sdk.pageData.time),this.changeViewItemProperty(t),this.refreshViewItem(t.itemId)}else console.warn(`Item does not have property ${t.propertyName}.`);else console.warn(`Id ${t.itemId} is not a item id.`)}changeViewItemProperty(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.viewProperties.forEach((e,i)=>{if(!this.sdk.pageData?.property.asyncMode&&i!==this.sdk.pageData?.activeData.view)return;const{scene:s}=e;switch(t.propertyName){case"position":case"rotation":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const e=this.sdk.pageData.items.find(e=>e.id===t.itemId),i=e?.property[t.propertyName],r=t.propertyValue.map((t,e)=>t-(i?.[e]??0));this.changeSceneItemProperty(s,{...t,propertyValue:r})}break;case"size":if(Array.isArray(t.propertyValue)&&2===t.propertyValue.length){const e=this.sdk.pageData.items.find(e=>e.id===t.itemId),i=e?.property[t.propertyName],r=t.propertyValue.map((t,e)=>t/(i?.[e]??0));this.changeSceneItemProperty(s,{...t,propertyValue:r})}break;default:this.changeSceneItemProperty(s,t)}})}changeSceneItemProperty(t,e){switch(e.propertyName){case"alignment":if([w.spec.TextAlignment.left,w.spec.TextAlignment.middle,w.spec.TextAlignment.right].includes(e.propertyValue)){const i=t.components.find(t=>t.item.id===e.itemId&&[w.spec.DataType.TextComponent,w.spec.DataType.RichTextComponent].includes(t.dataType));i?.options&&"textAlign"in i.options&&(console.log(e.propertyValue),i.options.textAlign=e.propertyValue)}break;case"color":if(Array.isArray(e.propertyValue)&&4===e.propertyValue.length){const i=t.components.find(t=>t.item.id===e.itemId&&[w.spec.DataType.TextComponent,w.spec.DataType.RichTextComponent].includes(t.dataType));i?.options&&(i.options.textColor=[...e.propertyValue])}break;case"font":if("string"==typeof e.propertyValue){const i=e.propertyValue.split("/"),s=i[i.length-1]?.split(".")[0],r=t.fonts?.find(t=>"family"in t&&t.family===s||"fontFamily"in t&&t.fontFamily===s);!r&&t.fonts&&s&&t.fonts.push({fontFamily:s,fontURL:e.propertyValue});const a=t.components.find(t=>t.item.id===e.itemId&&[w.spec.DataType.TextComponent,w.spec.DataType.RichTextComponent].includes(t.dataType));a?.options&&(a.options.fontFamily=s)}break;case"text":if("string"==typeof e.propertyValue){const i=t.components.find(t=>t.item.id===e.itemId&&[w.spec.DataType.TextComponent,w.spec.DataType.RichTextComponent].includes(t.dataType));i?.options&&(i.options.text=e.propertyValue)}break;case"weight":if("string"==typeof e.propertyValue){const i=t.components.find(t=>t.item.id===e.itemId&&[w.spec.DataType.TextComponent,w.spec.DataType.RichTextComponent].includes(t.dataType));i?.options&&(i.options.fontWeight=e.propertyValue)}break;case"image":if("string"==typeof e.propertyValue){t.components.filter(t=>t.item.id===e.itemId).forEach(i=>{if(!("renderer"in i))return;const s=t.textures?.find(t=>t.id===i.renderer.texture.id);if(s&&"source"in s&&s.source){const i=t?.images.find(t=>t.id===s.source.id);i?.url&&i?.webp&&(i.url=e.propertyValue,i.webp=e.propertyValue),i&&"template"in i&&i.template.background&&(i.template.background.url=e.propertyValue)}})}break;case"position":if(Array.isArray(e.propertyValue)&&3===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.position.x+=e.propertyValue[0],i.transform.position.y+=e.propertyValue[1],i.transform.position.z+=e.propertyValue[2])}break;case"rotation":if(Array.isArray(e.propertyValue)&&3===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.eulerHint.x+=e.propertyValue[0],i.transform.eulerHint.y+=e.propertyValue[1],i.transform.eulerHint.z+=e.propertyValue[2])}break;case"size":if(Array.isArray(e.propertyValue)&&2===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.scale.x*=e.propertyValue[0],i.transform.scale.y*=e.propertyValue[1])}break;case"visible":{const i=t.items.find(t=>t.id===e.itemId);if(i&&(i.visible=e.propertyValue,me.config.pageConfig.groupVisible)){this.getChildrenSceneItemIds(e.itemId,t).forEach(i=>{const s=t.items.find(t=>t.id===i);s&&(s.visible=e.propertyValue)})}break}}}transformSceneItem(t,e,i){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.viewProperties.forEach((s,r)=>{if(!this.sdk.pageData?.property.asyncMode&&r!==this.sdk.pageData?.activeData.view)return;const{scene:a}=s;switch(e){case"position":if(Array.isArray(i)&&3===i.length){const e=a.items.find(e=>e.id===t);e?.transform&&(e.transform.position.x+=i[0],e.transform.position.y+=i[1],e.transform.position.z+=i[2])}break;case"rotation":if(Array.isArray(i)&&3===i.length){const e=a.items.find(e=>e.id===t);e?.transform&&(e.transform.eulerHint.x+=i[0],e.transform.eulerHint.y+=i[1],e.transform.eulerHint.z+=i[2])}break;case"scale":if(Array.isArray(i)&&3===i.length){const e=a.items.find(e=>e.id===t);e?.transform&&(e.transform.scale.x*=i[0],e.transform.scale.y*=i[1],e.transform.scale.z*=i[2])}}})}refreshViewItem(t){const e=this.sdk.pageData;(0,w.assertExist)(e,"You must call SDK#run() first");const i=e.items.findIndex(e=>e.id===t);if(i<0)return void console.log(`item ${t} is not existed.`);const s=e.items[i],r=this.getPlayerItemById(t);r&&s&&(e.items[i]=this.createViewItemByPlayerItem(r,s.parentId))}getPlayerItemById(t){return this.player.getCompositions()[0]?.items.find(e=>e.getInstanceId()===t)}getPixelSizeByWorldSize(t,e){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const i=[0,0],s=e.composition?.camera,r=this.sdk.pageData.viewProperties[this.sdk.pageData.activeData.view??0]?.size;if(s&&r){const{z:a}=e.transform.getWorldPosition(),{x:o,y:n}=s.getInverseVPRatio(a);i[0]=Math.abs(t[0]*r[0]/o/2),i[1]=Math.abs(t[1]*r[1]/n/-2)}else console.warn("camera is not existed.");return i}},Ht=l(require("jszip"),1),Nt=l(require("jszip"),1),Lt="ready",Kt="executable",Ot="dispose",jt={APNG:"APNG",MP4:"MP4",WebM:"WebM",Images:"Images",WebP:"WebP",GIF:"GIF",AlphaMaskVideo:"AlphaMaskVideo"},$t="idle",Yt="convertImage",qt="transcoding",Jt="audio",Xt="jpeg",Zt="webp",Qt="png",te=(jt.MP4,jt.WebP,jt.APNG,jt.GIF,jt.AlphaMaskVideo,jt.Images,jt.MP4,jt.WebP,jt.APNG,jt.GIF,jt.AlphaMaskVideo,jt.Images,"default"),ee="exporting",ie="success",se="error",re=class{constructor(t){m(this,"sampleRate"),m(this,"duration"),m(this,"channels");const{sampleRate:e=44100,duration:i=1,channels:s=2}=t??{};this.sampleRate=e,this.duration=i,this.channels=s}getBuffer(){const t=this.sampleRate*this.duration*this.channels*2,e=44+t,i=new ArrayBuffer(e),s=new DataView(i);let r=0;const a=t=>{for(let e=0;e<t.length;e++)s.setUint8(r++,t.charCodeAt(e))},o=t=>{s.setUint32(r,t,!0),r+=4},n=t=>{s.setUint16(r,t,!0),r+=2};a("RIFF"),o(e-8),a("WAVE"),a("fmt "),o(16),n(1),n(this.channels),o(this.sampleRate),o(this.sampleRate*this.channels*2),n(2*this.channels),n(16),a("data"),o(t);for(let e=0;e<t;e++)s.setUint8(r++,0);return new Uint8Array(i)}},ae=["@vvfx/sdk","exporter"],oe=class extends w.EventEmitter{constructor(t){super(),m(this,"status",Lt),m(this,"stage",$t),m(this,"mediaType"),m(this,"loggerInTranscoding"),m(this,"multiThreading"),m(this,"extraCanvas"),m(this,"player"),u(this,Dt,0),u(this,It),u(this,bt),u(this,Ct),u(this,Et),u(this,At,[]),u(this,St),u(this,zt),u(this,Tt,[]),u(this,_t,0),u(this,Mt),u(this,Vt,[]),u(this,kt,0),u(this,Bt,0),u(this,Ft,0),u(this,Ut,0),u(this,Rt,[]),u(this,Wt,!0);const{mediaType:e,extraCanvas:i,loggerInTranscoding:s,multiThreading:r}=t;this.mediaType=e,this.loggerInTranscoding=s??!1,this.multiThreading=r??!1,this.extraCanvas=i??void 0,this.onInit()}get canceled(){return this.status===Ot}get config(){const t=this.player?.getCompositions()??[],e=t?.[0],i=e?.name??(new Date).getTime().toString(),s=e?.getDuration()??0,r=e?.startTime??0,a=g(this,Mt)?.time;return{name:i,startTime:r,oldTotalTime:s,newTotalTime:a,fps:g(this,Mt)?.fps??30,backgroundColor:g(this,Mt)?.backgroundColor??"#000000",loop:g(this,Mt)?.loop??!0,audioEnable:g(this,Mt)?.audioEnable??!1}}get progress(){const t=g(this,Bt)||1,e=g(this,Ft)||1,i=Math.min(t/e,1),s=Math.min(g(this,kt),t)/t*.4,r=Math.min(g(this,Ut),t)/t*.6,a=Math.min(s+r,1);g(this,Vt)[g(this,_t)]=i;const o=g(this,Vt).reduce((t,e,i)=>i<g(this,_t)?t+(e||0):t,0)+a*i;return Math.min((n=o,Math.round(100*n)/100),1);var n}get transImageType(){return this.mediaType===jt.MP4?Xt:this.mediaType===jt.WebP?Zt:Qt}async onInit(){try{gt("log",[...ae,"ready"],"starting"),this.status=Lt,await this.loadHelper(this.mediaType),this.status=Kt,gt("log",[...ae,"ready"],"success"),this.emit("ready",this.mediaType)}catch(t){this.status=Ot,this.onError(t)}finally{return this.status}}onReset(){this.stage=$t,window.cancelAnimationFrame(g(this,Dt)),f(this,Dt,0),this.player?.pause(),this.clearTaskInfo(),this.setProgress()}onError(t){gt("log",[...ae,"error"],t),this.onFinish(!1,g(this,Rt)),this.emit("error",t),this.dispose()}onFinish(t,e){gt("log",[...ae,"finish"],t?"success":"failed"),this.emit("progress",1),this.emit("finish",t,e)}async loadHelper(t){const e="WebP"===t&&!g(this,Ct),i=[jt.MP4,jt.APNG,jt.GIF,jt.AlphaMaskVideo].includes(t)&&!g(this,bt);e&&f(this,Ct,await vt()),i&&(f(this,bt,await async function(t){const{multiThreading:e}=t??{},i=new lt.FFmpeg,s=!!e,r={classWorkerURL:await(0,mt.toBlobURL)(wt.CLASSWORKER,"text/javascript"),coreURL:"",wasmURL:""};return s?(r.coreURL=await(0,mt.toBlobURL)(wt.MT.CORE,"text/javascript"),r.wasmURL=await(0,mt.toBlobURL)(wt.MT.WASM,"application/wasm"),r.workerURL=await(0,mt.toBlobURL)(wt.MT.WORKER,"text/javascript")):(r.coreURL=await(0,mt.toBlobURL)(wt.DEFAULT.CORE,"text/javascript"),r.wasmURL=await(0,mt.toBlobURL)(wt.DEFAULT.WASM,"application/wasm")),await i.load(r),i}({multiThreading:this.multiThreading})),g(this,bt).on("log",({message:t})=>{if(this.loggerInTranscoding&&gt("log",[...ae,"transcoding log"],t),this.canceled||this.stage!==qt)return;const e=/frame=\s*(\d+)/.exec(t);if(e?.[1]){const t=Number(e[1]);this.setProgress({currentTaskInTranscodingFrameIndex:t})}}))}getAllTaskFrames(t){return t.reduce((t,e)=>{const{scene:i,fps:s}=e,r=i.compositions?.[0]?.duration??0;return t+Math.round(r*(s??30))},0)}setProgress(t){void 0!==t?.completedTaskPercentArray&&f(this,Vt,t.completedTaskPercentArray),void 0!==t?.currentTaskFrameIndex&&f(this,kt,t.currentTaskFrameIndex),void 0!==t?.currentTaskTotalFrames&&f(this,Bt,t.currentTaskTotalFrames),void 0!==t?.currentTaskInTranscodingFrameIndex&&f(this,Ut,t.currentTaskInTranscodingFrameIndex),void 0!==t?.allTaskFrames&&f(this,Ft,t.allTaskFrames),this.emit("progress",this.progress)}forwardPlayerTime(t,e=!1){(0,w.assertExist)(this.player);const{oldTotalTime:i,startTime:s}=this.config;(0,w.assertExist)(i);const r=1e3*i-1e3*i%15;return t=Math.min(t,r/1e3),e?this.player.gotoAndPlay(t-s):this.player.gotoAndStop(t-s),t}getWavAudio(t){f(this,St,new re),g(this,bt)?g(this,bt).writeFile(t,g(this,St).getBuffer()):gt("log",[...ae,"getWavAudio"],"ffmpegCore is not ready")}async getImagesZip(t,e){const i=new Nt.default,s=i.folder(t);return(0,w.assertExist)(s),g(this,Tt).forEach((t,i)=>{s.file(t,e[i])}),i.generateAsync({type:"arraybuffer"})}getWebP(){(0,w.assertExist)(g(this,Ct));const t=Math.round(1e3/this.config.fps/1),e="out.webp",i=`${g(this,Tt).join(` -d ${t} `)} -d ${t} -o ${e} -loop ${this.config.loop?0:1}`.split(" "),s=g(this,Ct).cwrap("main","string",["number","number"]),[r,a]=function(t,e){const i=t._malloc(e.length*Uint32Array.BYTES_PER_ELEMENT);return e.forEach((e,s)=>{const r=t._malloc(e.length+1);t.writeAsciiToMemory(e,r),t.setValue(i+Uint32Array.BYTES_PER_ELEMENT*s,r,"i32")}),[e.length,i]}(g(this,Ct),i);dt(r&&a,"getWebP has error"),s(r,a);const o=g(this,Ct).FS.readFile(e);return g(this,Tt).forEach(t=>{g(this,Ct)?.FS.unlink(t)}),o}async getAPNG(){(0,w.assertExist)(g(this,bt));this.stage=qt;const t="export.apng";if(0!==await g(this,bt).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-plays",this.config.loop?"0":"1","-y",t]))throw new Error("the command executed by ffmpeg to generate a apng failed.");return t}async getGIF(){(0,w.assertExist)(g(this,bt));this.stage=qt;const t="export.gif";if(0!==await g(this,bt).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-loop",this.config.loop?"0":"-1","-vf","scale=-1:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse","-y",t]))throw new Error("the command executed by ffmpeg to generate a gif failed.");return t}async getMP4(t,e){(0,w.assertExist)(g(this,bt));this.stage=qt;const i="export.mp4";let s;const r=e?",setpts=PTS/"+Math.round(t/e*100)/100:"",a=e??t;this.config.audioEnable&&!g(this,St)&&(f(this,zt,"audio.wav"),this.getWavAudio(g(this,zt)));if(0!==await g(this,bt).exec(["-framerate",String(this.config.fps),"-start_number",String(1),"-i",`image-%4d.${this.transImageType}`,"-c:v","libx264","-crf","23","-pix_fmt","yuv420p","-vf",`pad=ceil(iw/2)*2:ceil(ih/2)*2${r}`,"-y",i]))throw new Error("the command executed by ffmpeg to generate a mp4 failed.");if(g(this,zt)&&g(this,St)){this.stage=Jt,s="export-with-audio.mp4";if(0!==await g(this,bt).exec(["-i",i,"-i",g(this,zt),"-c:v","copy","-c:a","aac","-t",`${a}`,"-y",s]))throw new Error("the command executed by ffmpeg to generate a audio of video failed.")}return s&&g(this,bt).deleteFile(i).catch(()=>{gt("log",[...ae,"ffmpeg delete file error"])}),s??i}async getAlphaMaskVideo(t,e){(0,w.assertExist)(g(this,bt));this.stage=qt;const i="export.mp4",s=e?",setpts=PTS/"+Math.round(t/e*100)/100:"";return await g(this,bt).exec(["-framerate",String(this.config.fps),"-start_number",String(1),"-i",`image-%4d.${this.transImageType}`,"-c:v","libx264","-crf","23","-pix_fmt","yuv420p","-vf",`pad=ceil(iw/2)*2:ceil(ih/2)*2${s}`,"-y",i]),i}async getVideoByType(t,e){(0,w.assertExist)(g(this,bt));const i=this.mediaType===jt.APNG,s=this.mediaType===jt.GIF,r=this.mediaType===jt.AlphaMaskVideo,a=this.mediaType===jt.MP4;let o="";try{i&&(o=await this.getAPNG()),s&&(o=await this.getGIF()),a&&(o=await this.getMP4(t,e)),r&&(o=await this.getAlphaMaskVideo(t,e)),this.stage=$t}catch(t){throw t}finally{for(const t of g(this,Tt))t&&g(this,bt).deleteFile(t)}let n=null;try{(0,w.assertExist)(o);const t=await g(this,bt).readFile(o);n="string"==typeof t?(new TextEncoder).encode(t):new Uint8Array(t)}finally{g(this,bt).deleteFile(o).catch(()=>{gt("log",[...ae,"ffmpeg delete file error"])})}return n}onRecordWebM(t){const e=new MediaRecorder(t.captureStream(this.config.fps),{mimeType:"video/webm;codecs=vp9"});f(this,Et,e),g(this,Et).start(0);const i=[];g(this,Et).ondataavailable=t=>{t.data.size>0&&i.push(t.data)},f(this,At,i)}async onExportImageFrame(t){try{if(this.canceled)return;const{canvas:s,imageBuffers:r,startTime:a,oldTotalTime:o,newTotalTime:n}=t;(0,w.assertExist)(this.player),(0,w.assertExist)(g(this,It));const c=g(this,kt)+1;this.stage=Yt,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:c}),this.loggerInTranscoding&&gt("log",[...ae,"converting log"],`converting ${c} frame image`),c>=1&&this.forwardPlayerTime(c/this.config.fps+a),xt(g(this,It),s,this.config.backgroundColor);let h=s;this.mediaType===jt.AlphaMaskVideo&&((0,w.assertExist)(this.extraCanvas),function(t,e){e.width=2*t.width,e.height=t.height;const i=t.getContext("2d");if(!i)throw new Error("inputCtx is null");const s=e.getContext("2d");if(!s)throw new Error("ctx is null");s.clearRect(0,0,e.width,e.height);const r=i.getImageData(0,0,t.width,t.height),a=i.getImageData(0,0,t.width,t.height),o=r.data;for(let t=0;t<o.length;t+=4){const e=Math.max(0,(o[t+3]??0)-5)/250*255;e<=0?(o[t]=0,o[t+1]=0,o[t+2]=0,o[t+3]=255):(o[t]=(o[t]??0)*e/255,o[t+1]=(o[t+1]??0)*e/255,o[t+2]=(o[t+2]??0)*e/255,o[t+3]=255)}s.putImageData(r,0,0);const n=a.data;for(let t=0;t<n.length;t+=4){const e=Math.max(0,(n[t+3]??0)-5)/250*255;n[t]=e,n[t+1]=e,n[t+2]=e,n[t+3]=255}s.putImageData(a,t.width,0)}(s,this.extraCanvas),h=this.extraCanvas);const p=await async function(t,e,i){return new Promise((s,r)=>{t.toBlob(t=>{t?s(t.arrayBuffer()):r("toBlob failed")},e,i)})}(h,`image/${this.transImageType}`,1),l=`image-${e=c,i=4,String(e).padStart(i,"0")}.${this.transImageType}`;this.mediaType===jt.Images?r.push(p):this.mediaType===jt.WebP?((0,w.assertExist)(g(this,Ct)),g(this,Ct).FS.writeFile(l,new Uint8Array(p))):((0,w.assertExist)(g(this,bt)),await g(this,bt).writeFile(l,new Uint8Array(p))),g(this,Tt).push(l);if(c===g(this,Bt)){this.player?.pause(),await new Promise(t=>{window.requestAnimationFrame(t)});let t=null;"Images"===this.mediaType?t=await this.getImagesZip(this.config.name,r):"WebP"===this.mediaType?t=this.getWebP():[jt.MP4,jt.APNG,jt.GIF,jt.AlphaMaskVideo].includes(this.mediaType)&&(t=await this.getVideoByType(o,n)??null),t&&(gt("log",[...ae,"done"],"success"),this.emit("done",g(this,Mt),!0,t))}else f(this,Dt,window.requestAnimationFrame(()=>{this.canceled||this.onExportImageFrame({canvas:s,imageBuffers:r,startTime:a,oldTotalTime:o,newTotalTime:n})}))}catch(t){gt("log",[...ae,"onExportImageFrame","failed"],t),this.emit("done",g(this,Mt),!1)}var e,i}async onExportWebMFrame(t){try{if(this.canceled)return;(0,w.assertExist)(this.player),(0,w.assertExist)(g(this,It));const e=g(this,kt)+1;if(this.stage=Yt,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:e}),this.loggerInTranscoding&&gt("log",[...ae,"converting log"],`converting ${e} frame image`),xt(g(this,It),t,this.config.backgroundColor),1===e&&(this.player.play(),this.onRecordWebM(t)),e<g(this,Bt))f(this,Dt,window.requestAnimationFrame(()=>{this.canceled||this.onExportWebMFrame(t)}));else{this.player?.pause(),g(this,Et)?.stop();const t=new Blob(g(this,At),{type:"video/webm"}),e=await t.arrayBuffer();gt("log",[...ae,"done"],"success"),this.emit("done",g(this,Mt),!0,e)}}catch(t){gt("log",[...ae,"done"],"failed",t),this.emit("done",g(this,Mt),!1)}}async runTask(t){try{if(this.canceled)return;(0,w.assertExist)(this.player),(0,w.assertExist)(g(this,It));const{size:e,startTime:i,containerCanvas:s}=t,{oldTotalTime:r,newTotalTime:a}=this.config,[o,n]=e;if(g(this,It).width=o,g(this,It).height=n,s.width=o,s.height=n,this.player.resize(),f(this,Tt,[]),[jt.MP4,jt.APNG,jt.Images,jt.WebP,jt.GIF,jt.AlphaMaskVideo].includes(this.mediaType)){const t={canvas:s,imageBuffers:[],startTime:i,oldTotalTime:r,newTotalTime:a};await this.onExportImageFrame(t)}else"WebM"===this.mediaType&&await this.onExportWebMFrame(s)}catch(t){gt("log",[...ae,"run task error"],t),this.emit("done",g(this,Mt),!1)}}clearTaskInfo(){f(this,_t,0),f(this,Mt,void 0),f(this,Vt,[]),f(this,kt,0),f(this,Bt,0),f(this,Ft,0),f(this,Ut,0),f(this,Rt,[]),f(this,Wt,!0)}clearFFMpegCore(){if(g(this,bt)){for(const t of g(this,Tt))t&&g(this,bt).deleteFile(t);f(this,Tt,[]),g(this,bt).terminate(),f(this,bt,void 0)}}clearImage2WebPCore(){g(this,Ct)&&(g(this,Ct).FS.quit(),f(this,Ct,void 0))}clearMediaRecorder(){g(this,Et)&&(g(this,Et).stop(),f(this,Et,void 0)),f(this,At,[])}clearAllListeners(){for(const t of this.getListeners("ready"))this.off("ready",t);for(const t of this.getListeners("progress"))this.off("progress",t);for(const t of this.getListeners("done"))this.off("done",t);for(const t of this.getListeners("finish"))this.off("finish",t);for(const t of this.getListeners("error"))this.off("error",t)}onCancel(){this.canceled||(this.onFinish(!1,g(this,Rt)),this.status=Ot,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),gt("log",ae,"canceled"))}async onExport(t){const e=t.length;try{if(this.status===Lt)return gt("log",[...ae],"readying"),void this.on("ready",()=>{this.onExport(t)});if(this.status===Ot){if(await this.onInit()===Ot)throw new Error("init environment failed")}if(this.clearTaskInfo(),!g(this,It)){const t=document.createElement("canvas");t.dataset.key="player-canvas",f(this,It,t)}this.player||(this.player=new w.Player({canvas:g(this,It),pixelRatio:1,transparentBackground:!0,renderOptions:{willCaptureImage:!0}}),this.player.on("rendererror",t=>{this.onError(t)}),this.player.on("webglcontextlost",t=>{this.onError(t)}));let e=null;e??(e=document.querySelector('canvas[data-key="container-canvas"]')),e??(e=document.createElement("canvas")),e.dataset.key="container-canvas",e.style.display="none",this.setProgress({allTaskFrames:this.getAllTaskFrames(t)});const i=[];let s=!0;for(const[r,a]of t.entries()){if(this.canceled){s=!1;break}f(this,_t,r),f(this,Mt,a);const{size:t,scene:o}=a;await new Promise(async n=>{try{if(!this.player)throw new Error("player not found");gt("log",[...ae,"export"],"start",a),Pt(this.player),await this.player.loadScene(o,{env:"editor",autoplay:!1});const c=this.config.oldTotalTime,h=0;this.player.pause(),this.setProgress({currentTaskFrameIndex:0,currentTaskTotalFrames:Math.round(c*this.config.fps)});const p=(t,e,a)=>{this.off("done",p),e&&a?i[r]=a:s=!1,n()};this.on("done",p);const l={size:t,startTime:h,containerCanvas:e};await this.runTask(l)}catch(t){gt("log",[...ae,"export error"],t),s=!1,n()}})}f(this,Rt,i),f(this,Wt,s)}catch(t){this.onError(t),f(this,Wt,!1)}e>=1&&g(this,Wt)?this.onFinish(!0,g(this,Rt)):this.onFinish(!1,g(this,Rt))}dispose(){this.status=Ot,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),this.player?.dispose(),this.player=void 0,g(this,It)?.remove(),f(this,It,void 0),f(this,zt,void 0),f(this,St,void 0)}};Dt=new WeakMap,It=new WeakMap,bt=new WeakMap,Ct=new WeakMap,Et=new WeakMap,At=new WeakMap,St=new WeakMap,zt=new WeakMap,Tt=new WeakMap,_t=new WeakMap,Mt=new WeakMap,Vt=new WeakMap,kt=new WeakMap,Bt=new WeakMap,Ft=new WeakMap,Ut=new WeakMap,Rt=new WeakMap,Wt=new WeakMap;var ne=class extends w.EventEmitter{constructor(t){super(),m(this,"_config"),m(this,"_status",te),m(this,"_exportMedia"),this._config=t,this._exportMedia=new oe(t)}get status(){return this._status}onExportMP4(t,e){const i=t[0]?.folderName,s=new Ht.default;e.forEach((e,i)=>{if(!e)return;const{name:r}=t[i]??{};r&&s.file(`${r}.mp4`,e)}),s.generateAsync({type:"blob"}).then(t=>{ut(t,`${i}.zip`,"application/zip")}).catch(t=>{gt("error",["@vvfx/sdk"],"export mp4 is error",t)})}onExportGIF(t,e){const i=t[0]?.folderName,s=new Ht.default;e.forEach((e,i)=>{if(!e)return;const{name:r}=t[i]??{};r&&s.file(`${r}.gif`,e)}),s.generateAsync({type:"blob"}).then(t=>{ut(t,`${i}.zip`,"application/zip")}).catch(t=>{gt("error",["@vvfx/sdk"],"export gif is error",t)})}onExportImages(t,e){const i=t[0]?.folderName,s=new Ht.default;e.forEach((e,i)=>{if(!e)return;const{name:r}=t[i]??{};r&&s.file(`${r}.zip`,e)}),s.generateAsync({type:"blob"}).then(t=>{ut(t,`${i}.zip`,"application/zip")}).catch(t=>{gt("error",["@vvfx/sdk"],"export Images is error",t)})}onExportProgress(t){this.emit("progress",t)}onExportDone(t,e,i){this.emit("done",t,e,i)}onExportError(t){this._status=se,gt("error",["@vvfx/sdk"],"export is error",t)}onExport(t){this._status=ee,this._exportMedia.onExport(t),this._exportMedia.on("progress",this.onExportProgress.bind(this)),this._exportMedia.on("done",this.onExportDone.bind(this)),this._exportMedia.once("finish",(e,i)=>{this._status=e?ie:se,this.emit("complete",e),i&&0!==i.length&&(this._config.mediaType===jt.MP4?this.onExportMP4(t,i):this._config.mediaType===jt.GIF?this.onExportGIF(t,i):this._config.mediaType===jt.Images&&this.onExportImages(t,i))}),this._exportMedia.on("error",this.onExportError.bind(this))}onCancel(){this._status=se,this._exportMedia.onCancel(),this.emit("complete",!1)}dispose(){this._exportMedia.dispose()}},ce=class{constructor(){m(this,"enabled",!0),m(this,"_player"),m(this,"_container"),this._container=document.createElement("canvas"),this._player=new w.Player({canvas:this._container,manualRender:!0,renderOptions:{willCaptureImage:!0}})}async generate(t,e,i,s,r){if(!this.enabled)return void console.warn("Screen shot is not opened, use #SDK.setConfig() open this feature.");const[a,o]=e;this._container.width=a,this._container.height=o,this._player.resize();const n=JSON.parse(JSON.stringify(t));await this._player.loadScene(n,{reusable:!0,autoplay:!1}),this._player.gotoAndStop(s);const[c,h]=i,p=document.createElement("canvas");p.width=c,p.height=h;const l=p.getContext("2d");l&&(l.fillStyle="rgba(255, 255, 255, 1)",l.fillRect(0,0,c,h),this.drawImageCover(l,this._player.canvas,0,0,c,h,.5,.5));const m=p.toDataURL("image/png");return Pt(this._player),m}dispose(){this._player.dispose()}drawImageCover(t,e,i,s,r,a,o,n,c){2===arguments.length&&(i=s=0,r=t.canvas.width,a=t.canvas.height),o="number"==typeof o?b(o,0,1):.5,n="number"==typeof n?b(n,0,1):.5,c??(c={left:0,top:0,width:e instanceof HTMLVideoElement?e.videoWidth:e.width,height:e instanceof HTMLVideoElement?e.videoHeight:e.height});const h=c.width,p=c.height,l=Math.min(r/h,a/p);let m=h*l,d=p*l,g=1;m<r&&(g=r/m),Math.abs(g-1)<1e-14&&d<a&&(g=a/d),m*=g,d*=g;const u=Math.max(h/(m/r),0),f=Math.max(p/(d/a),0),y=Math.min((h-u)*o,h),w=Math.min((p-f)*n,p);t.drawImage(e,y+c.left,w+c.top,u,f,i,s,r,a)}},he={topAdsorption:"T",leftAdsorption:"L",rightAdsorption:"R",bottomAdsorption:"B",centerAdsorption:"C",bottomCenterAdsorption:"BC"},pe=class{constructor(t){m(this,"_player"),m(this,"_container"),m(this,"size",[0,0]),m(this,"_pageDataUtils"),this._container=document.createElement("canvas"),this._player=new w.Player({canvas:this._container,manualRender:!0}),this._pageDataUtils=t}async adjustment(t,e,i,s,r,a){if(!me.config.sizeAdaptConfig.enabled)return console.warn("Size adapt is not opened, use #SDK.setConfig() open this feature."),t;this._player??(this._player=new w.Player({canvas:this._container,manualRender:!0})),r??(r=[0,0,0,0]),a??(a=i[0]<i[1]?"y":"x"),this.size=[...s],this._container.width=this.size[0],this._container.height=this.size[1],Pt(this._player),this._player.resize();const o=JSON.parse(JSON.stringify(t));await this._player.loadScene(o,{reusable:!0,autoplay:!1}),this._player.gotoAndStop(e);const n=this._player.getCompositions()[0];if(n){const[e,o]=s,c=i[0]/i[1],h=e/o;c>h&&this.keepDistribute(t,n,h/c,s);const[p,l,m,d]=r,g=e-m-d,u=o-p-l,f=[(m-d)/2,(p-l)/2],y=(new V).setFromCenterAndSize(new _(e,o).divide(2),new _(e,o)),w=(new V).setFromCenterAndSize(new _(e,o).divide(2).add(new _(...f)),new _(g,u));this.keepAdsorption("topAdsorption",t,n,f,y,w,a),this.keepAdsorption("bottomAdsorption",t,n,f,y,w,a),this.keepAdsorption("leftAdsorption",t,n,f,y,w,a),this.keepAdsorption("rightAdsorption",t,n,f,y,w,a),this.keepAdsorption("centerAdsorption",t,n,f,y,w,a),this.keepDoubleAdsorption("bottomCenterAdsorption",t,n,f,y,w)}return t}keepDistribute(t,e,i,s){const r=t=>{const i=(new U).copyFrom(e.camera.getViewProjectionMatrix());return(new _).copyFrom(t.applyMatrix(i).toVector2()).toViewCoordinate(s[0],s[1])};["topAdsorption","centerAdsorption","bottomAdsorption"].forEach(a=>{e.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===he[a]&&!t.parentId).forEach(a=>{const o=e.items.filter(t=>t.parentId===a.getInstanceId()),n=o.find(t=>"check-area"===t.name),c=n?this.getViewBoxByHeadlessPlayerItem(n,[],r):this.getViewBoxByHeadlessPlayerItem(a,o,r),h=a.transform.position.clone(),p=c.getCenter(),l=new _(...s.map(t=>t/2)),m=p.y-l.y;((t,i,r)=>{const{z:a}=t.transform.getWorldPosition(),{x:o,y:n}=e.camera.getInverseVPRatio(a);t.transform.translate(2*i*o/s[0],-2*r*n/s[1],0)})(a,0,m/i-m),a.transform.updateLocalMatrix();const d=a.transform.position.clone().subtract(h).toArray();this._pageDataUtils.changeSceneItemProperty(t,{itemId:a.getInstanceId(),type:a.type,propertyName:"position",propertyValue:d})})})}keepAdsorption(t,e,i,s,r,a,o){const{x:n,y:c}=r.getSize(),h=(t,e,s)=>{const{z:r}=t.transform.getWorldPosition(),{x:a,y:o}=i.camera.getInverseVPRatio(r);t.transform.translate(2*e*a/n,-2*s*o/c,0)},p=t=>{const e=(new U).copyFrom(i.camera.getViewProjectionMatrix());return(new _).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(n,c)},l=he[t];i.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===l&&!t.parentId).forEach(r=>{const n=i.items.filter(t=>t.parentId===r.getInstanceId()),c=n.find(t=>"check-area"===t.name),l=r.transform.position.clone(),m=["leftAdsorption","rightAdsorption"].includes(t)?"x":"y",d=["leftAdsorption","topAdsorption"].includes(t)?1:-1,g=["leftAdsorption","topAdsorption"].includes(t)?"min":"max",u=["leftAdsorption","topAdsorption"].includes(t)?"max":"min",f=3===r.name.split("-").length,y=Number(r.name.split("-")[1]),w=new _,x=[1,1],v=c?this.getViewBoxByHeadlessPlayerItem(c,[],p):this.getViewBoxByHeadlessPlayerItem(r,n,p);h(r,...s),v.getSize().x>a.getSize().x&&(x[0]=a.getSize().x/v.getSize().x,x[1]=a.getSize().x/v.getSize().x,r.scale(...x,1)),r.transform.updateLocalMatrix();const P=c?this.getViewBoxByHeadlessPlayerItem(c,[],p):this.getViewBoxByHeadlessPlayerItem(r,n,p),D=new _;if(!a.containsBox(P)){const{min:t,max:e}=P,{min:i,max:s}=a;D.x+=t.x<i.x?i.x-t.x:0,D.x+=e.x>s.x?s.x-e.x:0,D.y+=t.y<i.y?i.y-t.y:0,D.y+=e.y>s.y?s.y-e.y:0,h(r,...D.toArray()),r.transform.updateLocalMatrix()}const I=c?this.getViewBoxByHeadlessPlayerItem(c,[],p):this.getViewBoxByHeadlessPlayerItem(r,n,p);if(!Number.isNaN(y)&&f)if("centerAdsorption"!==t){const t=Math.abs(I[u][m]-a[g][m]),e=a.getSize()[m]*y;t>e&&(w[m]=(e-t)*d,h(r,...w.toArray()),r.transform.updateLocalMatrix())}else{const t=I.getSize()[o],e=a.getSize()[o];if(t/e>y){const i=e*y/t;r.scale(i,i,1),x[0]*=i,x[1]*=i}}const b=c?this.getViewBoxByHeadlessPlayerItem(c,[],p):this.getViewBoxByHeadlessPlayerItem(r,n,p),C=i.items.filter(t=>"T"===t.name.split("-")[0]?.toLocaleUpperCase()&&!t.parentId),E=new V;if(C.forEach(t=>{const e=i.items.filter(e=>e.parentId===t.getInstanceId()),s=e.find(t=>"check-area"===t.name),r=s?this.getViewBoxByHeadlessPlayerItem(s,[],p):this.getViewBoxByHeadlessPlayerItem(t,e,p);E.union(r)}),!E.isEmpty()&&E.max.y>b.min.y)if("centerAdsorption"===t){const t=E.max.y-b.min.y;h(r,0,t),r.transform.updateLocalMatrix()}else if(["leftAdsorption","rightAdsorption"].includes(t)){const t=b.getSize().y,e=a.getSize().y-(E.max.y-a.min.y);let i=E.max.y-b.min.y;if(t>e){const s=e/t;x[0]*=s,x[1]*=s,r.scale(s,s,1),r.transform.updateLocalMatrix(),i-=(t-e)/2}h(r,0,i),r.transform.updateLocalMatrix()}const A=r.transform.position.clone().subtract(l).toArray();this._pageDataUtils.changeSceneItemProperty(e,{itemId:r.getInstanceId(),type:r.type,propertyName:"position",propertyValue:A}),this._pageDataUtils.changeSceneItemProperty(e,{itemId:r.getInstanceId(),type:r.type,propertyName:"size",propertyValue:x})})}keepDoubleAdsorption(t,e,i,s,r,a){const{x:o,y:n}=r.getSize(),c=(t,e,s)=>{const{z:r}=t.transform.getWorldPosition(),{x:a,y:c}=i.camera.getInverseVPRatio(r);t.transform.translate(2*e*a/o,-2*s*c/n,0)},h=t=>{const e=(new U).copyFrom(i.camera.getViewProjectionMatrix());return(new _).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(o,n)},p=he[t];i.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===p&&!t.parentId).forEach(t=>{const r=i.items.filter(e=>e.parentId===t.getInstanceId()),o=r.find(t=>"check-area"===t.name),n=t.transform.position.clone(),p=3===t.name.split("-").length,l=Number(t.name.split("-")[1]),m=[1,1],d=o?this.getViewBoxByHeadlessPlayerItem(o,[],h):this.getViewBoxByHeadlessPlayerItem(t,r,h);c(t,...s),d.getSize().x>a.getSize().x&&(m[0]=a.getSize().x/d.getSize().x,m[1]=a.getSize().x/d.getSize().x,t.scale(...m,1)),t.transform.updateLocalMatrix();const g=o?this.getViewBoxByHeadlessPlayerItem(o,[],h):this.getViewBoxByHeadlessPlayerItem(t,r,h);if(!Number.isNaN(l)&&p){const e=g.getSize().y,i=a.getSize().y;if(e/i>l){const s=i*l/e;t.scale(s,s,1),m[0]*=s,m[1]*=s}}const u=o?this.getViewBoxByHeadlessPlayerItem(o,[],h):this.getViewBoxByHeadlessPlayerItem(t,r,h),f=new _;if(!a.containsBox(u)){const{min:e,max:i}=u,{min:s,max:r}=a;f.x+=e.x<s.x?s.x-e.x:0,f.x+=i.x>r.x?r.x-i.x:0,f.y+=e.y<s.y?s.y-e.y:0,f.y+=i.y>r.y?r.y-i.y:0,c(t,...f.toArray()),t.transform.updateLocalMatrix()}const y=t.transform.position.clone().subtract(n).toArray();this._pageDataUtils.changeSceneItemProperty(e,{itemId:t.getInstanceId(),type:t.type,propertyName:"position",propertyValue:y}),this._pageDataUtils.changeSceneItemProperty(e,{itemId:t.getInstanceId(),type:t.type,propertyName:"size",propertyValue:m})})}getViewBoxByHeadlessPlayerItem(t,e,i){const s=new V,{transform:r,composition:a}=t;switch(t.type){case w.spec.ItemType.sprite:case w.spec.ItemType.plugin:case w.spec.ItemType.video:case w.spec.ItemType.richtext:case w.spec.ItemType.text:case w.spec.ItemType.shape:{r.setValid(!0),r.updateLocalMatrix();const{size:t}=r,o=(new U).copyFrom(a?.transform.getWorldMatrix()??new U).invert().multiply(r.getWorldMatrix()),{x:n,y:c}=t.clone().divide(2),h=new F(n,c,0).applyMatrix(o),p=new F(n,-c,0).applyMatrix(o),l=new F(-n,-c,0).applyMatrix(o),m=new F(-n,c,0).applyMatrix(o),d=i(h).round(2),g=i(p).round(2),u=i(l).round(2),f=i(m).round(2);s.setFromVec2Array([d,g,u,f]);const y=e?.map(t=>{const e=a?.items.filter(e=>e.parentId===t.getInstanceId())??[];return this.getViewBoxByHeadlessPlayerItem(t,e,i)});y&&y.map(t=>s.union(t));break}case w.spec.ItemType.null:{const t=e?.map(t=>{const e=a?.items.filter(e=>e.parentId===t.getInstanceId())??[];return this.getViewBoxByHeadlessPlayerItem(t,e,i)});t&&t.map(t=>s.union(t));break}}return s}dispose(){this._player?.dispose()}},le=class t{constructor(e){m(this,"_eventEmitter",new w.EventEmitter),m(this,"_pageData"),m(this,"_screenShot"),m(this,"_exporter"),m(this,"_pageDataUtils"),m(this,"_sizeAdapt"),m(this,"_gestureHandler"),m(this,"disposables",[]),m(this,"_isSwitchScene",!1),m(this,"player"),m(this,"_playerContainer"),m(this,"on",this._eventEmitter.on);const[i,s]=[e.offsetWidth,e.offsetHeight],r=document.createElement("div");r.id="player-container",r.style.width=`${i}px`,r.style.height=`${s}px`,r.style.position="absolute",r.style.backgroundRepeat="no-repeat",r.style.backgroundPosition="center center",e.appendChild(r),this._playerContainer=r,this.player=new w.Player({container:r,interactive:!0,pixelRatio:window.devicePixelRatio||1}),this.player.on("update",()=>{if((0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._isSwitchScene)return;const t=this.player.getCompositions()[0]?.time;if(this._pageData.playing)if(void 0!==t)this._pageData.time===t&&this.player.pause(),this._pageData.time=t,this._pageDataUtils.refreshPageTime(t);else{this._pageData.playing=!1,this.setPlayProgress(100);const t=this._pageData.viewProperties[this._pageData.activeData.view??0]?.scene,e=t?.compositions.find(e=>e.id===t.compositionId);this._pageData.time=e?.duration??2,this._pageDataUtils.refreshPageTime(this._pageData.time)}this._eventEmitter.emit("progress",{duration:this.player.getCompositions()[0]?.getDuration()??2,time:this._pageData.time,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!this._pageData.playing})}),this._eventEmitter.on("pageDataChange",t=>{this._pageData=t,this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("zoomChange",t=>{(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.property.zoom=t,this._pageDataUtils.refreshInteractionParam(),this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("selectedItemChange",t=>{(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems=[...t],this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("preSelectedItemChange",t=>{(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t,this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("selectedViewChange",t=>{(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.view=t;const e=this._pageData.viewProperties[t];this._gestureHandler.ignoreInteraction=!!e?.ignoreInteraction}),this._eventEmitter.on("sdkConfigChange",(t,e)=>{this._exporter&&!ft(t.exportVideoConfig,e.exportVideoConfig)&&(this._exporter.dispose(),this.initExporter(e.exportVideoConfig))}),this._pageDataUtils=new Gt(this.player,r,this._eventEmitter,this),this.initExporter(t.config.exportVideoConfig),this._gestureHandler=new nt(e),this._gestureHandler.registerViewEvent(),this._screenShot=new ce,this._sizeAdapt=new pe(this._pageDataUtils);const a=new ResizeObserver(()=>{const t=[e.offsetWidth,e.offsetHeight],i=this._pageData?.viewProperties[this._pageData.activeData.view??0];if(!i)return;const{size:s}=i,[r,a]=this._pageDataUtils.getPlayerSizeByParent(t,s);this._playerContainer.style.width=`${r}px`,this._playerContainer.style.height=`${a}px`,this.player.resize(),this._gestureHandler.resize()});a.observe(e),this.disposables.push(()=>{a.disconnect()})}get pageData(){return this._pageData}get exportStatus(){return this?._exporter?.status}get exportOptions(){if(!this.pageData)return[];const t=this.pageData.viewProperties.filter(t=>!t.ignoreInteraction),e=t[0]?.scene?.compositions?.[0]?.name??"videos",i=[];return t.map((t,s)=>{const{size:r,scene:a,export:{name:o,time:n,audioEnable:c,fps:h}}=t,p=r?.[0]&&r?.[1]?` (${s+1})_${r[0]}×${r[1]}`:` (${s+1})`;let l="";return l=o?function(t,e){if(!e.includes(t))return t;let i=1,s=`${t} (${i})`;for(;e.includes(s);)i++,s=`${t} (${i})`;return s}(o,i):`${e}${p}`,i.push(l),{folderName:e,name:l,size:r,fps:h,scene:JSON.parse(JSON.stringify(a)),time:n,audioEnable:c}})}dispose(){this.player?.dispose(),this._screenShot?.dispose(),this._pageData=void 0,this._playerContainer.remove(),this?._exporter?.dispose(),this._screenShot.dispose(),this._gestureHandler.dispose(),this.disposables.forEach(t=>{t()})}async getInitParam(t){const e=JSON.parse(JSON.stringify(t));if("string"==typeof e.scene)try{const t=await fetch(e.scene,{mode:"cors",credentials:"omit",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}, statusText: ${t.statusText}`);const i=await t.json();return{...e,scene:i}}catch(t){throw new Error(`Failed to fetch scene data from ${e.scene}: ${t instanceof Error?t.message:String(t)}`)}return{...e,scene:e.scene}}initExporter(t){this._exporter=new ne(t),this._exporter.on("progress",t=>{this._eventEmitter.emit("exportProgress",t)}),this._exporter.on("done",(t,e,i)=>{this._eventEmitter.emit("exportDone",t,e,i)}),this._exporter.on("complete",t=>{this._eventEmitter.emit("exportComplete",t)})}async initSDK(e){var i;const{scene:s,viewParams:r,options:a}=e,o=[];if(t.config.pageConfig.staticPreview){const t=JSON.parse(JSON.stringify(s)),e=t.compositions.find(e=>e.id===t.compositionId)??t.compositions[0];if(e){const[i,s]=e.previewSize??[1080,1920],r=e.duration??0;o.push({size:[i,s],safeArea:[0,0,0,0],previewSafeAreas:[],id:0,scene:t,ignoreInteraction:!0,export:{time:r,fileSizeLimit:1,audioEnable:!1}})}}for(let e=0;e<r.length;e++){const a=r[e];if(!a)continue;let n=JSON.parse(JSON.stringify(s));const c=n.compositions.find(t=>t.id===n.compositionId)??n.compositions[0];(0,w.assertExist)(c);const h=c.previewSize??[750,1624],p=h,l=a.size??h;c.previewSize=l;const m=c.duration??0,d=a.safeArea??[0,0,0,0];t.config.sizeAdaptConfig.enabled&&(n=await this._sizeAdapt.adjustment(n,m,p,l,d,a.adaptionDirection)),(i=a.export).time??(i.time=m),o.push({...a,size:l,safeArea:d,previewSafeAreas:[...a.previewSafeAreas??[]],id:e+1,scene:n,ignoreInteraction:!1})}const n=o[0]?.scene;if(!n)return void console.warn("SDK need a view property at least.");const c=n.compositions.find(t=>t.id===n.compositionId)??n.compositions[0],h={...a,zoom:1,translation:[0,0],asyncMode:a.asyncMode??!1},p=(c?.duration??0)-.1;this._pageData={scene:JSON.parse(JSON.stringify(s)),time:p,property:h,activeData:{selectedItems:[]},items:[],viewProperties:o,playing:!1},this._pageDataUtils.init(),this._gestureHandler.init(this._pageDataUtils),this._gestureHandler.ignoreInteraction=!!o[0]?.ignoreInteraction,t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaEnabled=h.safeAreaPreview,this._eventEmitter.emit("progress",{duration:p,time:p,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!this._pageData.playing}),await this._pageDataUtils.loadScene(0),this._pageDataUtils.refreshPageTime(p)}async run(t){const e=await this.getInitParam(t);await this.initSDK(e),this._eventEmitter.emit("pageDataChange",this.getPageData())}getPageData(){return JSON.parse(JSON.stringify(this._pageData))}getActiveItems(){return(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems}setPreSelectedItem(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t}getPreSelectedItem(){return(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem??""}setSelectedItems(t){this._pageDataUtils.clearPreSelectedItem(),this._pageDataUtils.clearSelectedItems(),this._pageDataUtils.addSelectedItems([...t])}getItemProperty(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const e=this._pageData.items.find(e=>e.id===t.itemId);if(e&&e.type===t.type)return{type:e.type,property:e.property}}getItemPropertyValue(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const e=this.getItemProperty(t)?.property?.[t.propertyName];return e}async setItemPropertyValue(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const e=this._pageData.viewProperties[this._pageData.activeData.view??0]?.ignoreInteraction;e?console.warn("Static scene cannot change."):(await this._pageDataUtils.changeItemProperty(t),this._gestureHandler.refresh(),this._gestureHandler.render(),this._eventEmitter.emit("pageDataChange",this.getPageData()))}async generateScreenShot(t,e=[300,400],i){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const s=this.pageData?.viewProperties?.[t];if(!s)return"";const{scene:r,size:[a,o]}=s,n=r.compositionId,c=r.compositions.find(t=>t.id===n);i??(i=c?.duration??0);const h=JSON.parse(JSON.stringify(r));return await this._screenShot.generate(h,[a,o],e,i)}async switchScene(t){if((0,w.assertExist)(this._pageData,"You must call SDK#run() first"),t===this._pageData.activeData.view)return;this._isSwitchScene=!0;if(this._pageData.viewProperties[t]){const e=this._pageData.playing;this._pageData.activeData={view:t,selectedItems:[],preSelectedItem:void 0},await this._pageDataUtils.loadScene(t),e&&(this._pageData.playing=e,this.player.gotoAndPlay(this._pageData.time))}else console.warn("target scene does not exist.");this._eventEmitter.emit("selectedViewChange",t),this._eventEmitter.emit("pageDataChange",this.getPageData()),this._isSwitchScene=!1}getConfig(){return(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),{safeAreaPreview:this._pageData.property.safeAreaPreview,zoom:this._pageData.property.zoom,adsorption:this._pageData.property.adsorption,asyncMode:this._pageData.property.asyncMode}}setConfig(e){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const{adsorption:i,safeAreaPreview:s,zoom:r}=this._pageData.property;this._pageData.property={...this._pageData.property,...e},this._pageData.property.zoom!==r&&this._pageDataUtils.setPageZoom(this._pageData.property.zoom),i!==e.adsorption&&(t.config.gestureHandlerConfig.adsorptionGizmoEnabled=e.adsorption),s!==e.safeAreaPreview&&(t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaEnabled=e.safeAreaPreview),this._gestureHandler.refresh(),this._gestureHandler.render()}async setPlayProgress(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const e=(this.player.getCompositions()[0]?.getDuration()??2)*t/100;this._pageData.time=e;!this.player.getCompositions().length&&(Pt(this.player),await this._pageDataUtils.loadScene(this._pageData.activeData.view??0));this._pageData.playing?this.player.gotoAndPlay(e):(this.player.gotoAndStop(e),this._eventEmitter.emit("progress",{duration:this.player.getCompositions()[0]?.getDuration()??2,time:e,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!0})),this._pageDataUtils.refreshPageTime(e)}getViewItems(){return this.getPageData()?.items??[]}async setPlayState(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const e="play"===t;if(this._pageData.playing!==e){if(this._pageData.playing=e,this._gestureHandler.ignoreInteraction=e,e){const t=this.player.getCompositions();await this.player.loadScene(this._pageData.viewProperties[this._pageData.activeData.view].scene,{autoplay:!1}),this.player.gotoAndPlay(this._pageData.time),this.destroyCompositions(t)}else this.player.gotoAndStop(this._pageData.time);this._gestureHandler.refresh(),this._gestureHandler.render()}}getViewThumbnail(){return(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.viewProperties.map(t=>({id:t.id,thumbnail:this.generateScreenShot(t.id)}))}getViewScene(){return(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.viewProperties.map(t=>({id:t.id,thumbnail:t.scene}))}destroyCompositions(t){t.forEach(t=>{t.dispose();const e=this.player.getCompositions(),i=e.indexOf(t);i>-1&&e.splice(i,1)})}onExport(){t.config.exportVideoConfig.enabled&&((0,w.assertExist)(this.pageData,"You must call SDK#run() first"),(0,w.assertExist)(this._exporter,"You must init exporter first"),this._exporter.onExport(this.exportOptions))}cancelExport(){(0,w.assertExist)(this._exporter,"You must init exporter first"),this._exporter.onCancel()}async loadPageData(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData={view:this._pageData.viewProperties.length,selectedItems:[],preSelectedItem:void 0},this._pageData.viewProperties.push(...t.viewProperties),this._pageDataUtils.init(),this._gestureHandler.init(this._pageDataUtils),await this._pageDataUtils.loadScene(this.pageData?.activeData.view??0),this._eventEmitter.emit("pageDataChange",this.getPageData())}async runByPageData(t){const e=JSON.parse(JSON.stringify(t));e.property.zoom=1,e.property.translation=[0,0],this._pageData=e,this._pageDataUtils.init(),this._gestureHandler.init(this._pageDataUtils),await this._pageDataUtils.loadScene(this.pageData?.activeData.view??0),this._pageDataUtils.refreshPageTime(this._pageData.time),this._eventEmitter.emit("pageDataChange",this.getPageData())}async reloadPageDataByScene(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");let e=JSON.parse(JSON.stringify(t));if("string"==typeof e)try{const t=await fetch(e,{mode:"cors",credentials:"omit",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}, statusText: ${t.statusText}`);e=await t.json()}catch(t){throw new Error(`Failed to fetch scene data from ${e}: ${t instanceof Error?t.message:String(t)}`)}this._pageData.time=e.compositions.find(t=>t.id===e.compositionId)?.duration??2,this._pageData.viewProperties.forEach(t=>{t.scene=JSON.parse(JSON.stringify(e))}),this._pageDataUtils.init(),this._gestureHandler.init(this._pageDataUtils),await this._pageDataUtils.loadScene(this._pageData.activeData.view??0),this._eventEmitter.emit("progress",{duration:this.player.getCompositions()[0]?.getDuration()??2,time:this._pageData.time,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!this._pageData.playing})}async addViewParams(e){var i;(0,w.assertExist)(this._pageData);const s=[],r=this._pageData.viewProperties[this._pageData.viewProperties.length-1]?.id??this._pageData.viewProperties.length-1;for(let a=0;a<e.length;a++){const o=e[a];if(!o)continue;let n=JSON.parse(JSON.stringify(this._pageData.scene));const c=n.compositions.find(t=>t.id===n.compositionId)??n.compositions[0];(0,w.assertExist)(c);const{previewSize:h=[750,1624]}=c,p=h,l=o.size??h;c.previewSize=l;const m=c.duration??0,d=o.safeArea??[0,0,0,0];t.config.sizeAdaptConfig.enabled&&(n=await this._sizeAdapt.adjustment(n,m,p,l,d,o.adaptionDirection)),(i=o.export).time??(i.time=m),s.push({...o,size:l,safeArea:d,previewSafeAreas:[...o.previewSafeAreas??[]],id:r+1+a,scene:n,ignoreInteraction:!1})}this._pageData.viewProperties.push(...s),this._eventEmitter.emit("pageDataChange",this.getPageData())}async deleteViewParams(t){t.sort((t,e)=>t-e);for(let e=0;e<t.length;e++){const i=t[e];(0,w.assertExist)(this._pageData);const s=i-e,r=this._pageData.viewProperties.findIndex(t=>t.id===s);if(!1!==this._pageData.viewProperties[r]?.ignoreInteraction){console.warn("target view ignore interaction, it can not be deleted.");continue}if(r<0){console.warn("Target view is not existed.");continue}this._pageData.viewProperties.splice(r,1);const a=this._pageData.activeData.view??0;s===a?(this._pageData.activeData.view=0,await this._pageDataUtils.loadScene(0)):s<a&&(this._pageData.activeData.view=a-1),this._pageData.viewProperties.forEach(t=>{t.id>s&&(t.id-=1)})}this._eventEmitter.emit("selectedViewChange",this._pageData?.activeData?.view??0),this._eventEmitter.emit("pageDataChange",this.getPageData())}setExportParam(t,e){(0,w.assertExist)(this._pageData),this._pageData.viewProperties.forEach(i=>{void 0!==e&&i.id!==e||(i.export=t)})}setPageZoom(t){(0,w.assertExist)(this._pageData),this._pageData.property.zoom=t,this._pageDataUtils.setPageZoom(this._pageData.property.zoom),this._gestureHandler.refresh(),this._gestureHandler.render()}setStaticPreviewEnabled(e){t.config.pageConfig.staticPreview=e}setStaticPreviewName(e){t.config.pageConfig.staticPreviewName=e}setAsyncEnabled(e){t.config.pageConfig.asncMode=e}setGroupVisibleEnabled(e){t.config.pageConfig.groupVisible=e}addFilterItemNames(e){"string"==typeof e?ct(t.config.pageConfig.filterItemNames,e):e.forEach(e=>{ct(t.config.pageConfig.filterItemNames,e)})}setPreferenceBackgroundColor(e){t.config.gestureHandlerConfig.preferenceGizmoConfig.markColor=e[0]<<16|e[1]<<8|e[2],t.config.gestureHandlerConfig.preferenceGizmoConfig.markAlpha=e[3]??.3,this._gestureHandler.refresh(),this._gestureHandler.render()}setSafeAreaColor(e){t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaBoxColor=e[0]<<16|e[1]<<8|e[2],t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaBoxAlpha=e[3]??.3,this._gestureHandler.refresh(),this._gestureHandler.render()}setSizeAdaptEnabled(e){t.config.sizeAdaptConfig.enabled=e}setScreenShotEnabled(e){t.config.screenShotConfig.enabled=e}setExportVideoEnabled(e){t.config.exportVideoConfig.enabled=e}setSelectorGizmoPreSelectConfig(e,i){void 0!==e&&(t.config.gestureHandlerConfig.selectorGizmoConfig.preSelectedColor=e),void 0!==i&&(t.config.gestureHandlerConfig.selectorGizmoConfig.preSelectedWidth=i),this._gestureHandler.refresh(),this._gestureHandler.render()}setTranformGizmoWireframeConfig(e){void 0!==e.wireframeAlpha&&(t.config.gestureHandlerConfig.transformGizmoConfig.wireframeAlpha=e.wireframeAlpha),void 0!==e.wireframeColor&&(t.config.gestureHandlerConfig.transformGizmoConfig.wireframeColor=e.wireframeColor),void 0!==e.wireframeWidth&&(t.config.gestureHandlerConfig.transformGizmoConfig.wireframeWidth=e.wireframeWidth),this._gestureHandler.refresh(),this._gestureHandler.render()}getSDKConfig(){return t.config}setSDKConfig(e){const i=Object.assign({},t.config);this._eventEmitter.emit("sdkConfigChange",i,e),t.config=e}};m(le,"config",{pageConfig:{asncMode:!1,staticPreview:!0,staticPreviewName:"标准模板",filterItemNames:["check-area","ModelPluginItem"],groupVisible:!0},screenShotConfig:{enabled:!0},exportVideoConfig:{enabled:!0,mediaType:"MP4",loggerInTranscoding:!1},sizeAdaptConfig:{enabled:!0},gestureHandlerConfig:{enabled:!0,adsorptionGizmoEnabled:!0,adsorptionGizmoConfig:{lineWidth:2,lineColor:37375,distance:6},controlGizmoEnabled:!0,controlGizmoConfig:{zoomStep:.01},preferenceGizmoEnabled:!0,preferenceGizmoConfig:{boxColor:16711680,boxWidth:1,markColor:0,markAlpha:.17,safeAreaEnabled:!0,safeAreaBoxColor:65280,safeAreaBoxAlpha:.3},selectorGizmoEnabled:!0,selectorGizmoConfig:{preSelectedWidth:3,preSelectedColor:15425024,regionBoxColor:16777215,regionBoxAlpha:.17,regionWireframeColor:16777215,regionWireframeAlpha:.78,regionWireframeWidth:1},transformGizmoEnabled:!0,transformGizmoConfig:{wireframeColor:16711680,wireframeAlpha:1,wireframeWidth:1.5,cornerFillColor:16777215,cornerLineColor:0,cornerLineWidth:1,cornerLineAlpha:.3,scaleCircleSize:4,rotationCircleSize:8}}});var me=le;