@spiffcommerce/preview 2.1.26 → 2.1.28
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/main.js +1 -1
- package/dist/module.js +1 -1
- package/dist/types.d.ts +12 -1
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=require("@babylonjs/core/Actions/actionManager"),t=require("@babylonjs/core/Actions/directActions"),i=require("@babylonjs/core/Engines/engine"),a=require("@babylonjs/core/Engines/nullEngine"),r=require("@babylonjs/core/Layers/glowLayer"),n=require("@babylonjs/core/Layers/highlightLayer"),s=require("@babylonjs/core/Loading/sceneLoader"),o=require("@babylonjs/core/Materials/PBR/pbrMaterial"),c=require("@babylonjs/core/Materials/Textures/cubeTexture"),l=require("@babylonjs/core/Materials/Textures/dynamicTexture"),h=require("@babylonjs/core/Maths/math.color"),u=require("@babylonjs/core/Maths/math.vector"),d=require("@babylonjs/core/Meshes/Compression/dracoCompression"),m=require("@babylonjs/core/Misc/observable"),g=require("@babylonjs/core/Misc/tools"),p=require("@babylonjs/core/scene"),b=require("@babylonjs/loaders/glTF");require("@babylonjs/core/Engines/Extensions/engine.views"),require("@babylonjs/core/Meshes/instancedMesh"),require("@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader"),require("@babylonjs/core/Materials/Textures/Loaders/envTextureLoader"),require("@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader"),require("@babylonjs/core/Animations/animatable"),require("@babylonjs/core/Misc/screenshotTools"),require("@babylonjs/core/Rendering/boundingBoxRenderer"),require("@babylonjs/loaders/glTF/2.0/Extensions");var f=require("@babylonjs/core/Materials/Textures/texture"),v=require("@babylonjs/core/Materials/Textures/mirrorTexture"),y=require("@babylonjs/core/Maths/math"),x=require("@babylonjs/core/Probes/reflectionProbe"),w=require("@babylonjs/core/Animations/animation"),M=require("@babylonjs/core/Animations/easing"),T=require("@babylonjs/core/Cameras/arcRotateCamera"),C=require("@babylonjs/core/Misc/assetsManager");function A(e,t){return Object.keys(t).forEach((function(i){"default"===i||"__esModule"===i||e.hasOwnProperty(i)||Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[i]}})})),e}function L(e,t,i,a){Object.defineProperty(e,t,{get:i,set:a,enumerable:!0,configurable:!0})}var R={};let O;var P;let E;var S;L(R,"ProductCameraRig",(()=>O)),L(R,"MaterialEffectMode",(()=>E)),(P=O||(O={}))[P.Orbit=0]="Orbit",P[P.Pan=1]="Pan",(S=E||(E={})).None="None",S.RemoveWhenSelected="RemoveWhenSelected",S.ApplyWhenSelected="ApplyWhenSelected";var I={};L(I,"SpiffCommerce3DPreviewService",(()=>ae)),L(I,"createBaseModel",(()=>re));const B=new Map;async function F(e,t,i){return new Promise(((a,r)=>{const n=B.get(e);if(n&&n.scene.uid===t.uid)return a(n);s.SceneLoader.LoadAssetContainerAsync(e,void 0,t,i).then((t=>{B.set(e,t),a(t)})).catch(r)}))}function q(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class j{constructor(e){q(this,"customOptions",void 0),q(this,"getSceneClearColor",(()=>{const e=this.customOptions?.backgroundImage?0:1;if(this.customOptions&&this.customOptions.backgroundImage)return new(0,h.Color4)(0,0,0,e).toLinearSpace();if(this.customOptions&&this.customOptions.backgroundColor){const t=h.Color3.FromHexString(this.customOptions.backgroundColor);return new(0,h.Color4)(t.r,t.g,t.b,e).toLinearSpace()}return new(0,h.Color4)(.98,.98,.98,e).toLinearSpace()})),q(this,"highlightColorFromConfig",(()=>this.customOptions&&this.customOptions.highlightColor?this.hexToColor4(this.customOptions.highlightColor):new(0,h.Color4)(.98,.98,.98,1).toLinearSpace())),q(this,"hexToColor4",((e,t=1)=>{const i=h.Color3.FromHexString(e);return new(0,h.Color4)(i.r,i.g,i.b,t).toLinearSpace()})),this.customOptions=e}get options(){return this.customOptions}get scene(){return{clearColor:this.getSceneClearColor(),transparentBackground:this.customOptions?.backgroundImage,environmentFile:this.customOptions?.environmentFile??"assets/model-viewer/default.env"}}get camera(){return{autoOrientation:this.customOptions?.disableAutomaticOrientation??!0,autoRotation:{enabled:this.customOptions?.autoRotation??!1,idleTimeMs:this.customOptions?.idleTimeBeforeRotation??5e3},limits:{min:{alpha:this.customOptions?.lowerAlphaLimitDeg?this.customOptions?.lowerAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.lowerBetaLimitDeg?this.customOptions?.lowerBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.minZoomOverride},max:{alpha:this.customOptions?.upperAlphaLimitDeg?this.customOptions?.upperAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.upperBetaLimitDeg?this.customOptions?.upperBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.maxZoomOverride}}}}get highlights(){return{enabled:this.customOptions?.highlightOnMaterialHover??!1,color:this.highlightColorFromConfig()}}get lighting(){return{exposure:this.customOptions?.lighting?.exposure??.9,contrast:this.customOptions?.lighting?.contrast??1.6}}}var k={};L(k,"RenderingConfiguration",(()=>N)),L(k,"REFLECTION_PROBE_RESOLUTION",(()=>D));class N{static getDynamicTextureResolution(){return this.getIsMobile()||!N.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}static shouldMipMap(){return!0}static offscreenRenderingSupported(){return!navigator.userAgent.includes("SamsungBrowser")&&(!!window.Worker&&!!window.OffscreenCanvas)}static getMirrorTextureResolution(){return this.getIsMobile()?512:1024}static getIsMobile(){return window.innerWidth<=480}}const D=128;function V(e,t,a){t.forEach((t=>{const r=t.getID(),n=t.getName(),s=N.getDynamicTextureResolution();e.materials.filter((e=>e.name===n)).forEach((o=>{const c=a.get(r);if(c)_(o,c),c.update(false);else{const c=function(e,t,a,r){const n=new(0,l.DynamicTexture)(e,{width:a,height:r},t,N.shouldMipMap(),f.Texture.TRILINEAR_SAMPLINGMODE,i.Engine.TEXTUREFORMAT_RGBA),s=n.getContext();s&&(s.fillStyle="#f5f5f5",s.fillRect(0,0,a,r),n.update());return n}(n,e,s.width,s.height);a.set(r,c),t.setStaticContext(c.getContext()),_(o,c),c.onLoadObservable.addOnce((()=>{c.update(false)}))}}))}))}function _(e,t){if(e instanceof o.PBRMaterial){const i=e,a=i.albedoTexture;a?(t.wrapU=a.wrapU,t.wrapV=a.wrapV):(t.wrapU=1,t.wrapV=1),i.albedoTexture=t}else{const i=e,a=i.diffuseTexture;a&&(t.wrapU=a.wrapU,t.wrapV=a.wrapV),i.diffuseTexture=t}}function z(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class U{constructor(e){z(this,"name",void 0),z(this,"enabled",void 0),z(this,"loader",void 0),this.name="glbPostProcessor",this.enabled=!0,this.loader=e}onReady(){this.applyReflections(this.loader.babylonScene)}loadNodeAsync(e,t,i){return this.loader.loadNodeAsync(e,t,(function(e){t.extras&&Object.keys(t.extras).forEach((i=>{const a=t.extras[i];e.metadata[i]=a})),i(e)}))}loadMaterialPropertiesAsync(e,t,i){return this.enableMaterialExtrasIfRequired(t,i),this.loader.loadMaterialPropertiesAsync(e,t,i)}dispose(){}enableMaterialExtrasIfRequired(e,t){if(e.extras&&t instanceof o.PBRMaterial){if(e.extras.sheen){const i=t;i.sheen.isEnabled=!0,i.sheen.intensity=e.extras.sheen}if(e.extras.translucency){const i=t;i.subSurface.isTranslucencyEnabled=!0,i.subSurface.translucencyIntensity=e.extras.translucency,e.extras.translucencyR&&e.extras.translucencyG&&e.extras.translucencyB&&(i.subSurface.tintColor=new(0,y.Color3)(e.extras.translucencyR,e.extras.translucencyG,e.extras.translucencyB))}if(e.extras.refractionIOR){t.subSurface.indexOfRefraction=e.extras.refractionIOR}if(e.extras.useDepthPrePass){const e=t;e.needDepthPrePass=!0,e.forceIrradianceInFragment=!0}if(e.extras.useParallax){const i=t;i.useParallax=!0,i.useParallaxOcclusion=!0,i.parallaxScaleBias=e.extras.useParallax}}}applyReflections(e){function t(e){const t=[];return e.transformNodes.forEach((e=>{e.metadata&&e.metadata.reflective&&t.push(...e.getChildMeshes())})),e.meshes.forEach((e=>{e.metadata&&e.metadata.reflective&&!t.includes(e)&&t.push(e)})),t}e.meshes.forEach((i=>{const a=i.metadata;a&&(a.mirrorTexture&&function(i,a=1){const r=i.material;if(!r)return;const n=new(0,v.MirrorTexture)("mirror",N.getMirrorTextureResolution(),e,!0);n.renderList=t(e);const s=i.getVerticesData("normal");if(!s)throw new Error("Mirror attribute specified on: "+i.name+"But no normals exist to generate a mirror from!");i.computeWorldMatrix(!0);const o=i.getWorldMatrix(),c=y.Vector3.TransformNormal(new(0,y.Vector3)(s[0],s[1],s[2]),o).normalize(),l=y.Plane.FromPositionAndNormal(i.position,c.scale(-1));n.mirrorPlane=l,n.level=a,r.reflectionTexture=n}(i,a.mirrorTexture),a.reflectionProbe&&function(i){const a=i.material,r=new(0,x.ReflectionProbe)("probe-"+a.name,D,e);r.attachToMesh(i),r.renderList&&r.renderList.push(...t(e)),a.reflectionTexture=r.cubeTexture}(i))}))}}function G(e,t,i,a){const r=e.animationGroups,n=e=>e.targetedAnimations.map((e=>e.animation.framePerSecond)).reduce(((e,t)=>e+t),0)/e.targetedAnimations.length||0;void 0===a||void 0===i||a!==i?r.forEach((e=>{e.stop();const r=n(e);e.start(t,1,a*r,i*r)})):r.forEach((e=>{e.stop();const i=n(e),r=a*i;e.start(t,1,r,r)}))}function W(e){e.animationGroups.forEach((e=>{e.stop()}))}function H(e,t,i){var a,r,n;e.stopAnimation(t),t.animations=[],Math.abs(t.alpha)>2*Math.PI&&(t.alpha=(a=t.alpha,r=0,n=2*Math.PI,a<r?n-(r-a)%(n-r):r+(a-r)%(n-r)));const s=[],o=i.target,c=o?1:0;if(i.target&&Object.keys(i.target).length>0&&s.push(Z("cameraTargetLerp","target",(new(0,u.Vector3)).copyFrom(t.target),new(0,u.Vector3)(i.target.x,i.target.y,i.target.z),w.Animation.ANIMATIONTYPE_VECTOR3,0)),s.push(Z("cameraAlphaLerp","alpha",t.alpha,K(i.lonDeg),w.Animation.ANIMATIONTYPE_FLOAT,c)),s.push(Z("cameraBetaLerp","beta",t.beta,K(i.latDeg),w.Animation.ANIMATIONTYPE_FLOAT,c)),void 0!==i.radius){const e=Math.max(.01,i.radius);s.push(Z("cameraRadiusLerp","radius",t.radius,e,w.Animation.ANIMATIONTYPE_FLOAT,c))}t.animations.push(...s);const l=t.useAutoRotationBehavior;t.disableAutoRotationBehavior(),e.beginAnimation(t,0,o?120:60,!1,1,(()=>{t.animations=[],l&&t.enableAutoRotationBehavior()}))}function K(e){return e*Math.PI/180}function Z(e,t,i,a,r,n=0,s=w.Animation.ANIMATIONLOOPMODE_CONSTANT){const o=new(0,M.QuadraticEase);o.setEasingMode(M.EasingFunction.EASINGMODE_EASEINOUT);const c=new(0,w.Animation)(e,t,60,r,s),l=[];return n>0&&l.push({frame:0,value:i}),l.push({frame:60*n,value:i}),l.push({frame:60*(n+1),value:a}),c.setKeys(l),c.setEasingFunction(o),c}class Y extends T.ArcRotateCamera{constructor(e,t,i,a,r,n,s,o){var c,l,h;super(e,t,i,a,r,n,o),c=this,l="lastFocus",h=new(0,u.Vector3)(0,0,0),l in c?Object.defineProperty(c,l,{value:h,enumerable:!0,configurable:!0,writable:!0}):c[l]=h,this.minZ=.01,this.maxZ=1e3*this.radius,this.lowerRadiusLimit=.01*this.radius,this.enableFramingBehavior(),this.upperRadiusLimit=1.5*this.radius,this.wheelPrecision=100/this.radius,this.pinchPrecision=300/this.radius,this.wheelDeltaPercentage=.01,this.pinchDeltaPercentage=.005,this.useNaturalPinchZoom=!0,s.camera.autoOrientation&&(this.alpha+=Math.PI),s&&(s.camera.limits.min.beta&&(this.lowerBetaLimit=s.camera.limits.min.beta),s.camera.limits.max.beta&&(this.upperBetaLimit=s.camera.limits.max.beta),s.camera.limits.min.alpha&&(this.lowerAlphaLimit=s.camera.limits.min.alpha),s.camera.limits.max.alpha&&(this.upperAlphaLimit=s.camera.limits.max.alpha),s.camera.limits.min.radius&&(this.lowerRadiusLimit=s.camera.limits.min.radius),s.camera.limits.max.radius&&(this.upperRadiusLimit=s.camera.limits.max.radius),s.camera.autoRotation.enabled&&this.enableAutoRotationBehavior(s.camera.autoRotation.idleTimeMs))}getFramingBehavior(){return this.getBehaviorByName("Framing")}getAutoRotationBehavior(){const e=this.getBehaviorByName("AutoRotation");return e||void 0}enableFramingBehavior(){this.useFramingBehavior=!0;const e=this.getFramingBehavior();e.attach(this),e.framingTime=0,e.elevationReturnTime=-1,e.zoomStopsAnimation=!1,this.lowerRadiusLimit=null;const t=Q(this._scene);return e.zoomOnBoundingInfo(t.min,t.max),this.wheelPrecision=100/this.radius,null===this.lowerRadiusLimit&&(this.lowerRadiusLimit=.1),this.lastFocus.copyFrom(this.target),e}rerunFramingBehavior(e){const t=this.getFramingBehavior();t.framingTime=800;const i=Q(this._scene);t.zoomOnBoundingInfo(i.min,i.max,void 0,(()=>{e()})),t.framingTime=0}enableAutoRotationBehavior(e=5e3){this.useAutoRotationBehavior=!0;const t=this.getAutoRotationBehavior();t&&(t.idleRotationWaitTime=e)}disableAutoRotationBehavior(){this.useAutoRotationBehavior=!1}static create(e,t){e.activeCamera&&(e.activeCamera.dispose(),e.activeCamera=null);const i=Q(e),a=i.max.subtract(i.min),r=i.min.add(a.scale(.5)),n=new Y("ProductCamera",-Math.PI/2,Math.PI/2,1.5*a.length(),r,e,t);return n.panningInertia=0,n.panningOriginTarget.copyFrom(r),n.onAfterCheckInputsObservable.add((()=>{n.panningSensibility=1e3/a.length()})),e.activeCamera=n,n}}function Q(e){const t=e.meshes.filter((e=>e.name.toLowerCase().endsWith("_t")||e.name.toLowerCase().includes("_t_")));return e.getWorldExtends((e=>e.isVisible&&e.isEnabled()&&(0===t.length||t.includes(e))))}const X={albedoTexture:"albedoMap",bumpTexture:"normalMap",ambientTexture:"ambientMap",emissiveTexture:"emissionMap",opacityTexture:"alphaMap",metallicTexture:"metallicMap",refractionTexture:"refractionMap"};function $(e,t,i,a){["albedoTexture","bumpTexture","ambientTexture","emissiveTexture","opacityTexture","metallicTexture","refractionTexture"].forEach((r=>{!function(e,t,i,a,r){const n=X[e];if(!n)throw new Error("Unexpected texture name encountered.");const s=t[n]?.fileLink;s?a.addTextureTask(e,s,!1,!1):r&&i[e]&&(i[e]&&i[e].dispose(),i[e]=null,function(e,t){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!0);"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!1,t.useMetallnessFromMetallicTextureBlue=!1);"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!1,t.subSurface.refractionIntensity=1)}(e,i))}(r,e,t,i,a)})),function(e,t){if(!e.clearCoat)return;e.clearCoat===E.RemoveWhenSelected?(t.clearCoat.isEnabled=!1,t.clearCoat.indexOfRefraction=1.5):e.clearCoat===E.ApplyWhenSelected&&(t.clearCoat.isEnabled=!0,t.clearCoat.indexOfRefraction=e.clearCoatIOR||t.clearCoat.indexOfRefraction)}(e,t)}function J(e,t,i,a){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!1),"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!0,t.useMetallnessFromMetallicTextureBlue=!0),"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!0,t.subSurface.refractionIntensity=i.refractionIntensity||1),t[e]=a}function ee(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class te{constructor(){ee(this,"materialVariantMap",new Map),ee(this,"keysThatRemovedBaseModel",[]),ee(this,"loadedContainerForKey",new Map)}async applyMaterial(e,t,i,a,r){return new Promise((n=>{const s=e.materials.filter((e=>e.name===t)),o=this.materialVariantMap.get(t);if(this.materialVariantMap.set(t,{...o,...i}),0===s.length)return void n(void 0);const c=new(0,C.AssetsManager)(e);c.useDefaultLoadingScreen=!1,s.forEach((e=>$(i,e,c,r))),c.onProgress=(e,t,i)=>{a&&a(e/t*100,100,i.name)},c.onFinish=e=>{e.forEach((e=>{const t=e;a&&a(100,100,e.name),s.forEach((a=>J(e.name,a,i,t.texture)))})),n(void 0)},c.loadAsync()}))}async applyModel(e,t,i,a,r){if(a&&i&&!this.keysThatRemovedBaseModel.includes(t)&&this.keysThatRemovedBaseModel.push(t),!a){const i=this.keysThatRemovedBaseModel.includes(t);return this.loadedContainerForKey.get(t)?.removeAllFromScene(),e&&i&&await re(e.metadata.baseModel,e),Promise.resolve()}const n=await F(a,e,r);if(this.loadedContainerForKey.has(t)&&this.loadedContainerForKey.get(t)?.removeAllFromScene(),i){(await F(e.metadata.baseModel,e)).removeAllFromScene()}n.addAllToScene(),this.loadedContainerForKey.set(t,n);const s=[];this.materialVariantMap.forEach((async(t,i)=>{s.push(this.applyMaterial(e,i,t))})),await Promise.all(s)}}function ie(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}b.GLTF2.GLTFLoader.RegisterExtension("glbPostProcessor",(function(e){return new U(e)})),s.SceneLoader.OnPluginActivatedObservable.add((e=>{if("gltf"===e.name){e.transparencyAsCoverage=!0}}));class ae{constructor(e,t){ie(this,"engine",void 0),ie(this,"scene",void 0),ie(this,"configuration",void 0),ie(this,"loadProgress",new Map([["initialScene",0]])),ie(this,"materialReadyToLoadCallbacks",new Map),ie(this,"modelReadyToLoadCallbacks",new Map),ie(this,"queuedModelAnimation",void 0),ie(this,"queuedCameraAnimation",void 0),ie(this,"focusLostNotified",!1),ie(this,"loadObservable",new(0,m.Observable)),ie(this,"focusLostObservable",new(0,m.Observable)),ie(this,"dynamicTextures",new Map),ie(this,"highlightLayer",void 0),ie(this,"variantManager",new te),this.configuration=new j(t);d.DracoCompression.Configuration={decoder:{wasmUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.5/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.5/draco_decoder_gltf.wasm",fallbackUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.5/draco_decoder_gltf.js"}},e&&(e.getContext("webgl2")||e.getContext("webgl"));const r=console.log;console.log=()=>{};const n=e?new(0,i.Engine)(e,!0,{premultipliedAlpha:!1,preserveDrawingBuffer:!!t?.backgroundImage,audioEngine:!1,stencil:this.configuration.highlights.enabled,forceSRGBBufferSupportState:!0}):new(0,a.NullEngine);console.log=r,n.hideLoadingUI(),window.addEventListener("resize",this.fireResizeEvent.bind(this)),this.engine=n,this.scene=new(0,p.Scene)(n),this.scene.imageProcessingConfiguration.exposure=this.configuration.lighting.exposure,this.scene.imageProcessingConfiguration.contrast=this.configuration.lighting.contrast}registerFocusLostListener(e){this.focusLostObservable.add(e)}unregisterFocusLostListener(e){this.focusLostObservable.removeCallback(e)}registerLoadProgressListener(e){this.loadObservable.add(e),e(this.getLoadListenerEvent())}unregisterLoadProgressListener(e){this.loadObservable.removeCallback(e)}registerView(e){const t=e.height,i=e.width;this.engine.registerView(e),e.setAttribute("height",t.toString()),e.setAttribute("width",i.toString()),this.orbitEnabled()||this.setCameraState(O.Pan),this.reattachControls(e)}getNumViewports(){return this.engine.views?.length||0}unregisterView(e){this.engine.unRegisterView(e)}shutdown(){this.engine&&this.engine.dispose(),window.removeEventListener("resize",this.fireResizeEvent)}getSceneInitializationProgress(){return this.loadProgress.get("initialScene")}async initialize(i,a){if(this.scene.clearColor=this.configuration.scene.clearColor,this.scene.metadata={baseModel:i},this.scene.environmentTexture=c.CubeTexture.CreateFromPrefilteredData(this.configuration.scene.environmentFile,this.scene),i){const e=100;await re(i,this.scene,(t=>{this.loadProgress.set("initialScene",t.loaded*e/t.total),this.notifyLoadHandlers()}))}this.configuration.highlights.enabled&&this.scene.meshes.forEach((i=>{"targetcube_t"!==i.name&&"backgroundShell"!==i.name&&(i.isPickable=!0,i.actionManager||(i.actionManager=new(0,e.ActionManager)(this.scene)),i.actionManager.registerAction(new(0,t.ExecuteCodeAction)(e.ActionManager.OnPointerOutTrigger,(()=>{this.setHighlights([])}))),i.actionManager.registerAction(new(0,t.ExecuteCodeAction)(e.ActionManager.OnPointerOverTrigger,(e=>{if(e.meshUnderPointer){const t=e.meshUnderPointer.material;t&&this.setHighlights([t])}}))))}));const n=Y.create(this.scene,this.configuration),s=a?.getAll()||new Map;V(this.scene,s,this.dynamicTextures);if(this.scene.materials.some((e=>"emissiveTexture"in e&&null!==e.emissiveTexture))){new(0,r.GlowLayer)("GlowLayer",this.scene).intensity=.5}W(this.scene),this.materialReadyToLoadCallbacks.forEach(((e,t)=>{e.forEach(((e,i)=>{this.applyMaterialVariant(t,i,e)}))})),this.materialReadyToLoadCallbacks.clear(),this.modelReadyToLoadCallbacks.forEach((e=>{e(this.scene)})),this.modelReadyToLoadCallbacks.clear(),this.queuedModelAnimation&&(this.executeModelAnimation(this.queuedModelAnimation),this.queuedModelAnimation=void 0),this.queuedCameraAnimation&&(this.executeCameraAnimation(this.queuedCameraAnimation),this.queuedCameraAnimation=void 0),this.engine.views?.length>=1&&this.reattachControls(this.engine.views[this.engine.views.length-1].target),this.engine.runRenderLoop((()=>{this.engine.views&&(s.forEach(((e,t)=>{const i=this.dynamicTextures.get(t);i&&e.getStaticContextDirty()&&i.isReady()&&(i.update(!1),e.setStaticContextDirty(!1))})),this.configuration.scene.transparentBackground&&this.engine.views.forEach((e=>{const t=this.engine.getRenderingCanvas();e.target.getContext("2d").clearRect(0,0,t.width,t.height)})),this.scene.render(),n.target.equalsWithEpsilon(n.lastFocus,.1)||this.focusLostNotified||(this.focusLostObservable.notifyObservers(void 0),this.focusLostNotified=!0))}))}executeModelAnimation(e){100===this.getSceneInitializationProgress()?G(this.scene,e.loop,e.to,e.from):this.queuedModelAnimation=e}executeCameraAnimation(e){100===this.getSceneInitializationProgress()&&this.scene.activeCamera?H(this.scene,this.scene.activeCamera,e):this.queuedCameraAnimation=e}getCameraPose(){if(this.scene){const e=this.scene.activeCamera;if(e)return{lonDeg:Math.round(180*e.alpha/Math.PI),latDeg:Math.round(180*e.beta/Math.PI),radius:Math.round(1e4*(e.radius+Number.EPSILON))/1e4,target:{x:e.target.x,y:e.target.y,z:e.target.z}}}}setCameraPose(e){if(this.scene){const t=this.scene.activeCamera;t&&(t.target=new(0,u.Vector3)(e.target.x,e.target.y,e.target.z),t.radius=e.radius,t.alpha=e.latDeg,t.beta=e.lonDeg)}}async applyMaterialVariant(e,t,i,a){if(100===this.getSceneInitializationProgress())await this.variantManager.applyMaterial(this.scene,e,i,((e,t,i)=>{this.loadProgress.set(`key_${i}`,e/t*100),this.notifyLoadHandlers()}),a);else if(this.materialReadyToLoadCallbacks.has(e)){this.materialReadyToLoadCallbacks.get(e)?.set(t,i)}else{this.materialReadyToLoadCallbacks.set(e,new Map);this.materialReadyToLoadCallbacks.get(e)?.set(t,i)}}async applyModelVariant(e,t,i){100===this.getSceneInitializationProgress()?(await this.variantManager.applyModel(this.scene,e,i||!1,t.model,(t=>{this.loadProgress.set(e,100*t.loaded/t.total),this.notifyLoadHandlers()})),this.scene.materials.forEach((e=>{if(e&&0===e.getBindedMeshes().length){const t=e instanceof o.PBRMaterial&&!(e.albedoTexture instanceof l.DynamicTexture);e.dispose(!1,t)}})),V(this.scene,t.contextService.getAll(),this.dynamicTextures),W(this.scene)):this.modelReadyToLoadCallbacks.set(e,(()=>{this.applyModelVariant(e,t,i)}))}setCameraState(e){if(!this.engine?.views||!this.engine?.views[0])throw new Error("No views attached, camera state requires a view to attach controls onto.");e===O.Orbit?this.reattachControls(this.engine.views[0].target,2):this.reattachControls(this.engine.views[0].target,0)}animateToLastCameraFocus(){return new Promise((e=>{const t=this.scene.activeCamera,i=this.configuration;t.rerunFramingBehavior((()=>{this.focusLostNotified=!1,i.camera.limits.min.radius&&(t.lowerRadiusLimit=i.camera.limits.min.radius),i.camera.limits.max.radius&&(t.upperRadiusLimit=i.camera.limits.max.radius),e()}))}))}setAutoRotation(e){const t=this.scene.activeCamera;this.configuration.camera.autoRotation.enabled&&t&&(e?t.enableAutoRotationBehavior(this.configuration.camera.autoRotation.idleTimeMs):t.disableAutoRotationBehavior())}getCurrentConfiguration(){return this.configuration.options}async renderSceneScreenshot(e,t){const i=this.scene.activeCamera;if(!i)throw new Error("Missing product camera, cannot render screenshot!");var a;(a=i).getScene().stopAnimation(a),a.animations=[];const r=i.alpha,n=i.beta,s=i.radius,o=t.latDeg*Math.PI/180,c=t.lonDeg*Math.PI/180;i.alpha=c,i.beta=o,i.radius=t.radius||i.radius;const l=await g.Tools.CreateScreenshotUsingRenderTargetAsync(this.engine,i,e,"image/png",2,!0);return i.alpha=r,i.beta=n,i.radius=s,l}orbitEnabled(){const e=this.configuration;if(!e)return!0;const t=e.camera.limits.min.alpha,i=e.camera.limits.max.alpha,a=e.camera.limits.min.beta,r=e.camera.limits.max.beta;if(void 0===t||void 0===i||void 0===a||void 0===r)return!0;const n=[a,r],s=[t,i].every((e=>e===t)),o=n.every((e=>e===a));return!s&&!o}fireResizeEvent(){this.getNumViewports()>0&&this.engine.resize()}onMaterialSelected(i){this.scene.meshes.forEach((a=>{"targetcube_t"!==a.name&&"backgroundShell"!==a.name&&(a.actionManager||(a.actionManager=new(0,e.ActionManager)(this.scene)),a.actionManager.registerAction(new(0,t.ExecuteCodeAction)(e.ActionManager.OnPickDownTrigger,(e=>{if(e.meshUnderPointer){const t=e.meshUnderPointer.material;t&&i({id:t.id,name:t.name})}}))))}))}listMaterials(){const e=this.scene?.materials;return e?e.map((e=>({id:e.id,name:e.name}))):[]}setHighlights(e,t){0===e.length&&(this.highlightLayer?.dispose(),this.highlightLayer=void 0),this.highlightLayer||(this.highlightLayer=new(0,n.HighlightLayer)("highlights",this.scene,{isStroke:!0,blurVerticalSize:.85,blurHorizontalSize:.85}),this.highlightLayer.innerGlow=!0,this.highlightLayer.outerGlow=!1),this.highlightLayer.removeAllMeshes();const i=t?new(0,h.Color3)(t[0],t[1],t[2]).toLinearSpace():void 0;e.forEach((e=>{const t=this.scene.materials.find((t=>t.name===e.name&&t.id===e.id));t&&t.getBindedMeshes().forEach((e=>this.highlightLayer?.addMesh(e,i||h.Color3.FromHexString("#fcba03"))))}))}reattachControls(e,t=2){this.scene.detachControl(),this.engine.inputElement=e;const i=this.scene.activeCamera;if(i){i.attachControl(!0,!1,t);i.inputs.attached.pointers.multiTouchPanning=!1}this.scene.attachControl(!0,!0,!0)}getLoadListenerEvent(){const e=Array.from(this.loadProgress.values()).filter((e=>e<100)),t=e.reduce(((e,t)=>e+t),0)/e.length||0;return{loadValue:0===e.length?100:t,sceneInitialized:100===this.getSceneInitializationProgress()}}notifyLoadHandlers(){this.loadObservable.notifyObservers(this.getLoadListenerEvent())}}async function re(e,t,i){(await F(e,t,i)).addAllToScene()}A(module.exports,R),A(module.exports,I),A(module.exports,k);
|
|
1
|
+
var e=require("@babylonjs/core/Actions/actionManager"),t=require("@babylonjs/core/Actions/directActions"),i=require("@babylonjs/core/Engines/engine"),a=require("@babylonjs/core/Engines/nullEngine"),r=require("@babylonjs/core/Layers/glowLayer"),n=require("@babylonjs/core/Layers/highlightLayer"),s=require("@babylonjs/core/Loading/sceneLoader"),o=require("@babylonjs/core/Materials/PBR/pbrMaterial"),c=require("@babylonjs/core/Materials/Textures/cubeTexture"),l=require("@babylonjs/core/Materials/Textures/dynamicTexture"),h=require("@babylonjs/core/Maths/math.color"),u=require("@babylonjs/core/Maths/math.vector"),d=require("@babylonjs/core/Meshes/Compression/dracoCompression"),m=require("@babylonjs/core/Misc/observable"),g=require("@babylonjs/core/Misc/tools"),p=require("@babylonjs/core/scene"),b=require("@babylonjs/loaders/glTF");require("@babylonjs/core/Engines/Extensions/engine.views"),require("@babylonjs/core/Meshes/instancedMesh"),require("@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader"),require("@babylonjs/core/Materials/Textures/Loaders/envTextureLoader"),require("@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader"),require("@babylonjs/core/Animations/animatable"),require("@babylonjs/core/Misc/screenshotTools"),require("@babylonjs/core/Rendering/boundingBoxRenderer"),require("@babylonjs/loaders/glTF/2.0/Extensions");var f=require("@babylonjs/core/Materials/Textures/texture"),v=require("@babylonjs/core/Materials/Textures/mirrorTexture"),y=require("@babylonjs/core/Maths/math"),x=require("@babylonjs/core/Probes/reflectionProbe"),w=require("@babylonjs/core/Animations/animation"),M=require("@babylonjs/core/Animations/easing"),T=require("@babylonjs/core/Cameras/arcRotateCamera"),C=require("@babylonjs/core/Misc/assetsManager");function A(e,t){return Object.keys(t).forEach((function(i){"default"===i||"__esModule"===i||e.hasOwnProperty(i)||Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[i]}})})),e}function L(e,t,i,a){Object.defineProperty(e,t,{get:i,set:a,enumerable:!0,configurable:!0})}var R={};let O;var P;let E;var S;L(R,"ProductCameraRig",(()=>O)),L(R,"MaterialEffectMode",(()=>E)),(P=O||(O={}))[P.Orbit=0]="Orbit",P[P.Pan=1]="Pan",(S=E||(E={})).None="None",S.RemoveWhenSelected="RemoveWhenSelected",S.ApplyWhenSelected="ApplyWhenSelected";var B={};L(B,"SpiffCommerce3DPreviewService",(()=>ae)),L(B,"createBaseModel",(()=>re));const I=new Map;async function F(e,t,i){return new Promise(((a,r)=>{const n=I.get(e);if(n&&n.scene.uid===t.uid)return a(n);s.SceneLoader.LoadAssetContainerAsync(e,void 0,t,i).then((t=>{I.set(e,t),a(t)})).catch(r)}))}function q(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class j{constructor(e){q(this,"customOptions",void 0),q(this,"getSceneClearColor",(()=>{const e=this.customOptions?.transparentBackground||this.customOptions?.backgroundImage?0:1;if(this.customOptions&&this.customOptions?.transparentBackground||this.customOptions?.backgroundImage)return new(0,h.Color4)(0,0,0,e).toLinearSpace();if(this.customOptions&&this.customOptions.backgroundColor){const t=h.Color3.FromHexString(this.customOptions.backgroundColor);return new(0,h.Color4)(t.r,t.g,t.b,e).toLinearSpace()}return new(0,h.Color4)(.98,.98,.98,e).toLinearSpace()})),q(this,"highlightColorFromConfig",(()=>this.customOptions&&this.customOptions.highlightColor?this.hexToColor4(this.customOptions.highlightColor):new(0,h.Color4)(.98,.98,.98,1).toLinearSpace())),q(this,"hexToColor4",((e,t=1)=>{const i=h.Color3.FromHexString(e);return new(0,h.Color4)(i.r,i.g,i.b,t).toLinearSpace()})),this.customOptions=e}get options(){return this.customOptions}get scene(){return{clearColor:this.getSceneClearColor(),transparentBackground:this.customOptions?.transparentBackground||this.customOptions?.backgroundImage,environmentFile:this.customOptions?.environmentFile??"assets/model-viewer/default.env"}}get camera(){return{autoOrientation:this.customOptions?.disableAutomaticOrientation??!0,autoRotation:{enabled:this.customOptions?.autoRotation??!1,idleTimeMs:this.customOptions?.idleTimeBeforeRotation??5e3},limits:{min:{alpha:this.customOptions?.lowerAlphaLimitDeg?this.customOptions?.lowerAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.lowerBetaLimitDeg?this.customOptions?.lowerBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.minZoomOverride},max:{alpha:this.customOptions?.upperAlphaLimitDeg?this.customOptions?.upperAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.upperBetaLimitDeg?this.customOptions?.upperBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.maxZoomOverride}}}}get highlights(){return{enabled:this.customOptions?.highlightOnMaterialHover??!1,color:this.highlightColorFromConfig()}}get lighting(){return{exposure:this.customOptions?.lighting?.exposure??.9,contrast:this.customOptions?.lighting?.contrast??1.6}}}var k={};L(k,"RenderingConfiguration",(()=>N)),L(k,"REFLECTION_PROBE_RESOLUTION",(()=>D));class N{static getDynamicTextureResolution(){return this.getIsMobile()||!N.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}static shouldMipMap(){return!0}static offscreenRenderingSupported(){return!navigator.userAgent.includes("SamsungBrowser")&&(!!window.Worker&&!!window.OffscreenCanvas)}static getMirrorTextureResolution(){return this.getIsMobile()?512:1024}static getIsMobile(){return window.innerWidth<=480}}const D=128;function V(e,t,a){t.forEach((t=>{const r=t.getID(),n=t.getName(),s=N.getDynamicTextureResolution();e.materials.filter((e=>e.name===n)).forEach((o=>{const c=a.get(r);if(c)_(o,c),c.update(false);else{const c=function(e,t,a,r){const n=new(0,l.DynamicTexture)(e,{width:a,height:r},t,N.shouldMipMap(),f.Texture.TRILINEAR_SAMPLINGMODE,i.Engine.TEXTUREFORMAT_RGBA),s=n.getContext();s&&(s.fillStyle="#f5f5f5",s.fillRect(0,0,a,r),n.update());return n}(n,e,s.width,s.height);a.set(r,c),t.setStaticContext(c.getContext()),_(o,c),c.onLoadObservable.addOnce((()=>{c.update(false)}))}}))}))}function _(e,t){if(e instanceof o.PBRMaterial){const i=e,a=i.albedoTexture;a?(t.wrapU=a.wrapU,t.wrapV=a.wrapV):(t.wrapU=1,t.wrapV=1),i.albedoTexture=t}else{const i=e,a=i.diffuseTexture;a&&(t.wrapU=a.wrapU,t.wrapV=a.wrapV),i.diffuseTexture=t}}function z(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class U{constructor(e){z(this,"name",void 0),z(this,"enabled",void 0),z(this,"loader",void 0),this.name="glbPostProcessor",this.enabled=!0,this.loader=e}onReady(){this.applyReflections(this.loader.babylonScene)}loadNodeAsync(e,t,i){return this.loader.loadNodeAsync(e,t,(function(e){t.extras&&Object.keys(t.extras).forEach((i=>{const a=t.extras[i];e.metadata[i]=a})),i(e)}))}loadMaterialPropertiesAsync(e,t,i){return this.enableMaterialExtrasIfRequired(t,i),this.loader.loadMaterialPropertiesAsync(e,t,i)}dispose(){}enableMaterialExtrasIfRequired(e,t){if(e.extras&&t instanceof o.PBRMaterial){if(e.extras.sheen){const i=t;i.sheen.isEnabled=!0,i.sheen.intensity=e.extras.sheen}if(e.extras.translucency){const i=t;i.subSurface.isTranslucencyEnabled=!0,i.subSurface.translucencyIntensity=e.extras.translucency,e.extras.translucencyR&&e.extras.translucencyG&&e.extras.translucencyB&&(i.subSurface.tintColor=new(0,y.Color3)(e.extras.translucencyR,e.extras.translucencyG,e.extras.translucencyB))}if(e.extras.refractionIOR){t.subSurface.indexOfRefraction=e.extras.refractionIOR}if(e.extras.useDepthPrePass){const e=t;e.needDepthPrePass=!0,e.forceIrradianceInFragment=!0}if(e.extras.useParallax){const i=t;i.useParallax=!0,i.useParallaxOcclusion=!0,i.parallaxScaleBias=e.extras.useParallax}}}applyReflections(e){function t(e){const t=[];return e.transformNodes.forEach((e=>{e.metadata&&e.metadata.reflective&&t.push(...e.getChildMeshes())})),e.meshes.forEach((e=>{e.metadata&&e.metadata.reflective&&!t.includes(e)&&t.push(e)})),t}e.meshes.forEach((i=>{const a=i.metadata;a&&(a.mirrorTexture&&function(i,a=1){const r=i.material;if(!r)return;const n=new(0,v.MirrorTexture)("mirror",N.getMirrorTextureResolution(),e,!0);n.renderList=t(e);const s=i.getVerticesData("normal");if(!s)throw new Error("Mirror attribute specified on: "+i.name+"But no normals exist to generate a mirror from!");i.computeWorldMatrix(!0);const o=i.getWorldMatrix(),c=y.Vector3.TransformNormal(new(0,y.Vector3)(s[0],s[1],s[2]),o).normalize(),l=y.Plane.FromPositionAndNormal(i.position,c.scale(-1));n.mirrorPlane=l,n.level=a,r.reflectionTexture=n}(i,a.mirrorTexture),a.reflectionProbe&&function(i){const a=i.material,r=new(0,x.ReflectionProbe)("probe-"+a.name,D,e);r.attachToMesh(i),r.renderList&&r.renderList.push(...t(e)),a.reflectionTexture=r.cubeTexture}(i))}))}}function G(e,t,i,a){const r=e.animationGroups,n=e=>e.targetedAnimations.map((e=>e.animation.framePerSecond)).reduce(((e,t)=>e+t),0)/e.targetedAnimations.length||0;void 0===a||void 0===i||a!==i?r.forEach((e=>{e.stop();const r=n(e);e.start(t,1,a*r,i*r)})):r.forEach((e=>{e.stop();const i=n(e),r=a*i;e.start(t,1,r,r)}))}function W(e){e.animationGroups.forEach((e=>{e.stop()}))}function H(e,t,i){var a,r,n;e.stopAnimation(t),t.animations=[],Math.abs(t.alpha)>2*Math.PI&&(t.alpha=(a=t.alpha,r=0,n=2*Math.PI,a<r?n-(r-a)%(n-r):r+(a-r)%(n-r)));const s=[],o=i.target,c=o?1:0;if(i.target&&Object.keys(i.target).length>0&&s.push(Z("cameraTargetLerp","target",(new(0,u.Vector3)).copyFrom(t.target),new(0,u.Vector3)(i.target.x,i.target.y,i.target.z),w.Animation.ANIMATIONTYPE_VECTOR3,0)),s.push(Z("cameraAlphaLerp","alpha",t.alpha,K(i.lonDeg),w.Animation.ANIMATIONTYPE_FLOAT,c)),s.push(Z("cameraBetaLerp","beta",t.beta,K(i.latDeg),w.Animation.ANIMATIONTYPE_FLOAT,c)),void 0!==i.radius){const e=Math.max(.01,i.radius);s.push(Z("cameraRadiusLerp","radius",t.radius,e,w.Animation.ANIMATIONTYPE_FLOAT,c))}t.animations.push(...s);const l=t.useAutoRotationBehavior;t.disableAutoRotationBehavior(),e.beginAnimation(t,0,o?120:60,!1,1,(()=>{t.animations=[],l&&t.enableAutoRotationBehavior()}))}function K(e){return e*Math.PI/180}function Z(e,t,i,a,r,n=0,s=w.Animation.ANIMATIONLOOPMODE_CONSTANT){const o=new(0,M.QuadraticEase);o.setEasingMode(M.EasingFunction.EASINGMODE_EASEINOUT);const c=new(0,w.Animation)(e,t,60,r,s),l=[];return n>0&&l.push({frame:0,value:i}),l.push({frame:60*n,value:i}),l.push({frame:60*(n+1),value:a}),c.setKeys(l),c.setEasingFunction(o),c}class Y extends T.ArcRotateCamera{constructor(e,t,i,a,r,n,s,o){var c,l,h;super(e,t,i,a,r,n,o),c=this,l="lastFocus",h=new(0,u.Vector3)(0,0,0),l in c?Object.defineProperty(c,l,{value:h,enumerable:!0,configurable:!0,writable:!0}):c[l]=h,this.minZ=.01,this.maxZ=1e3*this.radius,this.lowerRadiusLimit=.01*this.radius,this.enableFramingBehavior(),this.upperRadiusLimit=1.5*this.radius,this.wheelPrecision=100/this.radius,this.pinchPrecision=300/this.radius,this.wheelDeltaPercentage=.01,this.pinchDeltaPercentage=.005,this.useNaturalPinchZoom=!0,s.camera.autoOrientation&&(this.alpha+=Math.PI),s&&(s.camera.limits.min.beta&&(this.lowerBetaLimit=s.camera.limits.min.beta),s.camera.limits.max.beta&&(this.upperBetaLimit=s.camera.limits.max.beta),s.camera.limits.min.alpha&&(this.lowerAlphaLimit=s.camera.limits.min.alpha),s.camera.limits.max.alpha&&(this.upperAlphaLimit=s.camera.limits.max.alpha),s.camera.limits.min.radius&&(this.lowerRadiusLimit=s.camera.limits.min.radius),s.camera.limits.max.radius&&(this.upperRadiusLimit=s.camera.limits.max.radius),s.camera.autoRotation.enabled&&this.enableAutoRotationBehavior(s.camera.autoRotation.idleTimeMs))}getFramingBehavior(){return this.getBehaviorByName("Framing")}getAutoRotationBehavior(){const e=this.getBehaviorByName("AutoRotation");return e||void 0}enableFramingBehavior(){this.useFramingBehavior=!0;const e=this.getFramingBehavior();e.attach(this),e.framingTime=0,e.elevationReturnTime=-1,e.zoomStopsAnimation=!1,this.lowerRadiusLimit=null;const t=Q(this._scene);return e.zoomOnBoundingInfo(t.min,t.max),this.wheelPrecision=100/this.radius,null===this.lowerRadiusLimit&&(this.lowerRadiusLimit=.1),this.lastFocus.copyFrom(this.target),e}rerunFramingBehavior(e){const t=this.getFramingBehavior();t.framingTime=800;const i=Q(this._scene);t.zoomOnBoundingInfo(i.min,i.max,void 0,(()=>{e()})),t.framingTime=0}enableAutoRotationBehavior(e=5e3){this.useAutoRotationBehavior=!0;const t=this.getAutoRotationBehavior();t&&(t.idleRotationWaitTime=e)}disableAutoRotationBehavior(){this.useAutoRotationBehavior=!1}static create(e,t){e.activeCamera&&(e.activeCamera.dispose(),e.activeCamera=null);const i=Q(e),a=i.max.subtract(i.min),r=i.min.add(a.scale(.5)),n=new Y("ProductCamera",-Math.PI/2,Math.PI/2,1.5*a.length(),r,e,t);return n.panningInertia=0,n.panningOriginTarget.copyFrom(r),n.onAfterCheckInputsObservable.add((()=>{n.panningSensibility=1e3/a.length()})),e.activeCamera=n,n}}function Q(e){const t=e.meshes.filter((e=>e.name.toLowerCase().endsWith("_t")||e.name.toLowerCase().includes("_t_")));return e.getWorldExtends((e=>e.isVisible&&e.isEnabled()&&(0===t.length||t.includes(e))))}const X={albedoTexture:"albedoMap",bumpTexture:"normalMap",ambientTexture:"ambientMap",emissiveTexture:"emissionMap",opacityTexture:"alphaMap",metallicTexture:"metallicMap",refractionTexture:"refractionMap"};function $(e,t,i,a){["albedoTexture","bumpTexture","ambientTexture","emissiveTexture","opacityTexture","metallicTexture","refractionTexture"].forEach((r=>{!function(e,t,i,a,r){const n=X[e];if(!n)throw new Error("Unexpected texture name encountered.");const s=t[n]?.fileLink;s?a.addTextureTask(e,s,!1,!1):r&&i[e]&&(i[e]&&i[e].dispose(),i[e]=null,function(e,t){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!0);"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!1,t.useMetallnessFromMetallicTextureBlue=!1);"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!1,t.subSurface.refractionIntensity=1)}(e,i))}(r,e,t,i,a)})),function(e,t){if(!e.clearCoat)return;e.clearCoat===E.RemoveWhenSelected?(t.clearCoat.isEnabled=!1,t.clearCoat.indexOfRefraction=1.5):e.clearCoat===E.ApplyWhenSelected&&(t.clearCoat.isEnabled=!0,t.clearCoat.indexOfRefraction=e.clearCoatIOR||t.clearCoat.indexOfRefraction)}(e,t)}function J(e,t,i,a){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!1),"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!0,t.useMetallnessFromMetallicTextureBlue=!0),"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!0,t.subSurface.refractionIntensity=i.refractionIntensity||1),t[e]=a}function ee(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class te{constructor(){ee(this,"materialVariantMap",new Map),ee(this,"keysThatRemovedBaseModel",[]),ee(this,"loadedContainerForKey",new Map)}async applyMaterial(e,t,i,a,r){return new Promise((n=>{const s=e.materials.filter((e=>e.name===t)),o=this.materialVariantMap.get(t);if(this.materialVariantMap.set(t,{...o,...i}),0===s.length)return void n(void 0);const c=new(0,C.AssetsManager)(e);c.useDefaultLoadingScreen=!1,s.forEach((e=>$(i,e,c,r))),c.onProgress=(e,t,i)=>{a&&a(e/t*100,100,i.name)},c.onFinish=e=>{e.forEach((e=>{const t=e;a&&a(100,100,e.name),s.forEach((a=>J(e.name,a,i,t.texture)))})),n(void 0)},c.loadAsync()}))}async applyModel(e,t,i,a,r){if(a&&i&&!this.keysThatRemovedBaseModel.includes(t)&&this.keysThatRemovedBaseModel.push(t),!a){const i=this.keysThatRemovedBaseModel.includes(t);return this.loadedContainerForKey.get(t)?.removeAllFromScene(),e&&i&&await re(e.metadata.baseModel,e),Promise.resolve()}const n=await F(a,e,r);if(this.loadedContainerForKey.has(t)&&this.loadedContainerForKey.get(t)?.removeAllFromScene(),i){(await F(e.metadata.baseModel,e)).removeAllFromScene()}n.addAllToScene(),this.loadedContainerForKey.set(t,n);const s=[];this.materialVariantMap.forEach((async(t,i)=>{s.push(this.applyMaterial(e,i,t))})),await Promise.all(s)}}function ie(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}b.GLTF2.GLTFLoader.RegisterExtension("glbPostProcessor",(function(e){return new U(e)})),s.SceneLoader.OnPluginActivatedObservable.add((e=>{if("gltf"===e.name){e.transparencyAsCoverage=!0}}));class ae{constructor(e){ie(this,"engine",void 0),ie(this,"scene",void 0),ie(this,"configuration",void 0),ie(this,"loadProgress",new Map([["initialScene",0]])),ie(this,"materialReadyToLoadCallbacks",new Map),ie(this,"modelReadyToLoadCallbacks",new Map),ie(this,"queuedModelAnimation",void 0),ie(this,"queuedCameraAnimation",void 0),ie(this,"focusLostNotified",!1),ie(this,"loadObservable",new(0,m.Observable)),ie(this,"focusLostObservable",new(0,m.Observable)),ie(this,"dynamicTextures",new Map),ie(this,"highlightLayer",void 0),ie(this,"variantManager",new te);const t=e?.noRender?void 0:document.createElement("canvas");this.configuration=new j(e);d.DracoCompression.Configuration={decoder:{wasmUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.5/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.5/draco_decoder_gltf.wasm",fallbackUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.5/draco_decoder_gltf.js"}},t&&(t.getContext("webgl2")||t.getContext("webgl"));const r=console.log;console.log=()=>{};const n=t?new(0,i.Engine)(t,!0,{premultipliedAlpha:!1,preserveDrawingBuffer:!!e?.backgroundImage,audioEngine:!1,stencil:this.configuration.highlights.enabled,forceSRGBBufferSupportState:!0}):new(0,a.NullEngine);console.log=r,n.hideLoadingUI(),window.addEventListener("resize",this.fireResizeEvent.bind(this)),this.engine=n,this.scene=new(0,p.Scene)(n),this.scene.imageProcessingConfiguration.exposure=this.configuration.lighting.exposure,this.scene.imageProcessingConfiguration.contrast=this.configuration.lighting.contrast}registerFocusLostListener(e){this.focusLostObservable.add(e)}unregisterFocusLostListener(e){this.focusLostObservable.removeCallback(e)}registerLoadProgressListener(e){this.loadObservable.add(e),e(this.getLoadListenerEvent())}unregisterLoadProgressListener(e){this.loadObservable.removeCallback(e)}registerView(e){const t=e.height,i=e.width;this.engine.registerView(e),e.setAttribute("height",t.toString()),e.setAttribute("width",i.toString()),this.orbitEnabled()||this.setCameraState(O.Pan),this.reattachControls(e)}getNumViewports(){return this.engine.views?.length||0}unregisterView(e){this.engine.unRegisterView(e)}shutdown(){this.engine&&this.engine.dispose(),window.removeEventListener("resize",this.fireResizeEvent)}getSceneInitializationProgress(){return this.loadProgress.get("initialScene")}async initialize(i,a){if(this.scene.clearColor=this.configuration.scene.clearColor,this.scene.metadata={baseModel:i},this.scene.environmentTexture=c.CubeTexture.CreateFromPrefilteredData(this.configuration.scene.environmentFile,this.scene),i){const e=100;await re(i,this.scene,(t=>{this.loadProgress.set("initialScene",t.loaded*e/t.total),this.notifyLoadHandlers()}))}this.configuration.highlights.enabled&&this.scene.meshes.forEach((i=>{"targetcube_t"!==i.name&&"backgroundShell"!==i.name&&(i.isPickable=!0,i.actionManager||(i.actionManager=new(0,e.ActionManager)(this.scene)),i.actionManager.registerAction(new(0,t.ExecuteCodeAction)(e.ActionManager.OnPointerOutTrigger,(()=>{this.setHighlights([])}))),i.actionManager.registerAction(new(0,t.ExecuteCodeAction)(e.ActionManager.OnPointerOverTrigger,(e=>{if(e.meshUnderPointer){const t=e.meshUnderPointer.material;t&&this.setHighlights([t])}}))))}));const n=Y.create(this.scene,this.configuration),s=a?.getAll()||new Map;V(this.scene,s,this.dynamicTextures);if(this.scene.materials.some((e=>"emissiveTexture"in e&&null!==e.emissiveTexture))){new(0,r.GlowLayer)("GlowLayer",this.scene).intensity=.5}W(this.scene),this.materialReadyToLoadCallbacks.forEach(((e,t)=>{e.forEach(((e,i)=>{this.applyMaterialVariant(t,i,e)}))})),this.materialReadyToLoadCallbacks.clear(),this.modelReadyToLoadCallbacks.forEach((e=>{e(this.scene)})),this.modelReadyToLoadCallbacks.clear(),this.queuedModelAnimation&&(this.executeModelAnimation(this.queuedModelAnimation),this.queuedModelAnimation=void 0),this.queuedCameraAnimation&&(this.executeCameraAnimation(this.queuedCameraAnimation),this.queuedCameraAnimation=void 0),this.engine.views?.length>=1&&this.reattachControls(this.engine.views[this.engine.views.length-1].target),this.engine.runRenderLoop((()=>{this.engine.views&&(s.forEach(((e,t)=>{const i=this.dynamicTextures.get(t);i&&e.getStaticContextDirty()&&i.isReady()&&(i.update(!1),e.setStaticContextDirty(!1))})),this.configuration.scene.transparentBackground&&this.engine.views.forEach((e=>{const t=this.engine.getRenderingCanvas();e.target.getContext("2d").clearRect(0,0,t.width,t.height)})),this.scene.render(),n.target.equalsWithEpsilon(n.lastFocus,.1)||this.focusLostNotified||(this.focusLostObservable.notifyObservers(void 0),this.focusLostNotified=!0))}))}executeModelAnimation(e){100===this.getSceneInitializationProgress()?G(this.scene,e.loop,e.to,e.from):this.queuedModelAnimation=e}executeCameraAnimation(e){100===this.getSceneInitializationProgress()&&this.scene.activeCamera?H(this.scene,this.scene.activeCamera,e):this.queuedCameraAnimation=e}getCameraPose(){if(this.scene){const e=this.scene.activeCamera;if(e)return{lonDeg:Math.round(180*e.alpha/Math.PI),latDeg:Math.round(180*e.beta/Math.PI),radius:Math.round(1e4*(e.radius+Number.EPSILON))/1e4,target:{x:e.target.x,y:e.target.y,z:e.target.z}}}}setCameraPose(e){if(this.scene){const t=this.scene.activeCamera;t&&(t.target=new(0,u.Vector3)(e.target.x,e.target.y,e.target.z),t.radius=e.radius,t.alpha=e.latDeg,t.beta=e.lonDeg)}}async applyMaterialVariant(e,t,i,a){if(100===this.getSceneInitializationProgress())await this.variantManager.applyMaterial(this.scene,e,i,((e,t,i)=>{this.loadProgress.set(`key_${i}`,e/t*100),this.notifyLoadHandlers()}),a);else if(this.materialReadyToLoadCallbacks.has(e)){this.materialReadyToLoadCallbacks.get(e)?.set(t,i)}else{this.materialReadyToLoadCallbacks.set(e,new Map);this.materialReadyToLoadCallbacks.get(e)?.set(t,i)}}async applyModelVariant(e,t,i){100===this.getSceneInitializationProgress()?(await this.variantManager.applyModel(this.scene,e,i||!1,t.model,(t=>{this.loadProgress.set(e,100*t.loaded/t.total),this.notifyLoadHandlers()})),this.scene.materials.forEach((e=>{if(e&&0===e.getBindedMeshes().length){const t=e instanceof o.PBRMaterial&&!(e.albedoTexture instanceof l.DynamicTexture);e.dispose(!1,t)}})),V(this.scene,t.contextService.getAll(),this.dynamicTextures),W(this.scene)):this.modelReadyToLoadCallbacks.set(e,(()=>{this.applyModelVariant(e,t,i)}))}setCameraState(e){if(!this.engine?.views||!this.engine?.views[0])throw new Error("No views attached, camera state requires a view to attach controls onto.");e===O.Orbit?this.reattachControls(this.engine.views[0].target,2):this.reattachControls(this.engine.views[0].target,0)}animateToLastCameraFocus(){return new Promise((e=>{const t=this.scene.activeCamera,i=this.configuration;t.rerunFramingBehavior((()=>{this.focusLostNotified=!1,i.camera.limits.min.radius&&(t.lowerRadiusLimit=i.camera.limits.min.radius),i.camera.limits.max.radius&&(t.upperRadiusLimit=i.camera.limits.max.radius),e()}))}))}setAutoRotation(e){const t=this.scene.activeCamera;this.configuration.camera.autoRotation.enabled&&t&&(e?t.enableAutoRotationBehavior(this.configuration.camera.autoRotation.idleTimeMs):t.disableAutoRotationBehavior())}getCurrentConfiguration(){return this.configuration.options}async renderSceneScreenshot(e,t){const i=this.scene.activeCamera;if(!i)throw new Error("Missing product camera, cannot render screenshot!");var a;(a=i).getScene().stopAnimation(a),a.animations=[];const r=i.alpha,n=i.beta,s=i.radius,o=t.latDeg*Math.PI/180,c=t.lonDeg*Math.PI/180;i.alpha=c,i.beta=o,i.radius=t.radius||i.radius;const l=await g.Tools.CreateScreenshotUsingRenderTargetAsync(this.engine,i,e,"image/png",2,!0);return i.alpha=r,i.beta=n,i.radius=s,l}orbitEnabled(){const e=this.configuration;if(!e)return!0;const t=e.camera.limits.min.alpha,i=e.camera.limits.max.alpha,a=e.camera.limits.min.beta,r=e.camera.limits.max.beta;if(void 0===t||void 0===i||void 0===a||void 0===r)return!0;const n=[a,r],s=[t,i].every((e=>e===t)),o=n.every((e=>e===a));return!s&&!o}fireResizeEvent(){this.getNumViewports()>0&&this.engine.resize()}onMaterialSelected(i){this.scene.meshes.forEach((a=>{"targetcube_t"!==a.name&&"backgroundShell"!==a.name&&(a.actionManager||(a.actionManager=new(0,e.ActionManager)(this.scene)),a.actionManager.registerAction(new(0,t.ExecuteCodeAction)(e.ActionManager.OnPickDownTrigger,(e=>{if(e.meshUnderPointer){const t=e.meshUnderPointer.material;t&&i({id:t.id,name:t.name})}}))))}))}listMaterials(){const e=this.scene?.materials;return e?e.map((e=>({id:e.id,name:e.name}))):[]}setHighlights(e,t){0===e.length&&(this.highlightLayer?.dispose(),this.highlightLayer=void 0),this.highlightLayer||(this.highlightLayer=new(0,n.HighlightLayer)("highlights",this.scene,{isStroke:!0,blurVerticalSize:.85,blurHorizontalSize:.85}),this.highlightLayer.innerGlow=!0,this.highlightLayer.outerGlow=!1),this.highlightLayer.removeAllMeshes();const i=t?new(0,h.Color3)(t[0],t[1],t[2]).toLinearSpace():void 0;e.forEach((e=>{const t=this.scene.materials.find((t=>t.name===e.name&&t.id===e.id));t&&t.getBindedMeshes().forEach((e=>this.highlightLayer?.addMesh(e,i||h.Color3.FromHexString("#fcba03"))))}))}reattachControls(e,t=2){this.scene.detachControl(),this.engine.inputElement=e;const i=this.scene.activeCamera;if(i){i.attachControl(!0,!1,t);i.inputs.attached.pointers.multiTouchPanning=!1}this.scene.attachControl(!0,!0,!0)}getLoadListenerEvent(){const e=Array.from(this.loadProgress.values()).filter((e=>e<100)),t=e.reduce(((e,t)=>e+t),0)/e.length||0;return{loadValue:0===e.length?100:t,sceneInitialized:100===this.getSceneInitializationProgress()}}notifyLoadHandlers(){this.loadObservable.notifyObservers(this.getLoadListenerEvent())}}async function re(e,t,i){(await F(e,t,i)).addAllToScene()}A(module.exports,R),A(module.exports,B),A(module.exports,k);
|
|
2
2
|
//# sourceMappingURL=main.js.map
|
package/dist/module.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ActionManager as e}from"@babylonjs/core/Actions/actionManager";import{ExecuteCodeAction as t}from"@babylonjs/core/Actions/directActions";import{Engine as a}from"@babylonjs/core/Engines/engine";import{NullEngine as i}from"@babylonjs/core/Engines/nullEngine";import{GlowLayer as r}from"@babylonjs/core/Layers/glowLayer";import{HighlightLayer as s}from"@babylonjs/core/Layers/highlightLayer";import{SceneLoader as o}from"@babylonjs/core/Loading/sceneLoader";import{PBRMaterial as n}from"@babylonjs/core/Materials/PBR/pbrMaterial";import{CubeTexture as c}from"@babylonjs/core/Materials/Textures/cubeTexture";import{DynamicTexture as l}from"@babylonjs/core/Materials/Textures/dynamicTexture";import{Color3 as h,Color4 as u}from"@babylonjs/core/Maths/math.color";import{Vector3 as m}from"@babylonjs/core/Maths/math.vector";import{DracoCompression as d}from"@babylonjs/core/Meshes/Compression/dracoCompression";import{Observable as g}from"@babylonjs/core/Misc/observable";import{Tools as p}from"@babylonjs/core/Misc/tools";import{Scene as f}from"@babylonjs/core/scene";import{GLTF2 as b}from"@babylonjs/loaders/glTF";import"@babylonjs/core/Engines/Extensions/engine.views";import"@babylonjs/core/Meshes/instancedMesh";import"@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader";import"@babylonjs/core/Materials/Textures/Loaders/envTextureLoader";import"@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader";import"@babylonjs/core/Animations/animatable";import"@babylonjs/core/Misc/screenshotTools";import"@babylonjs/core/Rendering/boundingBoxRenderer";import"@babylonjs/loaders/glTF/2.0/Extensions";import{Texture as v}from"@babylonjs/core/Materials/Textures/texture";import{MirrorTexture as y}from"@babylonjs/core/Materials/Textures/mirrorTexture";import{Color3 as w,Vector3 as x,Plane as M}from"@babylonjs/core/Maths/math";import{ReflectionProbe as T}from"@babylonjs/core/Probes/reflectionProbe";import{Animation as C}from"@babylonjs/core/Animations/animation";import{QuadraticEase as L,EasingFunction as R}from"@babylonjs/core/Animations/easing";import{ArcRotateCamera as A}from"@babylonjs/core/Cameras/arcRotateCamera";import{AssetsManager as O}from"@babylonjs/core/Misc/assetsManager";function P(e,t,a,i){Object.defineProperty(e,t,{get:a,set:i,enumerable:!0,configurable:!0})}var E={};let S;var I;let B;var F;P(E,"ProductCameraRig",(()=>S)),P(E,"MaterialEffectMode",(()=>B)),(I=S||(S={}))[I.Orbit=0]="Orbit",I[I.Pan=1]="Pan",(F=B||(B={})).None="None",F.RemoveWhenSelected="RemoveWhenSelected",F.ApplyWhenSelected="ApplyWhenSelected";var j={};P(j,"SpiffCommerce3DPreviewService",(()=>oe)),P(j,"createBaseModel",(()=>ne));const N=new Map;async function k(e,t,a){return new Promise(((i,r)=>{const s=N.get(e);if(s&&s.scene.uid===t.uid)return i(s);o.LoadAssetContainerAsync(e,void 0,t,a).then((t=>{N.set(e,t),i(t)})).catch(r)}))}function D(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class _{constructor(e){D(this,"customOptions",void 0),D(this,"getSceneClearColor",(()=>{const e=this.customOptions?.backgroundImage?0:1;if(this.customOptions&&this.customOptions.backgroundImage)return new u(0,0,0,e).toLinearSpace();if(this.customOptions&&this.customOptions.backgroundColor){const t=h.FromHexString(this.customOptions.backgroundColor);return new u(t.r,t.g,t.b,e).toLinearSpace()}return new u(.98,.98,.98,e).toLinearSpace()})),D(this,"highlightColorFromConfig",(()=>this.customOptions&&this.customOptions.highlightColor?this.hexToColor4(this.customOptions.highlightColor):new u(.98,.98,.98,1).toLinearSpace())),D(this,"hexToColor4",((e,t=1)=>{const a=h.FromHexString(e);return new u(a.r,a.g,a.b,t).toLinearSpace()})),this.customOptions=e}get options(){return this.customOptions}get scene(){return{clearColor:this.getSceneClearColor(),transparentBackground:this.customOptions?.backgroundImage,environmentFile:this.customOptions?.environmentFile??"assets/model-viewer/default.env"}}get camera(){return{autoOrientation:this.customOptions?.disableAutomaticOrientation??!0,autoRotation:{enabled:this.customOptions?.autoRotation??!1,idleTimeMs:this.customOptions?.idleTimeBeforeRotation??5e3},limits:{min:{alpha:this.customOptions?.lowerAlphaLimitDeg?this.customOptions?.lowerAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.lowerBetaLimitDeg?this.customOptions?.lowerBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.minZoomOverride},max:{alpha:this.customOptions?.upperAlphaLimitDeg?this.customOptions?.upperAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.upperBetaLimitDeg?this.customOptions?.upperBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.maxZoomOverride}}}}get highlights(){return{enabled:this.customOptions?.highlightOnMaterialHover??!1,color:this.highlightColorFromConfig()}}get lighting(){return{exposure:this.customOptions?.lighting?.exposure??.9,contrast:this.customOptions?.lighting?.contrast??1.6}}}var V={};P(V,"RenderingConfiguration",(()=>z)),P(V,"REFLECTION_PROBE_RESOLUTION",(()=>U));class z{static getDynamicTextureResolution(){return this.getIsMobile()||!z.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}static shouldMipMap(){return!0}static offscreenRenderingSupported(){return!navigator.userAgent.includes("SamsungBrowser")&&(!!window.Worker&&!!window.OffscreenCanvas)}static getMirrorTextureResolution(){return this.getIsMobile()?512:1024}static getIsMobile(){return window.innerWidth<=480}}const U=128;function G(e,t,i){t.forEach((t=>{const r=t.getID(),s=t.getName(),o=z.getDynamicTextureResolution();e.materials.filter((e=>e.name===s)).forEach((n=>{const c=i.get(r);if(c)q(n,c),c.update(false);else{const c=function(e,t,i,r){const s=new l(e,{width:i,height:r},t,z.shouldMipMap(),v.TRILINEAR_SAMPLINGMODE,a.TEXTUREFORMAT_RGBA),o=s.getContext();o&&(o.fillStyle="#f5f5f5",o.fillRect(0,0,i,r),s.update());return s}(s,e,o.width,o.height);i.set(r,c),t.setStaticContext(c.getContext()),q(n,c),c.onLoadObservable.addOnce((()=>{c.update(false)}))}}))}))}function q(e,t){if(e instanceof n){const a=e,i=a.albedoTexture;i?(t.wrapU=i.wrapU,t.wrapV=i.wrapV):(t.wrapU=1,t.wrapV=1),a.albedoTexture=t}else{const a=e,i=a.diffuseTexture;i&&(t.wrapU=i.wrapU,t.wrapV=i.wrapV),a.diffuseTexture=t}}function W(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class H{constructor(e){W(this,"name",void 0),W(this,"enabled",void 0),W(this,"loader",void 0),this.name="glbPostProcessor",this.enabled=!0,this.loader=e}onReady(){this.applyReflections(this.loader.babylonScene)}loadNodeAsync(e,t,a){return this.loader.loadNodeAsync(e,t,(function(e){t.extras&&Object.keys(t.extras).forEach((a=>{const i=t.extras[a];e.metadata[a]=i})),a(e)}))}loadMaterialPropertiesAsync(e,t,a){return this.enableMaterialExtrasIfRequired(t,a),this.loader.loadMaterialPropertiesAsync(e,t,a)}dispose(){}enableMaterialExtrasIfRequired(e,t){if(e.extras&&t instanceof n){if(e.extras.sheen){const a=t;a.sheen.isEnabled=!0,a.sheen.intensity=e.extras.sheen}if(e.extras.translucency){const a=t;a.subSurface.isTranslucencyEnabled=!0,a.subSurface.translucencyIntensity=e.extras.translucency,e.extras.translucencyR&&e.extras.translucencyG&&e.extras.translucencyB&&(a.subSurface.tintColor=new w(e.extras.translucencyR,e.extras.translucencyG,e.extras.translucencyB))}if(e.extras.refractionIOR){t.subSurface.indexOfRefraction=e.extras.refractionIOR}if(e.extras.useDepthPrePass){const e=t;e.needDepthPrePass=!0,e.forceIrradianceInFragment=!0}if(e.extras.useParallax){const a=t;a.useParallax=!0,a.useParallaxOcclusion=!0,a.parallaxScaleBias=e.extras.useParallax}}}applyReflections(e){function t(e){const t=[];return e.transformNodes.forEach((e=>{e.metadata&&e.metadata.reflective&&t.push(...e.getChildMeshes())})),e.meshes.forEach((e=>{e.metadata&&e.metadata.reflective&&!t.includes(e)&&t.push(e)})),t}e.meshes.forEach((a=>{const i=a.metadata;i&&(i.mirrorTexture&&function(a,i=1){const r=a.material;if(!r)return;const s=new y("mirror",z.getMirrorTextureResolution(),e,!0);s.renderList=t(e);const o=a.getVerticesData("normal");if(!o)throw new Error("Mirror attribute specified on: "+a.name+"But no normals exist to generate a mirror from!");a.computeWorldMatrix(!0);const n=a.getWorldMatrix(),c=x.TransformNormal(new x(o[0],o[1],o[2]),n).normalize(),l=M.FromPositionAndNormal(a.position,c.scale(-1));s.mirrorPlane=l,s.level=i,r.reflectionTexture=s}(a,i.mirrorTexture),i.reflectionProbe&&function(a){const i=a.material,r=new T("probe-"+i.name,U,e);r.attachToMesh(a),r.renderList&&r.renderList.push(...t(e)),i.reflectionTexture=r.cubeTexture}(a))}))}}function K(e,t,a,i){const r=e.animationGroups,s=e=>e.targetedAnimations.map((e=>e.animation.framePerSecond)).reduce(((e,t)=>e+t),0)/e.targetedAnimations.length||0;void 0===i||void 0===a||i!==a?r.forEach((e=>{e.stop();const r=s(e);e.start(t,1,i*r,a*r)})):r.forEach((e=>{e.stop();const a=s(e),r=i*a;e.start(t,1,r,r)}))}function Z(e){e.animationGroups.forEach((e=>{e.stop()}))}function Y(e,t,a){var i,r,s;e.stopAnimation(t),t.animations=[],Math.abs(t.alpha)>2*Math.PI&&(t.alpha=(i=t.alpha,r=0,s=2*Math.PI,i<r?s-(r-i)%(s-r):r+(i-r)%(s-r)));const o=[],n=a.target,c=n?1:0;if(a.target&&Object.keys(a.target).length>0&&o.push(X("cameraTargetLerp","target",(new m).copyFrom(t.target),new m(a.target.x,a.target.y,a.target.z),C.ANIMATIONTYPE_VECTOR3,0)),o.push(X("cameraAlphaLerp","alpha",t.alpha,Q(a.lonDeg),C.ANIMATIONTYPE_FLOAT,c)),o.push(X("cameraBetaLerp","beta",t.beta,Q(a.latDeg),C.ANIMATIONTYPE_FLOAT,c)),void 0!==a.radius){const e=Math.max(.01,a.radius);o.push(X("cameraRadiusLerp","radius",t.radius,e,C.ANIMATIONTYPE_FLOAT,c))}t.animations.push(...o);const l=t.useAutoRotationBehavior;t.disableAutoRotationBehavior(),e.beginAnimation(t,0,n?120:60,!1,1,(()=>{t.animations=[],l&&t.enableAutoRotationBehavior()}))}function Q(e){return e*Math.PI/180}function X(e,t,a,i,r,s=0,o=C.ANIMATIONLOOPMODE_CONSTANT){const n=new L;n.setEasingMode(R.EASINGMODE_EASEINOUT);const c=new C(e,t,60,r,o),l=[];return s>0&&l.push({frame:0,value:a}),l.push({frame:60*s,value:a}),l.push({frame:60*(s+1),value:i}),c.setKeys(l),c.setEasingFunction(n),c}class $ extends A{constructor(e,t,a,i,r,s,o,n){var c,l,h;super(e,t,a,i,r,s,n),c=this,l="lastFocus",h=new m(0,0,0),l in c?Object.defineProperty(c,l,{value:h,enumerable:!0,configurable:!0,writable:!0}):c[l]=h,this.minZ=.01,this.maxZ=1e3*this.radius,this.lowerRadiusLimit=.01*this.radius,this.enableFramingBehavior(),this.upperRadiusLimit=1.5*this.radius,this.wheelPrecision=100/this.radius,this.pinchPrecision=300/this.radius,this.wheelDeltaPercentage=.01,this.pinchDeltaPercentage=.005,this.useNaturalPinchZoom=!0,o.camera.autoOrientation&&(this.alpha+=Math.PI),o&&(o.camera.limits.min.beta&&(this.lowerBetaLimit=o.camera.limits.min.beta),o.camera.limits.max.beta&&(this.upperBetaLimit=o.camera.limits.max.beta),o.camera.limits.min.alpha&&(this.lowerAlphaLimit=o.camera.limits.min.alpha),o.camera.limits.max.alpha&&(this.upperAlphaLimit=o.camera.limits.max.alpha),o.camera.limits.min.radius&&(this.lowerRadiusLimit=o.camera.limits.min.radius),o.camera.limits.max.radius&&(this.upperRadiusLimit=o.camera.limits.max.radius),o.camera.autoRotation.enabled&&this.enableAutoRotationBehavior(o.camera.autoRotation.idleTimeMs))}getFramingBehavior(){return this.getBehaviorByName("Framing")}getAutoRotationBehavior(){const e=this.getBehaviorByName("AutoRotation");return e||void 0}enableFramingBehavior(){this.useFramingBehavior=!0;const e=this.getFramingBehavior();e.attach(this),e.framingTime=0,e.elevationReturnTime=-1,e.zoomStopsAnimation=!1,this.lowerRadiusLimit=null;const t=J(this._scene);return e.zoomOnBoundingInfo(t.min,t.max),this.wheelPrecision=100/this.radius,null===this.lowerRadiusLimit&&(this.lowerRadiusLimit=.1),this.lastFocus.copyFrom(this.target),e}rerunFramingBehavior(e){const t=this.getFramingBehavior();t.framingTime=800;const a=J(this._scene);t.zoomOnBoundingInfo(a.min,a.max,void 0,(()=>{e()})),t.framingTime=0}enableAutoRotationBehavior(e=5e3){this.useAutoRotationBehavior=!0;const t=this.getAutoRotationBehavior();t&&(t.idleRotationWaitTime=e)}disableAutoRotationBehavior(){this.useAutoRotationBehavior=!1}static create(e,t){e.activeCamera&&(e.activeCamera.dispose(),e.activeCamera=null);const a=J(e),i=a.max.subtract(a.min),r=a.min.add(i.scale(.5)),s=new $("ProductCamera",-Math.PI/2,Math.PI/2,1.5*i.length(),r,e,t);return s.panningInertia=0,s.panningOriginTarget.copyFrom(r),s.onAfterCheckInputsObservable.add((()=>{s.panningSensibility=1e3/i.length()})),e.activeCamera=s,s}}function J(e){const t=e.meshes.filter((e=>e.name.toLowerCase().endsWith("_t")||e.name.toLowerCase().includes("_t_")));return e.getWorldExtends((e=>e.isVisible&&e.isEnabled()&&(0===t.length||t.includes(e))))}const ee={albedoTexture:"albedoMap",bumpTexture:"normalMap",ambientTexture:"ambientMap",emissiveTexture:"emissionMap",opacityTexture:"alphaMap",metallicTexture:"metallicMap",refractionTexture:"refractionMap"};function te(e,t,a,i){["albedoTexture","bumpTexture","ambientTexture","emissiveTexture","opacityTexture","metallicTexture","refractionTexture"].forEach((r=>{!function(e,t,a,i,r){const s=ee[e];if(!s)throw new Error("Unexpected texture name encountered.");const o=t[s]?.fileLink;o?i.addTextureTask(e,o,!1,!1):r&&a[e]&&(a[e]&&a[e].dispose(),a[e]=null,function(e,t){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!0);"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!1,t.useMetallnessFromMetallicTextureBlue=!1);"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!1,t.subSurface.refractionIntensity=1)}(e,a))}(r,e,t,a,i)})),function(e,t){if(!e.clearCoat)return;e.clearCoat===B.RemoveWhenSelected?(t.clearCoat.isEnabled=!1,t.clearCoat.indexOfRefraction=1.5):e.clearCoat===B.ApplyWhenSelected&&(t.clearCoat.isEnabled=!0,t.clearCoat.indexOfRefraction=e.clearCoatIOR||t.clearCoat.indexOfRefraction)}(e,t)}function ae(e,t,a,i){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!1),"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!0,t.useMetallnessFromMetallicTextureBlue=!0),"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!0,t.subSurface.refractionIntensity=a.refractionIntensity||1),t[e]=i}function ie(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class re{constructor(){ie(this,"materialVariantMap",new Map),ie(this,"keysThatRemovedBaseModel",[]),ie(this,"loadedContainerForKey",new Map)}async applyMaterial(e,t,a,i,r){return new Promise((s=>{const o=e.materials.filter((e=>e.name===t)),n=this.materialVariantMap.get(t);if(this.materialVariantMap.set(t,{...n,...a}),0===o.length)return void s(void 0);const c=new O(e);c.useDefaultLoadingScreen=!1,o.forEach((e=>te(a,e,c,r))),c.onProgress=(e,t,a)=>{i&&i(e/t*100,100,a.name)},c.onFinish=e=>{e.forEach((e=>{const t=e;i&&i(100,100,e.name),o.forEach((i=>ae(e.name,i,a,t.texture)))})),s(void 0)},c.loadAsync()}))}async applyModel(e,t,a,i,r){if(i&&a&&!this.keysThatRemovedBaseModel.includes(t)&&this.keysThatRemovedBaseModel.push(t),!i){const a=this.keysThatRemovedBaseModel.includes(t);return this.loadedContainerForKey.get(t)?.removeAllFromScene(),e&&a&&await ne(e.metadata.baseModel,e),Promise.resolve()}const s=await k(i,e,r);if(this.loadedContainerForKey.has(t)&&this.loadedContainerForKey.get(t)?.removeAllFromScene(),a){(await k(e.metadata.baseModel,e)).removeAllFromScene()}s.addAllToScene(),this.loadedContainerForKey.set(t,s);const o=[];this.materialVariantMap.forEach((async(t,a)=>{o.push(this.applyMaterial(e,a,t))})),await Promise.all(o)}}function se(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}b.GLTFLoader.RegisterExtension("glbPostProcessor",(function(e){return new H(e)})),o.OnPluginActivatedObservable.add((e=>{if("gltf"===e.name){e.transparencyAsCoverage=!0}}));class oe{constructor(e,t){se(this,"engine",void 0),se(this,"scene",void 0),se(this,"configuration",void 0),se(this,"loadProgress",new Map([["initialScene",0]])),se(this,"materialReadyToLoadCallbacks",new Map),se(this,"modelReadyToLoadCallbacks",new Map),se(this,"queuedModelAnimation",void 0),se(this,"queuedCameraAnimation",void 0),se(this,"focusLostNotified",!1),se(this,"loadObservable",new g),se(this,"focusLostObservable",new g),se(this,"dynamicTextures",new Map),se(this,"highlightLayer",void 0),se(this,"variantManager",new re),this.configuration=new _(t);d.Configuration={decoder:{wasmUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.5/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.5/draco_decoder_gltf.wasm",fallbackUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.5/draco_decoder_gltf.js"}},e&&(e.getContext("webgl2")||e.getContext("webgl"));const r=console.log;console.log=()=>{};const s=e?new a(e,!0,{premultipliedAlpha:!1,preserveDrawingBuffer:!!t?.backgroundImage,audioEngine:!1,stencil:this.configuration.highlights.enabled,forceSRGBBufferSupportState:!0}):new i;console.log=r,s.hideLoadingUI(),window.addEventListener("resize",this.fireResizeEvent.bind(this)),this.engine=s,this.scene=new f(s),this.scene.imageProcessingConfiguration.exposure=this.configuration.lighting.exposure,this.scene.imageProcessingConfiguration.contrast=this.configuration.lighting.contrast}registerFocusLostListener(e){this.focusLostObservable.add(e)}unregisterFocusLostListener(e){this.focusLostObservable.removeCallback(e)}registerLoadProgressListener(e){this.loadObservable.add(e),e(this.getLoadListenerEvent())}unregisterLoadProgressListener(e){this.loadObservable.removeCallback(e)}registerView(e){const t=e.height,a=e.width;this.engine.registerView(e),e.setAttribute("height",t.toString()),e.setAttribute("width",a.toString()),this.orbitEnabled()||this.setCameraState(S.Pan),this.reattachControls(e)}getNumViewports(){return this.engine.views?.length||0}unregisterView(e){this.engine.unRegisterView(e)}shutdown(){this.engine&&this.engine.dispose(),window.removeEventListener("resize",this.fireResizeEvent)}getSceneInitializationProgress(){return this.loadProgress.get("initialScene")}async initialize(a,i){if(this.scene.clearColor=this.configuration.scene.clearColor,this.scene.metadata={baseModel:a},this.scene.environmentTexture=c.CreateFromPrefilteredData(this.configuration.scene.environmentFile,this.scene),a){const e=100;await ne(a,this.scene,(t=>{this.loadProgress.set("initialScene",t.loaded*e/t.total),this.notifyLoadHandlers()}))}this.configuration.highlights.enabled&&this.scene.meshes.forEach((a=>{"targetcube_t"!==a.name&&"backgroundShell"!==a.name&&(a.isPickable=!0,a.actionManager||(a.actionManager=new e(this.scene)),a.actionManager.registerAction(new t(e.OnPointerOutTrigger,(()=>{this.setHighlights([])}))),a.actionManager.registerAction(new t(e.OnPointerOverTrigger,(e=>{if(e.meshUnderPointer){const t=e.meshUnderPointer.material;t&&this.setHighlights([t])}}))))}));const s=$.create(this.scene,this.configuration),o=i?.getAll()||new Map;G(this.scene,o,this.dynamicTextures);if(this.scene.materials.some((e=>"emissiveTexture"in e&&null!==e.emissiveTexture))){new r("GlowLayer",this.scene).intensity=.5}Z(this.scene),this.materialReadyToLoadCallbacks.forEach(((e,t)=>{e.forEach(((e,a)=>{this.applyMaterialVariant(t,a,e)}))})),this.materialReadyToLoadCallbacks.clear(),this.modelReadyToLoadCallbacks.forEach((e=>{e(this.scene)})),this.modelReadyToLoadCallbacks.clear(),this.queuedModelAnimation&&(this.executeModelAnimation(this.queuedModelAnimation),this.queuedModelAnimation=void 0),this.queuedCameraAnimation&&(this.executeCameraAnimation(this.queuedCameraAnimation),this.queuedCameraAnimation=void 0),this.engine.views?.length>=1&&this.reattachControls(this.engine.views[this.engine.views.length-1].target),this.engine.runRenderLoop((()=>{this.engine.views&&(o.forEach(((e,t)=>{const a=this.dynamicTextures.get(t);a&&e.getStaticContextDirty()&&a.isReady()&&(a.update(!1),e.setStaticContextDirty(!1))})),this.configuration.scene.transparentBackground&&this.engine.views.forEach((e=>{const t=this.engine.getRenderingCanvas();e.target.getContext("2d").clearRect(0,0,t.width,t.height)})),this.scene.render(),s.target.equalsWithEpsilon(s.lastFocus,.1)||this.focusLostNotified||(this.focusLostObservable.notifyObservers(void 0),this.focusLostNotified=!0))}))}executeModelAnimation(e){100===this.getSceneInitializationProgress()?K(this.scene,e.loop,e.to,e.from):this.queuedModelAnimation=e}executeCameraAnimation(e){100===this.getSceneInitializationProgress()&&this.scene.activeCamera?Y(this.scene,this.scene.activeCamera,e):this.queuedCameraAnimation=e}getCameraPose(){if(this.scene){const e=this.scene.activeCamera;if(e)return{lonDeg:Math.round(180*e.alpha/Math.PI),latDeg:Math.round(180*e.beta/Math.PI),radius:Math.round(1e4*(e.radius+Number.EPSILON))/1e4,target:{x:e.target.x,y:e.target.y,z:e.target.z}}}}setCameraPose(e){if(this.scene){const t=this.scene.activeCamera;t&&(t.target=new m(e.target.x,e.target.y,e.target.z),t.radius=e.radius,t.alpha=e.latDeg,t.beta=e.lonDeg)}}async applyMaterialVariant(e,t,a,i){if(100===this.getSceneInitializationProgress())await this.variantManager.applyMaterial(this.scene,e,a,((e,t,a)=>{this.loadProgress.set(`key_${a}`,e/t*100),this.notifyLoadHandlers()}),i);else if(this.materialReadyToLoadCallbacks.has(e)){this.materialReadyToLoadCallbacks.get(e)?.set(t,a)}else{this.materialReadyToLoadCallbacks.set(e,new Map);this.materialReadyToLoadCallbacks.get(e)?.set(t,a)}}async applyModelVariant(e,t,a){100===this.getSceneInitializationProgress()?(await this.variantManager.applyModel(this.scene,e,a||!1,t.model,(t=>{this.loadProgress.set(e,100*t.loaded/t.total),this.notifyLoadHandlers()})),this.scene.materials.forEach((e=>{if(e&&0===e.getBindedMeshes().length){const t=e instanceof n&&!(e.albedoTexture instanceof l);e.dispose(!1,t)}})),G(this.scene,t.contextService.getAll(),this.dynamicTextures),Z(this.scene)):this.modelReadyToLoadCallbacks.set(e,(()=>{this.applyModelVariant(e,t,a)}))}setCameraState(e){if(!this.engine?.views||!this.engine?.views[0])throw new Error("No views attached, camera state requires a view to attach controls onto.");e===S.Orbit?this.reattachControls(this.engine.views[0].target,2):this.reattachControls(this.engine.views[0].target,0)}animateToLastCameraFocus(){return new Promise((e=>{const t=this.scene.activeCamera,a=this.configuration;t.rerunFramingBehavior((()=>{this.focusLostNotified=!1,a.camera.limits.min.radius&&(t.lowerRadiusLimit=a.camera.limits.min.radius),a.camera.limits.max.radius&&(t.upperRadiusLimit=a.camera.limits.max.radius),e()}))}))}setAutoRotation(e){const t=this.scene.activeCamera;this.configuration.camera.autoRotation.enabled&&t&&(e?t.enableAutoRotationBehavior(this.configuration.camera.autoRotation.idleTimeMs):t.disableAutoRotationBehavior())}getCurrentConfiguration(){return this.configuration.options}async renderSceneScreenshot(e,t){const a=this.scene.activeCamera;if(!a)throw new Error("Missing product camera, cannot render screenshot!");var i;(i=a).getScene().stopAnimation(i),i.animations=[];const r=a.alpha,s=a.beta,o=a.radius,n=t.latDeg*Math.PI/180,c=t.lonDeg*Math.PI/180;a.alpha=c,a.beta=n,a.radius=t.radius||a.radius;const l=await p.CreateScreenshotUsingRenderTargetAsync(this.engine,a,e,"image/png",2,!0);return a.alpha=r,a.beta=s,a.radius=o,l}orbitEnabled(){const e=this.configuration;if(!e)return!0;const t=e.camera.limits.min.alpha,a=e.camera.limits.max.alpha,i=e.camera.limits.min.beta,r=e.camera.limits.max.beta;if(void 0===t||void 0===a||void 0===i||void 0===r)return!0;const s=[i,r],o=[t,a].every((e=>e===t)),n=s.every((e=>e===i));return!o&&!n}fireResizeEvent(){this.getNumViewports()>0&&this.engine.resize()}onMaterialSelected(a){this.scene.meshes.forEach((i=>{"targetcube_t"!==i.name&&"backgroundShell"!==i.name&&(i.actionManager||(i.actionManager=new e(this.scene)),i.actionManager.registerAction(new t(e.OnPickDownTrigger,(e=>{if(e.meshUnderPointer){const t=e.meshUnderPointer.material;t&&a({id:t.id,name:t.name})}}))))}))}listMaterials(){const e=this.scene?.materials;return e?e.map((e=>({id:e.id,name:e.name}))):[]}setHighlights(e,t){0===e.length&&(this.highlightLayer?.dispose(),this.highlightLayer=void 0),this.highlightLayer||(this.highlightLayer=new s("highlights",this.scene,{isStroke:!0,blurVerticalSize:.85,blurHorizontalSize:.85}),this.highlightLayer.innerGlow=!0,this.highlightLayer.outerGlow=!1),this.highlightLayer.removeAllMeshes();const a=t?new h(t[0],t[1],t[2]).toLinearSpace():void 0;e.forEach((e=>{const t=this.scene.materials.find((t=>t.name===e.name&&t.id===e.id));t&&t.getBindedMeshes().forEach((e=>this.highlightLayer?.addMesh(e,a||h.FromHexString("#fcba03"))))}))}reattachControls(e,t=2){this.scene.detachControl(),this.engine.inputElement=e;const a=this.scene.activeCamera;if(a){a.attachControl(!0,!1,t);a.inputs.attached.pointers.multiTouchPanning=!1}this.scene.attachControl(!0,!0,!0)}getLoadListenerEvent(){const e=Array.from(this.loadProgress.values()).filter((e=>e<100)),t=e.reduce(((e,t)=>e+t),0)/e.length||0;return{loadValue:0===e.length?100:t,sceneInitialized:100===this.getSceneInitializationProgress()}}notifyLoadHandlers(){this.loadObservable.notifyObservers(this.getLoadListenerEvent())}}async function ne(e,t,a){(await k(e,t,a)).addAllToScene()}export{S as ProductCameraRig,B as MaterialEffectMode,oe as SpiffCommerce3DPreviewService,ne as createBaseModel,z as RenderingConfiguration,U as REFLECTION_PROBE_RESOLUTION};
|
|
1
|
+
import{ActionManager as e}from"@babylonjs/core/Actions/actionManager";import{ExecuteCodeAction as t}from"@babylonjs/core/Actions/directActions";import{Engine as a}from"@babylonjs/core/Engines/engine";import{NullEngine as i}from"@babylonjs/core/Engines/nullEngine";import{GlowLayer as r}from"@babylonjs/core/Layers/glowLayer";import{HighlightLayer as s}from"@babylonjs/core/Layers/highlightLayer";import{SceneLoader as n}from"@babylonjs/core/Loading/sceneLoader";import{PBRMaterial as o}from"@babylonjs/core/Materials/PBR/pbrMaterial";import{CubeTexture as c}from"@babylonjs/core/Materials/Textures/cubeTexture";import{DynamicTexture as l}from"@babylonjs/core/Materials/Textures/dynamicTexture";import{Color3 as h,Color4 as u}from"@babylonjs/core/Maths/math.color";import{Vector3 as m}from"@babylonjs/core/Maths/math.vector";import{DracoCompression as d}from"@babylonjs/core/Meshes/Compression/dracoCompression";import{Observable as g}from"@babylonjs/core/Misc/observable";import{Tools as p}from"@babylonjs/core/Misc/tools";import{Scene as f}from"@babylonjs/core/scene";import{GLTF2 as b}from"@babylonjs/loaders/glTF";import"@babylonjs/core/Engines/Extensions/engine.views";import"@babylonjs/core/Meshes/instancedMesh";import"@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader";import"@babylonjs/core/Materials/Textures/Loaders/envTextureLoader";import"@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader";import"@babylonjs/core/Animations/animatable";import"@babylonjs/core/Misc/screenshotTools";import"@babylonjs/core/Rendering/boundingBoxRenderer";import"@babylonjs/loaders/glTF/2.0/Extensions";import{Texture as v}from"@babylonjs/core/Materials/Textures/texture";import{MirrorTexture as y}from"@babylonjs/core/Materials/Textures/mirrorTexture";import{Color3 as w,Vector3 as x,Plane as M}from"@babylonjs/core/Maths/math";import{ReflectionProbe as T}from"@babylonjs/core/Probes/reflectionProbe";import{Animation as C}from"@babylonjs/core/Animations/animation";import{QuadraticEase as L,EasingFunction as R}from"@babylonjs/core/Animations/easing";import{ArcRotateCamera as A}from"@babylonjs/core/Cameras/arcRotateCamera";import{AssetsManager as O}from"@babylonjs/core/Misc/assetsManager";function P(e,t,a,i){Object.defineProperty(e,t,{get:a,set:i,enumerable:!0,configurable:!0})}var E={};let S;var I;let B;var F;P(E,"ProductCameraRig",(()=>S)),P(E,"MaterialEffectMode",(()=>B)),(I=S||(S={}))[I.Orbit=0]="Orbit",I[I.Pan=1]="Pan",(F=B||(B={})).None="None",F.RemoveWhenSelected="RemoveWhenSelected",F.ApplyWhenSelected="ApplyWhenSelected";var j={};P(j,"SpiffCommerce3DPreviewService",(()=>ne)),P(j,"createBaseModel",(()=>oe));const k=new Map;async function N(e,t,a){return new Promise(((i,r)=>{const s=k.get(e);if(s&&s.scene.uid===t.uid)return i(s);n.LoadAssetContainerAsync(e,void 0,t,a).then((t=>{k.set(e,t),i(t)})).catch(r)}))}function D(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class _{constructor(e){D(this,"customOptions",void 0),D(this,"getSceneClearColor",(()=>{const e=this.customOptions?.transparentBackground||this.customOptions?.backgroundImage?0:1;if(this.customOptions&&this.customOptions?.transparentBackground||this.customOptions?.backgroundImage)return new u(0,0,0,e).toLinearSpace();if(this.customOptions&&this.customOptions.backgroundColor){const t=h.FromHexString(this.customOptions.backgroundColor);return new u(t.r,t.g,t.b,e).toLinearSpace()}return new u(.98,.98,.98,e).toLinearSpace()})),D(this,"highlightColorFromConfig",(()=>this.customOptions&&this.customOptions.highlightColor?this.hexToColor4(this.customOptions.highlightColor):new u(.98,.98,.98,1).toLinearSpace())),D(this,"hexToColor4",((e,t=1)=>{const a=h.FromHexString(e);return new u(a.r,a.g,a.b,t).toLinearSpace()})),this.customOptions=e}get options(){return this.customOptions}get scene(){return{clearColor:this.getSceneClearColor(),transparentBackground:this.customOptions?.transparentBackground||this.customOptions?.backgroundImage,environmentFile:this.customOptions?.environmentFile??"assets/model-viewer/default.env"}}get camera(){return{autoOrientation:this.customOptions?.disableAutomaticOrientation??!0,autoRotation:{enabled:this.customOptions?.autoRotation??!1,idleTimeMs:this.customOptions?.idleTimeBeforeRotation??5e3},limits:{min:{alpha:this.customOptions?.lowerAlphaLimitDeg?this.customOptions?.lowerAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.lowerBetaLimitDeg?this.customOptions?.lowerBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.minZoomOverride},max:{alpha:this.customOptions?.upperAlphaLimitDeg?this.customOptions?.upperAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.upperBetaLimitDeg?this.customOptions?.upperBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.maxZoomOverride}}}}get highlights(){return{enabled:this.customOptions?.highlightOnMaterialHover??!1,color:this.highlightColorFromConfig()}}get lighting(){return{exposure:this.customOptions?.lighting?.exposure??.9,contrast:this.customOptions?.lighting?.contrast??1.6}}}var V={};P(V,"RenderingConfiguration",(()=>z)),P(V,"REFLECTION_PROBE_RESOLUTION",(()=>U));class z{static getDynamicTextureResolution(){return this.getIsMobile()||!z.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}static shouldMipMap(){return!0}static offscreenRenderingSupported(){return!navigator.userAgent.includes("SamsungBrowser")&&(!!window.Worker&&!!window.OffscreenCanvas)}static getMirrorTextureResolution(){return this.getIsMobile()?512:1024}static getIsMobile(){return window.innerWidth<=480}}const U=128;function G(e,t,i){t.forEach((t=>{const r=t.getID(),s=t.getName(),n=z.getDynamicTextureResolution();e.materials.filter((e=>e.name===s)).forEach((o=>{const c=i.get(r);if(c)q(o,c),c.update(false);else{const c=function(e,t,i,r){const s=new l(e,{width:i,height:r},t,z.shouldMipMap(),v.TRILINEAR_SAMPLINGMODE,a.TEXTUREFORMAT_RGBA),n=s.getContext();n&&(n.fillStyle="#f5f5f5",n.fillRect(0,0,i,r),s.update());return s}(s,e,n.width,n.height);i.set(r,c),t.setStaticContext(c.getContext()),q(o,c),c.onLoadObservable.addOnce((()=>{c.update(false)}))}}))}))}function q(e,t){if(e instanceof o){const a=e,i=a.albedoTexture;i?(t.wrapU=i.wrapU,t.wrapV=i.wrapV):(t.wrapU=1,t.wrapV=1),a.albedoTexture=t}else{const a=e,i=a.diffuseTexture;i&&(t.wrapU=i.wrapU,t.wrapV=i.wrapV),a.diffuseTexture=t}}function W(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class H{constructor(e){W(this,"name",void 0),W(this,"enabled",void 0),W(this,"loader",void 0),this.name="glbPostProcessor",this.enabled=!0,this.loader=e}onReady(){this.applyReflections(this.loader.babylonScene)}loadNodeAsync(e,t,a){return this.loader.loadNodeAsync(e,t,(function(e){t.extras&&Object.keys(t.extras).forEach((a=>{const i=t.extras[a];e.metadata[a]=i})),a(e)}))}loadMaterialPropertiesAsync(e,t,a){return this.enableMaterialExtrasIfRequired(t,a),this.loader.loadMaterialPropertiesAsync(e,t,a)}dispose(){}enableMaterialExtrasIfRequired(e,t){if(e.extras&&t instanceof o){if(e.extras.sheen){const a=t;a.sheen.isEnabled=!0,a.sheen.intensity=e.extras.sheen}if(e.extras.translucency){const a=t;a.subSurface.isTranslucencyEnabled=!0,a.subSurface.translucencyIntensity=e.extras.translucency,e.extras.translucencyR&&e.extras.translucencyG&&e.extras.translucencyB&&(a.subSurface.tintColor=new w(e.extras.translucencyR,e.extras.translucencyG,e.extras.translucencyB))}if(e.extras.refractionIOR){t.subSurface.indexOfRefraction=e.extras.refractionIOR}if(e.extras.useDepthPrePass){const e=t;e.needDepthPrePass=!0,e.forceIrradianceInFragment=!0}if(e.extras.useParallax){const a=t;a.useParallax=!0,a.useParallaxOcclusion=!0,a.parallaxScaleBias=e.extras.useParallax}}}applyReflections(e){function t(e){const t=[];return e.transformNodes.forEach((e=>{e.metadata&&e.metadata.reflective&&t.push(...e.getChildMeshes())})),e.meshes.forEach((e=>{e.metadata&&e.metadata.reflective&&!t.includes(e)&&t.push(e)})),t}e.meshes.forEach((a=>{const i=a.metadata;i&&(i.mirrorTexture&&function(a,i=1){const r=a.material;if(!r)return;const s=new y("mirror",z.getMirrorTextureResolution(),e,!0);s.renderList=t(e);const n=a.getVerticesData("normal");if(!n)throw new Error("Mirror attribute specified on: "+a.name+"But no normals exist to generate a mirror from!");a.computeWorldMatrix(!0);const o=a.getWorldMatrix(),c=x.TransformNormal(new x(n[0],n[1],n[2]),o).normalize(),l=M.FromPositionAndNormal(a.position,c.scale(-1));s.mirrorPlane=l,s.level=i,r.reflectionTexture=s}(a,i.mirrorTexture),i.reflectionProbe&&function(a){const i=a.material,r=new T("probe-"+i.name,U,e);r.attachToMesh(a),r.renderList&&r.renderList.push(...t(e)),i.reflectionTexture=r.cubeTexture}(a))}))}}function K(e,t,a,i){const r=e.animationGroups,s=e=>e.targetedAnimations.map((e=>e.animation.framePerSecond)).reduce(((e,t)=>e+t),0)/e.targetedAnimations.length||0;void 0===i||void 0===a||i!==a?r.forEach((e=>{e.stop();const r=s(e);e.start(t,1,i*r,a*r)})):r.forEach((e=>{e.stop();const a=s(e),r=i*a;e.start(t,1,r,r)}))}function Z(e){e.animationGroups.forEach((e=>{e.stop()}))}function Y(e,t,a){var i,r,s;e.stopAnimation(t),t.animations=[],Math.abs(t.alpha)>2*Math.PI&&(t.alpha=(i=t.alpha,r=0,s=2*Math.PI,i<r?s-(r-i)%(s-r):r+(i-r)%(s-r)));const n=[],o=a.target,c=o?1:0;if(a.target&&Object.keys(a.target).length>0&&n.push(X("cameraTargetLerp","target",(new m).copyFrom(t.target),new m(a.target.x,a.target.y,a.target.z),C.ANIMATIONTYPE_VECTOR3,0)),n.push(X("cameraAlphaLerp","alpha",t.alpha,Q(a.lonDeg),C.ANIMATIONTYPE_FLOAT,c)),n.push(X("cameraBetaLerp","beta",t.beta,Q(a.latDeg),C.ANIMATIONTYPE_FLOAT,c)),void 0!==a.radius){const e=Math.max(.01,a.radius);n.push(X("cameraRadiusLerp","radius",t.radius,e,C.ANIMATIONTYPE_FLOAT,c))}t.animations.push(...n);const l=t.useAutoRotationBehavior;t.disableAutoRotationBehavior(),e.beginAnimation(t,0,o?120:60,!1,1,(()=>{t.animations=[],l&&t.enableAutoRotationBehavior()}))}function Q(e){return e*Math.PI/180}function X(e,t,a,i,r,s=0,n=C.ANIMATIONLOOPMODE_CONSTANT){const o=new L;o.setEasingMode(R.EASINGMODE_EASEINOUT);const c=new C(e,t,60,r,n),l=[];return s>0&&l.push({frame:0,value:a}),l.push({frame:60*s,value:a}),l.push({frame:60*(s+1),value:i}),c.setKeys(l),c.setEasingFunction(o),c}class $ extends A{constructor(e,t,a,i,r,s,n,o){var c,l,h;super(e,t,a,i,r,s,o),c=this,l="lastFocus",h=new m(0,0,0),l in c?Object.defineProperty(c,l,{value:h,enumerable:!0,configurable:!0,writable:!0}):c[l]=h,this.minZ=.01,this.maxZ=1e3*this.radius,this.lowerRadiusLimit=.01*this.radius,this.enableFramingBehavior(),this.upperRadiusLimit=1.5*this.radius,this.wheelPrecision=100/this.radius,this.pinchPrecision=300/this.radius,this.wheelDeltaPercentage=.01,this.pinchDeltaPercentage=.005,this.useNaturalPinchZoom=!0,n.camera.autoOrientation&&(this.alpha+=Math.PI),n&&(n.camera.limits.min.beta&&(this.lowerBetaLimit=n.camera.limits.min.beta),n.camera.limits.max.beta&&(this.upperBetaLimit=n.camera.limits.max.beta),n.camera.limits.min.alpha&&(this.lowerAlphaLimit=n.camera.limits.min.alpha),n.camera.limits.max.alpha&&(this.upperAlphaLimit=n.camera.limits.max.alpha),n.camera.limits.min.radius&&(this.lowerRadiusLimit=n.camera.limits.min.radius),n.camera.limits.max.radius&&(this.upperRadiusLimit=n.camera.limits.max.radius),n.camera.autoRotation.enabled&&this.enableAutoRotationBehavior(n.camera.autoRotation.idleTimeMs))}getFramingBehavior(){return this.getBehaviorByName("Framing")}getAutoRotationBehavior(){const e=this.getBehaviorByName("AutoRotation");return e||void 0}enableFramingBehavior(){this.useFramingBehavior=!0;const e=this.getFramingBehavior();e.attach(this),e.framingTime=0,e.elevationReturnTime=-1,e.zoomStopsAnimation=!1,this.lowerRadiusLimit=null;const t=J(this._scene);return e.zoomOnBoundingInfo(t.min,t.max),this.wheelPrecision=100/this.radius,null===this.lowerRadiusLimit&&(this.lowerRadiusLimit=.1),this.lastFocus.copyFrom(this.target),e}rerunFramingBehavior(e){const t=this.getFramingBehavior();t.framingTime=800;const a=J(this._scene);t.zoomOnBoundingInfo(a.min,a.max,void 0,(()=>{e()})),t.framingTime=0}enableAutoRotationBehavior(e=5e3){this.useAutoRotationBehavior=!0;const t=this.getAutoRotationBehavior();t&&(t.idleRotationWaitTime=e)}disableAutoRotationBehavior(){this.useAutoRotationBehavior=!1}static create(e,t){e.activeCamera&&(e.activeCamera.dispose(),e.activeCamera=null);const a=J(e),i=a.max.subtract(a.min),r=a.min.add(i.scale(.5)),s=new $("ProductCamera",-Math.PI/2,Math.PI/2,1.5*i.length(),r,e,t);return s.panningInertia=0,s.panningOriginTarget.copyFrom(r),s.onAfterCheckInputsObservable.add((()=>{s.panningSensibility=1e3/i.length()})),e.activeCamera=s,s}}function J(e){const t=e.meshes.filter((e=>e.name.toLowerCase().endsWith("_t")||e.name.toLowerCase().includes("_t_")));return e.getWorldExtends((e=>e.isVisible&&e.isEnabled()&&(0===t.length||t.includes(e))))}const ee={albedoTexture:"albedoMap",bumpTexture:"normalMap",ambientTexture:"ambientMap",emissiveTexture:"emissionMap",opacityTexture:"alphaMap",metallicTexture:"metallicMap",refractionTexture:"refractionMap"};function te(e,t,a,i){["albedoTexture","bumpTexture","ambientTexture","emissiveTexture","opacityTexture","metallicTexture","refractionTexture"].forEach((r=>{!function(e,t,a,i,r){const s=ee[e];if(!s)throw new Error("Unexpected texture name encountered.");const n=t[s]?.fileLink;n?i.addTextureTask(e,n,!1,!1):r&&a[e]&&(a[e]&&a[e].dispose(),a[e]=null,function(e,t){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!0);"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!1,t.useMetallnessFromMetallicTextureBlue=!1);"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!1,t.subSurface.refractionIntensity=1)}(e,a))}(r,e,t,a,i)})),function(e,t){if(!e.clearCoat)return;e.clearCoat===B.RemoveWhenSelected?(t.clearCoat.isEnabled=!1,t.clearCoat.indexOfRefraction=1.5):e.clearCoat===B.ApplyWhenSelected&&(t.clearCoat.isEnabled=!0,t.clearCoat.indexOfRefraction=e.clearCoatIOR||t.clearCoat.indexOfRefraction)}(e,t)}function ae(e,t,a,i){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!1),"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!0,t.useMetallnessFromMetallicTextureBlue=!0),"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!0,t.subSurface.refractionIntensity=a.refractionIntensity||1),t[e]=i}function ie(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class re{constructor(){ie(this,"materialVariantMap",new Map),ie(this,"keysThatRemovedBaseModel",[]),ie(this,"loadedContainerForKey",new Map)}async applyMaterial(e,t,a,i,r){return new Promise((s=>{const n=e.materials.filter((e=>e.name===t)),o=this.materialVariantMap.get(t);if(this.materialVariantMap.set(t,{...o,...a}),0===n.length)return void s(void 0);const c=new O(e);c.useDefaultLoadingScreen=!1,n.forEach((e=>te(a,e,c,r))),c.onProgress=(e,t,a)=>{i&&i(e/t*100,100,a.name)},c.onFinish=e=>{e.forEach((e=>{const t=e;i&&i(100,100,e.name),n.forEach((i=>ae(e.name,i,a,t.texture)))})),s(void 0)},c.loadAsync()}))}async applyModel(e,t,a,i,r){if(i&&a&&!this.keysThatRemovedBaseModel.includes(t)&&this.keysThatRemovedBaseModel.push(t),!i){const a=this.keysThatRemovedBaseModel.includes(t);return this.loadedContainerForKey.get(t)?.removeAllFromScene(),e&&a&&await oe(e.metadata.baseModel,e),Promise.resolve()}const s=await N(i,e,r);if(this.loadedContainerForKey.has(t)&&this.loadedContainerForKey.get(t)?.removeAllFromScene(),a){(await N(e.metadata.baseModel,e)).removeAllFromScene()}s.addAllToScene(),this.loadedContainerForKey.set(t,s);const n=[];this.materialVariantMap.forEach((async(t,a)=>{n.push(this.applyMaterial(e,a,t))})),await Promise.all(n)}}function se(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}b.GLTFLoader.RegisterExtension("glbPostProcessor",(function(e){return new H(e)})),n.OnPluginActivatedObservable.add((e=>{if("gltf"===e.name){e.transparencyAsCoverage=!0}}));class ne{constructor(e){se(this,"engine",void 0),se(this,"scene",void 0),se(this,"configuration",void 0),se(this,"loadProgress",new Map([["initialScene",0]])),se(this,"materialReadyToLoadCallbacks",new Map),se(this,"modelReadyToLoadCallbacks",new Map),se(this,"queuedModelAnimation",void 0),se(this,"queuedCameraAnimation",void 0),se(this,"focusLostNotified",!1),se(this,"loadObservable",new g),se(this,"focusLostObservable",new g),se(this,"dynamicTextures",new Map),se(this,"highlightLayer",void 0),se(this,"variantManager",new re);const t=e?.noRender?void 0:document.createElement("canvas");this.configuration=new _(e);d.Configuration={decoder:{wasmUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.5/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.5/draco_decoder_gltf.wasm",fallbackUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.5/draco_decoder_gltf.js"}},t&&(t.getContext("webgl2")||t.getContext("webgl"));const r=console.log;console.log=()=>{};const s=t?new a(t,!0,{premultipliedAlpha:!1,preserveDrawingBuffer:!!e?.backgroundImage,audioEngine:!1,stencil:this.configuration.highlights.enabled,forceSRGBBufferSupportState:!0}):new i;console.log=r,s.hideLoadingUI(),window.addEventListener("resize",this.fireResizeEvent.bind(this)),this.engine=s,this.scene=new f(s),this.scene.imageProcessingConfiguration.exposure=this.configuration.lighting.exposure,this.scene.imageProcessingConfiguration.contrast=this.configuration.lighting.contrast}registerFocusLostListener(e){this.focusLostObservable.add(e)}unregisterFocusLostListener(e){this.focusLostObservable.removeCallback(e)}registerLoadProgressListener(e){this.loadObservable.add(e),e(this.getLoadListenerEvent())}unregisterLoadProgressListener(e){this.loadObservable.removeCallback(e)}registerView(e){const t=e.height,a=e.width;this.engine.registerView(e),e.setAttribute("height",t.toString()),e.setAttribute("width",a.toString()),this.orbitEnabled()||this.setCameraState(S.Pan),this.reattachControls(e)}getNumViewports(){return this.engine.views?.length||0}unregisterView(e){this.engine.unRegisterView(e)}shutdown(){this.engine&&this.engine.dispose(),window.removeEventListener("resize",this.fireResizeEvent)}getSceneInitializationProgress(){return this.loadProgress.get("initialScene")}async initialize(a,i){if(this.scene.clearColor=this.configuration.scene.clearColor,this.scene.metadata={baseModel:a},this.scene.environmentTexture=c.CreateFromPrefilteredData(this.configuration.scene.environmentFile,this.scene),a){const e=100;await oe(a,this.scene,(t=>{this.loadProgress.set("initialScene",t.loaded*e/t.total),this.notifyLoadHandlers()}))}this.configuration.highlights.enabled&&this.scene.meshes.forEach((a=>{"targetcube_t"!==a.name&&"backgroundShell"!==a.name&&(a.isPickable=!0,a.actionManager||(a.actionManager=new e(this.scene)),a.actionManager.registerAction(new t(e.OnPointerOutTrigger,(()=>{this.setHighlights([])}))),a.actionManager.registerAction(new t(e.OnPointerOverTrigger,(e=>{if(e.meshUnderPointer){const t=e.meshUnderPointer.material;t&&this.setHighlights([t])}}))))}));const s=$.create(this.scene,this.configuration),n=i?.getAll()||new Map;G(this.scene,n,this.dynamicTextures);if(this.scene.materials.some((e=>"emissiveTexture"in e&&null!==e.emissiveTexture))){new r("GlowLayer",this.scene).intensity=.5}Z(this.scene),this.materialReadyToLoadCallbacks.forEach(((e,t)=>{e.forEach(((e,a)=>{this.applyMaterialVariant(t,a,e)}))})),this.materialReadyToLoadCallbacks.clear(),this.modelReadyToLoadCallbacks.forEach((e=>{e(this.scene)})),this.modelReadyToLoadCallbacks.clear(),this.queuedModelAnimation&&(this.executeModelAnimation(this.queuedModelAnimation),this.queuedModelAnimation=void 0),this.queuedCameraAnimation&&(this.executeCameraAnimation(this.queuedCameraAnimation),this.queuedCameraAnimation=void 0),this.engine.views?.length>=1&&this.reattachControls(this.engine.views[this.engine.views.length-1].target),this.engine.runRenderLoop((()=>{this.engine.views&&(n.forEach(((e,t)=>{const a=this.dynamicTextures.get(t);a&&e.getStaticContextDirty()&&a.isReady()&&(a.update(!1),e.setStaticContextDirty(!1))})),this.configuration.scene.transparentBackground&&this.engine.views.forEach((e=>{const t=this.engine.getRenderingCanvas();e.target.getContext("2d").clearRect(0,0,t.width,t.height)})),this.scene.render(),s.target.equalsWithEpsilon(s.lastFocus,.1)||this.focusLostNotified||(this.focusLostObservable.notifyObservers(void 0),this.focusLostNotified=!0))}))}executeModelAnimation(e){100===this.getSceneInitializationProgress()?K(this.scene,e.loop,e.to,e.from):this.queuedModelAnimation=e}executeCameraAnimation(e){100===this.getSceneInitializationProgress()&&this.scene.activeCamera?Y(this.scene,this.scene.activeCamera,e):this.queuedCameraAnimation=e}getCameraPose(){if(this.scene){const e=this.scene.activeCamera;if(e)return{lonDeg:Math.round(180*e.alpha/Math.PI),latDeg:Math.round(180*e.beta/Math.PI),radius:Math.round(1e4*(e.radius+Number.EPSILON))/1e4,target:{x:e.target.x,y:e.target.y,z:e.target.z}}}}setCameraPose(e){if(this.scene){const t=this.scene.activeCamera;t&&(t.target=new m(e.target.x,e.target.y,e.target.z),t.radius=e.radius,t.alpha=e.latDeg,t.beta=e.lonDeg)}}async applyMaterialVariant(e,t,a,i){if(100===this.getSceneInitializationProgress())await this.variantManager.applyMaterial(this.scene,e,a,((e,t,a)=>{this.loadProgress.set(`key_${a}`,e/t*100),this.notifyLoadHandlers()}),i);else if(this.materialReadyToLoadCallbacks.has(e)){this.materialReadyToLoadCallbacks.get(e)?.set(t,a)}else{this.materialReadyToLoadCallbacks.set(e,new Map);this.materialReadyToLoadCallbacks.get(e)?.set(t,a)}}async applyModelVariant(e,t,a){100===this.getSceneInitializationProgress()?(await this.variantManager.applyModel(this.scene,e,a||!1,t.model,(t=>{this.loadProgress.set(e,100*t.loaded/t.total),this.notifyLoadHandlers()})),this.scene.materials.forEach((e=>{if(e&&0===e.getBindedMeshes().length){const t=e instanceof o&&!(e.albedoTexture instanceof l);e.dispose(!1,t)}})),G(this.scene,t.contextService.getAll(),this.dynamicTextures),Z(this.scene)):this.modelReadyToLoadCallbacks.set(e,(()=>{this.applyModelVariant(e,t,a)}))}setCameraState(e){if(!this.engine?.views||!this.engine?.views[0])throw new Error("No views attached, camera state requires a view to attach controls onto.");e===S.Orbit?this.reattachControls(this.engine.views[0].target,2):this.reattachControls(this.engine.views[0].target,0)}animateToLastCameraFocus(){return new Promise((e=>{const t=this.scene.activeCamera,a=this.configuration;t.rerunFramingBehavior((()=>{this.focusLostNotified=!1,a.camera.limits.min.radius&&(t.lowerRadiusLimit=a.camera.limits.min.radius),a.camera.limits.max.radius&&(t.upperRadiusLimit=a.camera.limits.max.radius),e()}))}))}setAutoRotation(e){const t=this.scene.activeCamera;this.configuration.camera.autoRotation.enabled&&t&&(e?t.enableAutoRotationBehavior(this.configuration.camera.autoRotation.idleTimeMs):t.disableAutoRotationBehavior())}getCurrentConfiguration(){return this.configuration.options}async renderSceneScreenshot(e,t){const a=this.scene.activeCamera;if(!a)throw new Error("Missing product camera, cannot render screenshot!");var i;(i=a).getScene().stopAnimation(i),i.animations=[];const r=a.alpha,s=a.beta,n=a.radius,o=t.latDeg*Math.PI/180,c=t.lonDeg*Math.PI/180;a.alpha=c,a.beta=o,a.radius=t.radius||a.radius;const l=await p.CreateScreenshotUsingRenderTargetAsync(this.engine,a,e,"image/png",2,!0);return a.alpha=r,a.beta=s,a.radius=n,l}orbitEnabled(){const e=this.configuration;if(!e)return!0;const t=e.camera.limits.min.alpha,a=e.camera.limits.max.alpha,i=e.camera.limits.min.beta,r=e.camera.limits.max.beta;if(void 0===t||void 0===a||void 0===i||void 0===r)return!0;const s=[i,r],n=[t,a].every((e=>e===t)),o=s.every((e=>e===i));return!n&&!o}fireResizeEvent(){this.getNumViewports()>0&&this.engine.resize()}onMaterialSelected(a){this.scene.meshes.forEach((i=>{"targetcube_t"!==i.name&&"backgroundShell"!==i.name&&(i.actionManager||(i.actionManager=new e(this.scene)),i.actionManager.registerAction(new t(e.OnPickDownTrigger,(e=>{if(e.meshUnderPointer){const t=e.meshUnderPointer.material;t&&a({id:t.id,name:t.name})}}))))}))}listMaterials(){const e=this.scene?.materials;return e?e.map((e=>({id:e.id,name:e.name}))):[]}setHighlights(e,t){0===e.length&&(this.highlightLayer?.dispose(),this.highlightLayer=void 0),this.highlightLayer||(this.highlightLayer=new s("highlights",this.scene,{isStroke:!0,blurVerticalSize:.85,blurHorizontalSize:.85}),this.highlightLayer.innerGlow=!0,this.highlightLayer.outerGlow=!1),this.highlightLayer.removeAllMeshes();const a=t?new h(t[0],t[1],t[2]).toLinearSpace():void 0;e.forEach((e=>{const t=this.scene.materials.find((t=>t.name===e.name&&t.id===e.id));t&&t.getBindedMeshes().forEach((e=>this.highlightLayer?.addMesh(e,a||h.FromHexString("#fcba03"))))}))}reattachControls(e,t=2){this.scene.detachControl(),this.engine.inputElement=e;const a=this.scene.activeCamera;if(a){a.attachControl(!0,!1,t);a.inputs.attached.pointers.multiTouchPanning=!1}this.scene.attachControl(!0,!0,!0)}getLoadListenerEvent(){const e=Array.from(this.loadProgress.values()).filter((e=>e<100)),t=e.reduce(((e,t)=>e+t),0)/e.length||0;return{loadValue:0===e.length?100:t,sceneInitialized:100===this.getSceneInitializationProgress()}}notifyLoadHandlers(){this.loadObservable.notifyObservers(this.getLoadListenerEvent())}}async function oe(e,t,a){(await N(e,t,a)).addAllToScene()}export{S as ProductCameraRig,B as MaterialEffectMode,ne as SpiffCommerce3DPreviewService,oe as createBaseModel,z as RenderingConfiguration,U as REFLECTION_PROBE_RESOLUTION};
|
|
2
2
|
//# sourceMappingURL=module.js.map
|
package/dist/types.d.ts
CHANGED
|
@@ -337,8 +337,13 @@ export type PreviewOptions = {
|
|
|
337
337
|
/**
|
|
338
338
|
* Image to be used as a background when running withh transparency, the image
|
|
339
339
|
* will be scaled and centered to fill the preview based on aspect ratio.
|
|
340
|
+
* Will implicitly set transparency to true.
|
|
340
341
|
*/
|
|
341
342
|
readonly backgroundImage?: string;
|
|
343
|
+
/**
|
|
344
|
+
* When true, the canvas background will be transparent.
|
|
345
|
+
*/
|
|
346
|
+
readonly transparentBackground?: boolean;
|
|
342
347
|
/**
|
|
343
348
|
* The closest zoom the camera can achieve to the product.
|
|
344
349
|
*/
|
|
@@ -409,6 +414,12 @@ export type PreviewOptions = {
|
|
|
409
414
|
*/
|
|
410
415
|
contrast?: number;
|
|
411
416
|
};
|
|
417
|
+
/**
|
|
418
|
+
* When true the preview system operates in a noRender mode. It silently accepts all requests and modifies internal state
|
|
419
|
+
* based on those requests. However no rendering will actually be occuring. Can be useful in situations where testing requires
|
|
420
|
+
* a 3D preview but the actual rendering is not important.
|
|
421
|
+
*/
|
|
422
|
+
readonly noRender?: boolean;
|
|
412
423
|
};
|
|
413
424
|
/**
|
|
414
425
|
* Defines an animation to be play on a product.
|
|
@@ -490,7 +501,7 @@ export type PowerOfTwoNumber = 128 | 256 | 512 | 1024 | 2048 | 4096 | 8192;
|
|
|
490
501
|
* they can use this one to get things running more quickly.
|
|
491
502
|
*/
|
|
492
503
|
export class SpiffCommerce3DPreviewService implements ThreeDPreviewService {
|
|
493
|
-
constructor(
|
|
504
|
+
constructor(options?: PreviewOptions);
|
|
494
505
|
registerFocusLostListener(listener: () => void): void;
|
|
495
506
|
unregisterFocusLostListener(listener: () => void): void;
|
|
496
507
|
registerLoadProgressListener(listener: (e: LoadProgressEventData) => void): void;
|
package/package.json
CHANGED