@vvfx/sdk 0.0.0-alpha.25 → 0.0.0-alpha.26
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 +1 -1
- package/dist/index.global.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,r=t=>{throw TypeError(t)},a=(e,i)=>{for(var s in i)t(e,s,{get:i[s],enumerable:!0})},o=(r,a,o,n)=>{if(a&&"object"==typeof a||"function"==typeof a)for(let c of i(a))s.call(r,c)||c===o||t(r,c,{get:()=>a[c],enumerable:!(n=e(a,c))||n.enumerable});return r},n=(t,e,i)=>(o(t,e,"default"),i&&o(i,e,"default")),c=(e,i,s)=>((e,i,s)=>i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s)(e,"symbol"!=typeof i?i+"":i,s),h=(t,e,i)=>e.has(t)||r("Cannot "+i),p=(t,e,i)=>(h(t,e,"read from private field"),i?i.call(t):e.get(t)),l=(t,e,i)=>e.has(t)?r("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),m=(t,e,i,s)=>(h(t,e,"write to private field"),s?s.call(t,i):e.set(t,i),i);import"@galacean/effects";import{spec as d,VFXItem as g,Player as f,math as u,Composition as y,EventEmitter as w,assertExist as x,SpriteComponent as v,TextComponent as P,Texture as I}from"@galacean/effects";import"@galacean/effects-plugin-rich-text";import{RichTextComponent as D}from"@galacean/effects-plugin-rich-text";import"@galacean/effects-plugin-model";import"@galacean/effects-plugin-multimedia";import{VideoComponent as b}from"@galacean/effects-plugin-multimedia";import"@galacean/effects-plugin-spine";import{Application as C}from"@pixi/app";var A=class{constructor(){c(this,"interactive"),c(this,"type"),c(this,"active"),this.type="null",this.active=!1,this.interactive=!1}},S=1e-6;function z(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 T=Math.PI/180,_=180/Math.PI;function E(t){return Math.atan2(-t.y,-t.x)+Math.PI}function M(t,e,i=Math.round){if(Number.isInteger(t))return t;const s=Math.pow(10,e);return i(t*s)/s}function V(t,e){return Math.abs(t-e)<S||t===1/0&&e===1/0||t===-1/0&&e===-1/0}function k(t){return isNaN(t)||Math.abs(t)<S}var B=class t extends u.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}},F=class t{constructor(t=new B,e=new B){c(this,"start",new B),c(this,"end",new B),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 B).subtractVectors(this.end,this.start).normalize()}getCenter(t=new B){return t.addVectors(this.start,this.end).multiply(.5)}delta(t=new B){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 B){return this.delta(e).multiply(t).add(this.start)}closestPointToPointParameter(t,e){const i=new B,s=new B;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=z(a,0,1)),a}closestPointToPoint(t,e,i=new B){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 B).subtractVectors(this.end,this.start).length()}crossWithLine(t){const e=this.delta(),i=t.delta(),s=(new B).subtractVectors(t.start,this.start),r=(new B).subtractVectors(t.end,this.start),a=(new B).subtractVectors(this.start,t.start),o=(new B).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}},U=class t{constructor(t=new B(1/0,1/0),e=new B(-1/0,-1/0)){c(this,"corners",[]),c(this,"min",new B(1/0,1/0)),c(this,"max",new B(-1/0,-1/0)),this.min=t.clone(),this.max=e.clone(),this.isEmpty()?this.corners=[]:this.corners=[t.clone(),new B(e.x,t.y),e.clone(),new B(t.x,e.y)]}set(t,e){return this.min.copyFrom(t),this.max.copyFrom(e),this.corners=[t.clone(),new B(e.x,t.y),e.clone(),new B(t.x,e.y)],this}setFromVec2Array(t){return this.min=(new B).copyFrom(t[0]),this.max=(new B).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 B).copyFrom(t[0]),this.max=(new B).copyFrom(t[0]),t.forEach(t=>{this.min=this.min.min(t),this.max=this.max.max(t)}),this.corners.push(new B(this.min.x,this.min.y)),this.corners.push(new B(this.min.x,this.max.y)),this.corners.push(new B(this.max.x,this.max.y)),this.corners.push(new B(this.max.x,this.min.y)),this}setFromCenterAndSize(t,e){const i=(new B).copyFrom(e).multiply(.5);return this.min.copyFrom(t).subtract(i),this.max.copyFrom(t).add(i),this.corners=[this.min.clone(),new B(this.max.x,this.min.y),this.max.clone(),new B(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 B){return this.isEmpty()?t.set(0,0):t.addVectors(this.min,this.max).multiply(.5)}getSize(t=new B){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 B(s.x-i.x,s.y-i.y),a=new B(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 B){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 B){return e.copyFrom(t).clamp(this.min,this.max)}distanceToPoint(t){return(new B).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 B(this.max.x,this.min.y),this.max.clone(),new B(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 F(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 F(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}},R=class t{constructor(t=new B,e=0){c(this,"center"),c(this,"radius"),this.center=t.clone(),this.radius=e}set(t,e){return this.center=(new B).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 B,this.radius=0,this}isEmpty(){return 0===this.radius}getCenter(t=new B){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}},W=class extends u.Quaternion{},G=class t extends u.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 W).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}},H=class t extends u.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=G.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,f=a*m,u=a*d,y=a*g,w=o*d,x=o*g,v=n*g,P=c*m,I=c*d,D=c*g,{x:b,y:C,z:A}=i;return r[0]=(1-(w+v))*b,r[1]=(u+D)*b,r[2]=(y-I)*b,r[3]=0,r[4]=(u-D)*C,r[5]=(1-(f+v))*C,r[6]=(x+P)*C,r[7]=0,r[8]=(y+I)*A,r[9]=(x-P)*A,r[10]=(1-(f+w))*A,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 G,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===u.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===u.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===u.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===u.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===u.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===u.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}},N=class extends u.Euler{constructor(t=0,e=0,i=0,s=u.EulerOrder.XYZ){super(t,e,i,s)}getInvertMatrixByEuler(){return(new H).makeRotationFromEuler(this).invert()}toDegreeVector3(t){return t?t.set(this.x*_,this.y*_,this.z*_):new G(this.x*_,this.y*_,this.z*_)}setFromDegreeVector3(t,e){return this.set(t.x*T,t.y*T,t.z*T,e??this.order)}},L=class t{constructor(t=0,e=new G(0,0,1)){c(this,"distance"),c(this,"normal");const i=e.length();0===i&&(this.normal=new G(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 G(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}},K=class t extends u.Ray{constructor(t=new G,e=new G(1,0,0)){super(t,e),c(this,"origin"),c(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(k(e))return k(t.distanceToPoint(this.origin))?0:NaN;const i=(-this.origin.dot(t.normal)-t.distance)/e;return i>0?i:NaN}},O=class{constructor(t=new K){c(this,"ray"),this.ray=t.clone()}setFromCamera(t,e){const i=e.position,s=new G(t.x,t.y,.5).applyMatrix(e.inverseViewProjectMatrix).subtract(i).normalize();return this.ray.set(i,s),this}rayCastPlane(t){const e=new G,i=this.ray.rayCastPlane(t,e);if(!isNaN(i))return{distance:i,point:this.ray.at(i)}}},j=class extends A{constructor(t){super(),c(this,"defaultInteractive",!0),c(this,"interactive",!0),c(this,"lastPoint",new B),c(this,"SDKUtils"),this.SDKUtils=t,this.type="control"}initialize(){}preparationAction(){}cancelPreparation(){}refreshResults(){}preAction(){}action(t){if(!Te.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 B(r,a);e||i?(o.y=z(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*Te.config.gestureHandlerConfig.controlGizmoConfig.zoomStep;this.SDKUtils.pageZoom(e)}pan(t){this.SDKUtils.pageMove(t)}getRenderObjects(){return[]}};import{Graphics as $}from"@pixi/graphics";var Y=class extends A{constructor(t){super(),c(this,"interactive",!0),c(this,"result",{type:"null",box:new U}),c(this,"selectedItemIds",[]),c(this,"cursorPoint",new B),c(this,"startPoint",new B),c(this,"graphics",new $),c(this,"pageDataUtils"),c(this,"clearResult",!1),c(this,"type"),this.pageDataUtils=t,this.type="selector"}initialize(){}actionKey(){}endActionKey(){}getRenderObjects(){return Te.config.gestureHandlerConfig.selectorGizmoEnabled?this.clearResult?(this.result={type:"null",box:new U},this.clearResult=!1,[]):(this.refreshResults(),[this.graphics]):[]}cancelPreparation(){this.result.type="null",this.pageDataUtils.clearPreSelectedItem()}preparationAction(t){if(this.result.box=new U,!Te.config.gestureHandlerConfig.selectorGizmoEnabled)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const e=new B(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 B(t.clientX,t.clientY),this.cursorPoint=new B(t.offsetX,t.offsetY),this.active=!0,this.type):(this.pageDataUtils.addSelectedItems([this.selectedItemIds[0]]),this.clearResult=!0,"transform")}action(t){const e=(new B).addVectors(this.cursorPoint,(new B).subtractVectors(new B(t.clientX,t.clientY),this.startPoint)),i=(new B).subtractVectors(this.cursorPoint,e),s=(new B).addVectors(this.cursorPoint,e).multiply(.5);i.x=Math.abs(i.x),i.y=Math.abs(i.y);const r=(new U).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 K,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===d.ItemType.mesh||s.getComponent(v)?.renderer?.occlusion||s.getComponent(P)?.renderer?.occlusion||s.getComponent(b)?.renderer?.occlusion||s.getComponent(D)?.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}=Te.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()}};import{Graphics as J}from"@pixi/graphics";import{assertExist as X}from"@galacean/effects";var q=class extends A{constructor(t,e){super(),c(this,"type"),c(this,"interactive",!0),c(this,"wireframe"),c(this,"cursorResult",{type:"normal",angle:0}),c(this,"cursorPoint",new B),c(this,"lastPoint",new B),c(this,"rotationAngle",0),c(this,"active",!1),c(this,"enableAdsorption",!0),c(this,"scaleParam"),c(this,"activeType","null"),c(this,"lastWorldPosition",new G),c(this,"pageDataUtils"),c(this,"adsorptionGizmo"),c(this,"graphics",new J),this.type="transform",this.pageDataUtils=t,this.adsorptionGizmo=e,this.wireframe={edges:[],anchor:new B,scaleCorners:[],rotationCorners:[],interactive:!0,cornerEnable:!0,directionEnable:!0,box:new U,totalBox:new U,childrenBoxes:[],activeType:"null",interactiveDirection:new B,scaleCorner:new B,scaleEdgeCorners:[]}}initialize(){}actionKey(){}endActionKey(){}getRenderObjects(){return Te.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 B(t.clientX,t.clientY),this.cursorPoint=new B(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 G,this.activeType=e?"null":this.activeType,this.type}preparationAction(t){if(!Te.config.gestureHandlerConfig.transformGizmoEnabled)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const e=new B(t.offsetX,t.offsetY),i=this.wireframe;this.refreshTransformType(e);const{interactiveDirection:s}=i;return this.refreshCursorResult(this.activeType,E(s)),this.active="null"!==this.activeType,this.active?this.type:void 0}action(t){if(!Te.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 G}const e=new B(t.clientX,t.clientY),i=(new B).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();X(n);let c=0;switch(a){case"rotation":{const t=r.clone(),e=new G,a=M(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 B).subtractVectors(this.cursorPoint,t),(new B).subtractVectors(this.cursorPoint.add(i),t))*_,3);e.z=a,this.rotationAngle+=a,c=E(o)+this.rotationAngle*T,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 U).filter(t=>!t.isEmpty()),i=new B(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);this.adsorptionGizmo.boxTranslationAdsorption(t,this.wireframe.box,e);const r=new B(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!==d.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 H).extractRotation(n.matrix).invert(),h=(new G).subtractVectors(e,i).applyMatrix(c),p=h.clone().multiply(a),l=t.subtract(r).subtract(i).applyMatrix(c),m=new G(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}([V(h.x,0)?1:Math.abs(l.x/h.x),V(h.y,0)?1:Math.abs(l.y/h.y)]),g=l.toArray()[d],f=p.toArray()[d];if(V(a.x,a.y)&&V(a.z,a.x)){const t=V(f,0)?1:Math.abs(g/f);m.set(t,t,t)}else if(0===d){m.x=V(f,0)?1:Math.abs(g/f);const t=h.y*g/h.x;m.y=V(p.y,0)?1:t/p.y;const e=h.z*g/h.x;m.z=V(p.z,0)?1:e/p.z}else if(1===d){m.y=V(f,0)?1:Math.abs(g/f);const t=h.x*g/h.y;m.x=V(p.x,0)?1:t/p.x;const e=h.z*g/h.y;m.z=V(p.z,0)?1:e/p.z}else{m.z=V(f,0)?1:Math.abs(g/f);const t=h.x*g/h.z;m.x=V(p.x,0)?1:t/p.x;const e=h.y*g/h.z;m.y=V(p.y,0)?1:e/p.y}this.scaleParam.lastScalar.multiply(m),s.forEach(t=>{this.pageDataUtils.scaleItem(t.id,m)})}c=E(o);break}}this.refreshCursorResult(a,c),this.lastPoint.copyFrom(e)}endAction(t){this.active=!1;const e=new B(t.clientX,t.clientY),i=(new B).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,E(a)),this.adsorptionGizmo.clearAbsorptionResult(),this.rotationAngle=0,this.cursorPoint=new B,this.lastPoint=new B}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)*_};break;case"rotation":this.cursorResult={type:"rotation",angle:(e+Math.PI/4)*_};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 G).copyFrom(this.pageDataUtils.getPlayerItemById(i.id).transform.anchor).applyMatrix(t.matrix),r=(new G).setFromMatrixPosition(t.matrix),a=(new N).setFromQuaternion((new W).setFromRotationMatrix(t.matrix))}this.pageDataUtils.interactionUtils.initInteractionPlane(r,a),this.scaleParam={shift:new G,center:new G,corner:new G,lastScalar:new G(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 G}this.scaleParam.shift=(this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(t)??new G).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}=Te.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 F(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 B,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 U;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 U).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!==d.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 F((new B).copyFrom(t),(new B).copyFrom(a[(e+1)%4])))});const{scaleCircleSize:o,rotationCircleSize:n}=Te.config.gestureHandlerConfig.transformGizmoConfig;this.wireframe.box.corners.forEach(t=>{this.wireframe.scaleCorners.push(new R(t,o));const e=(new B).subtractVectors(t,this.wireframe.box.getCenter()),i=(new B).copyFrom(this.wireframe.box.getCenter()).add((new B).copyFrom(e).normalize().multiply(e.length()+n-o));this.wireframe.rotationCorners.push(new R(i,n))})}setAdsorptionEnabled(t){this.enableAdsorption=t}};import{Graphics as Z}from"@pixi/graphics";var Q=class extends A{constructor(){super(),c(this,"interactive",!1),c(this,"results",[]),c(this,"graphics",new Z),c(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=[],!Te.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 B(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=[],!Te.config.gestureHandlerConfig.adsorptionGizmoEnabled)return void console.warn("Adsorption is not opened, use #SDK.setAdsorptionConfig() open this feature.");const a=new B(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)<Te.config.gestureHandlerConfig.adsorptionGizmoConfig.distance&&this.refreshPointAbsorptionResult(t,e,"x"),s&&Math.abs(t.y-e.y)<Te.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 B(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 F(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 F(i,s))})}refreshRenderObject(){this.graphics.clear();const{lineWidth:t,lineColor:e}=Te.config.gestureHandlerConfig.adsorptionGizmoConfig;this.results.forEach(i=>{this.graphics.lineStyle(t,e),this.graphics.drawLine(i)})}getRenderObjects(){return Te.config.gestureHandlerConfig.adsorptionGizmoEnabled?(this.refreshResults(),this.refreshRenderObject(),[this.graphics]):[]}clearAbsorptionResult(){this.results=[],this.absorptionResult={}}},tt={};a(tt,{Application:()=>rt,utils:()=>it});var et={};a(et,{Application:()=>rt,utils:()=>it}),n(et,ht),n(et,pt),n(et,lt),n(et,mt),n(et,dt),n(et,gt),n(et,ft),n(et,ut),n(et,yt),n(et,wt),n(et,xt),n(et,vt);import"@pixi/polyfill";import*as it from"@pixi/utils";import{InteractionManager as st}from"@pixi/interaction";import{Application as rt}from"@pixi/app";import{Renderer as at,BatchRenderer as ot}from"@pixi/core";import{AppLoaderPlugin as nt}from"@pixi/loaders";import{TickerPlugin as ct}from"@pixi/ticker";import*as ht from"@pixi/constants";import*as pt from"@pixi/core";import*as lt from"@pixi/display";import*as mt from"@pixi/graphics";import*as dt from"@pixi/loaders";import*as gt from"@pixi/interaction";import*as ft from"@pixi/math";import*as ut from"@pixi/runner";import*as yt from"@pixi/sprite";import*as wt from"@pixi/text";import*as xt from"@pixi/ticker";import*as vt from"@pixi/settings";it.skipHello(),at.registerPlugin("interaction",st),at.registerPlugin("batch",ot),rt.registerPlugin(ct),rt.registerPlugin(nt),et.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()},et.Graphics.prototype.fillBox=function(t){const e=t.getSize();this.drawRect(t.min.x,t.min.y,e.x,e.y)},et.Graphics.prototype.drawLine=function(t){if(this.beginFill(),t instanceof F)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()},n(tt,et);var Pt=class extends A{constructor(t){super(),c(this,"interactive",!1),c(this,"box",new U),c(this,"graphics",new tt.Graphics),c(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 U,!Te.config.gestureHandlerConfig.preferenceGizmoEnabled)return void console.warn("Preference gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const t=this.PageDataUtils.getPageData();x(t);const{container:e}=this.PageDataUtils;if(e){const{zoom:i}=t.property,{offsetWidth:s,offsetHeight:r}=e,a=new B(s,r).multiply(i),o=this.PageDataUtils.getViewportLeftTopPosition().add(a.clone().divide(2));this.box=(new U).setFromCenterAndSize(o,a)}}refreshRenderObjects(){const{boxWidth:t,boxColor:e,markColor:i,markAlpha:s,safeAreaEnabled:r,safeAreaBoxColor:a,safeAreaBoxAlpha:o}=Te.config.gestureHandlerConfig.preferenceGizmoConfig;this.graphics=new tt.Graphics;const{offsetWidth:n,offsetHeight:c}=this.PageDataUtils.container.parentElement,h=new U(new B(0,0),new B(n,this.box.min.y)),p=new U(new B(0,this.box.min.y),new B(this.box.min.x,c)),l=new U(new B(this.box.min.x,this.box.max.y),new B(n,c)),m=new U(new B(this.box.max.x,this.box.min.y),new B(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();x(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:f,max:u}=this.box;this.graphics.beginFill(a,o);const y=new U(f,new B(u.x,f.y+l)),w=new U(new B(f.x,f.y+l),new B(f.x+m,u.y)),x=new U(new B(u.x-d,f.y+l),new B(u.x,u.y)),v=new U(new B(f.x+m,u.y-g),new B(u.x-d,u.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 B(r/t[0]*n.x,a/t[1]*n.y),h=new B(i/t[0]*n.x+c.x/2,s/t[1]*n.y+c.y/2).add(f),p=(new U).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 Te.config.gestureHandlerConfig.preferenceGizmoEnabled?(this.refreshRenderObjects(),[this.graphics]):[]}},It="https://mdn.alipayobjects.com/rms/uri/file/as/0.0.6",Dt={normal:{type:"preset",content:"default"},rotation:{type:"svg",content:"default",url:`${It}/icons/cursor-rotate-32.svg`},scale:{type:"svg",content:"default",url:`${It}/icons/cursor-scale-32.svg`}};var bt=class{constructor(t){c(this,"wireframeApplication"),c(this,"gizmos",[]),c(this,"activeGizmo"),c(this,"selectorGizmo"),c(this,"transformGizmo"),c(this,"controlGizmo"),c(this,"preferenceGizmo"),c(this,"spaceClickTime"),c(this,"spaceEmit",!1),c(this,"_ignoreInteraction",!1),c(this,"clickButtons",0),c(this,"container"),c(this,"clickTime",0),c(this,"firstClick",!0),c(this,"dblclickTimeSpan",500),this.gizmos=[];const{width:e,height:i}=t.getBoundingClientRect();this.wireframeApplication=new C({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(Dt).map(([t,e])=>{const{url:i}=e;if(i)return fetch(i).then(t=>t.text()).then(i=>Dt[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 q?this.activeGizmo.cursorResult:void 0;this.setCursor(e)}init(t){this.gizmos=[],this.controlGizmo=new j(t),this.selectorGizmo=new Y(t);const e=new Q;this.transformGizmo=new q(t,e),this.preferenceGizmo=new Pt(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=Dt[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)}import{assertExist as At}from"@galacean/effects";var St=class{constructor(t){c(this,"plane",new L),c(this,"ray",new K),c(this,"viewportParam",{width:0,height:0,viewWidth:0,viewHeight:0,panelWidth:0,panelHeight:0,scale:1,ratio:1,translation:new B,rulerWidth:0}),c(this,"cameraParam",{position:new G,rotation:new G,focusPosition:new G,focusRotation:new G,viewProjectionMatrix:new H,inverseViewProjectionMatrix:new H}),c(this,"pageDataUtils"),this.pageDataUtils=t}refreshViewParam(){const t=this.pageDataUtils.getPageData();At(t,"You must run SDK first");const e=new B(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 B(...s.map(t=>t/i)),this.viewportParam.rulerWidth=0}refreshCameraParam(){const{player:t}=this.pageDataUtils,e=t?.getCompositions()?.[0]?.camera;if(e){const t=H.fromArray(e.getViewProjectionMatrix().toArray()),i=H.fromArray(e.getViewMatrix().toArray()).invert(),s=new W;i.decompose(this.cameraParam.position,s,new G),this.cameraParam.rotation=(new N).setFromQuaternion(s).toDegreeVector3(),this.cameraParam.focusPosition=new G(...this.cameraParam.position.toVector2().toArray(),this.cameraParam.position.z>0?0:2*this.cameraParam.position.z),this.cameraParam.focusPosition.applyEuler((new N).setFromDegreeVector3(this.cameraParam.rotation.clone()),this.cameraParam.position),this.cameraParam.focusRotation=(new N).setFromQuaternion(s.invert()).toDegreeVector3(),this.cameraParam.viewProjectionMatrix=t,this.cameraParam.inverseViewProjectionMatrix=H.fromArray(e.getInverseViewProjectionMatrix().toArray())}}initInteractionPlane(t,e){t??(t=this.cameraParam.focusPosition),e??(e=(new N).setFromDegreeVector3(this.cameraParam.rotation));const i=new G(0,0,1).applyEuler(e);this.plane.setFromNormalAndCoplanarPoint(t,i)}getWorldSizeByViewSize(t,e=!0,i){const s=e||!i?(new N).setFromDegreeVector3(this.cameraParam.rotation):(new N).setFromQuaternion((new W).setFromRotationMatrix(this.pageDataUtils.getItemTransformById(i.id).matrix)),r=i?(new G).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 G(0,0,0);const n=(new N).setFromQuaternion((new W).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 B).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 O).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 B(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}};import{FFmpeg as zt}from"@ffmpeg/ffmpeg";import{toBlobURL as Tt}from"@ffmpeg/util";function _t(t,e="asserts failed"){if(!t)throw new Error(e)}function Et(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 Mt(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 Vt(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(!Vt(t[s],e[s]))return!1}return!0}var kt={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"},Bt={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 Ft(t,e,i,s){const r=e.getContext("2d");_t(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 Ut(){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)})}(kt.SCRIPT,{crossOrigin:"anonymous"});const e={locateFile:(t,e)=>t.endsWith("createWebPCore.wasm")?kt.WASM:e+t};t(await window.createWebPCore(e))}catch(t){e(t)}})}function Rt(t){for(const e of t.getCompositions())for(const t of e.textures)t.isDestroyed||t.dispose();t.assetManagers=[],t.destroyCurrentCompositions()}var Wt=class{constructor(t,e,i,s){c(this,"sdk"),c(this,"player"),c(this,"container"),c(this,"emitter"),c(this,"interactionUtils"),this.player=t,this.sdk=s,this.container=e,this.emitter=i}init(){this.interactionUtils=new St(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===d.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===d.EndBehavior.restart||a===d.EndBehavior.freeze)}addSelectedItems(t){var e;x(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){x(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=t,this.emitter.emit("preSelectedItemChange",t)}clearPreSelectedItem(){x(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();x(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){Rt(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){x(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.time=t}pageZoom(t){var e;x(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=z(t,-.1,.1),r=M(z(i+s,.3,10),2);this.sdk.pageData.property.zoom=r,this.container.style.scale=`${r}`,this.emitter.emit("zoomChange",r)}setPageZoom(t){x(this.sdk.pageData,"You must call SDK#run() first");const e=M(z(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){x(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 H).copyFrom(i.transform.getParentMatrix()??new H);s.setPosition(new G);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 H,parentMatrix:new H},i=this.getPlayerItemById(t);if(void 0!==i?.transform){i.transform.updateLocalMatrix();const t=H.fromArray(i.composition?.transform.getWorldMatrix().elements??[]).invert();e.matrix=t.clone().multiply(H.fromArray(i.transform.getWorldMatrix().elements)),e.parentMatrix=t.clone().multiply(H.fromArray(i.transform.parentTransform?.getWorldMatrix().elements??(new H).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)Te.config.pageConfig.filterItemNames.includes(i.name)||(s([i]),this.addViewItemsByItems(t,i.children,i.getInstanceId()))}createViewItemByPlayerItem(t,e){x(this.sdk.pageData,"You must call SDK#run() first");const{transform:i,composition:s,isVisible:r}=t;i.updateLocalMatrix();const a=(new H).copyFrom(s?.transform.getWorldMatrix()??(new H).identity()).invert().multiply(i.getWorldMatrix()),o=new G,n=new W,c=new G;a.decompose(o,n,c);const h=(new N).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=>M(t,2)),l=h.toArray().map(t=>M(t,2)),m=c.toArray().map(t=>M(t,2)),g=i.size.toArray(),f={position:p,rotation:l,size:this.getPixelSizeByWorldSize([m[0]*g[0],m[1]*g[1],m[2]],t).map(t=>M(t,2)),visible:r,keyPropertyEditing:!1};switch(t.type){case d.ItemType.sprite:{const e=this.getActiveScene()?.scene;if(e){e.components.filter(e=>e.item.id===t.getInstanceId()).forEach(t=>{if(f.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);f.keyPropertyEditing=!!t?.template;const s=t?.url??"";s&&Object.assign(f,{image:s})}})}break}case d.ItemType.text:case d.ItemType.richtext:{const e=this.getActiveScene()?.scene;if(f.keyPropertyEditing=!0,e){e.components.filter(e=>e.item.id===t.getInstanceId()).forEach(t=>{if(![d.DataType.TextComponent,d.DataType.RichTextComponent].includes(t.dataType))return;const{textAlign:e,textColor:i,text:s,fontWeight:r,fontFamily:a}=t.options;Object.assign(f,{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:f}}getViewBoxById(t){const e=new U,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 G).copyFrom(e.transform.anchor).applyMatrix((new H).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 U;switch(t.type){case d.ItemType.sprite:case d.ItemType.plugin:case d.ItemType.video:case d.ItemType.richtext:case d.ItemType.text:case d.ItemType.shape:{const{transform:s,composition:r}=t;s.updateLocalMatrix();const{size:a}=s,o=(new H).copyFrom(r?.transform.getWorldMatrix()??new H).invert().multiply(s.getWorldMatrix()),{x:n,y:c}=a.clone().divide(2),h=new G(n,c,0).applyMatrix(o),p=new G(n,-c,0).applyMatrix(o),l=new G(-n,-c,0).applyMatrix(o),m=new G(-n,c,0).applyMatrix(o),d=this.interactionUtils.projectPoint(h).round(2),g=this.interactionUtils.projectPoint(p).round(2),f=this.interactionUtils.projectPoint(l).round(2),u=this.interactionUtils.projectPoint(m).round(2);i.setFromVec2Array([d,g,f,u]);const y=e?.map(t=>this.getViewBoxById(t.getInstanceId()));y&&y.map(t=>i.union(t));break}case d.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 B;const{zoom:t,translation:e}=this.sdk.pageData.property,{offsetWidth:i,offsetHeight:s}=this.container.parentElement,{offsetWidth:r,offsetHeight:a}=this.container,o=new B(i,s),n=new B(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 B(t/2,e/2).add(new B(...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 B(i,s).multiply(e),a=this.getViewportLeftTopPosition(),o=t.clone().subtract(a);return new B(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){x(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":[d.TextAlignment.left,d.TextAlignment.middle,d.TextAlignment.right].includes(t.propertyValue)&&i.getComponent(P).setTextAlign(t.propertyValue);break;case"color":Array.isArray(t.propertyValue)&&4===t.propertyValue.length&&(console.log(t.propertyValue),i.getComponent(P).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(P).setFontFamily(s)}break;case"text":"string"==typeof t.propertyValue&&i.getComponent(P).setText(t.propertyValue);break;case"weight":[d.TextWeight.normal,d.TextWeight.bold,d.TextWeight.lighter].includes(t.propertyValue)&&i.getComponent(P).setFontWeight(t.propertyValue);break;case"image":"string"==typeof t.propertyValue&&i.getComponent(v).setTexture(await I.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 G(...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 G(...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 G(...r,1))}break;case"visible":if("boolean"==typeof t.propertyValue&&(i.setVisible(t.propertyValue),Te.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){x(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([d.TextAlignment.left,d.TextAlignment.middle,d.TextAlignment.right].includes(e.propertyValue)){const i=t.components.find(t=>t.item.id===e.itemId&&[d.DataType.TextComponent,d.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&&[d.DataType.TextComponent,d.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&&[d.DataType.TextComponent,d.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&&[d.DataType.TextComponent,d.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&&[d.DataType.TextComponent,d.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,Te.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){x(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;x(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){x(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}};import Gt from"jszip";import Ht from"jszip";var Nt,Lt,Kt,Ot,jt,$t,Yt,Jt,Xt,qt,Zt,Qt,te,ee,ie,se,re,ae,oe="ready",ne="executable",ce="dispose",he={APNG:"APNG",MP4:"MP4",WebM:"WebM",Images:"Images",WebP:"WebP",GIF:"GIF",AlphaMaskVideo:"AlphaMaskVideo"},pe="idle",le="convertImage",me="transcoding",de="audio",ge="jpeg",fe="webp",ue="png",ye=(he.MP4,he.WebP,he.APNG,he.GIF,he.AlphaMaskVideo,he.Images,he.MP4,he.WebP,he.APNG,he.GIF,he.AlphaMaskVideo,he.Images,"default"),we="exporting",xe="success",ve="error",Pe=class{constructor(t){c(this,"sampleRate"),c(this,"duration"),c(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)}},Ie=["@vvfx/sdk","exporter"],De=class extends w{constructor(t){super(),c(this,"status",oe),c(this,"stage",pe),c(this,"mediaType"),c(this,"loggerInTranscoding"),c(this,"multiThreading"),c(this,"extraCanvas"),c(this,"player"),l(this,Nt,0),l(this,Lt),l(this,Kt),l(this,Ot),l(this,jt),l(this,$t,[]),l(this,Yt),l(this,Jt),l(this,Xt,[]),l(this,qt,0),l(this,Zt),l(this,Qt,[]),l(this,te,0),l(this,ee,0),l(this,ie,0),l(this,se,0),l(this,re,[]),l(this,ae,!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===ce}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=p(this,Zt)?.time;return{name:i,startTime:r,oldTotalTime:s,newTotalTime:a,fps:p(this,Zt)?.fps??30,backgroundColor:p(this,Zt)?.backgroundColor??"#000000",loop:p(this,Zt)?.loop??!0,audioEnable:p(this,Zt)?.audioEnable??!1}}get progress(){const t=p(this,ee)||1,e=p(this,ie)||1,i=Math.min(t/e,1),s=Math.min(p(this,te),t)/t*.4,r=Math.min(p(this,se),t)/t*.6,a=Math.min(s+r,1);p(this,Qt)[p(this,qt)]=i;const o=p(this,Qt).reduce((t,e,i)=>i<p(this,qt)?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===he.MP4?ge:this.mediaType===he.WebP?fe:ue}async onInit(){try{Et("log",[...Ie,"ready"],"starting"),this.status=oe,await this.loadHelper(this.mediaType),this.status=ne,Et("log",[...Ie,"ready"],"success"),this.emit("ready",this.mediaType)}catch(t){this.status=ce,this.onError(t)}finally{return this.status}}onReset(){this.stage=pe,window.cancelAnimationFrame(p(this,Nt)),m(this,Nt,0),this.player?.pause(),this.clearTaskInfo(),this.setProgress()}onError(t){Et("log",[...Ie,"error"],t),this.onFinish(!1),this.emit("error",t),this.dispose()}onFinish(t,e){Et("log",[...Ie,"finish"],t?"success":"failed"),this.emit("progress",1),this.emit("done",t),this.emit("finish",t,e)}async loadHelper(t){const e="WebP"===t&&!p(this,Ot),i=[he.MP4,he.APNG,he.GIF,he.AlphaMaskVideo].includes(t)&&!p(this,Kt);e&&m(this,Ot,await Ut()),i&&(m(this,Kt,await async function(t){const{multiThreading:e}=t??{},i=new zt,s=!!e,r={classWorkerURL:await Tt(Bt.CLASSWORKER,"text/javascript"),coreURL:"",wasmURL:""};return s?(r.coreURL=await Tt(Bt.MT.CORE,"text/javascript"),r.wasmURL=await Tt(Bt.MT.WASM,"application/wasm"),r.workerURL=await Tt(Bt.MT.WORKER,"text/javascript")):(r.coreURL=await Tt(Bt.DEFAULT.CORE,"text/javascript"),r.wasmURL=await Tt(Bt.DEFAULT.WASM,"application/wasm")),await i.load(r),i}({multiThreading:this.multiThreading})),p(this,Kt).on("log",({message:t})=>{if(this.loggerInTranscoding&&Et("log",[...Ie,"transcoding log"],t),this.canceled||this.stage!==me)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&&m(this,Qt,t.completedTaskPercentArray),void 0!==t?.currentTaskFrameIndex&&m(this,te,t.currentTaskFrameIndex),void 0!==t?.currentTaskTotalFrames&&m(this,ee,t.currentTaskTotalFrames),void 0!==t?.currentTaskInTranscodingFrameIndex&&m(this,se,t.currentTaskInTranscodingFrameIndex),void 0!==t?.allTaskFrames&&m(this,ie,t.allTaskFrames),this.emit("progress",this.progress)}forwardPlayerTime(t,e=!1){x(this.player);const{oldTotalTime:i,startTime:s}=this.config;x(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){m(this,Yt,new Pe),p(this,Kt)?p(this,Kt).writeFile(t,p(this,Yt).getBuffer()):Et("log",[...Ie,"getWavAudio"],"ffmpegCore is not ready")}async getImagesZip(t,e){const i=new Ht,s=i.folder(t);return x(s),p(this,Xt).forEach((t,i)=>{s.file(t,e[i])}),i.generateAsync({type:"arraybuffer"})}getWebP(){x(p(this,Ot));const t=Math.round(1e3/this.config.fps/1),e="out.webp",i=`${p(this,Xt).join(` -d ${t} `)} -d ${t} -o ${e} -loop ${this.config.loop?0:1}`.split(" "),s=p(this,Ot).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]}(p(this,Ot),i);_t(r&&a,"getWebP has error"),s(r,a);const o=p(this,Ot).FS.readFile(e);return p(this,Xt).forEach(t=>{p(this,Ot)?.FS.unlink(t)}),o}async getAPNG(){x(p(this,Kt));this.stage=me;const t="export.apng";return await p(this,Kt).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-plays",this.config.loop?"0":"1","-y",t]),t}async getGIF(){x(p(this,Kt));this.stage=me;const t="export.gif";return await p(this,Kt).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]),t}async getMP4(t,e){x(p(this,Kt));this.stage=me;const i="export.mp4";let s;const r=e?",setpts=PTS/"+Math.round(t/e*100)/100:"",a=e??t;return this.config.audioEnable&&!p(this,Yt)&&(m(this,Jt,"audio.wav"),this.getWavAudio(p(this,Jt))),await p(this,Kt).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]),p(this,Jt)&&p(this,Yt)&&(this.stage=de,s="export-with-audio.mp4",await p(this,Kt).exec(["-i",i,"-i",p(this,Jt),"-c:v","copy","-c:a","aac","-t",`${a}`,"-y",s])),s&&p(this,Kt).deleteFile(i).catch(()=>{Et("log",[...Ie,"ffmpeg delete file error"])}),s??i}async getAlphaMaskVideo(t,e){x(p(this,Kt));this.stage=me;const i="export.mp4",s=e?",setpts=PTS/"+Math.round(t/e*100)/100:"";return await p(this,Kt).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){x(p(this,Kt));const i=this.mediaType===he.APNG,s=this.mediaType===he.GIF,r=this.mediaType===he.AlphaMaskVideo,a=this.mediaType===he.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=pe}catch(t){throw t}finally{for(const t of p(this,Xt))t&&p(this,Kt).deleteFile(t)}let n=null;try{x(o);const t=await p(this,Kt).readFile(o);n="string"==typeof t?(new TextEncoder).encode(t):new Uint8Array(t)}finally{p(this,Kt).deleteFile(o).catch(()=>{Et("log",[...Ie,"ffmpeg delete file error"])})}return n}onRecordWebM(t){const e=new MediaRecorder(t.captureStream(this.config.fps),{mimeType:"video/webm;codecs=vp9"});m(this,jt,e),p(this,jt).start(0);const i=[];p(this,jt).ondataavailable=t=>{t.data.size>0&&i.push(t.data)},m(this,$t,i)}async onExportImageFrame(t){try{if(this.canceled)return;const{canvas:s,imageBuffers:r,startTime:a,oldTotalTime:o,newTotalTime:n}=t;x(this.player),x(p(this,Lt));const c=p(this,te)+1;this.stage=le,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:c}),this.loggerInTranscoding&&Et("log",[...Ie,"converting log"],`converting ${c} frame image`),c>=1&&this.forwardPlayerTime(c/this.config.fps+a),Ft(p(this,Lt),s,this.config.backgroundColor);let h=s;this.mediaType===he.AlphaMaskVideo&&(x(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 l=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),d=`image-${e=c,i=4,String(e).padStart(i,"0")}.${this.transImageType}`;this.mediaType===he.Images?r.push(l):this.mediaType===he.WebP?(x(p(this,Ot)),p(this,Ot).FS.writeFile(d,new Uint8Array(l))):(x(p(this,Kt)),await p(this,Kt).writeFile(d,new Uint8Array(l))),p(this,Xt).push(d);if(c===p(this,ee)){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():[he.MP4,he.APNG,he.GIF,he.AlphaMaskVideo].includes(this.mediaType)&&(t=await this.getVideoByType(o,n)??null),t&&(Et("log",[...Ie,"done"],"success"),this.emit("done",!0,t))}else m(this,Nt,window.requestAnimationFrame(()=>{this.canceled||this.onExportImageFrame({canvas:s,imageBuffers:r,startTime:a,oldTotalTime:o,newTotalTime:n})}))}catch(t){this.onError(t)}var e,i}async onExportWebMFrame(t){try{if(this.canceled)return;x(this.player),x(p(this,Lt));const e=p(this,te)+1;if(this.stage=le,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:e}),this.loggerInTranscoding&&Et("log",[...Ie,"converting log"],`converting ${e} frame image`),Ft(p(this,Lt),t,this.config.backgroundColor),1===e&&(this.player.play(),this.onRecordWebM(t)),e<p(this,ee))m(this,Nt,window.requestAnimationFrame(()=>{this.canceled||this.onExportWebMFrame(t)}));else{this.player?.pause(),p(this,jt)?.stop();const t=new Blob(p(this,$t),{type:"video/webm"}),e=await t.arrayBuffer();Et("log",[...Ie,"done"],"success"),this.emit("done",!0,e)}}catch(t){Et("log",[...Ie,"done"],"failed",t),this.emit("done",!1)}}async runTask(t){try{if(this.canceled)return;x(this.player),x(p(this,Lt));const{size:e,startTime:i,containerCanvas:s}=t,{oldTotalTime:r,newTotalTime:a}=this.config,[o,n]=e;if(p(this,Lt).width=o,p(this,Lt).height=n,s.width=o,s.height=n,this.player.resize(),m(this,Xt,[]),[he.MP4,he.APNG,he.Images,he.WebP,he.GIF,he.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){Et("log",[...Ie,"run task error"],t),this.emit("done",!1)}}clearTaskInfo(){m(this,qt,0),m(this,Zt,void 0),m(this,Qt,[]),m(this,te,0),m(this,ee,0),m(this,ie,0),m(this,se,0),m(this,re,[]),m(this,ae,!0)}clearFFMpegCore(){if(p(this,Kt)){for(const t of p(this,Xt))t&&p(this,Kt).deleteFile(t);m(this,Xt,[]),p(this,Kt).terminate(),m(this,Kt,void 0)}}clearImage2WebPCore(){p(this,Ot)&&(p(this,Ot).FS.quit(),m(this,Ot,void 0))}clearMediaRecorder(){p(this,jt)&&(p(this,jt).stop(),m(this,jt,void 0)),m(this,$t,[])}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),this.status=ce,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),Et("log",Ie,"canceled"))}async onExport(t){const e=t.length;try{if(this.status===oe)return Et("log",[...Ie],"readying"),void this.on("ready",()=>{this.onExport(t)});if(this.status===ce){if(await this.onInit()===ce)throw new Error("init environment failed")}if(this.clearTaskInfo(),!p(this,Lt)){const t=document.createElement("canvas");t.dataset.key="player-canvas",m(this,Lt,t)}this.player||(this.player=new f({canvas:p(this,Lt),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}m(this,qt,r),m(this,Zt,a);const{size:t,scene:o}=a;await new Promise(async n=>{try{if(!this.player)throw new Error("player not found");Et("log",[...Ie,"export"],"start",a),Rt(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)=>{this.off("done",p),t&&e?i[r]=e:s=!1,n()};this.on("done",p);const l={size:t,startTime:h,containerCanvas:e};await this.runTask(l)}catch(t){Et("log",[...Ie,"export error"],t),s=!1,n()}})}m(this,re,i),m(this,ae,s)}catch(t){this.onError(t),m(this,ae,!1)}e>=1&&p(this,ae)?this.onFinish(!0,p(this,re)):this.onFinish(!1)}dispose(){this.status=ce,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),this.player?.dispose(),this.player=void 0,p(this,Lt)?.remove(),m(this,Lt,void 0),m(this,Jt,void 0),m(this,Yt,void 0)}};Nt=new WeakMap,Lt=new WeakMap,Kt=new WeakMap,Ot=new WeakMap,jt=new WeakMap,$t=new WeakMap,Yt=new WeakMap,Jt=new WeakMap,Xt=new WeakMap,qt=new WeakMap,Zt=new WeakMap,Qt=new WeakMap,te=new WeakMap,ee=new WeakMap,ie=new WeakMap,se=new WeakMap,re=new WeakMap,ae=new WeakMap;var be=class extends w{constructor(t){super(),c(this,"_config"),c(this,"_status",ye),c(this,"_exportMedia"),this._config=t,this._exportMedia=new De(t)}get status(){return this._status}onExportProgress(t){this.emit("progress",t)}onExportMP4(t,e){const i=t[0]?.folderName,s=new Gt;e.forEach((e,i)=>{const{name:r}=t[i]??{};r&&s.file(`${r}.mp4`,e)}),s.generateAsync({type:"blob"}).then(t=>{Mt(t,`${i}.zip`,"application/zip")}).catch(t=>{Et("error",["@vvfx/sdk"],"export mp4 is error",t)})}onExportGIF(t,e){const i=t[0]?.folderName,s=new Gt;e.forEach((e,i)=>{const{name:r}=t[i]??{};r&&s.file(`${r}.gif`,e)}),s.generateAsync({type:"blob"}).then(t=>{Mt(t,`${i}.zip`,"application/zip")}).catch(t=>{Et("error",["@vvfx/sdk"],"export gif is error",t)})}onExportImages(t,e){const i=t[0]?.folderName,s=new Gt;e.forEach((e,i)=>{const{name:r}=t[i]??{};r&&s.file(`${r}.zip`,e)}),s.generateAsync({type:"blob"}).then(t=>{Mt(t,`${i}.zip`,"application/zip")}).catch(t=>{Et("error",["@vvfx/sdk"],"export Images is error",t)})}onExportError(t){this._status=ve,Et("error",["@vvfx/sdk"],"export is error",t)}onExport(t){this._status=we,this._exportMedia.onExport(t),this._exportMedia.on("progress",this.onExportProgress.bind(this)),this._exportMedia.once("finish",(e,i)=>{this._status=e?xe:ve,this.emit("complete",e),i&&0!==i.length&&(this._config.mediaType===he.MP4?this.onExportMP4(t,i):this._config.mediaType===he.GIF?this.onExportGIF(t,i):this._config.mediaType===he.Images&&this.onExportImages(t,i))}),this._exportMedia.on("error",this.onExportError.bind(this))}onCancel(){this._status=ve,this._exportMedia.onCancel(),this.emit("complete",!1)}dispose(){this._exportMedia.dispose()}},Ce=class{constructor(){c(this,"enabled",!0),c(this,"_player"),c(this,"_container"),this._container=document.createElement("canvas"),this._player=new f({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 Rt(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?z(o,0,1):.5,n="number"==typeof n?z(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 f=Math.max(h/(m/r),0),u=Math.max(p/(d/a),0),y=Math.min((h-f)*o,h),w=Math.min((p-u)*n,p);t.drawImage(e,y+c.left,w+c.top,f,u,i,s,r,a)}},Ae={topAdsorption:"T",leftAdsorption:"L",rightAdsorption:"R",bottomAdsorption:"B",centerAdsorption:"C",bottomCenterAdsorption:"BC"},Se=class{constructor(t){c(this,"_player"),c(this,"_container"),c(this,"size",[0,0]),c(this,"_pageDataUtils"),this._container=document.createElement("canvas"),this._player=new f({canvas:this._container,manualRender:!0}),this._pageDataUtils=t}async adjustment(t,e,i,s,r){if(!Te.config.sizeAdaptConfig.enabled)return console.warn("Size adapt is not opened, use #SDK.setConfig() open this feature."),t;this._player??(this._player=new f({canvas:this._container,manualRender:!0})),this.size=[...s],this._container.width=this.size[0],this._container.height=this.size[1],Rt(this._player),this._player.resize();const a=JSON.parse(JSON.stringify(t));await this._player.loadScene(a,{reusable:!0,autoplay:!1}),this._player.gotoAndStop(e);const o=this._player.getCompositions()[0];if(o){const[e,a]=s,n=i[0]/i[1],c=e/a;n>c&&this.keepDistribute(t,o,c/n,s);const[h,p,l,m]=r,d=e-l-m,g=a-h-p,f=[(l-m)/2,(h-p)/2],u=(new U).setFromCenterAndSize(new B(e,a).divide(2),new B(e,a)),y=(new U).setFromCenterAndSize(new B(e,a).divide(2).add(new B(...f)),new B(d,g));this.keepAdsorption("topAdsorption",t,o,f,u,y),this.keepAdsorption("bottomAdsorption",t,o,f,u,y),this.keepAdsorption("leftAdsorption",t,o,f,u,y),this.keepAdsorption("rightAdsorption",t,o,f,u,y),this.keepAdsorption("centerAdsorption",t,o,f,u,y),this.keepDoubleAdsorption("bottomCenterAdsorption",t,o,f,u,y)}return t}keepDistribute(t,e,i,s){const r=t=>{const i=(new H).copyFrom(e.camera.getViewProjectionMatrix());return(new B).copyFrom(t.applyMatrix(i).toVector2()).toViewCoordinate(s[0],s[1])};["topAdsorption","centerAdsorption","bottomAdsorption"].forEach(a=>{e.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===Ae[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 B(...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){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 H).copyFrom(i.camera.getViewProjectionMatrix());return(new B).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(o,n)},p=Ae[t];i.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===p&&!t.parentId).forEach(r=>{const o=i.items.filter(t=>t.parentId===r.getInstanceId()),n=o.find(t=>"check-area"===t.name),p=r.transform.position.clone(),l=["leftAdsorption","rightAdsorption"].includes(t)?"x":"y",m=["leftAdsorption","topAdsorption"].includes(t)?1:-1,d=["leftAdsorption","topAdsorption"].includes(t)?"min":"max",g=["leftAdsorption","topAdsorption"].includes(t)?"max":"min",f=3===r.name.split("-").length,u=Number(r.name.split("-")[1]),y=new B,w=[1,1],x=n?this.getViewBoxByHeadlessPlayerItem(n,[],h):this.getViewBoxByHeadlessPlayerItem(r,o,h);c(r,...s),x.getSize().x>a.getSize().x&&(w[0]=a.getSize().x/x.getSize().x,w[1]=a.getSize().x/x.getSize().x,r.scale(...w,1)),r.transform.updateLocalMatrix();const v=n?this.getViewBoxByHeadlessPlayerItem(n,[],h):this.getViewBoxByHeadlessPlayerItem(r,o,h),P=new B;if(!a.containsBox(v)){const{min:t,max:e}=v,{min:i,max:s}=a;P.x+=t.x<i.x?i.x-t.x:0,P.x+=e.x>s.x?s.x-e.x:0,P.y+=t.y<i.y?i.y-t.y:0,P.y+=e.y>s.y?s.y-e.y:0,c(r,...P.toArray()),r.transform.updateLocalMatrix()}const I=n?this.getViewBoxByHeadlessPlayerItem(n,[],h):this.getViewBoxByHeadlessPlayerItem(r,o,h);if(!Number.isNaN(u)&&f)if("centerAdsorption"!==t){const t=Math.abs(I[g][l]-a[d][l]),e=a.getSize()[l]*u;t>e&&(y[l]=(e-t)*m,c(r,...y.toArray()),r.transform.updateLocalMatrix())}else{const t=I.getSize().y,e=a.getSize().y;if(t/e>u){const i=e*u/t;r.scale(i,i,1),w[0]*=i,w[1]*=i}}const D=n?this.getViewBoxByHeadlessPlayerItem(n,[],h):this.getViewBoxByHeadlessPlayerItem(r,o,h),b=i.items.filter(t=>"T"===t.name.split("-")[0]?.toLocaleUpperCase()&&!t.parentId),C=new U;if(b.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,[],h):this.getViewBoxByHeadlessPlayerItem(t,e,h);C.union(r)}),!C.isEmpty()&&C.max.y>D.min.y)if("centerAdsorption"===t){const t=C.max.y-D.min.y;c(r,0,t),r.transform.updateLocalMatrix()}else if(["leftAdsorption","rightAdsorption"].includes(t)){const t=D.getSize().y,e=a.getSize().y-(C.max.y-a.min.y);let i=C.max.y-D.min.y;if(t>e){const s=e/t;w[0]*=s,w[1]*=s,r.scale(s,s,1),r.transform.updateLocalMatrix(),i-=(t-e)/2}c(r,0,i),r.transform.updateLocalMatrix()}const A=r.transform.position.clone().subtract(p).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:w})})}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 H).copyFrom(i.camera.getViewProjectionMatrix());return(new B).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(o,n)},p=Ae[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 f=o?this.getViewBoxByHeadlessPlayerItem(o,[],h):this.getViewBoxByHeadlessPlayerItem(t,r,h),u=new B;if(!a.containsBox(f)){const{min:e,max:i}=f,{min:s,max:r}=a;u.x+=e.x<s.x?s.x-e.x:0,u.x+=i.x>r.x?r.x-i.x:0,u.y+=e.y<s.y?s.y-e.y:0,u.y+=i.y>r.y?r.y-i.y:0,c(t,...u.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 U,{transform:r,composition:a}=t;switch(t.type){case d.ItemType.sprite:case d.ItemType.plugin:case d.ItemType.video:case d.ItemType.richtext:case d.ItemType.text:case d.ItemType.shape:{r.setValid(!0),r.updateLocalMatrix();const{size:t}=r,o=(new H).copyFrom(a?.transform.getWorldMatrix()??new H).invert().multiply(r.getWorldMatrix()),{x:n,y:c}=t.clone().divide(2),h=new G(n,c,0).applyMatrix(o),p=new G(n,-c,0).applyMatrix(o),l=new G(-n,-c,0).applyMatrix(o),m=new G(-n,c,0).applyMatrix(o),d=i(h).round(2),g=i(p).round(2),f=i(l).round(2),u=i(m).round(2);s.setFromVec2Array([d,g,f,u]);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 d.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()}},ze=class t{constructor(e){c(this,"_eventEmitter",new w),c(this,"_pageData"),c(this,"_screenShot"),c(this,"_exporter"),c(this,"_pageDataUtils"),c(this,"_sizeAdapt"),c(this,"_gestureHandler"),c(this,"disposables",[]),c(this,"_isSwitchScene",!1),c(this,"player"),c(this,"_playerContainer"),c(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 f({container:r,interactive:!0,pixelRatio:window.devicePixelRatio||1}),this.player.on("update",()=>{if(x(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=>{x(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=>{x(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems=[...t],this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("preSelectedItemChange",t=>{x(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t,this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("selectedViewChange",t=>{x(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&&!Vt(t.exportVideoConfig,e.exportVideoConfig)&&(this._exporter.dispose(),this.initExporter(e.exportVideoConfig))}),this._pageDataUtils=new Wt(this.player,r,this._eventEmitter,this),this.initExporter(t.config.exportVideoConfig),this._gestureHandler=new bt(e),this._gestureHandler.registerViewEvent(),this._screenShot=new Ce,this._sizeAdapt=new Se(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 be(t),this._exporter.on("progress",t=>{this._eventEmitter.emit("exportProgress",t)}),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];x(c);const h=c.previewSize??a.size,[p,l]=a.size;c.previewSize=[p,l];const m=c.duration??0,d=a.safeArea??[0,0,0,0];t.config.sizeAdaptConfig.enabled&&(n=await this._sizeAdapt.adjustment(n,m,h,[p,l],d)),(i=a.export).time??(i.time=m),o.push({...a,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 x(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems}setPreSelectedItem(t){x(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t}getPreSelectedItem(){return x(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){x(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){x(this._pageData,"You must call SDK#run() first");const e=this.getItemProperty(t)?.property?.[t.propertyName];return e}async setItemPropertyValue(t){x(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){x(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(x(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 x(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){x(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){x(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&&(Rt(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){x(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 x(this._pageData,"You must call SDK#run() first"),this._pageData.viewProperties.map(t=>({id:t.id,thumbnail:this.generateScreenShot(t.id)}))}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&&(x(this.pageData,"You must call SDK#run() first"),x(this._exporter,"You must init exporter first"),this._exporter.onExport(this.exportOptions))}cancelExport(){x(this._exporter,"You must init exporter first"),this._exporter.onCancel()}async loadPageData(t){x(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){x(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;x(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];x(c);const h=c.previewSize??o.size,[p,l]=o.size;c.previewSize=[p,l];const m=c.duration??0,d=o.safeArea??[0,0,0,0];t.config.sizeAdaptConfig.enabled&&(n=await this._sizeAdapt.adjustment(n,m,h,[p,l],d)),(i=o.export).time??(i.time=m),s.push({...o,safeArea:d,previewSafeAreas:[...o.previewSafeAreas??[]],id:r+1+a,scene:n,ignoreInteraction:!1})}this._pageData.viewProperties.push(...s),this._eventEmitter.emit("pageDataChange",this.getPageData())}deleteViewParams(t){t.forEach(async t=>{x(this._pageData);const e=this._pageData.viewProperties.findIndex(e=>e.id===t);if(!1!==this._pageData.viewProperties[e]?.ignoreInteraction)return void console.warn("target view ignore interaction, it can not be deleted.");this._pageData.viewProperties.splice(e,1);const i=this._pageData.activeData.view??0;t===i?await this._pageDataUtils.loadScene(i):t<i&&(this._pageData.activeData.view=i-1,await this._pageDataUtils.loadScene(this._pageData.activeData.view)),this._pageData.viewProperties.forEach(e=>{e.id>t&&(e.id-=1)})}),this._eventEmitter.emit("pageDataChange",this.getPageData())}setExportParam(t,e){x(this._pageData),this._pageData.viewProperties.forEach(i=>{void 0!==e&&i.id!==e||(i.export=t)})}setPageZoom(t){x(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}};c(ze,"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 Te=ze;export{Te as SDK,d as spec};
|
|
1
|
+
var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,r=t=>{throw TypeError(t)},a=(e,i)=>{for(var s in i)t(e,s,{get:i[s],enumerable:!0})},o=(r,a,o,n)=>{if(a&&"object"==typeof a||"function"==typeof a)for(let c of i(a))s.call(r,c)||c===o||t(r,c,{get:()=>a[c],enumerable:!(n=e(a,c))||n.enumerable});return r},n=(t,e,i)=>(o(t,e,"default"),i&&o(i,e,"default")),c=(e,i,s)=>((e,i,s)=>i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s)(e,"symbol"!=typeof i?i+"":i,s),h=(t,e,i)=>e.has(t)||r("Cannot "+i),p=(t,e,i)=>(h(t,e,"read from private field"),i?i.call(t):e.get(t)),l=(t,e,i)=>e.has(t)?r("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),m=(t,e,i,s)=>(h(t,e,"write to private field"),s?s.call(t,i):e.set(t,i),i);import"@galacean/effects";import{spec as d,VFXItem as g,Player as f,math as u,Composition as y,EventEmitter as w,assertExist as x,SpriteComponent as v,TextComponent as P,Texture as I}from"@galacean/effects";import"@galacean/effects-plugin-rich-text";import{RichTextComponent as D}from"@galacean/effects-plugin-rich-text";import"@galacean/effects-plugin-model";import"@galacean/effects-plugin-multimedia";import{VideoComponent as b}from"@galacean/effects-plugin-multimedia";import"@galacean/effects-plugin-spine";import{Application as C}from"@pixi/app";var A=class{constructor(){c(this,"interactive"),c(this,"type"),c(this,"active"),this.type="null",this.active=!1,this.interactive=!1}},S=1e-6;function z(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 T=Math.PI/180,_=180/Math.PI;function E(t){return Math.atan2(-t.y,-t.x)+Math.PI}function M(t,e,i=Math.round){if(Number.isInteger(t))return t;const s=Math.pow(10,e);return i(t*s)/s}function V(t,e){return Math.abs(t-e)<S||t===1/0&&e===1/0||t===-1/0&&e===-1/0}function k(t){return isNaN(t)||Math.abs(t)<S}var B=class t extends u.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}},F=class t{constructor(t=new B,e=new B){c(this,"start",new B),c(this,"end",new B),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 B).subtractVectors(this.end,this.start).normalize()}getCenter(t=new B){return t.addVectors(this.start,this.end).multiply(.5)}delta(t=new B){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 B){return this.delta(e).multiply(t).add(this.start)}closestPointToPointParameter(t,e){const i=new B,s=new B;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=z(a,0,1)),a}closestPointToPoint(t,e,i=new B){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 B).subtractVectors(this.end,this.start).length()}crossWithLine(t){const e=this.delta(),i=t.delta(),s=(new B).subtractVectors(t.start,this.start),r=(new B).subtractVectors(t.end,this.start),a=(new B).subtractVectors(this.start,t.start),o=(new B).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}},U=class t{constructor(t=new B(1/0,1/0),e=new B(-1/0,-1/0)){c(this,"corners",[]),c(this,"min",new B(1/0,1/0)),c(this,"max",new B(-1/0,-1/0)),this.min=t.clone(),this.max=e.clone(),this.isEmpty()?this.corners=[]:this.corners=[t.clone(),new B(e.x,t.y),e.clone(),new B(t.x,e.y)]}set(t,e){return this.min.copyFrom(t),this.max.copyFrom(e),this.corners=[t.clone(),new B(e.x,t.y),e.clone(),new B(t.x,e.y)],this}setFromVec2Array(t){return this.min=(new B).copyFrom(t[0]),this.max=(new B).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 B).copyFrom(t[0]),this.max=(new B).copyFrom(t[0]),t.forEach(t=>{this.min=this.min.min(t),this.max=this.max.max(t)}),this.corners.push(new B(this.min.x,this.min.y)),this.corners.push(new B(this.min.x,this.max.y)),this.corners.push(new B(this.max.x,this.max.y)),this.corners.push(new B(this.max.x,this.min.y)),this}setFromCenterAndSize(t,e){const i=(new B).copyFrom(e).multiply(.5);return this.min.copyFrom(t).subtract(i),this.max.copyFrom(t).add(i),this.corners=[this.min.clone(),new B(this.max.x,this.min.y),this.max.clone(),new B(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 B){return this.isEmpty()?t.set(0,0):t.addVectors(this.min,this.max).multiply(.5)}getSize(t=new B){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 B(s.x-i.x,s.y-i.y),a=new B(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 B){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 B){return e.copyFrom(t).clamp(this.min,this.max)}distanceToPoint(t){return(new B).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 B(this.max.x,this.min.y),this.max.clone(),new B(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 F(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 F(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}},R=class t{constructor(t=new B,e=0){c(this,"center"),c(this,"radius"),this.center=t.clone(),this.radius=e}set(t,e){return this.center=(new B).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 B,this.radius=0,this}isEmpty(){return 0===this.radius}getCenter(t=new B){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}},W=class extends u.Quaternion{},G=class t extends u.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 W).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}},H=class t extends u.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=G.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,f=a*m,u=a*d,y=a*g,w=o*d,x=o*g,v=n*g,P=c*m,I=c*d,D=c*g,{x:b,y:C,z:A}=i;return r[0]=(1-(w+v))*b,r[1]=(u+D)*b,r[2]=(y-I)*b,r[3]=0,r[4]=(u-D)*C,r[5]=(1-(f+v))*C,r[6]=(x+P)*C,r[7]=0,r[8]=(y+I)*A,r[9]=(x-P)*A,r[10]=(1-(f+w))*A,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 G,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===u.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===u.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===u.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===u.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===u.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===u.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}},N=class extends u.Euler{constructor(t=0,e=0,i=0,s=u.EulerOrder.XYZ){super(t,e,i,s)}getInvertMatrixByEuler(){return(new H).makeRotationFromEuler(this).invert()}toDegreeVector3(t){return t?t.set(this.x*_,this.y*_,this.z*_):new G(this.x*_,this.y*_,this.z*_)}setFromDegreeVector3(t,e){return this.set(t.x*T,t.y*T,t.z*T,e??this.order)}},L=class t{constructor(t=0,e=new G(0,0,1)){c(this,"distance"),c(this,"normal");const i=e.length();0===i&&(this.normal=new G(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 G(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}},K=class t extends u.Ray{constructor(t=new G,e=new G(1,0,0)){super(t,e),c(this,"origin"),c(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(k(e))return k(t.distanceToPoint(this.origin))?0:NaN;const i=(-this.origin.dot(t.normal)-t.distance)/e;return i>0?i:NaN}},O=class{constructor(t=new K){c(this,"ray"),this.ray=t.clone()}setFromCamera(t,e){const i=e.position,s=new G(t.x,t.y,.5).applyMatrix(e.inverseViewProjectMatrix).subtract(i).normalize();return this.ray.set(i,s),this}rayCastPlane(t){const e=new G,i=this.ray.rayCastPlane(t,e);if(!isNaN(i))return{distance:i,point:this.ray.at(i)}}},j=class extends A{constructor(t){super(),c(this,"defaultInteractive",!0),c(this,"interactive",!0),c(this,"lastPoint",new B),c(this,"SDKUtils"),this.SDKUtils=t,this.type="control"}initialize(){}preparationAction(){}cancelPreparation(){}refreshResults(){}preAction(){}action(t){if(!Te.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 B(r,a);e||i?(o.y=z(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*Te.config.gestureHandlerConfig.controlGizmoConfig.zoomStep;this.SDKUtils.pageZoom(e)}pan(t){this.SDKUtils.pageMove(t)}getRenderObjects(){return[]}};import{Graphics as $}from"@pixi/graphics";var Y=class extends A{constructor(t){super(),c(this,"interactive",!0),c(this,"result",{type:"null",box:new U}),c(this,"selectedItemIds",[]),c(this,"cursorPoint",new B),c(this,"startPoint",new B),c(this,"graphics",new $),c(this,"pageDataUtils"),c(this,"clearResult",!1),c(this,"type"),this.pageDataUtils=t,this.type="selector"}initialize(){}actionKey(){}endActionKey(){}getRenderObjects(){return Te.config.gestureHandlerConfig.selectorGizmoEnabled?this.clearResult?(this.result={type:"null",box:new U},this.clearResult=!1,[]):(this.refreshResults(),[this.graphics]):[]}cancelPreparation(){this.result.type="null",this.pageDataUtils.clearPreSelectedItem()}preparationAction(t){if(this.result.box=new U,!Te.config.gestureHandlerConfig.selectorGizmoEnabled)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const e=new B(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 B(t.clientX,t.clientY),this.cursorPoint=new B(t.offsetX,t.offsetY),this.active=!0,this.type):(this.pageDataUtils.addSelectedItems([this.selectedItemIds[0]]),this.clearResult=!0,"transform")}action(t){const e=(new B).addVectors(this.cursorPoint,(new B).subtractVectors(new B(t.clientX,t.clientY),this.startPoint)),i=(new B).subtractVectors(this.cursorPoint,e),s=(new B).addVectors(this.cursorPoint,e).multiply(.5);i.x=Math.abs(i.x),i.y=Math.abs(i.y);const r=(new U).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 K,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===d.ItemType.mesh||s.getComponent(v)?.renderer?.occlusion||s.getComponent(P)?.renderer?.occlusion||s.getComponent(b)?.renderer?.occlusion||s.getComponent(D)?.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}=Te.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()}};import{Graphics as J}from"@pixi/graphics";import{assertExist as X}from"@galacean/effects";var q=class extends A{constructor(t,e){super(),c(this,"type"),c(this,"interactive",!0),c(this,"wireframe"),c(this,"cursorResult",{type:"normal",angle:0}),c(this,"cursorPoint",new B),c(this,"lastPoint",new B),c(this,"rotationAngle",0),c(this,"active",!1),c(this,"enableAdsorption",!0),c(this,"scaleParam"),c(this,"activeType","null"),c(this,"lastWorldPosition",new G),c(this,"pageDataUtils"),c(this,"adsorptionGizmo"),c(this,"graphics",new J),this.type="transform",this.pageDataUtils=t,this.adsorptionGizmo=e,this.wireframe={edges:[],anchor:new B,scaleCorners:[],rotationCorners:[],interactive:!0,cornerEnable:!0,directionEnable:!0,box:new U,totalBox:new U,childrenBoxes:[],activeType:"null",interactiveDirection:new B,scaleCorner:new B,scaleEdgeCorners:[]}}initialize(){}actionKey(){}endActionKey(){}getRenderObjects(){return Te.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 B(t.clientX,t.clientY),this.cursorPoint=new B(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 G,this.activeType=e?"null":this.activeType,this.type}preparationAction(t){if(!Te.config.gestureHandlerConfig.transformGizmoEnabled)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const e=new B(t.offsetX,t.offsetY),i=this.wireframe;this.refreshTransformType(e);const{interactiveDirection:s}=i;return this.refreshCursorResult(this.activeType,E(s)),this.active="null"!==this.activeType,this.active?this.type:void 0}action(t){if(!Te.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 G}const e=new B(t.clientX,t.clientY),i=(new B).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();X(n);let c=0;switch(a){case"rotation":{const t=r.clone(),e=new G,a=M(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 B).subtractVectors(this.cursorPoint,t),(new B).subtractVectors(this.cursorPoint.add(i),t))*_,3);e.z=a,this.rotationAngle+=a,c=E(o)+this.rotationAngle*T,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 U).filter(t=>!t.isEmpty()),i=new B(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);this.adsorptionGizmo.boxTranslationAdsorption(t,this.wireframe.box,e);const r=new B(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!==d.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 H).extractRotation(n.matrix).invert(),h=(new G).subtractVectors(e,i).applyMatrix(c),p=h.clone().multiply(a),l=t.subtract(r).subtract(i).applyMatrix(c),m=new G(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}([V(h.x,0)?1:Math.abs(l.x/h.x),V(h.y,0)?1:Math.abs(l.y/h.y)]),g=l.toArray()[d],f=p.toArray()[d];if(V(a.x,a.y)&&V(a.z,a.x)){const t=V(f,0)?1:Math.abs(g/f);m.set(t,t,t)}else if(0===d){m.x=V(f,0)?1:Math.abs(g/f);const t=h.y*g/h.x;m.y=V(p.y,0)?1:t/p.y;const e=h.z*g/h.x;m.z=V(p.z,0)?1:e/p.z}else if(1===d){m.y=V(f,0)?1:Math.abs(g/f);const t=h.x*g/h.y;m.x=V(p.x,0)?1:t/p.x;const e=h.z*g/h.y;m.z=V(p.z,0)?1:e/p.z}else{m.z=V(f,0)?1:Math.abs(g/f);const t=h.x*g/h.z;m.x=V(p.x,0)?1:t/p.x;const e=h.y*g/h.z;m.y=V(p.y,0)?1:e/p.y}this.scaleParam.lastScalar.multiply(m),s.forEach(t=>{this.pageDataUtils.scaleItem(t.id,m)})}c=E(o);break}}this.refreshCursorResult(a,c),this.lastPoint.copyFrom(e)}endAction(t){this.active=!1;const e=new B(t.clientX,t.clientY),i=(new B).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,E(a)),this.adsorptionGizmo.clearAbsorptionResult(),this.rotationAngle=0,this.cursorPoint=new B,this.lastPoint=new B}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)*_};break;case"rotation":this.cursorResult={type:"rotation",angle:(e+Math.PI/4)*_};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 G).copyFrom(this.pageDataUtils.getPlayerItemById(i.id).transform.anchor).applyMatrix(t.matrix),r=(new G).setFromMatrixPosition(t.matrix),a=(new N).setFromQuaternion((new W).setFromRotationMatrix(t.matrix))}this.pageDataUtils.interactionUtils.initInteractionPlane(r,a),this.scaleParam={shift:new G,center:new G,corner:new G,lastScalar:new G(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 G}this.scaleParam.shift=(this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(t)??new G).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}=Te.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 F(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 B,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 U;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 U).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!==d.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 F((new B).copyFrom(t),(new B).copyFrom(a[(e+1)%4])))});const{scaleCircleSize:o,rotationCircleSize:n}=Te.config.gestureHandlerConfig.transformGizmoConfig;this.wireframe.box.corners.forEach(t=>{this.wireframe.scaleCorners.push(new R(t,o));const e=(new B).subtractVectors(t,this.wireframe.box.getCenter()),i=(new B).copyFrom(this.wireframe.box.getCenter()).add((new B).copyFrom(e).normalize().multiply(e.length()+n-o));this.wireframe.rotationCorners.push(new R(i,n))})}setAdsorptionEnabled(t){this.enableAdsorption=t}};import{Graphics as Z}from"@pixi/graphics";var Q=class extends A{constructor(){super(),c(this,"interactive",!1),c(this,"results",[]),c(this,"graphics",new Z),c(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=[],!Te.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 B(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=[],!Te.config.gestureHandlerConfig.adsorptionGizmoEnabled)return void console.warn("Adsorption is not opened, use #SDK.setAdsorptionConfig() open this feature.");const a=new B(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)<Te.config.gestureHandlerConfig.adsorptionGizmoConfig.distance&&this.refreshPointAbsorptionResult(t,e,"x"),s&&Math.abs(t.y-e.y)<Te.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 B(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 F(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 F(i,s))})}refreshRenderObject(){this.graphics.clear();const{lineWidth:t,lineColor:e}=Te.config.gestureHandlerConfig.adsorptionGizmoConfig;this.results.forEach(i=>{this.graphics.lineStyle(t,e),this.graphics.drawLine(i)})}getRenderObjects(){return Te.config.gestureHandlerConfig.adsorptionGizmoEnabled?(this.refreshResults(),this.refreshRenderObject(),[this.graphics]):[]}clearAbsorptionResult(){this.results=[],this.absorptionResult={}}},tt={};a(tt,{Application:()=>rt,utils:()=>it});var et={};a(et,{Application:()=>rt,utils:()=>it}),n(et,ht),n(et,pt),n(et,lt),n(et,mt),n(et,dt),n(et,gt),n(et,ft),n(et,ut),n(et,yt),n(et,wt),n(et,xt),n(et,vt);import"@pixi/polyfill";import*as it from"@pixi/utils";import{InteractionManager as st}from"@pixi/interaction";import{Application as rt}from"@pixi/app";import{Renderer as at,BatchRenderer as ot}from"@pixi/core";import{AppLoaderPlugin as nt}from"@pixi/loaders";import{TickerPlugin as ct}from"@pixi/ticker";import*as ht from"@pixi/constants";import*as pt from"@pixi/core";import*as lt from"@pixi/display";import*as mt from"@pixi/graphics";import*as dt from"@pixi/loaders";import*as gt from"@pixi/interaction";import*as ft from"@pixi/math";import*as ut from"@pixi/runner";import*as yt from"@pixi/sprite";import*as wt from"@pixi/text";import*as xt from"@pixi/ticker";import*as vt from"@pixi/settings";it.skipHello(),at.registerPlugin("interaction",st),at.registerPlugin("batch",ot),rt.registerPlugin(ct),rt.registerPlugin(nt),et.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()},et.Graphics.prototype.fillBox=function(t){const e=t.getSize();this.drawRect(t.min.x,t.min.y,e.x,e.y)},et.Graphics.prototype.drawLine=function(t){if(this.beginFill(),t instanceof F)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()},n(tt,et);var Pt=class extends A{constructor(t){super(),c(this,"interactive",!1),c(this,"box",new U),c(this,"graphics",new tt.Graphics),c(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 U,!Te.config.gestureHandlerConfig.preferenceGizmoEnabled)return void console.warn("Preference gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const t=this.PageDataUtils.getPageData();x(t);const{container:e}=this.PageDataUtils;if(e){const{zoom:i}=t.property,{offsetWidth:s,offsetHeight:r}=e,a=new B(s,r).multiply(i),o=this.PageDataUtils.getViewportLeftTopPosition().add(a.clone().divide(2));this.box=(new U).setFromCenterAndSize(o,a)}}refreshRenderObjects(){const{boxWidth:t,boxColor:e,markColor:i,markAlpha:s,safeAreaEnabled:r,safeAreaBoxColor:a,safeAreaBoxAlpha:o}=Te.config.gestureHandlerConfig.preferenceGizmoConfig;this.graphics=new tt.Graphics;const{offsetWidth:n,offsetHeight:c}=this.PageDataUtils.container.parentElement,h=new U(new B(0,0),new B(n,this.box.min.y)),p=new U(new B(0,this.box.min.y),new B(this.box.min.x,c)),l=new U(new B(this.box.min.x,this.box.max.y),new B(n,c)),m=new U(new B(this.box.max.x,this.box.min.y),new B(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();x(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:f,max:u}=this.box;this.graphics.beginFill(a,o);const y=new U(f,new B(u.x,f.y+l)),w=new U(new B(f.x,f.y+l),new B(f.x+m,u.y)),x=new U(new B(u.x-d,f.y+l),new B(u.x,u.y)),v=new U(new B(f.x+m,u.y-g),new B(u.x-d,u.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 B(r/t[0]*n.x,a/t[1]*n.y),h=new B(i/t[0]*n.x+c.x/2,s/t[1]*n.y+c.y/2).add(f),p=(new U).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 Te.config.gestureHandlerConfig.preferenceGizmoEnabled?(this.refreshRenderObjects(),[this.graphics]):[]}},It="https://mdn.alipayobjects.com/rms/uri/file/as/0.0.6",Dt={normal:{type:"preset",content:"default"},rotation:{type:"svg",content:"default",url:`${It}/icons/cursor-rotate-32.svg`},scale:{type:"svg",content:"default",url:`${It}/icons/cursor-scale-32.svg`}};var bt=class{constructor(t){c(this,"wireframeApplication"),c(this,"gizmos",[]),c(this,"activeGizmo"),c(this,"selectorGizmo"),c(this,"transformGizmo"),c(this,"controlGizmo"),c(this,"preferenceGizmo"),c(this,"spaceClickTime"),c(this,"spaceEmit",!1),c(this,"_ignoreInteraction",!1),c(this,"clickButtons",0),c(this,"container"),c(this,"clickTime",0),c(this,"firstClick",!0),c(this,"dblclickTimeSpan",500),this.gizmos=[];const{width:e,height:i}=t.getBoundingClientRect();this.wireframeApplication=new C({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(Dt).map(([t,e])=>{const{url:i}=e;if(i)return fetch(i).then(t=>t.text()).then(i=>Dt[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 q?this.activeGizmo.cursorResult:void 0;this.setCursor(e)}init(t){this.gizmos=[],this.controlGizmo=new j(t),this.selectorGizmo=new Y(t);const e=new Q;this.transformGizmo=new q(t,e),this.preferenceGizmo=new Pt(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=Dt[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)}import{assertExist as At}from"@galacean/effects";var St=class{constructor(t){c(this,"plane",new L),c(this,"ray",new K),c(this,"viewportParam",{width:0,height:0,viewWidth:0,viewHeight:0,panelWidth:0,panelHeight:0,scale:1,ratio:1,translation:new B,rulerWidth:0}),c(this,"cameraParam",{position:new G,rotation:new G,focusPosition:new G,focusRotation:new G,viewProjectionMatrix:new H,inverseViewProjectionMatrix:new H}),c(this,"pageDataUtils"),this.pageDataUtils=t}refreshViewParam(){const t=this.pageDataUtils.getPageData();At(t,"You must run SDK first");const e=new B(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 B(...s.map(t=>t/i)),this.viewportParam.rulerWidth=0}refreshCameraParam(){const{player:t}=this.pageDataUtils,e=t?.getCompositions()?.[0]?.camera;if(e){const t=H.fromArray(e.getViewProjectionMatrix().toArray()),i=H.fromArray(e.getViewMatrix().toArray()).invert(),s=new W;i.decompose(this.cameraParam.position,s,new G),this.cameraParam.rotation=(new N).setFromQuaternion(s).toDegreeVector3(),this.cameraParam.focusPosition=new G(...this.cameraParam.position.toVector2().toArray(),this.cameraParam.position.z>0?0:2*this.cameraParam.position.z),this.cameraParam.focusPosition.applyEuler((new N).setFromDegreeVector3(this.cameraParam.rotation.clone()),this.cameraParam.position),this.cameraParam.focusRotation=(new N).setFromQuaternion(s.invert()).toDegreeVector3(),this.cameraParam.viewProjectionMatrix=t,this.cameraParam.inverseViewProjectionMatrix=H.fromArray(e.getInverseViewProjectionMatrix().toArray())}}initInteractionPlane(t,e){t??(t=this.cameraParam.focusPosition),e??(e=(new N).setFromDegreeVector3(this.cameraParam.rotation));const i=new G(0,0,1).applyEuler(e);this.plane.setFromNormalAndCoplanarPoint(t,i)}getWorldSizeByViewSize(t,e=!0,i){const s=e||!i?(new N).setFromDegreeVector3(this.cameraParam.rotation):(new N).setFromQuaternion((new W).setFromRotationMatrix(this.pageDataUtils.getItemTransformById(i.id).matrix)),r=i?(new G).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 G(0,0,0);const n=(new N).setFromQuaternion((new W).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 B).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 O).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 B(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}};import{FFmpeg as zt}from"@ffmpeg/ffmpeg";import{toBlobURL as Tt}from"@ffmpeg/util";function _t(t,e="asserts failed"){if(!t)throw new Error(e)}function Et(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 Mt(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 Vt(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(!Vt(t[s],e[s]))return!1}return!0}var kt={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"},Bt={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 Ft(t,e,i,s){const r=e.getContext("2d");_t(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 Ut(){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)})}(kt.SCRIPT,{crossOrigin:"anonymous"});const e={locateFile:(t,e)=>t.endsWith("createWebPCore.wasm")?kt.WASM:e+t};t(await window.createWebPCore(e))}catch(t){e(t)}})}function Rt(t){for(const e of t.getCompositions())for(const t of e.textures)t.isDestroyed||t.dispose();t.assetManagers=[],t.destroyCurrentCompositions()}var Wt=class{constructor(t,e,i,s){c(this,"sdk"),c(this,"player"),c(this,"container"),c(this,"emitter"),c(this,"interactionUtils"),this.player=t,this.sdk=s,this.container=e,this.emitter=i}init(){this.interactionUtils=new St(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===d.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===d.EndBehavior.restart||a===d.EndBehavior.freeze)}addSelectedItems(t){var e;x(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){x(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=t,this.emitter.emit("preSelectedItemChange",t)}clearPreSelectedItem(){x(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();x(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){Rt(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){x(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.time=t}pageZoom(t){var e;x(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=z(t,-.1,.1),r=M(z(i+s,.3,10),2);this.sdk.pageData.property.zoom=r,this.container.style.scale=`${r}`,this.emitter.emit("zoomChange",r)}setPageZoom(t){x(this.sdk.pageData,"You must call SDK#run() first");const e=M(z(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){x(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 H).copyFrom(i.transform.getParentMatrix()??new H);s.setPosition(new G);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 H,parentMatrix:new H},i=this.getPlayerItemById(t);if(void 0!==i?.transform){i.transform.updateLocalMatrix();const t=H.fromArray(i.composition?.transform.getWorldMatrix().elements??[]).invert();e.matrix=t.clone().multiply(H.fromArray(i.transform.getWorldMatrix().elements)),e.parentMatrix=t.clone().multiply(H.fromArray(i.transform.parentTransform?.getWorldMatrix().elements??(new H).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)Te.config.pageConfig.filterItemNames.includes(i.name)||(s([i]),this.addViewItemsByItems(t,i.children,i.getInstanceId()))}createViewItemByPlayerItem(t,e){x(this.sdk.pageData,"You must call SDK#run() first");const{transform:i,composition:s,isVisible:r}=t;i.updateLocalMatrix();const a=(new H).copyFrom(s?.transform.getWorldMatrix()??(new H).identity()).invert().multiply(i.getWorldMatrix()),o=new G,n=new W,c=new G;a.decompose(o,n,c);const h=(new N).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=>M(t,2)),l=h.toArray().map(t=>M(t,2)),m=c.toArray().map(t=>M(t,2)),g=i.size.toArray(),f={position:p,rotation:l,size:this.getPixelSizeByWorldSize([m[0]*g[0],m[1]*g[1],m[2]],t).map(t=>M(t,2)),visible:r,keyPropertyEditing:!1};switch(t.type){case d.ItemType.sprite:{const e=this.getActiveScene()?.scene;if(e){e.components.filter(e=>e.item.id===t.getInstanceId()).forEach(t=>{if(f.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);f.keyPropertyEditing=!!t?.template;const s=t?.url??"";s&&Object.assign(f,{image:s})}})}break}case d.ItemType.text:case d.ItemType.richtext:{const e=this.getActiveScene()?.scene;if(f.keyPropertyEditing=!0,e){e.components.filter(e=>e.item.id===t.getInstanceId()).forEach(t=>{if(![d.DataType.TextComponent,d.DataType.RichTextComponent].includes(t.dataType))return;const{textAlign:e,textColor:i,text:s,fontWeight:r,fontFamily:a}=t.options;Object.assign(f,{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:f}}getViewBoxById(t){const e=new U,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 G).copyFrom(e.transform.anchor).applyMatrix((new H).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 U;switch(t.type){case d.ItemType.sprite:case d.ItemType.plugin:case d.ItemType.video:case d.ItemType.richtext:case d.ItemType.text:case d.ItemType.shape:{const{transform:s,composition:r}=t;s.updateLocalMatrix();const{size:a}=s,o=(new H).copyFrom(r?.transform.getWorldMatrix()??new H).invert().multiply(s.getWorldMatrix()),{x:n,y:c}=a.clone().divide(2),h=new G(n,c,0).applyMatrix(o),p=new G(n,-c,0).applyMatrix(o),l=new G(-n,-c,0).applyMatrix(o),m=new G(-n,c,0).applyMatrix(o),d=this.interactionUtils.projectPoint(h).round(2),g=this.interactionUtils.projectPoint(p).round(2),f=this.interactionUtils.projectPoint(l).round(2),u=this.interactionUtils.projectPoint(m).round(2);i.setFromVec2Array([d,g,f,u]);const y=e?.map(t=>this.getViewBoxById(t.getInstanceId()));y&&y.map(t=>i.union(t));break}case d.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 B;const{zoom:t,translation:e}=this.sdk.pageData.property,{offsetWidth:i,offsetHeight:s}=this.container.parentElement,{offsetWidth:r,offsetHeight:a}=this.container,o=new B(i,s),n=new B(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 B(t/2,e/2).add(new B(...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 B(i,s).multiply(e),a=this.getViewportLeftTopPosition(),o=t.clone().subtract(a);return new B(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){x(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":[d.TextAlignment.left,d.TextAlignment.middle,d.TextAlignment.right].includes(t.propertyValue)&&i.getComponent(P).setTextAlign(t.propertyValue);break;case"color":Array.isArray(t.propertyValue)&&4===t.propertyValue.length&&(console.log(t.propertyValue),i.getComponent(P).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(P).setFontFamily(s)}break;case"text":"string"==typeof t.propertyValue&&i.getComponent(P).setText(t.propertyValue);break;case"weight":[d.TextWeight.normal,d.TextWeight.bold,d.TextWeight.lighter].includes(t.propertyValue)&&i.getComponent(P).setFontWeight(t.propertyValue);break;case"image":"string"==typeof t.propertyValue&&i.getComponent(v).setTexture(await I.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 G(...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 G(...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 G(...r,1))}break;case"visible":if("boolean"==typeof t.propertyValue&&(i.setVisible(t.propertyValue),Te.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){x(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([d.TextAlignment.left,d.TextAlignment.middle,d.TextAlignment.right].includes(e.propertyValue)){const i=t.components.find(t=>t.item.id===e.itemId&&[d.DataType.TextComponent,d.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&&[d.DataType.TextComponent,d.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&&[d.DataType.TextComponent,d.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&&[d.DataType.TextComponent,d.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&&[d.DataType.TextComponent,d.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,Te.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){x(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;x(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){x(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}};import Gt from"jszip";import Ht from"jszip";var Nt,Lt,Kt,Ot,jt,$t,Yt,Jt,Xt,qt,Zt,Qt,te,ee,ie,se,re,ae,oe="ready",ne="executable",ce="dispose",he={APNG:"APNG",MP4:"MP4",WebM:"WebM",Images:"Images",WebP:"WebP",GIF:"GIF",AlphaMaskVideo:"AlphaMaskVideo"},pe="idle",le="convertImage",me="transcoding",de="audio",ge="jpeg",fe="webp",ue="png",ye=(he.MP4,he.WebP,he.APNG,he.GIF,he.AlphaMaskVideo,he.Images,he.MP4,he.WebP,he.APNG,he.GIF,he.AlphaMaskVideo,he.Images,"default"),we="exporting",xe="success",ve="error",Pe=class{constructor(t){c(this,"sampleRate"),c(this,"duration"),c(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)}},Ie=["@vvfx/sdk","exporter"],De=class extends w{constructor(t){super(),c(this,"status",oe),c(this,"stage",pe),c(this,"mediaType"),c(this,"loggerInTranscoding"),c(this,"multiThreading"),c(this,"extraCanvas"),c(this,"player"),l(this,Nt,0),l(this,Lt),l(this,Kt),l(this,Ot),l(this,jt),l(this,$t,[]),l(this,Yt),l(this,Jt),l(this,Xt,[]),l(this,qt,0),l(this,Zt),l(this,Qt,[]),l(this,te,0),l(this,ee,0),l(this,ie,0),l(this,se,0),l(this,re,[]),l(this,ae,!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===ce}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=p(this,Zt)?.time;return{name:i,startTime:r,oldTotalTime:s,newTotalTime:a,fps:p(this,Zt)?.fps??30,backgroundColor:p(this,Zt)?.backgroundColor??"#000000",loop:p(this,Zt)?.loop??!0,audioEnable:p(this,Zt)?.audioEnable??!1}}get progress(){const t=p(this,ee)||1,e=p(this,ie)||1,i=Math.min(t/e,1),s=Math.min(p(this,te),t)/t*.4,r=Math.min(p(this,se),t)/t*.6,a=Math.min(s+r,1);p(this,Qt)[p(this,qt)]=i;const o=p(this,Qt).reduce((t,e,i)=>i<p(this,qt)?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===he.MP4?ge:this.mediaType===he.WebP?fe:ue}async onInit(){try{Et("log",[...Ie,"ready"],"starting"),this.status=oe,await this.loadHelper(this.mediaType),this.status=ne,Et("log",[...Ie,"ready"],"success"),this.emit("ready",this.mediaType)}catch(t){this.status=ce,this.onError(t)}finally{return this.status}}onReset(){this.stage=pe,window.cancelAnimationFrame(p(this,Nt)),m(this,Nt,0),this.player?.pause(),this.clearTaskInfo(),this.setProgress()}onError(t){Et("log",[...Ie,"error"],t),this.onFinish(!1),this.emit("error",t),this.dispose()}onFinish(t,e){Et("log",[...Ie,"finish"],t?"success":"failed"),this.emit("progress",1),this.emit("done",t),this.emit("finish",t,e)}async loadHelper(t){const e="WebP"===t&&!p(this,Ot),i=[he.MP4,he.APNG,he.GIF,he.AlphaMaskVideo].includes(t)&&!p(this,Kt);e&&m(this,Ot,await Ut()),i&&(m(this,Kt,await async function(t){const{multiThreading:e}=t??{},i=new zt,s=!!e,r={classWorkerURL:await Tt(Bt.CLASSWORKER,"text/javascript"),coreURL:"",wasmURL:""};return s?(r.coreURL=await Tt(Bt.MT.CORE,"text/javascript"),r.wasmURL=await Tt(Bt.MT.WASM,"application/wasm"),r.workerURL=await Tt(Bt.MT.WORKER,"text/javascript")):(r.coreURL=await Tt(Bt.DEFAULT.CORE,"text/javascript"),r.wasmURL=await Tt(Bt.DEFAULT.WASM,"application/wasm")),await i.load(r),i}({multiThreading:this.multiThreading})),p(this,Kt).on("log",({message:t})=>{if(this.loggerInTranscoding&&Et("log",[...Ie,"transcoding log"],t),this.canceled||this.stage!==me)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&&m(this,Qt,t.completedTaskPercentArray),void 0!==t?.currentTaskFrameIndex&&m(this,te,t.currentTaskFrameIndex),void 0!==t?.currentTaskTotalFrames&&m(this,ee,t.currentTaskTotalFrames),void 0!==t?.currentTaskInTranscodingFrameIndex&&m(this,se,t.currentTaskInTranscodingFrameIndex),void 0!==t?.allTaskFrames&&m(this,ie,t.allTaskFrames),this.emit("progress",this.progress)}forwardPlayerTime(t,e=!1){x(this.player);const{oldTotalTime:i,startTime:s}=this.config;x(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){m(this,Yt,new Pe),p(this,Kt)?p(this,Kt).writeFile(t,p(this,Yt).getBuffer()):Et("log",[...Ie,"getWavAudio"],"ffmpegCore is not ready")}async getImagesZip(t,e){const i=new Ht,s=i.folder(t);return x(s),p(this,Xt).forEach((t,i)=>{s.file(t,e[i])}),i.generateAsync({type:"arraybuffer"})}getWebP(){x(p(this,Ot));const t=Math.round(1e3/this.config.fps/1),e="out.webp",i=`${p(this,Xt).join(` -d ${t} `)} -d ${t} -o ${e} -loop ${this.config.loop?0:1}`.split(" "),s=p(this,Ot).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]}(p(this,Ot),i);_t(r&&a,"getWebP has error"),s(r,a);const o=p(this,Ot).FS.readFile(e);return p(this,Xt).forEach(t=>{p(this,Ot)?.FS.unlink(t)}),o}async getAPNG(){x(p(this,Kt));this.stage=me;const t="export.apng";return await p(this,Kt).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-plays",this.config.loop?"0":"1","-y",t]),t}async getGIF(){x(p(this,Kt));this.stage=me;const t="export.gif";return await p(this,Kt).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]),t}async getMP4(t,e){x(p(this,Kt));this.stage=me;const i="export.mp4";let s;const r=e?",setpts=PTS/"+Math.round(t/e*100)/100:"",a=e??t;return this.config.audioEnable&&!p(this,Yt)&&(m(this,Jt,"audio.wav"),this.getWavAudio(p(this,Jt))),await p(this,Kt).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]),p(this,Jt)&&p(this,Yt)&&(this.stage=de,s="export-with-audio.mp4",await p(this,Kt).exec(["-i",i,"-i",p(this,Jt),"-c:v","copy","-c:a","aac","-t",`${a}`,"-y",s])),s&&p(this,Kt).deleteFile(i).catch(()=>{Et("log",[...Ie,"ffmpeg delete file error"])}),s??i}async getAlphaMaskVideo(t,e){x(p(this,Kt));this.stage=me;const i="export.mp4",s=e?",setpts=PTS/"+Math.round(t/e*100)/100:"";return await p(this,Kt).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){x(p(this,Kt));const i=this.mediaType===he.APNG,s=this.mediaType===he.GIF,r=this.mediaType===he.AlphaMaskVideo,a=this.mediaType===he.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=pe}catch(t){throw t}finally{for(const t of p(this,Xt))t&&p(this,Kt).deleteFile(t)}let n=null;try{x(o);const t=await p(this,Kt).readFile(o);n="string"==typeof t?(new TextEncoder).encode(t):new Uint8Array(t)}finally{p(this,Kt).deleteFile(o).catch(()=>{Et("log",[...Ie,"ffmpeg delete file error"])})}return n}onRecordWebM(t){const e=new MediaRecorder(t.captureStream(this.config.fps),{mimeType:"video/webm;codecs=vp9"});m(this,jt,e),p(this,jt).start(0);const i=[];p(this,jt).ondataavailable=t=>{t.data.size>0&&i.push(t.data)},m(this,$t,i)}async onExportImageFrame(t){try{if(this.canceled)return;const{canvas:s,imageBuffers:r,startTime:a,oldTotalTime:o,newTotalTime:n}=t;x(this.player),x(p(this,Lt));const c=p(this,te)+1;this.stage=le,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:c}),this.loggerInTranscoding&&Et("log",[...Ie,"converting log"],`converting ${c} frame image`),c>=1&&this.forwardPlayerTime(c/this.config.fps+a),Ft(p(this,Lt),s,this.config.backgroundColor);let h=s;this.mediaType===he.AlphaMaskVideo&&(x(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 l=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),d=`image-${e=c,i=4,String(e).padStart(i,"0")}.${this.transImageType}`;this.mediaType===he.Images?r.push(l):this.mediaType===he.WebP?(x(p(this,Ot)),p(this,Ot).FS.writeFile(d,new Uint8Array(l))):(x(p(this,Kt)),await p(this,Kt).writeFile(d,new Uint8Array(l))),p(this,Xt).push(d);if(c===p(this,ee)){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():[he.MP4,he.APNG,he.GIF,he.AlphaMaskVideo].includes(this.mediaType)&&(t=await this.getVideoByType(o,n)??null),t&&(Et("log",[...Ie,"done"],"success"),this.emit("done",!0,t))}else m(this,Nt,window.requestAnimationFrame(()=>{this.canceled||this.onExportImageFrame({canvas:s,imageBuffers:r,startTime:a,oldTotalTime:o,newTotalTime:n})}))}catch(t){this.onError(t)}var e,i}async onExportWebMFrame(t){try{if(this.canceled)return;x(this.player),x(p(this,Lt));const e=p(this,te)+1;if(this.stage=le,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:e}),this.loggerInTranscoding&&Et("log",[...Ie,"converting log"],`converting ${e} frame image`),Ft(p(this,Lt),t,this.config.backgroundColor),1===e&&(this.player.play(),this.onRecordWebM(t)),e<p(this,ee))m(this,Nt,window.requestAnimationFrame(()=>{this.canceled||this.onExportWebMFrame(t)}));else{this.player?.pause(),p(this,jt)?.stop();const t=new Blob(p(this,$t),{type:"video/webm"}),e=await t.arrayBuffer();Et("log",[...Ie,"done"],"success"),this.emit("done",!0,e)}}catch(t){Et("log",[...Ie,"done"],"failed",t),this.emit("done",!1)}}async runTask(t){try{if(this.canceled)return;x(this.player),x(p(this,Lt));const{size:e,startTime:i,containerCanvas:s}=t,{oldTotalTime:r,newTotalTime:a}=this.config,[o,n]=e;if(p(this,Lt).width=o,p(this,Lt).height=n,s.width=o,s.height=n,this.player.resize(),m(this,Xt,[]),[he.MP4,he.APNG,he.Images,he.WebP,he.GIF,he.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){Et("log",[...Ie,"run task error"],t),this.emit("done",!1)}}clearTaskInfo(){m(this,qt,0),m(this,Zt,void 0),m(this,Qt,[]),m(this,te,0),m(this,ee,0),m(this,ie,0),m(this,se,0),m(this,re,[]),m(this,ae,!0)}clearFFMpegCore(){if(p(this,Kt)){for(const t of p(this,Xt))t&&p(this,Kt).deleteFile(t);m(this,Xt,[]),p(this,Kt).terminate(),m(this,Kt,void 0)}}clearImage2WebPCore(){p(this,Ot)&&(p(this,Ot).FS.quit(),m(this,Ot,void 0))}clearMediaRecorder(){p(this,jt)&&(p(this,jt).stop(),m(this,jt,void 0)),m(this,$t,[])}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),this.status=ce,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),Et("log",Ie,"canceled"))}async onExport(t){const e=t.length;try{if(this.status===oe)return Et("log",[...Ie],"readying"),void this.on("ready",()=>{this.onExport(t)});if(this.status===ce){if(await this.onInit()===ce)throw new Error("init environment failed")}if(this.clearTaskInfo(),!p(this,Lt)){const t=document.createElement("canvas");t.dataset.key="player-canvas",m(this,Lt,t)}this.player||(this.player=new f({canvas:p(this,Lt),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}m(this,qt,r),m(this,Zt,a);const{size:t,scene:o}=a;await new Promise(async n=>{try{if(!this.player)throw new Error("player not found");Et("log",[...Ie,"export"],"start",a),Rt(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)=>{this.off("done",p),t&&e?i[r]=e:s=!1,n()};this.on("done",p);const l={size:t,startTime:h,containerCanvas:e};await this.runTask(l)}catch(t){Et("log",[...Ie,"export error"],t),s=!1,n()}})}m(this,re,i),m(this,ae,s)}catch(t){this.onError(t),m(this,ae,!1)}e>=1&&p(this,ae)?this.onFinish(!0,p(this,re)):this.onFinish(!1)}dispose(){this.status=ce,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),this.player?.dispose(),this.player=void 0,p(this,Lt)?.remove(),m(this,Lt,void 0),m(this,Jt,void 0),m(this,Yt,void 0)}};Nt=new WeakMap,Lt=new WeakMap,Kt=new WeakMap,Ot=new WeakMap,jt=new WeakMap,$t=new WeakMap,Yt=new WeakMap,Jt=new WeakMap,Xt=new WeakMap,qt=new WeakMap,Zt=new WeakMap,Qt=new WeakMap,te=new WeakMap,ee=new WeakMap,ie=new WeakMap,se=new WeakMap,re=new WeakMap,ae=new WeakMap;var be=class extends w{constructor(t){super(),c(this,"_config"),c(this,"_status",ye),c(this,"_exportMedia"),this._config=t,this._exportMedia=new De(t)}get status(){return this._status}onExportProgress(t){this.emit("progress",t)}onExportMP4(t,e){const i=t[0]?.folderName,s=new Gt;e.forEach((e,i)=>{const{name:r}=t[i]??{};r&&s.file(`${r}.mp4`,e)}),s.generateAsync({type:"blob"}).then(t=>{Mt(t,`${i}.zip`,"application/zip")}).catch(t=>{Et("error",["@vvfx/sdk"],"export mp4 is error",t)})}onExportGIF(t,e){const i=t[0]?.folderName,s=new Gt;e.forEach((e,i)=>{const{name:r}=t[i]??{};r&&s.file(`${r}.gif`,e)}),s.generateAsync({type:"blob"}).then(t=>{Mt(t,`${i}.zip`,"application/zip")}).catch(t=>{Et("error",["@vvfx/sdk"],"export gif is error",t)})}onExportImages(t,e){const i=t[0]?.folderName,s=new Gt;e.forEach((e,i)=>{const{name:r}=t[i]??{};r&&s.file(`${r}.zip`,e)}),s.generateAsync({type:"blob"}).then(t=>{Mt(t,`${i}.zip`,"application/zip")}).catch(t=>{Et("error",["@vvfx/sdk"],"export Images is error",t)})}onExportError(t){this._status=ve,Et("error",["@vvfx/sdk"],"export is error",t)}onExport(t){this._status=we,this._exportMedia.onExport(t),this._exportMedia.on("progress",this.onExportProgress.bind(this)),this._exportMedia.once("finish",(e,i)=>{this._status=e?xe:ve,this.emit("complete",e),i&&0!==i.length&&(this._config.mediaType===he.MP4?this.onExportMP4(t,i):this._config.mediaType===he.GIF?this.onExportGIF(t,i):this._config.mediaType===he.Images&&this.onExportImages(t,i))}),this._exportMedia.on("error",this.onExportError.bind(this))}onCancel(){this._status=ve,this._exportMedia.onCancel(),this.emit("complete",!1)}dispose(){this._exportMedia.dispose()}},Ce=class{constructor(){c(this,"enabled",!0),c(this,"_player"),c(this,"_container"),this._container=document.createElement("canvas"),this._player=new f({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 Rt(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?z(o,0,1):.5,n="number"==typeof n?z(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 f=Math.max(h/(m/r),0),u=Math.max(p/(d/a),0),y=Math.min((h-f)*o,h),w=Math.min((p-u)*n,p);t.drawImage(e,y+c.left,w+c.top,f,u,i,s,r,a)}},Ae={topAdsorption:"T",leftAdsorption:"L",rightAdsorption:"R",bottomAdsorption:"B",centerAdsorption:"C",bottomCenterAdsorption:"BC"},Se=class{constructor(t){c(this,"_player"),c(this,"_container"),c(this,"size",[0,0]),c(this,"_pageDataUtils"),this._container=document.createElement("canvas"),this._player=new f({canvas:this._container,manualRender:!0}),this._pageDataUtils=t}async adjustment(t,e,i,s,r){if(!Te.config.sizeAdaptConfig.enabled)return console.warn("Size adapt is not opened, use #SDK.setConfig() open this feature."),t;this._player??(this._player=new f({canvas:this._container,manualRender:!0})),this.size=[...s],this._container.width=this.size[0],this._container.height=this.size[1],Rt(this._player),this._player.resize();const a=JSON.parse(JSON.stringify(t));await this._player.loadScene(a,{reusable:!0,autoplay:!1}),this._player.gotoAndStop(e);const o=this._player.getCompositions()[0];if(o){const[e,a]=s,n=i[0]/i[1],c=e/a;n>c&&this.keepDistribute(t,o,c/n,s);const[h,p,l,m]=r,d=e-l-m,g=a-h-p,f=[(l-m)/2,(h-p)/2],u=(new U).setFromCenterAndSize(new B(e,a).divide(2),new B(e,a)),y=(new U).setFromCenterAndSize(new B(e,a).divide(2).add(new B(...f)),new B(d,g));this.keepAdsorption("topAdsorption",t,o,f,u,y),this.keepAdsorption("bottomAdsorption",t,o,f,u,y),this.keepAdsorption("leftAdsorption",t,o,f,u,y),this.keepAdsorption("rightAdsorption",t,o,f,u,y),this.keepAdsorption("centerAdsorption",t,o,f,u,y),this.keepDoubleAdsorption("bottomCenterAdsorption",t,o,f,u,y)}return t}keepDistribute(t,e,i,s){const r=t=>{const i=(new H).copyFrom(e.camera.getViewProjectionMatrix());return(new B).copyFrom(t.applyMatrix(i).toVector2()).toViewCoordinate(s[0],s[1])};["topAdsorption","centerAdsorption","bottomAdsorption"].forEach(a=>{e.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===Ae[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 B(...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){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 H).copyFrom(i.camera.getViewProjectionMatrix());return(new B).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(o,n)},p=Ae[t];i.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===p&&!t.parentId).forEach(r=>{const o=i.items.filter(t=>t.parentId===r.getInstanceId()),n=o.find(t=>"check-area"===t.name),p=r.transform.position.clone(),l=["leftAdsorption","rightAdsorption"].includes(t)?"x":"y",m=["leftAdsorption","topAdsorption"].includes(t)?1:-1,d=["leftAdsorption","topAdsorption"].includes(t)?"min":"max",g=["leftAdsorption","topAdsorption"].includes(t)?"max":"min",f=3===r.name.split("-").length,u=Number(r.name.split("-")[1]),y=new B,w=[1,1],x=n?this.getViewBoxByHeadlessPlayerItem(n,[],h):this.getViewBoxByHeadlessPlayerItem(r,o,h);c(r,...s),x.getSize().x>a.getSize().x&&(w[0]=a.getSize().x/x.getSize().x,w[1]=a.getSize().x/x.getSize().x,r.scale(...w,1)),r.transform.updateLocalMatrix();const v=n?this.getViewBoxByHeadlessPlayerItem(n,[],h):this.getViewBoxByHeadlessPlayerItem(r,o,h),P=new B;if(!a.containsBox(v)){const{min:t,max:e}=v,{min:i,max:s}=a;P.x+=t.x<i.x?i.x-t.x:0,P.x+=e.x>s.x?s.x-e.x:0,P.y+=t.y<i.y?i.y-t.y:0,P.y+=e.y>s.y?s.y-e.y:0,c(r,...P.toArray()),r.transform.updateLocalMatrix()}const I=n?this.getViewBoxByHeadlessPlayerItem(n,[],h):this.getViewBoxByHeadlessPlayerItem(r,o,h);if(!Number.isNaN(u)&&f)if("centerAdsorption"!==t){const t=Math.abs(I[g][l]-a[d][l]),e=a.getSize()[l]*u;t>e&&(y[l]=(e-t)*m,c(r,...y.toArray()),r.transform.updateLocalMatrix())}else{const t=I.getSize().y,e=a.getSize().y;if(t/e>u){const i=e*u/t;r.scale(i,i,1),w[0]*=i,w[1]*=i}}const D=n?this.getViewBoxByHeadlessPlayerItem(n,[],h):this.getViewBoxByHeadlessPlayerItem(r,o,h),b=i.items.filter(t=>"T"===t.name.split("-")[0]?.toLocaleUpperCase()&&!t.parentId),C=new U;if(b.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,[],h):this.getViewBoxByHeadlessPlayerItem(t,e,h);C.union(r)}),!C.isEmpty()&&C.max.y>D.min.y)if("centerAdsorption"===t){const t=C.max.y-D.min.y;c(r,0,t),r.transform.updateLocalMatrix()}else if(["leftAdsorption","rightAdsorption"].includes(t)){const t=D.getSize().y,e=a.getSize().y-(C.max.y-a.min.y);let i=C.max.y-D.min.y;if(t>e){const s=e/t;w[0]*=s,w[1]*=s,r.scale(s,s,1),r.transform.updateLocalMatrix(),i-=(t-e)/2}c(r,0,i),r.transform.updateLocalMatrix()}const A=r.transform.position.clone().subtract(p).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:w})})}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 H).copyFrom(i.camera.getViewProjectionMatrix());return(new B).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(o,n)},p=Ae[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 f=o?this.getViewBoxByHeadlessPlayerItem(o,[],h):this.getViewBoxByHeadlessPlayerItem(t,r,h),u=new B;if(!a.containsBox(f)){const{min:e,max:i}=f,{min:s,max:r}=a;u.x+=e.x<s.x?s.x-e.x:0,u.x+=i.x>r.x?r.x-i.x:0,u.y+=e.y<s.y?s.y-e.y:0,u.y+=i.y>r.y?r.y-i.y:0,c(t,...u.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 U,{transform:r,composition:a}=t;switch(t.type){case d.ItemType.sprite:case d.ItemType.plugin:case d.ItemType.video:case d.ItemType.richtext:case d.ItemType.text:case d.ItemType.shape:{r.setValid(!0),r.updateLocalMatrix();const{size:t}=r,o=(new H).copyFrom(a?.transform.getWorldMatrix()??new H).invert().multiply(r.getWorldMatrix()),{x:n,y:c}=t.clone().divide(2),h=new G(n,c,0).applyMatrix(o),p=new G(n,-c,0).applyMatrix(o),l=new G(-n,-c,0).applyMatrix(o),m=new G(-n,c,0).applyMatrix(o),d=i(h).round(2),g=i(p).round(2),f=i(l).round(2),u=i(m).round(2);s.setFromVec2Array([d,g,f,u]);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 d.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()}},ze=class t{constructor(e){c(this,"_eventEmitter",new w),c(this,"_pageData"),c(this,"_screenShot"),c(this,"_exporter"),c(this,"_pageDataUtils"),c(this,"_sizeAdapt"),c(this,"_gestureHandler"),c(this,"disposables",[]),c(this,"_isSwitchScene",!1),c(this,"player"),c(this,"_playerContainer"),c(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 f({container:r,interactive:!0,pixelRatio:window.devicePixelRatio||1}),this.player.on("update",()=>{if(x(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=>{x(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=>{x(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems=[...t],this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("preSelectedItemChange",t=>{x(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t,this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("selectedViewChange",t=>{x(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&&!Vt(t.exportVideoConfig,e.exportVideoConfig)&&(this._exporter.dispose(),this.initExporter(e.exportVideoConfig))}),this._pageDataUtils=new Wt(this.player,r,this._eventEmitter,this),this.initExporter(t.config.exportVideoConfig),this._gestureHandler=new bt(e),this._gestureHandler.registerViewEvent(),this._screenShot=new Ce,this._sizeAdapt=new Se(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 be(t),this._exporter.on("progress",t=>{this._eventEmitter.emit("exportProgress",t)}),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];x(c);const h=c.previewSize??a.size,[p,l]=a.size;c.previewSize=[p,l];const m=c.duration??0,d=a.safeArea??[0,0,0,0];t.config.sizeAdaptConfig.enabled&&(n=await this._sizeAdapt.adjustment(n,m,h,[p,l],d)),(i=a.export).time??(i.time=m),o.push({...a,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 x(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems}setPreSelectedItem(t){x(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t}getPreSelectedItem(){return x(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){x(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){x(this._pageData,"You must call SDK#run() first");const e=this.getItemProperty(t)?.property?.[t.propertyName];return e}async setItemPropertyValue(t){x(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){x(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(x(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 x(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){x(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){x(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&&(Rt(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){x(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 x(this._pageData,"You must call SDK#run() first"),this._pageData.viewProperties.map(t=>({id:t.id,thumbnail:this.generateScreenShot(t.id)}))}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&&(x(this.pageData,"You must call SDK#run() first"),x(this._exporter,"You must init exporter first"),this._exporter.onExport(this.exportOptions))}cancelExport(){x(this._exporter,"You must init exporter first"),this._exporter.onCancel()}async loadPageData(t){x(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){x(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;x(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];x(c);const h=c.previewSize??o.size,[p,l]=o.size;c.previewSize=[p,l];const m=c.duration??0,d=o.safeArea??[0,0,0,0];t.config.sizeAdaptConfig.enabled&&(n=await this._sizeAdapt.adjustment(n,m,h,[p,l],d)),(i=o.export).time??(i.time=m),s.push({...o,safeArea:d,previewSafeAreas:[...o.previewSafeAreas??[]],id:r+1+a,scene:n,ignoreInteraction:!1})}this._pageData.viewProperties.push(...s),this._eventEmitter.emit("pageDataChange",this.getPageData())}deleteViewParams(t){t.sort((t,e)=>t-e),t.forEach(async(t,e)=>{x(this._pageData);const i=t-e,s=this._pageData.viewProperties.findIndex(t=>t.id===i);if(!1!==this._pageData.viewProperties[s]?.ignoreInteraction)return void console.warn("target view ignore interaction, it can not be deleted.");this._pageData.viewProperties.splice(s,1);const r=this._pageData.activeData.view??0;i===r?await this._pageDataUtils.loadScene(r):i<r&&(this._pageData.activeData.view=r-1,await this._pageDataUtils.loadScene(this._pageData.activeData.view)),this._pageData.viewProperties.forEach(t=>{t.id>i&&(t.id-=1)})}),this._eventEmitter.emit("pageDataChange",this.getPageData())}setExportParam(t,e){x(this._pageData),this._pageData.viewProperties.forEach(i=>{void 0!==e&&i.id!==e||(i.export=t)})}setPageZoom(t){x(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}};c(ze,"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 Te=ze;export{Te as SDK,d as spec};
|