@spiffcommerce/preview 2.1.45 → 3.0.0

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 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"),n=require("@babylonjs/core/Engines/nullEngine"),a=require("@babylonjs/core/Layers/glowLayer"),r=require("@babylonjs/core/Layers/highlightLayer"),o=require("@babylonjs/core/Loading/sceneLoader"),s=require("@babylonjs/core/Materials/PBR/pbrMaterial"),l=require("@babylonjs/core/Materials/Textures/cubeTexture"),c=require("@babylonjs/core/Materials/Textures/dynamicTexture"),h=require("@babylonjs/core/Maths/math.color"),d=require("@babylonjs/core/Maths/math.vector"),u=require("@babylonjs/core/Meshes/Compression/dracoCompression"),g=require("@babylonjs/core/Misc/observable"),m=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"),P=require("@babylonjs/core/Probes/reflectionProbe"),w=require("@babylonjs/core/Animations/animation"),x=require("@babylonjs/core/Animations/easing"),M=require("@babylonjs/core/Cameras/arcRotateCamera"),C=require("@babylonjs/core/Materials/colorCurves"),A=require("@babylonjs/core/Materials/imageProcessingConfiguration"),T=require("@babylonjs/core/PostProcesses/RenderPipeline"),L=require("@babylonjs/core/PostProcesses/depthOfFieldEffect");require("@babylonjs/core/Rendering/depthRendererSceneComponent");var O=require("@babylonjs/core/Misc/assetsManager");function E(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 R(e,t,i,n){Object.defineProperty(e,t,{get:i,set:n,enumerable:!0,configurable:!0})}var S={};let F;var I;let B;var D;R(S,"ProductCameraRig",(()=>F)),R(S,"MaterialEffectMode",(()=>B)),(I=F||(F={}))[I.Orbit=0]="Orbit",I[I.Pan=1]="Pan",(D=B||(B={})).None="None",D.RemoveWhenSelected="RemoveWhenSelected",D.ApplyWhenSelected="ApplyWhenSelected";var q={};R(q,"SpiffCommerce3DPreviewService",(()=>he)),R(q,"createBaseModel",(()=>de));const j=new Map;async function k(e,t,i){return new Promise(((n,a)=>{const r=j.get(e);if(r&&r.scene.uid===t.uid)return n(r);o.SceneLoader.LoadAssetContainerAsync(e,void 0,t,i).then((t=>{j.set(e,t),n(t)})).catch(a)}))}function N(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class V{constructor(e){N(this,"customOptions",void 0),N(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()})),N(this,"highlightColorFromConfig",(()=>this.customOptions&&this.customOptions.highlightColor?this.hexToColor4(this.customOptions.highlightColor):new(0,h.Color4)(.98,.98,.98,1).toLinearSpace())),N(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 z={};R(z,"RenderingConfiguration",(()=>H)),R(z,"REFLECTION_PROBE_RESOLUTION",(()=>_)),R(z,"renderingPipelineDefaults",(()=>G));class H{static getDynamicTextureResolution(){return this.getIsMobile()||!H.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 _=128,G={antiAliasing:{samples:4,fxaaEnabled:!1},bloom:{enabled:!1,kernel:64,scale:.5,threshold:.9,weight:.15},chromaticAberration:{enabled:!1,aberrationAmount:30,direction:{x:0,y:0},radialIntensity:0},colorCurves:{enabled:!1},depthOfField:{enabled:!1,blurLevel:"Low",focalLength:50,focusDistance:2e3,fStop:1.4,lensSize:50},grain:{enabled:!1,animated:!1,intensity:30},misc:{contrast:1,exposure:1,toneMappingEnabled:!1,toneMappingType:"Standard"},sharpen:{enabled:!1,colorAmount:1,edgeAmount:.3},vignette:{enabled:!1,blendMode:"Multiply",cameraFov:.5,center:{x:0,y:0},colorHex:"#000000ff",colorRgba:{r:0,g:0,b:0,a:1},stretch:0,weight:1}};function U(e,t,n){t.forEach((t=>{const a=t.getID(),r=t.getName(),o=H.getDynamicTextureResolution();e.materials.filter((e=>e.name===r)).forEach((s=>{const l=n.get(a);if(l)W(s,l),l.update(false);else{const l=function(e,t,n,a){const r=new(0,c.DynamicTexture)(e,{width:n,height:a},t,H.shouldMipMap(),f.Texture.TRILINEAR_SAMPLINGMODE,i.Engine.TEXTUREFORMAT_RGBA),o=r.getContext();o&&(o.fillStyle="#f5f5f5",o.fillRect(0,0,n,a),r.update());return r}(r,e,o.width,o.height);n.set(a,l),t.setStaticContext(l.getContext()),W(s,l),l.onLoadObservable.addOnce((()=>{l.update(false)}))}}))}))}function W(e,t){if(e instanceof s.PBRMaterial){const i=e,n=i.albedoTexture;n?(t.wrapU=n.wrapU,t.wrapV=n.wrapV):(t.wrapU=1,t.wrapV=1),i.albedoTexture=t}else{const i=e,n=i.diffuseTexture;n&&(t.wrapU=n.wrapU,t.wrapV=n.wrapV),i.diffuseTexture=t}}function K(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class Y{constructor(e){K(this,"name",void 0),K(this,"enabled",void 0),K(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 n=t.extras[i];e.metadata[i]=n})),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 s.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.volumeIndexOfRefraction=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 n=i.metadata;n&&(n.mirrorTexture&&function(i,n=1){const a=i.material;if(!a)return;const r=new(0,v.MirrorTexture)("mirror",H.getMirrorTextureResolution(),e,!0);r.renderList=t(e);const o=i.getVerticesData("normal");if(!o)throw new Error("Mirror attribute specified on: "+i.name+"But no normals exist to generate a mirror from!");i.computeWorldMatrix(!0);const s=i.getWorldMatrix(),l=y.Vector3.TransformNormal(new(0,y.Vector3)(o[0],o[1],o[2]),s).normalize(),c=y.Plane.FromPositionAndNormal(i.position,l.scale(-1));r.mirrorPlane=c,r.level=n,a.reflectionTexture=r}(i,n.mirrorTexture),n.reflectionProbe&&function(i){const n=i.material,a=new(0,P.ReflectionProbe)("probe-"+n.name,_,e);a.attachToMesh(i),a.renderList&&a.renderList.push(...t(e)),n.reflectionTexture=a.cubeTexture}(i))}))}}function Q(e,t,i,n){const a=e.animationGroups,r=e=>e.targetedAnimations.map((e=>e.animation.framePerSecond)).reduce(((e,t)=>e+t),0)/e.targetedAnimations.length||0;void 0===n||void 0===i||n!==i?a.forEach((e=>{e.stop();const a=r(e);e.start(t,1,n*a,i*a)})):a.forEach((e=>{e.stop();const i=r(e),a=n*i;e.start(t,1,a,a)}))}function Z(e){e.animationGroups.forEach((e=>{e.stop()}))}function X(e,t,i){var n,a,r;e.stopAnimation(t),t.animations=[],Math.abs(t.alpha)>2*Math.PI&&(t.alpha=(n=t.alpha,a=0,r=2*Math.PI,n<a?r-(a-n)%(r-a):a+(n-a)%(r-a)));const o=[],s=i.target,l=s?1:0;if(i.target&&Object.keys(i.target).length>0&&o.push(J("cameraTargetLerp","target",(new(0,d.Vector3)).copyFrom(t.target),new(0,d.Vector3)(i.target.x,i.target.y,i.target.z),w.Animation.ANIMATIONTYPE_VECTOR3,0)),o.push(J("cameraAlphaLerp","alpha",t.alpha,$(i.lonDeg),w.Animation.ANIMATIONTYPE_FLOAT,l)),o.push(J("cameraBetaLerp","beta",t.beta,$(i.latDeg),w.Animation.ANIMATIONTYPE_FLOAT,l)),void 0!==i.radius){const e=Math.max(.01,i.radius);o.push(J("cameraRadiusLerp","radius",t.radius,e,w.Animation.ANIMATIONTYPE_FLOAT,l))}t.animations.push(...o);const c=t.useAutoRotationBehavior;t.disableAutoRotationBehavior(),e.beginAnimation(t,0,s?120:60,!1,1,(()=>{t.animations=[],c&&t.enableAutoRotationBehavior()}))}function $(e){return e*Math.PI/180}function J(e,t,i,n,a,r=0,o=w.Animation.ANIMATIONLOOPMODE_CONSTANT){const s=new(0,x.QuadraticEase);s.setEasingMode(x.EasingFunction.EASINGMODE_EASEINOUT);const l=new(0,w.Animation)(e,t,60,a,o),c=[];return r>0&&c.push({frame:0,value:i}),c.push({frame:60*r,value:i}),c.push({frame:60*(r+1),value:n}),l.setKeys(c),l.setEasingFunction(s),l}class ee extends M.ArcRotateCamera{constructor(e,t,i,n,a,r,o,s){var l,c,h;super(e,t,i,n,a,r,s),l=this,c="lastFocus",h=new(0,d.Vector3)(0,0,0),c in l?Object.defineProperty(l,c,{value:h,enumerable:!0,configurable:!0,writable:!0}):l[c]=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=te(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=te(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=te(e),n=i.max.subtract(i.min),a=i.min.add(n.scale(.5)),r=new ee("ProductCamera",-Math.PI/2,Math.PI/2,1.5*n.length(),a,e,t);return r.panningInertia=0,r.panningOriginTarget.copyFrom(a),r.onAfterCheckInputsObservable.add((()=>{r.panningSensibility=1e3/n.length()})),e.activeCamera=r,r}}function te(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))))}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}class ne{constructor(e,t=!0,i=null){ie(this,"renderingPipeline",void 0),ie(this,"currentConfiguration",void 0),this.renderingPipeline=new(0,T.DefaultRenderingPipeline)("default",t,e,i?[i]:void 0,!1),this.renderingPipeline.isSupported&&this.renderingPipeline.prepare()}dispose(){this.renderingPipeline.dispose()}addCamera(e){this.renderingPipeline.isSupported&&this.renderingPipeline.addCamera(e)}removeCamera(e){this.renderingPipeline.isSupported&&this.renderingPipeline.removeCamera(e)}getConfiguration(){return this.currentConfiguration}setConfiguration(e){if(this.renderingPipeline.isSupported){if(this.renderingPipeline.samples=e.antiAliasing?.samples??G.antiAliasing.samples,this.renderingPipeline.fxaaEnabled=e.antiAliasing?.fxaaEnabled??G.antiAliasing.fxaaEnabled,this.renderingPipeline.bloomEnabled=e.bloom?.enabled??G.bloom.enabled,this.renderingPipeline.bloomKernel=e.bloom?.kernel??G.bloom.kernel,this.renderingPipeline.bloomScale=e.bloom?.scale??G.bloom.scale,this.renderingPipeline.bloomThreshold=e.bloom?.threshold??G.bloom.threshold,this.renderingPipeline.bloomWeight=e.bloom?.weight??G.bloom.weight,this.renderingPipeline.chromaticAberrationEnabled=e.chromaticAberration?.enabled??G.chromaticAberration.enabled,this.renderingPipeline.chromaticAberration.aberrationAmount=e.chromaticAberration?.aberrationAmount??G.chromaticAberration.aberrationAmount,this.renderingPipeline.chromaticAberration.radialIntensity=e.chromaticAberration?.radialIntensity??G.chromaticAberration.radialIntensity,this.renderingPipeline.chromaticAberration.direction=e.chromaticAberration?.direction?new(0,d.Vector2)(e.chromaticAberration.direction.x,e.chromaticAberration.direction.y):new(0,d.Vector2)(G.chromaticAberration.direction.x,G.chromaticAberration.direction.y),this.renderingPipeline.imageProcessing.colorCurvesEnabled=e.colorCurves?.enabled??G.colorCurves.enabled,this.renderingPipeline.imageProcessing.colorCurves=e.colorCurves?this.updateColorCurve(e.colorCurves):new(0,C.ColorCurves),this.renderingPipeline.depthOfFieldEnabled=e.depthOfField?.enabled??G.depthOfField.enabled,e.depthOfField)switch(e.depthOfField.blurLevel??G.depthOfField.blurLevel){case"Low":this.renderingPipeline.depthOfFieldBlurLevel=L.DepthOfFieldEffectBlurLevel.Low;break;case"Medium":this.renderingPipeline.depthOfFieldBlurLevel=L.DepthOfFieldEffectBlurLevel.Medium;break;case"High":this.renderingPipeline.depthOfFieldBlurLevel=L.DepthOfFieldEffectBlurLevel.High}if(this.renderingPipeline.depthOfField.focalLength=e.depthOfField?.focalLength??G.depthOfField.focalLength,this.renderingPipeline.depthOfField.fStop=e.depthOfField?.fStop??G.depthOfField.fStop,this.renderingPipeline.depthOfField.focusDistance=e.depthOfField?.focusDistance??G.depthOfField.focusDistance,this.renderingPipeline.depthOfField.lensSize=e.depthOfField?.lensSize??G.depthOfField.lensSize,this.renderingPipeline.grainEnabled=e.grain?.enabled??G.grain.enabled,this.renderingPipeline.grain.animated=e.grain?.animated??G.grain.animated,this.renderingPipeline.grain.intensity=e.grain?.intensity??G.grain.intensity,this.renderingPipeline.imageProcessing.contrast=e.misc?.contrast??G.misc.contrast,this.renderingPipeline.imageProcessing.exposure=e.misc?.exposure??G.misc.exposure,this.renderingPipeline.imageProcessing.toneMappingEnabled=e.misc?.toneMappingEnabled??G.misc.toneMappingEnabled,this.renderingPipeline.imageProcessing.toneMappingEnabled)switch(e.misc.toneMappingType??G.misc.toneMappingType){case"Standard":this.renderingPipeline.imageProcessing.toneMappingType=A.ImageProcessingConfiguration.TONEMAPPING_STANDARD;break;case"ACES":this.renderingPipeline.imageProcessing.toneMappingType=A.ImageProcessingConfiguration.TONEMAPPING_ACES}if(this.renderingPipeline.sharpenEnabled=e.sharpen?.enabled??G.sharpen.enabled,this.renderingPipeline.sharpen.colorAmount=e.sharpen?.colorAmount??G.sharpen.colorAmount,this.renderingPipeline.sharpen.edgeAmount=e.sharpen?.edgeAmount??G.sharpen.edgeAmount,this.renderingPipeline.imageProcessing.vignetteEnabled=e.vignette?.enabled??G.vignette.enabled,e.vignette?.center?(this.renderingPipeline.imageProcessing.vignetteCenterX=e.vignette.center.x,this.renderingPipeline.imageProcessing.vignetteCenterY=e.vignette.center.y):(this.renderingPipeline.imageProcessing.vignetteCenterX=G.vignette.center.x,this.renderingPipeline.imageProcessing.vignetteCenterY=G.vignette.center.y),e.vignette)switch(e.vignette?.blendMode??G.vignette.blendMode){case"Multiply":this.renderingPipeline.imageProcessing.vignetteBlendMode=A.ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;break;case"Opaque":this.renderingPipeline.imageProcessing.vignetteBlendMode=A.ImageProcessingConfiguration.VIGNETTEMODE_OPAQUE}e.vignette?.colorRgba?this.renderingPipeline.imageProcessing.vignetteColor=new(0,h.Color4)(e.vignette.colorRgba.r,e.vignette.colorRgba.g,e.vignette.colorRgba.b,e.vignette.colorRgba.a):e.vignette?.colorHex?this.renderingPipeline.imageProcessing.vignetteColor=h.Color4.FromHexString(e.vignette.colorHex):this.renderingPipeline.imageProcessing.vignetteColor=new(0,h.Color4)(G.vignette.colorRgba.r,G.vignette.colorRgba.g,G.vignette.colorRgba.b,G.vignette.colorRgba.a),this.renderingPipeline.imageProcessing.vignetteStretch=e.vignette?.stretch??G.vignette.stretch,this.renderingPipeline.imageProcessing.vignetteWeight=e.vignette?.weight??G.vignette.weight,this.renderingPipeline.prepare(),this.currentConfiguration=e}}updateColorCurve(e){const t=new(0,C.ColorCurves);return t.globalDensity=e.globalDensity??t.globalDensity,t.globalExposure=e.globalExposure??t.globalExposure,t.globalHue=e.globalHue??t.globalHue,t.globalSaturation=e.globalSaturation??t.globalSaturation,t.highlightsDensity=e.highlightsDensity??t.highlightsDensity,t.highlightsExposure=e.highlightsExposure??t.highlightsExposure,t.highlightsHue=e.highlightsHue??t.highlightsHue,t.highlightsSaturation=e.highlightsSaturation??t.highlightsSaturation,t.midtonesDensity=e.midtonesDensity??t.midtonesDensity,t.midtonesExposure=e.midtonesExposure??t.midtonesExposure,t.midtonesHue=e.midtonesHue??t.midtonesHue,t.midtonesSaturation=e.midtonesSaturation??t.midtonesSaturation,t.shadowsDensity=e.shadowsDensity??t.shadowsDensity,t.shadowsExposure=e.shadowsExposure??t.shadowsExposure,t.shadowsHue=e.shadowsHue??t.shadowsHue,t.shadowsSaturation=e.shadowsSaturation??t.shadowsSaturation,t}}const ae={albedoTexture:"albedoMap",bumpTexture:"normalMap",ambientTexture:"ambientMap",emissiveTexture:"emissionMap",opacityTexture:"alphaMap",metallicTexture:"metallicMap",refractionTexture:"refractionMap"};function re(e,t,i,n){["albedoTexture","bumpTexture","ambientTexture","emissiveTexture","opacityTexture","metallicTexture","refractionTexture"].forEach((a=>{!function(e,t,i,n,a){const r=ae[e];if(!r)throw new Error("Unexpected texture name encountered.");const o=t[r]?.fileLink;o?n.addTextureTask(e,o,!1,!1):a&&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))}(a,e,t,i,n)})),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 oe(e,t,i,n){"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]=n}function se(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class le{constructor(){se(this,"materialVariantMap",new Map),se(this,"keysThatRemovedBaseModel",[]),se(this,"loadedContainerForKey",new Map)}async applyMaterial(e,t,i,n,a){return new Promise((r=>{const o=e.materials.filter((e=>e.name===t)),s=this.materialVariantMap.get(t);if(this.materialVariantMap.set(t,{...s,...i}),0===o.length)return void r(void 0);const l=new(0,O.AssetsManager)(e);l.useDefaultLoadingScreen=!1,o.forEach((e=>re(i,e,l,a))),l.onProgress=(e,t,i)=>{n&&n(e/t*100,100,i.name)},l.onFinish=e=>{e.forEach((e=>{const t=e;n&&n(100,100,e.name),o.forEach((n=>oe(e.name,n,i,t.texture)))})),r(void 0)},l.loadAsync()}))}async applyModel(e,t,i,n,a){if(n&&i&&!this.keysThatRemovedBaseModel.includes(t)&&this.keysThatRemovedBaseModel.push(t),!n){const i=this.keysThatRemovedBaseModel.includes(t);return this.loadedContainerForKey.get(t)?.removeAllFromScene(),e&&i&&await de(e.metadata.baseModel,e),Promise.resolve()}const r=await k(n,e,a);if(this.loadedContainerForKey.has(t)&&this.loadedContainerForKey.get(t)?.removeAllFromScene(),i){(await k(e.metadata.baseModel,e)).removeAllFromScene()}r.addAllToScene(),this.loadedContainerForKey.set(t,r);const o=[];this.materialVariantMap.forEach((async(t,i)=>{o.push(this.applyMaterial(e,i,t))})),await Promise.all(o)}}function ce(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 Y(e)})),o.SceneLoader.OnPluginActivatedObservable.add((e=>{if("gltf"===e.name){e.transparencyAsCoverage=!0}}));class he{constructor(e){ce(this,"engine",void 0),ce(this,"scene",void 0),ce(this,"configuration",void 0),ce(this,"loadProgress",new Map([["initialScene",0]])),ce(this,"materialReadyToLoadCallbacks",new Map),ce(this,"modelReadyToLoadCallbacks",new Map),ce(this,"queuedModelAnimation",void 0),ce(this,"queuedCameraAnimation",void 0),ce(this,"focusLostNotified",!1),ce(this,"loadObservable",new(0,g.Observable)),ce(this,"focusLostObservable",new(0,g.Observable)),ce(this,"dynamicTextures",new Map),ce(this,"highlightLayer",void 0),ce(this,"variantManager",new le),ce(this,"renderingPipeline",void 0);const t=e?.noRender?void 0:document.createElement("canvas");this.configuration=new V(e);u.DracoCompression.Configuration={decoder:{wasmUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.6/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.6/draco_decoder_gltf.wasm",fallbackUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.6/draco_decoder_gltf.js"}},t&&(t.getContext("webgl2")||t.getContext("webgl"));const a=console.log;console.log=()=>{};const r=t?new(0,i.Engine)(t,!0,{adaptToDeviceRatio:!0,limitDeviceRatio:2,premultipliedAlpha:!1,preserveDrawingBuffer:!!e?.backgroundImage,audioEngine:!1,stencil:this.configuration.highlights.enabled,forceSRGBBufferSupportState:!0}):new(0,n.NullEngine);console.log=a,r.hideLoadingUI(),window.addEventListener("resize",this.fireResizeEvent.bind(this)),this.engine=r,this.scene=new(0,p.Scene)(r),this.renderingPipeline=new ne(this.scene,!0),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(F.Pan),this.reattachControls(e)}getNumViewports(){return this.engine.views?.length||0}unregisterView(e){this.engine.unRegisterView(e)}shutdown(){this.renderingPipeline.dispose(),this.engine&&this.engine.dispose(),window.removeEventListener("resize",this.fireResizeEvent)}getSceneInitializationProgress(){return this.loadProgress.get("initialScene")}async initialize(i,n){if(this.scene.clearColor=this.configuration.scene.clearColor,this.scene.metadata={baseModel:i},this.scene.environmentTexture=l.CubeTexture.CreateFromPrefilteredData(this.configuration.scene.environmentFile,this.scene),i){const e=100;await de(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 r=ee.create(this.scene,this.configuration);this.renderingPipeline.addCamera(r),this.configuration.options?.renderingPipelineConfiguration&&this.renderingPipeline.setConfiguration(this.configuration.options.renderingPipelineConfiguration);const o=n?.getAll()||new Map;U(this.scene,o,this.dynamicTextures);if(this.scene.materials.some((e=>"emissiveTexture"in e&&null!==e.emissiveTexture))){new(0,a.GlowLayer)("GlowLayer",this.scene).intensity=.5}Z(this.scene),this.engine.views?.length>=1&&this.reattachControls(this.engine.views[this.engine.views.length-1].target),await this.processQueuedLoadEvents(),this.engine.runRenderLoop((()=>{this.engine.views&&(o.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(),r.target.equalsWithEpsilon(r.lastFocus,.1)||this.focusLostNotified||(this.focusLostObservable.notifyObservers(void 0),this.focusLostNotified=!0))}))}executeModelAnimation(e){100===this.getSceneInitializationProgress()?Q(this.scene,e.loop,e.to,e.from):this.queuedModelAnimation=e}executeCameraAnimation(e){100===this.getSceneInitializationProgress()&&this.scene.activeCamera?X(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,d.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,n){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()}),n);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 s.PBRMaterial&&!(e.albedoTexture instanceof c.DynamicTexture);e.dispose(!1,t)}})),U(this.scene,t.contextService.getAll(),this.dynamicTextures),Z(this.scene)):this.modelReadyToLoadCallbacks.set(e,(async()=>{await this.applyModelVariant(e,t,i)}))}getQueuedMaterialVariants(){return this.materialReadyToLoadCallbacks.size}getQueuedModelVariants(){return this.modelReadyToLoadCallbacks.size}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===F.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 n;(n=i).getScene().stopAnimation(n),n.animations=[];const a=i.alpha,r=i.beta,o=i.radius,s=t.latDeg*Math.PI/180,l=t.lonDeg*Math.PI/180;i.alpha=l,i.beta=s,i.radius=t.radius||i.radius;const c=await m.Tools.CreateScreenshotUsingRenderTargetAsync(this.engine,i,e,"image/png",2,!0);return i.alpha=a,i.beta=r,i.radius=o,c}orbitEnabled(){const e=this.configuration;if(!e)return!0;const t=e.camera.limits.min.alpha,i=e.camera.limits.max.alpha,n=e.camera.limits.min.beta,a=e.camera.limits.max.beta;if(void 0===t||void 0===i||void 0===n||void 0===a)return!0;const r=[n,a],o=[t,i].every((e=>e===t)),s=r.every((e=>e===n));return!o&&!s}fireResizeEvent(){this.getNumViewports()>0&&this.engine.resize()}onMaterialSelected(i){this.scene.meshes.forEach((n=>{"targetcube_t"!==n.name&&"backgroundShell"!==n.name&&(n.actionManager||(n.actionManager=new(0,e.ActionManager)(this.scene)),n.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,r.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"))))}))}setRenderingPipelineConfiguration(e){this.renderingPipeline&&this.renderingPipeline.setConfiguration(e)}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 processQueuedLoadEvents(){await Promise.all(Array.from(this.modelReadyToLoadCallbacks.values()).map((e=>e(this.scene)))),this.modelReadyToLoadCallbacks.clear(),this.materialReadyToLoadCallbacks.forEach(((e,t)=>{e.forEach(((e,i)=>{this.applyMaterialVariant(t,i,e)}))})),this.materialReadyToLoadCallbacks.clear(),this.queuedModelAnimation&&(this.executeModelAnimation(this.queuedModelAnimation),this.queuedModelAnimation=void 0),this.queuedCameraAnimation&&(this.executeCameraAnimation(this.queuedCameraAnimation),this.queuedCameraAnimation=void 0)}}async function de(e,t,i){(await k(e,t,i)).addAllToScene()}E(module.exports,S),E(module.exports,q),E(module.exports,z);
1
+ var e=require("@babylonjs/core/Engines/engine"),t=require("@babylonjs/core/Engines/nullEngine"),i=require("@babylonjs/core/Layers/highlightLayer"),a=require("@babylonjs/core/Loading/sceneLoader"),r=require("@babylonjs/core/Materials/Textures/cubeTexture"),n=require("@babylonjs/core/Maths/math.color"),s=require("@babylonjs/core/Maths/math.vector"),o=require("@babylonjs/core/Meshes/Compression/dracoCompression"),l=require("@babylonjs/core/Misc/observable"),c=require("@babylonjs/core/Misc/tools"),h=require("@babylonjs/core/scene"),d=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 u=require("@babylonjs/core/Materials/PBR/pbrMaterial"),g=require("@babylonjs/core/Materials/Textures/mirrorTexture"),m=require("@babylonjs/core/Maths/math"),p=require("@babylonjs/core/Probes/reflectionProbe"),b=require("@babylonjs/core/Actions/actionManager"),f=require("@babylonjs/core/Actions/directActions"),v=require("@babylonjs/core/Layers/glowLayer"),y=require("@babylonjs/core/Meshes/transformNode"),P=require("@babylonjs/core/Materials/Textures/dynamicTexture"),M=require("@babylonjs/core/Materials/Textures/texture"),w=require("@babylonjs/core/Animations/animation"),C=require("@babylonjs/core/Animations/easing"),x=require("@babylonjs/core/Misc/assetsManager"),O=require("@babylonjs/core/Cameras/arcRotateCamera"),A=require("@babylonjs/core/Materials/colorCurves"),T=require("@babylonjs/core/Materials/imageProcessingConfiguration"),L=require("@babylonjs/core/PostProcesses/RenderPipeline"),R=require("@babylonjs/core/PostProcesses/depthOfFieldEffect");function E(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 S(e,t,i,a){Object.defineProperty(e,t,{get:i,set:a,enumerable:!0,configurable:!0})}require("@babylonjs/core/Rendering/depthRendererSceneComponent");var I={};let F;var D;let k;var B;S(I,"ProductCameraRig",(()=>F)),S(I,"MaterialEffectMode",(()=>k)),(D=F||(F={}))[D.Orbit=0]="Orbit",D[D.Pan=1]="Pan",(B=k||(k={})).None="None",B.RemoveWhenSelected="RemoveWhenSelected",B.ApplyWhenSelected="ApplyWhenSelected";var V={};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}S(V,"SpiffCommerce3DPreviewService",(()=>be));class q{constructor(e){z(this,"customOptions",void 0),z(this,"getSceneClearColor",(()=>{const e=this.customOptions?.transparentBackground||this.customOptions?.backgroundImage?0:1;if(this.customOptions&&this.customOptions?.transparentBackground||this.customOptions?.backgroundImage)return new(0,n.Color4)(0,0,0,e).toLinearSpace();if(this.customOptions&&this.customOptions.backgroundColor){const t=n.Color3.FromHexString(this.customOptions.backgroundColor);return new(0,n.Color4)(t.r,t.g,t.b,e).toLinearSpace()}return new(0,n.Color4)(.98,.98,.98,e).toLinearSpace()})),z(this,"highlightColorFromConfig",(()=>this.customOptions&&this.customOptions.highlightColor?this.hexToColor4(this.customOptions.highlightColor):new(0,n.Color4)(.98,.98,.98,1).toLinearSpace())),z(this,"hexToColor4",((e,t=1)=>{const i=n.Color3.FromHexString(e);return new(0,n.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 j={};S(j,"RenderingConfiguration",(()=>N)),S(j,"REFLECTION_PROBE_RESOLUTION",(()=>H)),S(j,"renderingPipelineDefaults",(()=>_));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 H=128,_={antiAliasing:{samples:4,fxaaEnabled:!1},bloom:{enabled:!1,kernel:64,scale:.5,threshold:.9,weight:.15},chromaticAberration:{enabled:!1,aberrationAmount:30,direction:{x:0,y:0},radialIntensity:0},colorCurves:{enabled:!1},depthOfField:{enabled:!1,blurLevel:"Low",focalLength:50,focusDistance:2e3,fStop:1.4,lensSize:50},grain:{enabled:!1,animated:!1,intensity:30},misc:{contrast:1,exposure:1,toneMappingEnabled:!1,toneMappingType:"Standard"},sharpen:{enabled:!1,colorAmount:1,edgeAmount:.3},vignette:{enabled:!1,blendMode:"Multiply",cameraFov:.5,center:{x:0,y:0},colorHex:"#000000ff",colorRgba:{r:0,g:0,b:0,a:1},stretch:0,weight:1}};function G(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){G(this,"name",void 0),G(this,"enabled",void 0),G(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)}))}async loadMaterialPropertiesAsync(e,t,i){await this.loader.loadMaterialPropertiesAsync(e,t,i),this.enableMaterialExtrasIfRequired(t,i)}dispose(){}enableMaterialExtrasIfRequired(e,t){if(e.extras&&t instanceof u.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,m.Color3)(e.extras.translucencyR,e.extras.translucencyG,e.extras.translucencyB))}if(e.extras.refractionIOR){const i=t;i.subSurface.isRefractionEnabled=!0,i.subSurface.volumeIndexOfRefraction=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,g.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(),l=m.Vector3.TransformNormal(new(0,m.Vector3)(s[0],s[1],s[2]),o).normalize(),c=m.Plane.FromPositionAndNormal(i.position,l.scale(-1));n.mirrorPlane=c,n.level=a,r.reflectionTexture=n}(i,a.mirrorTexture),a.reflectionProbe&&function(i){const a=i.material,r=new(0,p.ReflectionProbe)("probe-"+a.name,H,e);r.attachToMesh(i),r.renderList&&r.renderList.push(...t(e)),a.reflectionTexture=r.cubeTexture}(i))}))}}const W=new Map;async function K(e,t,i){return new Promise(((r,n)=>{const s=W.get(e);if(s&&s.scene.uid===t.uid)return r(s);a.SceneLoader.LoadAssetContainerAsync(e,void 0,t,i).then((t=>{W.set(e,t),r(t)})).catch(n)}))}function Q(t,i,a,r,n=""){a.forEach((a=>{const s=a.getID(),o=a.getName(),l=N.getDynamicTextureResolution();t.filter((e=>e.name===n+o)).forEach((t=>{const n=r.get(s);if(n)Y(t,n),n.update(false);else{const n=function(t,i,a,r){const n=new(0,P.DynamicTexture)(t,{width:a,height:r},i,N.shouldMipMap(),M.Texture.TRILINEAR_SAMPLINGMODE,e.Engine.TEXTUREFORMAT_RGBA),s=n.getContext();s&&(s.fillStyle="#f5f5f5",s.fillRect(0,0,a,r),n.update());return n}(o,i,l.width,l.height);r.set(s,n),a.setStaticContext(n.getContext()),Y(t,n),n.onLoadObservable.addOnce((()=>{n.update(false)}))}}))}))}function Y(e,t){if(e instanceof u.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(){const e=()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1);return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()}function $(e,t,i,a){const r=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?e.forEach((e=>{e.stop();const n=r(e);e.start(t,1,a*n,i*n)})):e.forEach((e=>{e.stop();const i=r(e),n=a*i;e.start(t,1,n,n)}))}function X(e){e.forEach((e=>{e.stop()}))}function J(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 o=[],l=i.target,c=l?1:0;if(i.target&&Object.keys(i.target).length>0&&o.push(te("cameraTargetLerp","target",(new(0,s.Vector3)).copyFrom(t.target),new(0,s.Vector3)(i.target.x,i.target.y,i.target.z),w.Animation.ANIMATIONTYPE_VECTOR3,0)),o.push(te("cameraAlphaLerp","alpha",t.alpha,ee(i.lonDeg),w.Animation.ANIMATIONTYPE_FLOAT,c)),o.push(te("cameraBetaLerp","beta",t.beta,ee(i.latDeg),w.Animation.ANIMATIONTYPE_FLOAT,c)),void 0!==i.radius){const e=Math.max(.01,i.radius);o.push(te("cameraRadiusLerp","radius",t.radius,e,w.Animation.ANIMATIONTYPE_FLOAT,c))}t.animations.push(...o);const h=t.useAutoRotationBehavior;t.disableAutoRotationBehavior(),e.beginAnimation(t,0,l?120:60,!1,1,(()=>{t.animations=[],h&&t.enableAutoRotationBehavior()}))}function ee(e){return e*Math.PI/180}function te(e,t,i,a,r,n=0,s=w.Animation.ANIMATIONLOOPMODE_CONSTANT){const o=new(0,C.QuadraticEase);o.setEasingMode(C.EasingFunction.EASINGMODE_EASEINOUT);const l=new(0,w.Animation)(e,t,60,r,s),c=[];return n>0&&c.push({frame:0,value:i}),c.push({frame:60*n,value:i}),c.push({frame:60*(n+1),value:a}),l.setKeys(c),l.setEasingFunction(o),l}const ie={albedoTexture:"albedoMap",bumpTexture:"normalMap",ambientTexture:"ambientMap",emissiveTexture:"emissionMap",opacityTexture:"alphaMap",metallicTexture:"metallicMap",refractionTexture:"refractionMap"};function ae(e,t,i,a){["albedoTexture","bumpTexture","ambientTexture","emissiveTexture","opacityTexture","metallicTexture","refractionTexture"].forEach((r=>{!function(e,t,i,a,r){const n=ie[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===k.RemoveWhenSelected?(t.clearCoat.isEnabled=!1,t.clearCoat.indexOfRefraction=1.5):e.clearCoat===k.ApplyWhenSelected&&(t.clearCoat.isEnabled=!0,t.clearCoat.indexOfRefraction=e.clearCoatIOR||t.clearCoat.indexOfRefraction)}(e,t)}function re(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 ne(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class se{constructor(e,t,i){ne(this,"materialVariantMap",new Map),ne(this,"keysThatRemovedBaseModel",[]),ne(this,"loadedContainerForKey",new Map),ne(this,"loadedMaterialsForKey",new Map),ne(this,"scene",void 0),ne(this,"renameClonedAsset",void 0),ne(this,"setBaseModelEnabled",void 0),this.scene=e,this.renameClonedAsset=t,this.setBaseModelEnabled=i}async applyMaterial(e,t,i,a){return new Promise((r=>{e=this.renameClonedAsset(e);const n=this.scene.materials.filter((t=>t.name===e)),s=this.materialVariantMap.get(e);if(this.materialVariantMap.set(e,{...s,...t}),0===n.length)return void r(void 0);const o=new(0,x.AssetsManager)(this.scene);o.useDefaultLoadingScreen=!1,n.forEach((e=>ae(t,e,o,a))),o.onProgress=(e,t,a)=>{i&&i(e/t*100,100,a.name)},o.onFinish=e=>{e.forEach((e=>{const a=e;i&&i(100,100,e.name),n.forEach((i=>re(e.name,i,t,a.texture)))})),r(void 0)},o.loadAsync()}))}async applyModel(e,t,i,a){if(i&&t&&!this.keysThatRemovedBaseModel.includes(e)&&this.keysThatRemovedBaseModel.push(e),!i)return this.keysThatRemovedBaseModel.includes(e)&&this.setBaseModelEnabled(!0),this.loadedContainerForKey.get(e)?.dispose(),this.loadedMaterialsForKey.delete(e),Promise.resolve(void 0);this.loadedContainerForKey.has(e)&&(this.loadedContainerForKey.get(e)?.dispose(),this.loadedMaterialsForKey.delete(e)),t&&this.setBaseModelEnabled(!1);const r=(await K(i,this.scene,a)).instantiateModelsToScene(this.renameClonedAsset,!0);this.loadedContainerForKey.set(e,r),this.loadedMaterialsForKey.set(e,oe(r));const n=[];return this.materialVariantMap.forEach((async(e,t)=>{n.push(this.applyMaterial(t,e))})),await Promise.all(n),r}getAllMaterials(){const e=[];return this.loadedMaterialsForKey.forEach((t=>{t.forEach((t=>{e.includes(t)||e.push(t)}))})),e}}function oe(e){const t=[];return e.rootNodes.forEach((e=>{e.getChildMeshes().forEach((e=>{e.material&&t.push(e.material),e.subMeshes&&e.subMeshes.forEach((e=>{const i=e.getMaterial(!1);i&&t.push(i)}))}))})),t}function le(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class ce{constructor(e){le(this,"id",void 0),le(this,"previewService",void 0),le(this,"scene",void 0),le(this,"variantManager",void 0),le(this,"materialSelectedObservable",new(0,l.Observable)),le(this,"materialDeselectedObservable",new(0,l.Observable)),le(this,"materialVariantObservable",new(0,l.Observable)),le(this,"modelVariantObservable",new(0,l.Observable)),le(this,"queuedModelAnimation",void 0),le(this,"materialReadyToLoadCallbacks",new Map),le(this,"modelReadyToLoadCallbacks",new Map),le(this,"dynamicTextures",new Map),le(this,"assetContainer",void 0),le(this,"canvasPanels",void 0),le(this,"contextService",void 0),le(this,"importPromise",void 0),le(this,"initialized",!1),le(this,"materials",[]),le(this,"modelInstance",void 0),le(this,"transformRoot",void 0);const{modelDetails:t,previewService:i,progressHandler:a,scene:r}=e;this.contextService=t.contextService,this.id=Z(),this.previewService=i,this.scene=r,this.variantManager=new se(r,this.renameClonedAsset.bind(this),this.setEnabled.bind(this)),this.previewService.registerInitializedListener((async()=>await this.processQueuedEvents()));this.importPromise=(async()=>{this.assetContainer=await K(t.model,r,a),this.initialized=!0,this.transformRoot=new(0,y.TransformNode)("root",this.scene),this.instantiate()})()}async applyMaterialVariant(e,t,i,a){if(100===this.previewService.getSceneInitializationProgress()&&this.initialized)await this.variantManager.applyMaterial(e,i,((e,t,i)=>{this.materialVariantObservable.notifyObservers({remainingCount:e,totalCount:t,taskName:i})}),a);else if(this.materialReadyToLoadCallbacks.has(e)){this.materialReadyToLoadCallbacks.get(e)?.set(t,this.applyMaterialVariant.bind(this,e,t,i,a))}else{this.materialReadyToLoadCallbacks.set(e,new Map);this.materialReadyToLoadCallbacks.get(e)?.set(t,this.applyMaterialVariant.bind(this,e,t,i,a))}}async applyModelVariant(e,t,i){if(100!==this.previewService.getSceneInitializationProgress()||!this.initialized)return void this.modelReadyToLoadCallbacks.set(e,this.applyModelVariant.bind(this,e,t,i));const a=await this.variantManager.applyModel(e,i,t?.model,(t=>{this.modelVariantObservable.notifyObservers({...t,key:e})}));this.modelInstance&&X(this.modelInstance.animationGroups),this.contextService||(this.contextService=t?.contextService),a&&this.configureModelInstance(a)}executeAnimation(e){100===this.previewService.getSceneInitializationProgress()?this.modelInstance&&$(this.modelInstance.animationGroups,e.loop,e.to,e.from):this.queuedModelAnimation=e}getId(){return this.id}listMaterials(){const e=this.scene?.materials.filter((e=>e.name.startsWith(this.id)));return e?e.map((e=>({id:e.id,name:e.name}))):[]}registerMaterialSelectedCallback(e){this.materialSelectedObservable.add(e)}unregisterMaterialSelectedCallback(e){this.materialSelectedObservable.removeCallback(e)}registerMaterialDeselectedCallback(e){this.materialDeselectedObservable.add(e)}unregisterMaterialDeselectedCallback(e){this.materialDeselectedObservable.removeCallback(e)}get position(){return this.transformRoot.position}set position(e){this.transformRoot.position=new(0,s.Vector3)(e.x,e.y,e.z)}get rotation(){return this.transformRoot.rotation}set rotation(e){this.transformRoot.rotation=new(0,s.Vector3)(e.x,e.y,e.z)}get scale(){return this.transformRoot.scaling}set scale(e){this.transformRoot.scaling=new(0,s.Vector3)(e.x,e.y,e.z)}attachPickingHandler(e){e.rootNodes.forEach((e=>{e.getChildMeshes(!1).forEach((e=>{"targetcube_t"!==e.name&&"backgroundShell"!==e.name&&(e.isPickable=!0,e.actionManager||(e.actionManager=new(0,b.ActionManager)(this.scene)),e.actionManager||(e.actionManager=new(0,b.ActionManager)(this.scene)),e.actionManager.registerAction(new(0,f.ExecuteCodeAction)(b.ActionManager.OnPointerOutTrigger,(()=>{e.material&&this.materialDeselectedObservable.notifyObservers({id:e.material.id,name:e.material.name})}))),e.actionManager.registerAction(new(0,f.ExecuteCodeAction)(b.ActionManager.OnPickDownTrigger,(t=>{t.meshUnderPointer&&e.material&&this.materialSelectedObservable.notifyObservers({id:e.material.id,name:e.material.name})}))))}))}))}getImportPromise(){return this.importPromise}getQueuedMaterialVariantCount(){return this.materialReadyToLoadCallbacks.size}getQueuedModelVariantCount(){return this.modelReadyToLoadCallbacks.size}configureModelInstance(e){const t=this.transformRoot.position,i=this.transformRoot.rotation,a=this.transformRoot.scaling;this.transformRoot.position=s.Vector3.Zero(),this.transformRoot.rotation=s.Vector3.Zero(),this.transformRoot.scaling=s.Vector3.One(),e.rootNodes.forEach((e=>{e.parent=this.transformRoot})),this.transformRoot.position=t,this.transformRoot.rotation=i,this.transformRoot.scaling=a,this.canvasPanels=this.contextService?.getAll()||new Map,Q(this.materials.concat(this.variantManager.getAllMaterials()),this.scene,this.canvasPanels,this.dynamicTextures,`${this.id}_`),this.attachPickingHandler(e)}dispose(){this.modelInstance.dispose(),this.modelInstance=void 0}instantiate(){this.modelInstance=this.assetContainer.instantiateModelsToScene(this.renameClonedAsset.bind(this),!0),this.materials=oe(this.modelInstance),this.configureModelInstance(this.modelInstance);if(this.materials.some((e=>"emissiveTexture"in e&&null!==e.emissiveTexture))){new(0,v.GlowLayer)("GlowLayer",this.scene).intensity=.5}this.processQueuedEvents()}renameClonedAsset(e){return`${this.id}_${e}`}setEnabled(e){e&&!this.modelInstance?this.instantiate():!e&&this.modelInstance&&this.dispose()}updateDynamicTextures(){this.canvasPanels?.forEach(((e,t)=>{const i=this.dynamicTextures.get(t);i&&e.getStaticContextDirty()&&i.isReady()&&(i.update(!1),e.setStaticContextDirty(!1))}))}registerMaterialVariantListener(e){this.materialVariantObservable.add(e)}unregisterMaterialVariantListener(e){this.materialVariantObservable.removeCallback(e)}registerModelVariantListener(e){this.modelVariantObservable.add(e)}unregisterModelVariantListener(e){this.modelVariantObservable.removeCallback(e)}async processQueuedEvents(){100===this.previewService.getSceneInitializationProgress()&&(await Promise.all(Array.from(this.materialReadyToLoadCallbacks.values()).map((e=>Array.from(e.values()).map((e=>e()))))),this.materialReadyToLoadCallbacks.clear(),await Promise.all(Array.from(this.modelReadyToLoadCallbacks.values()).map((e=>e()))),this.modelReadyToLoadCallbacks.clear(),this.queuedModelAnimation&&(this.executeAnimation(this.queuedModelAnimation),this.queuedModelAnimation=void 0))}}function he(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class de extends O.ArcRotateCamera{constructor(e,t,i,a,r,n,o,l){super(e,t,i,a,r,n,l),he(this,"lastFocus",new(0,s.Vector3)(0,0,0)),he(this,"panDenominator",1),this.minZ=.01,this.setRadius(this.radius),this.enableFramingBehavior(),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=ue(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,t){const i=this.getFramingBehavior();i.framingTime=t||800;const a=ue(this._scene),r=a.max.subtract(a.min),n=a.min.add(r.scale(.5));this.setRadius(1.5*r.length()),this.wheelPrecision=100/this.radius,this.panningInertia=0,this.panningOriginTarget.copyFrom(n),this.panDenominator=r.length(),i.zoomOnBoundingInfo(a.min,a.max,void 0,(()=>{e&&e()})),i.framingTime=0}enableAutoRotationBehavior(e=5e3){this.useAutoRotationBehavior=!0;const t=this.getAutoRotationBehavior();t&&(t.idleRotationWaitTime=e)}disableAutoRotationBehavior(){this.useAutoRotationBehavior=!1}setRadius(e){this.radius=e,this.maxZ=1e3*this.radius,this.lowerRadiusLimit=.01*this.radius,this.upperRadiusLimit=1.5*this.radius,this.wheelPrecision=100/this.radius,this.pinchPrecision=300/this.radius}static create(e,t,i){const a=ue(e),r=a.max.subtract(a.min),n=a.min.add(r.scale(.5)),s=new de("ProductCamera",-Math.PI/2,Math.PI/2,1.5*r.length(),n,e,t);return s.panningInertia=0,s.panningOriginTarget.copyFrom(n),s.panDenominator=r.length(),s.onAfterCheckInputsObservable.add((()=>{s.panningSensibility=1e3/s.panDenominator})),i&&(e.activeCamera=s),s}}function ue(e){if(0===e.meshes.length)return{min:new(0,s.Vector3)(-1,-1,-1),max:new(0,s.Vector3)(1,1,1)};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))))}function ge(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class me{constructor(e,t=!0,i=null){ge(this,"renderingPipeline",void 0),ge(this,"currentConfiguration",void 0),this.renderingPipeline=new(0,L.DefaultRenderingPipeline)("default",t,e,i?[i]:void 0,!1),this.renderingPipeline.isSupported&&this.renderingPipeline.prepare()}dispose(){this.renderingPipeline.dispose()}addCamera(e){this.renderingPipeline.isSupported&&this.renderingPipeline.addCamera(e)}removeCamera(e){this.renderingPipeline.isSupported&&this.renderingPipeline.removeCamera(e)}getConfiguration(){return this.currentConfiguration}setConfiguration(e){if(this.renderingPipeline.isSupported){if(this.renderingPipeline.samples=e.antiAliasing?.samples??_.antiAliasing.samples,this.renderingPipeline.fxaaEnabled=e.antiAliasing?.fxaaEnabled??_.antiAliasing.fxaaEnabled,this.renderingPipeline.bloomEnabled=e.bloom?.enabled??_.bloom.enabled,this.renderingPipeline.bloomKernel=e.bloom?.kernel??_.bloom.kernel,this.renderingPipeline.bloomScale=e.bloom?.scale??_.bloom.scale,this.renderingPipeline.bloomThreshold=e.bloom?.threshold??_.bloom.threshold,this.renderingPipeline.bloomWeight=e.bloom?.weight??_.bloom.weight,this.renderingPipeline.chromaticAberrationEnabled=e.chromaticAberration?.enabled??_.chromaticAberration.enabled,this.renderingPipeline.chromaticAberration.aberrationAmount=e.chromaticAberration?.aberrationAmount??_.chromaticAberration.aberrationAmount,this.renderingPipeline.chromaticAberration.radialIntensity=e.chromaticAberration?.radialIntensity??_.chromaticAberration.radialIntensity,this.renderingPipeline.chromaticAberration.direction=e.chromaticAberration?.direction?new(0,s.Vector2)(e.chromaticAberration.direction.x,e.chromaticAberration.direction.y):new(0,s.Vector2)(_.chromaticAberration.direction.x,_.chromaticAberration.direction.y),this.renderingPipeline.imageProcessing.colorCurvesEnabled=e.colorCurves?.enabled??_.colorCurves.enabled,this.renderingPipeline.imageProcessing.colorCurves=e.colorCurves?this.updateColorCurve(e.colorCurves):new(0,A.ColorCurves),this.renderingPipeline.depthOfFieldEnabled=e.depthOfField?.enabled??_.depthOfField.enabled,e.depthOfField)switch(e.depthOfField.blurLevel??_.depthOfField.blurLevel){case"Low":this.renderingPipeline.depthOfFieldBlurLevel=R.DepthOfFieldEffectBlurLevel.Low;break;case"Medium":this.renderingPipeline.depthOfFieldBlurLevel=R.DepthOfFieldEffectBlurLevel.Medium;break;case"High":this.renderingPipeline.depthOfFieldBlurLevel=R.DepthOfFieldEffectBlurLevel.High}if(this.renderingPipeline.depthOfField.focalLength=e.depthOfField?.focalLength??_.depthOfField.focalLength,this.renderingPipeline.depthOfField.fStop=e.depthOfField?.fStop??_.depthOfField.fStop,this.renderingPipeline.depthOfField.focusDistance=e.depthOfField?.focusDistance??_.depthOfField.focusDistance,this.renderingPipeline.depthOfField.lensSize=e.depthOfField?.lensSize??_.depthOfField.lensSize,this.renderingPipeline.grainEnabled=e.grain?.enabled??_.grain.enabled,this.renderingPipeline.grain.animated=e.grain?.animated??_.grain.animated,this.renderingPipeline.grain.intensity=e.grain?.intensity??_.grain.intensity,this.renderingPipeline.imageProcessing.contrast=e.misc?.contrast??_.misc.contrast,this.renderingPipeline.imageProcessing.exposure=e.misc?.exposure??_.misc.exposure,this.renderingPipeline.imageProcessing.toneMappingEnabled=e.misc?.toneMappingEnabled??_.misc.toneMappingEnabled,this.renderingPipeline.imageProcessing.toneMappingEnabled)switch(e.misc.toneMappingType??_.misc.toneMappingType){case"Standard":this.renderingPipeline.imageProcessing.toneMappingType=T.ImageProcessingConfiguration.TONEMAPPING_STANDARD;break;case"ACES":this.renderingPipeline.imageProcessing.toneMappingType=T.ImageProcessingConfiguration.TONEMAPPING_ACES}if(this.renderingPipeline.sharpenEnabled=e.sharpen?.enabled??_.sharpen.enabled,this.renderingPipeline.sharpen.colorAmount=e.sharpen?.colorAmount??_.sharpen.colorAmount,this.renderingPipeline.sharpen.edgeAmount=e.sharpen?.edgeAmount??_.sharpen.edgeAmount,this.renderingPipeline.imageProcessing.vignetteEnabled=e.vignette?.enabled??_.vignette.enabled,e.vignette?.center?(this.renderingPipeline.imageProcessing.vignetteCenterX=e.vignette.center.x,this.renderingPipeline.imageProcessing.vignetteCenterY=e.vignette.center.y):(this.renderingPipeline.imageProcessing.vignetteCenterX=_.vignette.center.x,this.renderingPipeline.imageProcessing.vignetteCenterY=_.vignette.center.y),e.vignette)switch(e.vignette?.blendMode??_.vignette.blendMode){case"Multiply":this.renderingPipeline.imageProcessing.vignetteBlendMode=T.ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;break;case"Opaque":this.renderingPipeline.imageProcessing.vignetteBlendMode=T.ImageProcessingConfiguration.VIGNETTEMODE_OPAQUE}e.vignette?.colorRgba?this.renderingPipeline.imageProcessing.vignetteColor=new(0,n.Color4)(e.vignette.colorRgba.r,e.vignette.colorRgba.g,e.vignette.colorRgba.b,e.vignette.colorRgba.a):e.vignette?.colorHex?this.renderingPipeline.imageProcessing.vignetteColor=n.Color4.FromHexString(e.vignette.colorHex):this.renderingPipeline.imageProcessing.vignetteColor=new(0,n.Color4)(_.vignette.colorRgba.r,_.vignette.colorRgba.g,_.vignette.colorRgba.b,_.vignette.colorRgba.a),this.renderingPipeline.imageProcessing.vignetteStretch=e.vignette?.stretch??_.vignette.stretch,this.renderingPipeline.imageProcessing.vignetteWeight=e.vignette?.weight??_.vignette.weight,this.renderingPipeline.prepare(),this.currentConfiguration=e}}updateColorCurve(e){const t=new(0,A.ColorCurves);return t.globalDensity=e.globalDensity??t.globalDensity,t.globalExposure=e.globalExposure??t.globalExposure,t.globalHue=e.globalHue??t.globalHue,t.globalSaturation=e.globalSaturation??t.globalSaturation,t.highlightsDensity=e.highlightsDensity??t.highlightsDensity,t.highlightsExposure=e.highlightsExposure??t.highlightsExposure,t.highlightsHue=e.highlightsHue??t.highlightsHue,t.highlightsSaturation=e.highlightsSaturation??t.highlightsSaturation,t.midtonesDensity=e.midtonesDensity??t.midtonesDensity,t.midtonesExposure=e.midtonesExposure??t.midtonesExposure,t.midtonesHue=e.midtonesHue??t.midtonesHue,t.midtonesSaturation=e.midtonesSaturation??t.midtonesSaturation,t.shadowsDensity=e.shadowsDensity??t.shadowsDensity,t.shadowsExposure=e.shadowsExposure??t.shadowsExposure,t.shadowsHue=e.shadowsHue??t.shadowsHue,t.shadowsSaturation=e.shadowsSaturation??t.shadowsSaturation,t}}function pe(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}d.GLTF2.GLTFLoader.RegisterExtension("glbPostProcessor",(function(e){return new U(e)})),a.SceneLoader.OnPluginActivatedObservable.add((e=>{if("gltf"===e.name){e.transparencyAsCoverage=!0}}));class be{constructor(i){pe(this,"camera",void 0),pe(this,"configuration",void 0),pe(this,"engine",void 0),pe(this,"scene",void 0),pe(this,"loadProgress",new Map([["initialScene",0]])),pe(this,"queuedCameraAnimation",void 0),pe(this,"focusLostNotified",!1),pe(this,"loadObservable",new(0,l.Observable)),pe(this,"focusLostObservable",new(0,l.Observable)),pe(this,"initializedCallbacks",[]),pe(this,"isInitialized",!1),pe(this,"highlightLayer",void 0),pe(this,"renderingPipeline",void 0),pe(this,"modelContainers",new Map),pe(this,"plugins",[]);const a=i?.noRender?void 0:document.createElement("canvas");this.configuration=new q(i);o.DracoCompression.Configuration={decoder:{wasmUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.6/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.6/draco_decoder_gltf.wasm",fallbackUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.6/draco_decoder_gltf.js"}},a&&(a.getContext("webgl2")||a.getContext("webgl"));const r=console.log;console.log=()=>{};const n=a?new(0,e.Engine)(a,!0,{adaptToDeviceRatio:!0,limitDeviceRatio:2,premultipliedAlpha:!1,preserveDrawingBuffer:!!i?.backgroundImage,audioEngine:!1,stencil:this.configuration.highlights.enabled,forceSRGBBufferSupportState:!0}):new(0,t.NullEngine);console.log=r,n.hideLoadingUI(),window.addEventListener("resize",this.fireResizeEvent.bind(this)),this.engine=n,this.scene=new(0,h.Scene)(n),this.camera=de.create(this.scene,this.configuration),this.renderingPipeline=new me(this.scene,!0),this.renderingPipeline.addCamera(this.camera),this.scene.imageProcessingConfiguration.exposure=this.configuration.lighting.exposure,this.scene.imageProcessingConfiguration.contrast=this.configuration.lighting.contrast}getEngineContext(){return{engine:this.engine,scene:this.scene,camera:this.camera}}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)}registerInitializedListener(e){this.isInitialized||!this.isInitialized&&this.initializedCallbacks.push(e)}unregisterInitializedListener(e){if(this.isInitialized)return;const t=this.initializedCallbacks.indexOf(e);t>-1&&this.initializedCallbacks.splice(t,1)}getIsInitialized(){return this.isInitialized}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(F.Pan),this.reattachControls(e)}getNumViewports(){return this.engine.views?.length||0}unregisterView(e){this.engine.unRegisterView(e)}shutdown(){this.plugins.forEach((e=>e.dispose(!0))),this.renderingPipeline.dispose(),this.engine&&this.engine.dispose(),window.removeEventListener("resize",this.fireResizeEvent)}getSceneInitializationProgress(){return this.loadProgress.get("initialScene")}async initialize(e){let t;if(this.scene.clearColor=this.configuration.scene.clearColor,this.scene.environmentTexture=r.CubeTexture.CreateFromPrefilteredData(this.configuration.scene.environmentFile,this.scene),e){const i=100;t=await this.loadModel(e,(e=>{this.loadProgress.set("initialScene",e.loaded*i/e.total),this.notifyLoadHandlers()}))}return this.loadProgress.set("initialScene",100),this.notifyLoadHandlers(),this.scene.activeCamera=this.camera,this.camera.rerunFramingBehavior(void 0,1),this.configuration.options?.renderingPipelineConfiguration&&this.renderingPipeline.setConfiguration(this.configuration.options.renderingPipelineConfiguration),X(this.scene.animationGroups),this.engine.views?.length>=1&&this.reattachControls(this.engine.views[this.engine.views.length-1].target),await this.processQueuedLoadEvents(),await Promise.all(this.initializedCallbacks.map((e=>e()))),this.initializedCallbacks=[],this.isInitialized=!0,this.engine.runRenderLoop((()=>{this.engine.views&&(this.modelContainers.forEach((e=>{e.updateDynamicTextures()})),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(),this.camera.target.equalsWithEpsilon(this.camera.lastFocus,.1)||this.focusLostNotified||(this.focusLostObservable.notifyObservers(void 0),this.focusLostNotified=!0))})),t}executeCameraAnimation(e){100===this.getSceneInitializationProgress()&&this.camera&&this.scene.activeCamera===this.camera?J(this.scene,this.scene.activeCamera,e):this.queuedCameraAnimation=e}getCameraPose(){if(this.scene&&this.camera)return{lonDeg:Math.round(180*this.camera.alpha/Math.PI),latDeg:Math.round(180*this.camera.beta/Math.PI),radius:Math.round(1e4*(this.camera.radius+Number.EPSILON))/1e4,target:{x:this.camera.target.x,y:this.camera.target.y,z:this.camera.target.z}}}setCameraPose(e){this.scene&&this.camera&&(this.camera.target=new(0,s.Vector3)(e.target.x,e.target.y,e.target.z),this.camera.radius=e.radius,this.camera.alpha=e.latDeg,this.camera.beta=e.lonDeg)}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===F.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.configuration;this.camera.rerunFramingBehavior((()=>{this.focusLostNotified=!1,t.camera.limits.min.radius&&(this.camera.lowerRadiusLimit=t.camera.limits.min.radius),t.camera.limits.max.radius&&(this.camera.upperRadiusLimit=t.camera.limits.max.radius),e()}))}))}setAutoRotation(e){this.configuration.camera.autoRotation.enabled&&this.camera&&(e?this.camera.enableAutoRotationBehavior(this.configuration.camera.autoRotation.idleTimeMs):this.camera.disableAutoRotationBehavior())}getCurrentConfiguration(){return this.configuration.options}async renderSceneScreenshot(e,t){if(!this.camera)throw new Error("Missing product camera, cannot render screenshot!");var i;(i=this.camera).getScene().stopAnimation(i),i.animations=[];const a=this.camera.alpha,r=this.camera.beta,n=this.camera.radius,s=t.latDeg*Math.PI/180,o=t.lonDeg*Math.PI/180;this.camera.alpha=o,this.camera.beta=s,this.camera.radius=t.radius||this.camera.radius;const l=await c.Tools.CreateScreenshotUsingRenderTargetAsync(this.engine,this.camera,e,"image/png",2,!0);return this.camera.alpha=a,this.camera.beta=r,this.camera.radius=n,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()}setHighlights(e,t){0===e.length&&(this.highlightLayer?.dispose(),this.highlightLayer=void 0),this.highlightLayer||(this.highlightLayer=new(0,i.HighlightLayer)("highlights",this.scene,{isStroke:!0,blurVerticalSize:.85,blurHorizontalSize:.85}),this.highlightLayer.innerGlow=!0,this.highlightLayer.outerGlow=!1),this.highlightLayer.removeAllMeshes();const a=t?new(0,n.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,a||n.Color3.FromHexString("#fcba03"))))}))}setRenderingPipelineConfiguration(e){this.renderingPipeline&&this.renderingPipeline.setConfiguration(e)}async loadModel(e,t){const i=new ce({modelDetails:e,scene:this.scene,previewService:this,progressHandler:t});return i.registerMaterialVariantListener((e=>this.handleMaterialProgressCallback(e.remainingCount,e.totalCount,e.taskName))),i.registerModelVariantListener((e=>this.handleModelProgressCallback(e,e.key))),this.configuration.highlights.enabled&&(i.registerMaterialSelectedCallback((e=>{this.setHighlights([e])})),i.registerMaterialDeselectedCallback((()=>{this.setHighlights([])}))),this.modelContainers.set(i.getId(),i),await i.getImportPromise(),i}getAllModels(){return Array.from(this.modelContainers.values())}getModelById(e){return this.modelContainers.get(e)}registerPlugin(e){this.plugins.push(e),e.initialize(this,{camera:this.camera,engine:this.engine,scene:this.scene})}unregisterPlugin(e){const t=this.plugins.indexOf(e);if(t>-1){this.plugins.splice(t,1).forEach((e=>e.dispose(!1)))}}handleMaterialProgressCallback(e,t,i){this.loadProgress.set(`key_${i}`,e/t*100),this.notifyLoadHandlers()}handleModelProgressCallback(e,t){this.loadProgress.set(t,100*e.loaded/e.total),this.notifyLoadHandlers()}reattachControls(e,t=2){if(this.scene.detachControl(),this.engine.inputElement=e,this.camera){this.camera.attachControl(!0,!1,t);this.camera.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 processQueuedLoadEvents(){this.queuedCameraAnimation&&(this.executeCameraAnimation(this.queuedCameraAnimation),this.queuedCameraAnimation=void 0)}}E(module.exports,I),E(module.exports,V),E(module.exports,j);
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 i}from"@babylonjs/core/Engines/engine";import{NullEngine as a}from"@babylonjs/core/Engines/nullEngine";import{GlowLayer as n}from"@babylonjs/core/Layers/glowLayer";import{HighlightLayer as r}from"@babylonjs/core/Layers/highlightLayer";import{SceneLoader as s}from"@babylonjs/core/Loading/sceneLoader";import{PBRMaterial as o}from"@babylonjs/core/Materials/PBR/pbrMaterial";import{CubeTexture as l}from"@babylonjs/core/Materials/Textures/cubeTexture";import{DynamicTexture as c}from"@babylonjs/core/Materials/Textures/dynamicTexture";import{Color3 as h,Color4 as d}from"@babylonjs/core/Maths/math.color";import{Vector3 as g,Vector2 as u}from"@babylonjs/core/Maths/math.vector";import{DracoCompression as m}from"@babylonjs/core/Meshes/Compression/dracoCompression";import{Observable as p}from"@babylonjs/core/Misc/observable";import{Tools as b}from"@babylonjs/core/Misc/tools";import{Scene as f}from"@babylonjs/core/scene";import{GLTF2 as v}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 y}from"@babylonjs/core/Materials/Textures/texture";import{MirrorTexture as P}from"@babylonjs/core/Materials/Textures/mirrorTexture";import{Color3 as w,Vector3 as x,Plane as M}from"@babylonjs/core/Maths/math";import{ReflectionProbe as C}from"@babylonjs/core/Probes/reflectionProbe";import{Animation as T}from"@babylonjs/core/Animations/animation";import{QuadraticEase as A,EasingFunction as L}from"@babylonjs/core/Animations/easing";import{ArcRotateCamera as O}from"@babylonjs/core/Cameras/arcRotateCamera";import{ColorCurves as E}from"@babylonjs/core/Materials/colorCurves";import{ImageProcessingConfiguration as R}from"@babylonjs/core/Materials/imageProcessingConfiguration";import{DefaultRenderingPipeline as S}from"@babylonjs/core/PostProcesses/RenderPipeline";import{DepthOfFieldEffectBlurLevel as F}from"@babylonjs/core/PostProcesses/depthOfFieldEffect";import"@babylonjs/core/Rendering/depthRendererSceneComponent";import{AssetsManager as I}from"@babylonjs/core/Misc/assetsManager";function B(e,t,i,a){Object.defineProperty(e,t,{get:i,set:a,enumerable:!0,configurable:!0})}var D={};let k;var j;let N;var z;B(D,"ProductCameraRig",(()=>k)),B(D,"MaterialEffectMode",(()=>N)),(j=k||(k={}))[j.Orbit=0]="Orbit",j[j.Pan=1]="Pan",(z=N||(N={})).None="None",z.RemoveWhenSelected="RemoveWhenSelected",z.ApplyWhenSelected="ApplyWhenSelected";var H={};B(H,"SpiffCommerce3DPreviewService",(()=>me)),B(H,"createBaseModel",(()=>pe));const V=new Map;async function _(e,t,i){return new Promise(((a,n)=>{const r=V.get(e);if(r&&r.scene.uid===t.uid)return a(r);s.LoadAssetContainerAsync(e,void 0,t,i).then((t=>{V.set(e,t),a(t)})).catch(n)}))}function U(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class G{constructor(e){U(this,"customOptions",void 0),U(this,"getSceneClearColor",(()=>{const e=this.customOptions?.transparentBackground||this.customOptions?.backgroundImage?0:1;if(this.customOptions&&this.customOptions?.transparentBackground||this.customOptions?.backgroundImage)return new d(0,0,0,e).toLinearSpace();if(this.customOptions&&this.customOptions.backgroundColor){const t=h.FromHexString(this.customOptions.backgroundColor);return new d(t.r,t.g,t.b,e).toLinearSpace()}return new d(.98,.98,.98,e).toLinearSpace()})),U(this,"highlightColorFromConfig",(()=>this.customOptions&&this.customOptions.highlightColor?this.hexToColor4(this.customOptions.highlightColor):new d(.98,.98,.98,1).toLinearSpace())),U(this,"hexToColor4",((e,t=1)=>{const i=h.FromHexString(e);return new d(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 W={};B(W,"RenderingConfiguration",(()=>q)),B(W,"REFLECTION_PROBE_RESOLUTION",(()=>K)),B(W,"renderingPipelineDefaults",(()=>Y));class q{static getDynamicTextureResolution(){return this.getIsMobile()||!q.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 K=128,Y={antiAliasing:{samples:4,fxaaEnabled:!1},bloom:{enabled:!1,kernel:64,scale:.5,threshold:.9,weight:.15},chromaticAberration:{enabled:!1,aberrationAmount:30,direction:{x:0,y:0},radialIntensity:0},colorCurves:{enabled:!1},depthOfField:{enabled:!1,blurLevel:"Low",focalLength:50,focusDistance:2e3,fStop:1.4,lensSize:50},grain:{enabled:!1,animated:!1,intensity:30},misc:{contrast:1,exposure:1,toneMappingEnabled:!1,toneMappingType:"Standard"},sharpen:{enabled:!1,colorAmount:1,edgeAmount:.3},vignette:{enabled:!1,blendMode:"Multiply",cameraFov:.5,center:{x:0,y:0},colorHex:"#000000ff",colorRgba:{r:0,g:0,b:0,a:1},stretch:0,weight:1}};function Q(e,t,a){t.forEach((t=>{const n=t.getID(),r=t.getName(),s=q.getDynamicTextureResolution();e.materials.filter((e=>e.name===r)).forEach((o=>{const l=a.get(n);if(l)Z(o,l),l.update(false);else{const l=function(e,t,a,n){const r=new c(e,{width:a,height:n},t,q.shouldMipMap(),y.TRILINEAR_SAMPLINGMODE,i.TEXTUREFORMAT_RGBA),s=r.getContext();s&&(s.fillStyle="#f5f5f5",s.fillRect(0,0,a,n),r.update());return r}(r,e,s.width,s.height);a.set(n,l),t.setStaticContext(l.getContext()),Z(o,l),l.onLoadObservable.addOnce((()=>{l.update(false)}))}}))}))}function Z(e,t){if(e instanceof o){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 X(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class ${constructor(e){X(this,"name",void 0),X(this,"enabled",void 0),X(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){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 w(e.extras.translucencyR,e.extras.translucencyG,e.extras.translucencyB))}if(e.extras.refractionIOR){t.subSurface.volumeIndexOfRefraction=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 n=i.material;if(!n)return;const r=new P("mirror",q.getMirrorTextureResolution(),e,!0);r.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(),l=x.TransformNormal(new x(s[0],s[1],s[2]),o).normalize(),c=M.FromPositionAndNormal(i.position,l.scale(-1));r.mirrorPlane=c,r.level=a,n.reflectionTexture=r}(i,a.mirrorTexture),a.reflectionProbe&&function(i){const a=i.material,n=new C("probe-"+a.name,K,e);n.attachToMesh(i),n.renderList&&n.renderList.push(...t(e)),a.reflectionTexture=n.cubeTexture}(i))}))}}function J(e,t,i,a){const n=e.animationGroups,r=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?n.forEach((e=>{e.stop();const n=r(e);e.start(t,1,a*n,i*n)})):n.forEach((e=>{e.stop();const i=r(e),n=a*i;e.start(t,1,n,n)}))}function ee(e){e.animationGroups.forEach((e=>{e.stop()}))}function te(e,t,i){var a,n,r;e.stopAnimation(t),t.animations=[],Math.abs(t.alpha)>2*Math.PI&&(t.alpha=(a=t.alpha,n=0,r=2*Math.PI,a<n?r-(n-a)%(r-n):n+(a-n)%(r-n)));const s=[],o=i.target,l=o?1:0;if(i.target&&Object.keys(i.target).length>0&&s.push(ae("cameraTargetLerp","target",(new g).copyFrom(t.target),new g(i.target.x,i.target.y,i.target.z),T.ANIMATIONTYPE_VECTOR3,0)),s.push(ae("cameraAlphaLerp","alpha",t.alpha,ie(i.lonDeg),T.ANIMATIONTYPE_FLOAT,l)),s.push(ae("cameraBetaLerp","beta",t.beta,ie(i.latDeg),T.ANIMATIONTYPE_FLOAT,l)),void 0!==i.radius){const e=Math.max(.01,i.radius);s.push(ae("cameraRadiusLerp","radius",t.radius,e,T.ANIMATIONTYPE_FLOAT,l))}t.animations.push(...s);const c=t.useAutoRotationBehavior;t.disableAutoRotationBehavior(),e.beginAnimation(t,0,o?120:60,!1,1,(()=>{t.animations=[],c&&t.enableAutoRotationBehavior()}))}function ie(e){return e*Math.PI/180}function ae(e,t,i,a,n,r=0,s=T.ANIMATIONLOOPMODE_CONSTANT){const o=new A;o.setEasingMode(L.EASINGMODE_EASEINOUT);const l=new T(e,t,60,n,s),c=[];return r>0&&c.push({frame:0,value:i}),c.push({frame:60*r,value:i}),c.push({frame:60*(r+1),value:a}),l.setKeys(c),l.setEasingFunction(o),l}class ne extends O{constructor(e,t,i,a,n,r,s,o){var l,c,h;super(e,t,i,a,n,r,o),l=this,c="lastFocus",h=new g(0,0,0),c in l?Object.defineProperty(l,c,{value:h,enumerable:!0,configurable:!0,writable:!0}):l[c]=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=re(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=re(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=re(e),a=i.max.subtract(i.min),n=i.min.add(a.scale(.5)),r=new ne("ProductCamera",-Math.PI/2,Math.PI/2,1.5*a.length(),n,e,t);return r.panningInertia=0,r.panningOriginTarget.copyFrom(n),r.onAfterCheckInputsObservable.add((()=>{r.panningSensibility=1e3/a.length()})),e.activeCamera=r,r}}function re(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))))}function se(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class oe{constructor(e,t=!0,i=null){se(this,"renderingPipeline",void 0),se(this,"currentConfiguration",void 0),this.renderingPipeline=new S("default",t,e,i?[i]:void 0,!1),this.renderingPipeline.isSupported&&this.renderingPipeline.prepare()}dispose(){this.renderingPipeline.dispose()}addCamera(e){this.renderingPipeline.isSupported&&this.renderingPipeline.addCamera(e)}removeCamera(e){this.renderingPipeline.isSupported&&this.renderingPipeline.removeCamera(e)}getConfiguration(){return this.currentConfiguration}setConfiguration(e){if(this.renderingPipeline.isSupported){if(this.renderingPipeline.samples=e.antiAliasing?.samples??Y.antiAliasing.samples,this.renderingPipeline.fxaaEnabled=e.antiAliasing?.fxaaEnabled??Y.antiAliasing.fxaaEnabled,this.renderingPipeline.bloomEnabled=e.bloom?.enabled??Y.bloom.enabled,this.renderingPipeline.bloomKernel=e.bloom?.kernel??Y.bloom.kernel,this.renderingPipeline.bloomScale=e.bloom?.scale??Y.bloom.scale,this.renderingPipeline.bloomThreshold=e.bloom?.threshold??Y.bloom.threshold,this.renderingPipeline.bloomWeight=e.bloom?.weight??Y.bloom.weight,this.renderingPipeline.chromaticAberrationEnabled=e.chromaticAberration?.enabled??Y.chromaticAberration.enabled,this.renderingPipeline.chromaticAberration.aberrationAmount=e.chromaticAberration?.aberrationAmount??Y.chromaticAberration.aberrationAmount,this.renderingPipeline.chromaticAberration.radialIntensity=e.chromaticAberration?.radialIntensity??Y.chromaticAberration.radialIntensity,this.renderingPipeline.chromaticAberration.direction=e.chromaticAberration?.direction?new u(e.chromaticAberration.direction.x,e.chromaticAberration.direction.y):new u(Y.chromaticAberration.direction.x,Y.chromaticAberration.direction.y),this.renderingPipeline.imageProcessing.colorCurvesEnabled=e.colorCurves?.enabled??Y.colorCurves.enabled,this.renderingPipeline.imageProcessing.colorCurves=e.colorCurves?this.updateColorCurve(e.colorCurves):new E,this.renderingPipeline.depthOfFieldEnabled=e.depthOfField?.enabled??Y.depthOfField.enabled,e.depthOfField)switch(e.depthOfField.blurLevel??Y.depthOfField.blurLevel){case"Low":this.renderingPipeline.depthOfFieldBlurLevel=F.Low;break;case"Medium":this.renderingPipeline.depthOfFieldBlurLevel=F.Medium;break;case"High":this.renderingPipeline.depthOfFieldBlurLevel=F.High}if(this.renderingPipeline.depthOfField.focalLength=e.depthOfField?.focalLength??Y.depthOfField.focalLength,this.renderingPipeline.depthOfField.fStop=e.depthOfField?.fStop??Y.depthOfField.fStop,this.renderingPipeline.depthOfField.focusDistance=e.depthOfField?.focusDistance??Y.depthOfField.focusDistance,this.renderingPipeline.depthOfField.lensSize=e.depthOfField?.lensSize??Y.depthOfField.lensSize,this.renderingPipeline.grainEnabled=e.grain?.enabled??Y.grain.enabled,this.renderingPipeline.grain.animated=e.grain?.animated??Y.grain.animated,this.renderingPipeline.grain.intensity=e.grain?.intensity??Y.grain.intensity,this.renderingPipeline.imageProcessing.contrast=e.misc?.contrast??Y.misc.contrast,this.renderingPipeline.imageProcessing.exposure=e.misc?.exposure??Y.misc.exposure,this.renderingPipeline.imageProcessing.toneMappingEnabled=e.misc?.toneMappingEnabled??Y.misc.toneMappingEnabled,this.renderingPipeline.imageProcessing.toneMappingEnabled)switch(e.misc.toneMappingType??Y.misc.toneMappingType){case"Standard":this.renderingPipeline.imageProcessing.toneMappingType=R.TONEMAPPING_STANDARD;break;case"ACES":this.renderingPipeline.imageProcessing.toneMappingType=R.TONEMAPPING_ACES}if(this.renderingPipeline.sharpenEnabled=e.sharpen?.enabled??Y.sharpen.enabled,this.renderingPipeline.sharpen.colorAmount=e.sharpen?.colorAmount??Y.sharpen.colorAmount,this.renderingPipeline.sharpen.edgeAmount=e.sharpen?.edgeAmount??Y.sharpen.edgeAmount,this.renderingPipeline.imageProcessing.vignetteEnabled=e.vignette?.enabled??Y.vignette.enabled,e.vignette?.center?(this.renderingPipeline.imageProcessing.vignetteCenterX=e.vignette.center.x,this.renderingPipeline.imageProcessing.vignetteCenterY=e.vignette.center.y):(this.renderingPipeline.imageProcessing.vignetteCenterX=Y.vignette.center.x,this.renderingPipeline.imageProcessing.vignetteCenterY=Y.vignette.center.y),e.vignette)switch(e.vignette?.blendMode??Y.vignette.blendMode){case"Multiply":this.renderingPipeline.imageProcessing.vignetteBlendMode=R.VIGNETTEMODE_MULTIPLY;break;case"Opaque":this.renderingPipeline.imageProcessing.vignetteBlendMode=R.VIGNETTEMODE_OPAQUE}e.vignette?.colorRgba?this.renderingPipeline.imageProcessing.vignetteColor=new d(e.vignette.colorRgba.r,e.vignette.colorRgba.g,e.vignette.colorRgba.b,e.vignette.colorRgba.a):e.vignette?.colorHex?this.renderingPipeline.imageProcessing.vignetteColor=d.FromHexString(e.vignette.colorHex):this.renderingPipeline.imageProcessing.vignetteColor=new d(Y.vignette.colorRgba.r,Y.vignette.colorRgba.g,Y.vignette.colorRgba.b,Y.vignette.colorRgba.a),this.renderingPipeline.imageProcessing.vignetteStretch=e.vignette?.stretch??Y.vignette.stretch,this.renderingPipeline.imageProcessing.vignetteWeight=e.vignette?.weight??Y.vignette.weight,this.renderingPipeline.prepare(),this.currentConfiguration=e}}updateColorCurve(e){const t=new E;return t.globalDensity=e.globalDensity??t.globalDensity,t.globalExposure=e.globalExposure??t.globalExposure,t.globalHue=e.globalHue??t.globalHue,t.globalSaturation=e.globalSaturation??t.globalSaturation,t.highlightsDensity=e.highlightsDensity??t.highlightsDensity,t.highlightsExposure=e.highlightsExposure??t.highlightsExposure,t.highlightsHue=e.highlightsHue??t.highlightsHue,t.highlightsSaturation=e.highlightsSaturation??t.highlightsSaturation,t.midtonesDensity=e.midtonesDensity??t.midtonesDensity,t.midtonesExposure=e.midtonesExposure??t.midtonesExposure,t.midtonesHue=e.midtonesHue??t.midtonesHue,t.midtonesSaturation=e.midtonesSaturation??t.midtonesSaturation,t.shadowsDensity=e.shadowsDensity??t.shadowsDensity,t.shadowsExposure=e.shadowsExposure??t.shadowsExposure,t.shadowsHue=e.shadowsHue??t.shadowsHue,t.shadowsSaturation=e.shadowsSaturation??t.shadowsSaturation,t}}const le={albedoTexture:"albedoMap",bumpTexture:"normalMap",ambientTexture:"ambientMap",emissiveTexture:"emissionMap",opacityTexture:"alphaMap",metallicTexture:"metallicMap",refractionTexture:"refractionMap"};function ce(e,t,i,a){["albedoTexture","bumpTexture","ambientTexture","emissiveTexture","opacityTexture","metallicTexture","refractionTexture"].forEach((n=>{!function(e,t,i,a,n){const r=le[e];if(!r)throw new Error("Unexpected texture name encountered.");const s=t[r]?.fileLink;s?a.addTextureTask(e,s,!1,!1):n&&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))}(n,e,t,i,a)})),function(e,t){if(!e.clearCoat)return;e.clearCoat===N.RemoveWhenSelected?(t.clearCoat.isEnabled=!1,t.clearCoat.indexOfRefraction=1.5):e.clearCoat===N.ApplyWhenSelected&&(t.clearCoat.isEnabled=!0,t.clearCoat.indexOfRefraction=e.clearCoatIOR||t.clearCoat.indexOfRefraction)}(e,t)}function he(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 de(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class ge{constructor(){de(this,"materialVariantMap",new Map),de(this,"keysThatRemovedBaseModel",[]),de(this,"loadedContainerForKey",new Map)}async applyMaterial(e,t,i,a,n){return new Promise((r=>{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 r(void 0);const l=new I(e);l.useDefaultLoadingScreen=!1,s.forEach((e=>ce(i,e,l,n))),l.onProgress=(e,t,i)=>{a&&a(e/t*100,100,i.name)},l.onFinish=e=>{e.forEach((e=>{const t=e;a&&a(100,100,e.name),s.forEach((a=>he(e.name,a,i,t.texture)))})),r(void 0)},l.loadAsync()}))}async applyModel(e,t,i,a,n){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 pe(e.metadata.baseModel,e),Promise.resolve()}const r=await _(a,e,n);if(this.loadedContainerForKey.has(t)&&this.loadedContainerForKey.get(t)?.removeAllFromScene(),i){(await _(e.metadata.baseModel,e)).removeAllFromScene()}r.addAllToScene(),this.loadedContainerForKey.set(t,r);const s=[];this.materialVariantMap.forEach((async(t,i)=>{s.push(this.applyMaterial(e,i,t))})),await Promise.all(s)}}function ue(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}v.GLTFLoader.RegisterExtension("glbPostProcessor",(function(e){return new $(e)})),s.OnPluginActivatedObservable.add((e=>{if("gltf"===e.name){e.transparencyAsCoverage=!0}}));class me{constructor(e){ue(this,"engine",void 0),ue(this,"scene",void 0),ue(this,"configuration",void 0),ue(this,"loadProgress",new Map([["initialScene",0]])),ue(this,"materialReadyToLoadCallbacks",new Map),ue(this,"modelReadyToLoadCallbacks",new Map),ue(this,"queuedModelAnimation",void 0),ue(this,"queuedCameraAnimation",void 0),ue(this,"focusLostNotified",!1),ue(this,"loadObservable",new p),ue(this,"focusLostObservable",new p),ue(this,"dynamicTextures",new Map),ue(this,"highlightLayer",void 0),ue(this,"variantManager",new ge),ue(this,"renderingPipeline",void 0);const t=e?.noRender?void 0:document.createElement("canvas");this.configuration=new G(e);m.Configuration={decoder:{wasmUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.6/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.6/draco_decoder_gltf.wasm",fallbackUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.6/draco_decoder_gltf.js"}},t&&(t.getContext("webgl2")||t.getContext("webgl"));const n=console.log;console.log=()=>{};const r=t?new i(t,!0,{adaptToDeviceRatio:!0,limitDeviceRatio:2,premultipliedAlpha:!1,preserveDrawingBuffer:!!e?.backgroundImage,audioEngine:!1,stencil:this.configuration.highlights.enabled,forceSRGBBufferSupportState:!0}):new a;console.log=n,r.hideLoadingUI(),window.addEventListener("resize",this.fireResizeEvent.bind(this)),this.engine=r,this.scene=new f(r),this.renderingPipeline=new oe(this.scene,!0),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(k.Pan),this.reattachControls(e)}getNumViewports(){return this.engine.views?.length||0}unregisterView(e){this.engine.unRegisterView(e)}shutdown(){this.renderingPipeline.dispose(),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=l.CreateFromPrefilteredData(this.configuration.scene.environmentFile,this.scene),i){const e=100;await pe(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 e(this.scene)),i.actionManager.registerAction(new t(e.OnPointerOutTrigger,(()=>{this.setHighlights([])}))),i.actionManager.registerAction(new t(e.OnPointerOverTrigger,(e=>{if(e.meshUnderPointer){const t=e.meshUnderPointer.material;t&&this.setHighlights([t])}}))))}));const r=ne.create(this.scene,this.configuration);this.renderingPipeline.addCamera(r),this.configuration.options?.renderingPipelineConfiguration&&this.renderingPipeline.setConfiguration(this.configuration.options.renderingPipelineConfiguration);const s=a?.getAll()||new Map;Q(this.scene,s,this.dynamicTextures);if(this.scene.materials.some((e=>"emissiveTexture"in e&&null!==e.emissiveTexture))){new n("GlowLayer",this.scene).intensity=.5}ee(this.scene),this.engine.views?.length>=1&&this.reattachControls(this.engine.views[this.engine.views.length-1].target),await this.processQueuedLoadEvents(),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(),r.target.equalsWithEpsilon(r.lastFocus,.1)||this.focusLostNotified||(this.focusLostObservable.notifyObservers(void 0),this.focusLostNotified=!0))}))}executeModelAnimation(e){100===this.getSceneInitializationProgress()?J(this.scene,e.loop,e.to,e.from):this.queuedModelAnimation=e}executeCameraAnimation(e){100===this.getSceneInitializationProgress()&&this.scene.activeCamera?te(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 g(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&&!(e.albedoTexture instanceof c);e.dispose(!1,t)}})),Q(this.scene,t.contextService.getAll(),this.dynamicTextures),ee(this.scene)):this.modelReadyToLoadCallbacks.set(e,(async()=>{await this.applyModelVariant(e,t,i)}))}getQueuedMaterialVariants(){return this.materialReadyToLoadCallbacks.size}getQueuedModelVariants(){return this.modelReadyToLoadCallbacks.size}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===k.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 n=i.alpha,r=i.beta,s=i.radius,o=t.latDeg*Math.PI/180,l=t.lonDeg*Math.PI/180;i.alpha=l,i.beta=o,i.radius=t.radius||i.radius;const c=await b.CreateScreenshotUsingRenderTargetAsync(this.engine,i,e,"image/png",2,!0);return i.alpha=n,i.beta=r,i.radius=s,c}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,n=e.camera.limits.max.beta;if(void 0===t||void 0===i||void 0===a||void 0===n)return!0;const r=[a,n],s=[t,i].every((e=>e===t)),o=r.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 e(this.scene)),a.actionManager.registerAction(new t(e.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 r("highlights",this.scene,{isStroke:!0,blurVerticalSize:.85,blurHorizontalSize:.85}),this.highlightLayer.innerGlow=!0,this.highlightLayer.outerGlow=!1),this.highlightLayer.removeAllMeshes();const i=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,i||h.FromHexString("#fcba03"))))}))}setRenderingPipelineConfiguration(e){this.renderingPipeline&&this.renderingPipeline.setConfiguration(e)}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 processQueuedLoadEvents(){await Promise.all(Array.from(this.modelReadyToLoadCallbacks.values()).map((e=>e(this.scene)))),this.modelReadyToLoadCallbacks.clear(),this.materialReadyToLoadCallbacks.forEach(((e,t)=>{e.forEach(((e,i)=>{this.applyMaterialVariant(t,i,e)}))})),this.materialReadyToLoadCallbacks.clear(),this.queuedModelAnimation&&(this.executeModelAnimation(this.queuedModelAnimation),this.queuedModelAnimation=void 0),this.queuedCameraAnimation&&(this.executeCameraAnimation(this.queuedCameraAnimation),this.queuedCameraAnimation=void 0)}}async function pe(e,t,i){(await _(e,t,i)).addAllToScene()}export{k as ProductCameraRig,N as MaterialEffectMode,me as SpiffCommerce3DPreviewService,pe as createBaseModel,q as RenderingConfiguration,K as REFLECTION_PROBE_RESOLUTION,Y as renderingPipelineDefaults};
1
+ import{Engine as e}from"@babylonjs/core/Engines/engine";import{NullEngine as t}from"@babylonjs/core/Engines/nullEngine";import{HighlightLayer as i}from"@babylonjs/core/Layers/highlightLayer";import{SceneLoader as a}from"@babylonjs/core/Loading/sceneLoader";import{CubeTexture as n}from"@babylonjs/core/Materials/Textures/cubeTexture";import{Color3 as r,Color4 as s}from"@babylonjs/core/Maths/math.color";import{Vector3 as o,Vector2 as l}from"@babylonjs/core/Maths/math.vector";import{DracoCompression as c}from"@babylonjs/core/Meshes/Compression/dracoCompression";import{Observable as h}from"@babylonjs/core/Misc/observable";import{Tools as d}from"@babylonjs/core/Misc/tools";import{Scene as m}from"@babylonjs/core/scene";import{GLTF2 as g}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{PBRMaterial as u}from"@babylonjs/core/Materials/PBR/pbrMaterial";import{MirrorTexture as p}from"@babylonjs/core/Materials/Textures/mirrorTexture";import{Color3 as b,Vector3 as f,Plane as v}from"@babylonjs/core/Maths/math";import{ReflectionProbe as y}from"@babylonjs/core/Probes/reflectionProbe";import{ActionManager as P}from"@babylonjs/core/Actions/actionManager";import{ExecuteCodeAction as w}from"@babylonjs/core/Actions/directActions";import{GlowLayer as M}from"@babylonjs/core/Layers/glowLayer";import{TransformNode as C}from"@babylonjs/core/Meshes/transformNode";import{DynamicTexture as x}from"@babylonjs/core/Materials/Textures/dynamicTexture";import{Texture as O}from"@babylonjs/core/Materials/Textures/texture";import{Animation as A}from"@babylonjs/core/Animations/animation";import{QuadraticEase as R,EasingFunction as T}from"@babylonjs/core/Animations/easing";import{AssetsManager as L}from"@babylonjs/core/Misc/assetsManager";import{ArcRotateCamera as E}from"@babylonjs/core/Cameras/arcRotateCamera";import{ColorCurves as S}from"@babylonjs/core/Materials/colorCurves";import{ImageProcessingConfiguration as I}from"@babylonjs/core/Materials/imageProcessingConfiguration";import{DefaultRenderingPipeline as F}from"@babylonjs/core/PostProcesses/RenderPipeline";import{DepthOfFieldEffectBlurLevel as D}from"@babylonjs/core/PostProcesses/depthOfFieldEffect";import"@babylonjs/core/Rendering/depthRendererSceneComponent";function k(e,t,i,a){Object.defineProperty(e,t,{get:i,set:a,enumerable:!0,configurable:!0})}var B={};let z;var N;let j;var V;k(B,"ProductCameraRig",(()=>z)),k(B,"MaterialEffectMode",(()=>j)),(N=z||(z={}))[N.Orbit=0]="Orbit",N[N.Pan=1]="Pan",(V=j||(j={})).None="None",V.RemoveWhenSelected="RemoveWhenSelected",V.ApplyWhenSelected="ApplyWhenSelected";function H(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}k({},"SpiffCommerce3DPreviewService",(()=>ye));class _{constructor(e){H(this,"customOptions",void 0),H(this,"getSceneClearColor",(()=>{const e=this.customOptions?.transparentBackground||this.customOptions?.backgroundImage?0:1;if(this.customOptions&&this.customOptions?.transparentBackground||this.customOptions?.backgroundImage)return new s(0,0,0,e).toLinearSpace();if(this.customOptions&&this.customOptions.backgroundColor){const t=r.FromHexString(this.customOptions.backgroundColor);return new s(t.r,t.g,t.b,e).toLinearSpace()}return new s(.98,.98,.98,e).toLinearSpace()})),H(this,"highlightColorFromConfig",(()=>this.customOptions&&this.customOptions.highlightColor?this.hexToColor4(this.customOptions.highlightColor):new s(.98,.98,.98,1).toLinearSpace())),H(this,"hexToColor4",((e,t=1)=>{const i=r.FromHexString(e);return new s(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 G={};k(G,"RenderingConfiguration",(()=>U)),k(G,"REFLECTION_PROBE_RESOLUTION",(()=>W)),k(G,"renderingPipelineDefaults",(()=>q));class U{static getDynamicTextureResolution(){return this.getIsMobile()||!U.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 W=128,q={antiAliasing:{samples:4,fxaaEnabled:!1},bloom:{enabled:!1,kernel:64,scale:.5,threshold:.9,weight:.15},chromaticAberration:{enabled:!1,aberrationAmount:30,direction:{x:0,y:0},radialIntensity:0},colorCurves:{enabled:!1},depthOfField:{enabled:!1,blurLevel:"Low",focalLength:50,focusDistance:2e3,fStop:1.4,lensSize:50},grain:{enabled:!1,animated:!1,intensity:30},misc:{contrast:1,exposure:1,toneMappingEnabled:!1,toneMappingType:"Standard"},sharpen:{enabled:!1,colorAmount:1,edgeAmount:.3},vignette:{enabled:!1,blendMode:"Multiply",cameraFov:.5,center:{x:0,y:0},colorHex:"#000000ff",colorRgba:{r:0,g:0,b:0,a:1},stretch:0,weight:1}};function K(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class Q{constructor(e){K(this,"name",void 0),K(this,"enabled",void 0),K(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)}))}async loadMaterialPropertiesAsync(e,t,i){await this.loader.loadMaterialPropertiesAsync(e,t,i),this.enableMaterialExtrasIfRequired(t,i)}dispose(){}enableMaterialExtrasIfRequired(e,t){if(e.extras&&t instanceof u){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 b(e.extras.translucencyR,e.extras.translucencyG,e.extras.translucencyB))}if(e.extras.refractionIOR){const i=t;i.subSurface.isRefractionEnabled=!0,i.subSurface.volumeIndexOfRefraction=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 n=i.material;if(!n)return;const r=new p("mirror",U.getMirrorTextureResolution(),e,!0);r.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(),l=f.TransformNormal(new f(s[0],s[1],s[2]),o).normalize(),c=v.FromPositionAndNormal(i.position,l.scale(-1));r.mirrorPlane=c,r.level=a,n.reflectionTexture=r}(i,a.mirrorTexture),a.reflectionProbe&&function(i){const a=i.material,n=new y("probe-"+a.name,W,e);n.attachToMesh(i),n.renderList&&n.renderList.push(...t(e)),a.reflectionTexture=n.cubeTexture}(i))}))}}const Y=new Map;async function Z(e,t,i){return new Promise(((n,r)=>{const s=Y.get(e);if(s&&s.scene.uid===t.uid)return n(s);a.LoadAssetContainerAsync(e,void 0,t,i).then((t=>{Y.set(e,t),n(t)})).catch(r)}))}function $(t,i,a,n,r=""){a.forEach((a=>{const s=a.getID(),o=a.getName(),l=U.getDynamicTextureResolution();t.filter((e=>e.name===r+o)).forEach((t=>{const r=n.get(s);if(r)X(t,r),r.update(false);else{const r=function(t,i,a,n){const r=new x(t,{width:a,height:n},i,U.shouldMipMap(),O.TRILINEAR_SAMPLINGMODE,e.TEXTUREFORMAT_RGBA),s=r.getContext();s&&(s.fillStyle="#f5f5f5",s.fillRect(0,0,a,n),r.update());return r}(o,i,l.width,l.height);n.set(s,r),a.setStaticContext(r.getContext()),X(t,r),r.onLoadObservable.addOnce((()=>{r.update(false)}))}}))}))}function X(e,t){if(e instanceof u){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 J(){const e=()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1);return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()}function ee(e,t,i,a){const 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?e.forEach((e=>{e.stop();const r=n(e);e.start(t,1,a*r,i*r)})):e.forEach((e=>{e.stop();const i=n(e),r=a*i;e.start(t,1,r,r)}))}function te(e){e.forEach((e=>{e.stop()}))}function ie(e,t,i){var a,n,r;e.stopAnimation(t),t.animations=[],Math.abs(t.alpha)>2*Math.PI&&(t.alpha=(a=t.alpha,n=0,r=2*Math.PI,a<n?r-(n-a)%(r-n):n+(a-n)%(r-n)));const s=[],l=i.target,c=l?1:0;if(i.target&&Object.keys(i.target).length>0&&s.push(ne("cameraTargetLerp","target",(new o).copyFrom(t.target),new o(i.target.x,i.target.y,i.target.z),A.ANIMATIONTYPE_VECTOR3,0)),s.push(ne("cameraAlphaLerp","alpha",t.alpha,ae(i.lonDeg),A.ANIMATIONTYPE_FLOAT,c)),s.push(ne("cameraBetaLerp","beta",t.beta,ae(i.latDeg),A.ANIMATIONTYPE_FLOAT,c)),void 0!==i.radius){const e=Math.max(.01,i.radius);s.push(ne("cameraRadiusLerp","radius",t.radius,e,A.ANIMATIONTYPE_FLOAT,c))}t.animations.push(...s);const h=t.useAutoRotationBehavior;t.disableAutoRotationBehavior(),e.beginAnimation(t,0,l?120:60,!1,1,(()=>{t.animations=[],h&&t.enableAutoRotationBehavior()}))}function ae(e){return e*Math.PI/180}function ne(e,t,i,a,n,r=0,s=A.ANIMATIONLOOPMODE_CONSTANT){const o=new R;o.setEasingMode(T.EASINGMODE_EASEINOUT);const l=new A(e,t,60,n,s),c=[];return r>0&&c.push({frame:0,value:i}),c.push({frame:60*r,value:i}),c.push({frame:60*(r+1),value:a}),l.setKeys(c),l.setEasingFunction(o),l}const re={albedoTexture:"albedoMap",bumpTexture:"normalMap",ambientTexture:"ambientMap",emissiveTexture:"emissionMap",opacityTexture:"alphaMap",metallicTexture:"metallicMap",refractionTexture:"refractionMap"};function se(e,t,i,a){["albedoTexture","bumpTexture","ambientTexture","emissiveTexture","opacityTexture","metallicTexture","refractionTexture"].forEach((n=>{!function(e,t,i,a,n){const r=re[e];if(!r)throw new Error("Unexpected texture name encountered.");const s=t[r]?.fileLink;s?a.addTextureTask(e,s,!1,!1):n&&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))}(n,e,t,i,a)})),function(e,t){if(!e.clearCoat)return;e.clearCoat===j.RemoveWhenSelected?(t.clearCoat.isEnabled=!1,t.clearCoat.indexOfRefraction=1.5):e.clearCoat===j.ApplyWhenSelected&&(t.clearCoat.isEnabled=!0,t.clearCoat.indexOfRefraction=e.clearCoatIOR||t.clearCoat.indexOfRefraction)}(e,t)}function oe(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 le(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class ce{constructor(e,t,i){le(this,"materialVariantMap",new Map),le(this,"keysThatRemovedBaseModel",[]),le(this,"loadedContainerForKey",new Map),le(this,"loadedMaterialsForKey",new Map),le(this,"scene",void 0),le(this,"renameClonedAsset",void 0),le(this,"setBaseModelEnabled",void 0),this.scene=e,this.renameClonedAsset=t,this.setBaseModelEnabled=i}async applyMaterial(e,t,i,a){return new Promise((n=>{e=this.renameClonedAsset(e);const r=this.scene.materials.filter((t=>t.name===e)),s=this.materialVariantMap.get(e);if(this.materialVariantMap.set(e,{...s,...t}),0===r.length)return void n(void 0);const o=new L(this.scene);o.useDefaultLoadingScreen=!1,r.forEach((e=>se(t,e,o,a))),o.onProgress=(e,t,a)=>{i&&i(e/t*100,100,a.name)},o.onFinish=e=>{e.forEach((e=>{const a=e;i&&i(100,100,e.name),r.forEach((i=>oe(e.name,i,t,a.texture)))})),n(void 0)},o.loadAsync()}))}async applyModel(e,t,i,a){if(i&&t&&!this.keysThatRemovedBaseModel.includes(e)&&this.keysThatRemovedBaseModel.push(e),!i)return this.keysThatRemovedBaseModel.includes(e)&&this.setBaseModelEnabled(!0),this.loadedContainerForKey.get(e)?.dispose(),this.loadedMaterialsForKey.delete(e),Promise.resolve(void 0);this.loadedContainerForKey.has(e)&&(this.loadedContainerForKey.get(e)?.dispose(),this.loadedMaterialsForKey.delete(e)),t&&this.setBaseModelEnabled(!1);const n=(await Z(i,this.scene,a)).instantiateModelsToScene(this.renameClonedAsset,!0);this.loadedContainerForKey.set(e,n),this.loadedMaterialsForKey.set(e,he(n));const r=[];return this.materialVariantMap.forEach((async(e,t)=>{r.push(this.applyMaterial(t,e))})),await Promise.all(r),n}getAllMaterials(){const e=[];return this.loadedMaterialsForKey.forEach((t=>{t.forEach((t=>{e.includes(t)||e.push(t)}))})),e}}function he(e){const t=[];return e.rootNodes.forEach((e=>{e.getChildMeshes().forEach((e=>{e.material&&t.push(e.material),e.subMeshes&&e.subMeshes.forEach((e=>{const i=e.getMaterial(!1);i&&t.push(i)}))}))})),t}function de(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class me{constructor(e){de(this,"id",void 0),de(this,"previewService",void 0),de(this,"scene",void 0),de(this,"variantManager",void 0),de(this,"materialSelectedObservable",new h),de(this,"materialDeselectedObservable",new h),de(this,"materialVariantObservable",new h),de(this,"modelVariantObservable",new h),de(this,"queuedModelAnimation",void 0),de(this,"materialReadyToLoadCallbacks",new Map),de(this,"modelReadyToLoadCallbacks",new Map),de(this,"dynamicTextures",new Map),de(this,"assetContainer",void 0),de(this,"canvasPanels",void 0),de(this,"contextService",void 0),de(this,"importPromise",void 0),de(this,"initialized",!1),de(this,"materials",[]),de(this,"modelInstance",void 0),de(this,"transformRoot",void 0);const{modelDetails:t,previewService:i,progressHandler:a,scene:n}=e;this.contextService=t.contextService,this.id=J(),this.previewService=i,this.scene=n,this.variantManager=new ce(n,this.renameClonedAsset.bind(this),this.setEnabled.bind(this)),this.previewService.registerInitializedListener((async()=>await this.processQueuedEvents()));this.importPromise=(async()=>{this.assetContainer=await Z(t.model,n,a),this.initialized=!0,this.transformRoot=new C("root",this.scene),this.instantiate()})()}async applyMaterialVariant(e,t,i,a){if(100===this.previewService.getSceneInitializationProgress()&&this.initialized)await this.variantManager.applyMaterial(e,i,((e,t,i)=>{this.materialVariantObservable.notifyObservers({remainingCount:e,totalCount:t,taskName:i})}),a);else if(this.materialReadyToLoadCallbacks.has(e)){this.materialReadyToLoadCallbacks.get(e)?.set(t,this.applyMaterialVariant.bind(this,e,t,i,a))}else{this.materialReadyToLoadCallbacks.set(e,new Map);this.materialReadyToLoadCallbacks.get(e)?.set(t,this.applyMaterialVariant.bind(this,e,t,i,a))}}async applyModelVariant(e,t,i){if(100!==this.previewService.getSceneInitializationProgress()||!this.initialized)return void this.modelReadyToLoadCallbacks.set(e,this.applyModelVariant.bind(this,e,t,i));const a=await this.variantManager.applyModel(e,i,t?.model,(t=>{this.modelVariantObservable.notifyObservers({...t,key:e})}));this.modelInstance&&te(this.modelInstance.animationGroups),this.contextService||(this.contextService=t?.contextService),a&&this.configureModelInstance(a)}executeAnimation(e){100===this.previewService.getSceneInitializationProgress()?this.modelInstance&&ee(this.modelInstance.animationGroups,e.loop,e.to,e.from):this.queuedModelAnimation=e}getId(){return this.id}listMaterials(){const e=this.scene?.materials.filter((e=>e.name.startsWith(this.id)));return e?e.map((e=>({id:e.id,name:e.name}))):[]}registerMaterialSelectedCallback(e){this.materialSelectedObservable.add(e)}unregisterMaterialSelectedCallback(e){this.materialSelectedObservable.removeCallback(e)}registerMaterialDeselectedCallback(e){this.materialDeselectedObservable.add(e)}unregisterMaterialDeselectedCallback(e){this.materialDeselectedObservable.removeCallback(e)}get position(){return this.transformRoot.position}set position(e){this.transformRoot.position=new o(e.x,e.y,e.z)}get rotation(){return this.transformRoot.rotation}set rotation(e){this.transformRoot.rotation=new o(e.x,e.y,e.z)}get scale(){return this.transformRoot.scaling}set scale(e){this.transformRoot.scaling=new o(e.x,e.y,e.z)}attachPickingHandler(e){e.rootNodes.forEach((e=>{e.getChildMeshes(!1).forEach((e=>{"targetcube_t"!==e.name&&"backgroundShell"!==e.name&&(e.isPickable=!0,e.actionManager||(e.actionManager=new P(this.scene)),e.actionManager||(e.actionManager=new P(this.scene)),e.actionManager.registerAction(new w(P.OnPointerOutTrigger,(()=>{e.material&&this.materialDeselectedObservable.notifyObservers({id:e.material.id,name:e.material.name})}))),e.actionManager.registerAction(new w(P.OnPickDownTrigger,(t=>{t.meshUnderPointer&&e.material&&this.materialSelectedObservable.notifyObservers({id:e.material.id,name:e.material.name})}))))}))}))}getImportPromise(){return this.importPromise}getQueuedMaterialVariantCount(){return this.materialReadyToLoadCallbacks.size}getQueuedModelVariantCount(){return this.modelReadyToLoadCallbacks.size}configureModelInstance(e){const t=this.transformRoot.position,i=this.transformRoot.rotation,a=this.transformRoot.scaling;this.transformRoot.position=o.Zero(),this.transformRoot.rotation=o.Zero(),this.transformRoot.scaling=o.One(),e.rootNodes.forEach((e=>{e.parent=this.transformRoot})),this.transformRoot.position=t,this.transformRoot.rotation=i,this.transformRoot.scaling=a,this.canvasPanels=this.contextService?.getAll()||new Map,$(this.materials.concat(this.variantManager.getAllMaterials()),this.scene,this.canvasPanels,this.dynamicTextures,`${this.id}_`),this.attachPickingHandler(e)}dispose(){this.modelInstance.dispose(),this.modelInstance=void 0}instantiate(){this.modelInstance=this.assetContainer.instantiateModelsToScene(this.renameClonedAsset.bind(this),!0),this.materials=he(this.modelInstance),this.configureModelInstance(this.modelInstance);if(this.materials.some((e=>"emissiveTexture"in e&&null!==e.emissiveTexture))){new M("GlowLayer",this.scene).intensity=.5}this.processQueuedEvents()}renameClonedAsset(e){return`${this.id}_${e}`}setEnabled(e){e&&!this.modelInstance?this.instantiate():!e&&this.modelInstance&&this.dispose()}updateDynamicTextures(){this.canvasPanels?.forEach(((e,t)=>{const i=this.dynamicTextures.get(t);i&&e.getStaticContextDirty()&&i.isReady()&&(i.update(!1),e.setStaticContextDirty(!1))}))}registerMaterialVariantListener(e){this.materialVariantObservable.add(e)}unregisterMaterialVariantListener(e){this.materialVariantObservable.removeCallback(e)}registerModelVariantListener(e){this.modelVariantObservable.add(e)}unregisterModelVariantListener(e){this.modelVariantObservable.removeCallback(e)}async processQueuedEvents(){100===this.previewService.getSceneInitializationProgress()&&(await Promise.all(Array.from(this.materialReadyToLoadCallbacks.values()).map((e=>Array.from(e.values()).map((e=>e()))))),this.materialReadyToLoadCallbacks.clear(),await Promise.all(Array.from(this.modelReadyToLoadCallbacks.values()).map((e=>e()))),this.modelReadyToLoadCallbacks.clear(),this.queuedModelAnimation&&(this.executeAnimation(this.queuedModelAnimation),this.queuedModelAnimation=void 0))}}function ge(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class ue extends E{constructor(e,t,i,a,n,r,s,l){super(e,t,i,a,n,r,l),ge(this,"lastFocus",new o(0,0,0)),ge(this,"panDenominator",1),this.minZ=.01,this.setRadius(this.radius),this.enableFramingBehavior(),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=pe(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,t){const i=this.getFramingBehavior();i.framingTime=t||800;const a=pe(this._scene),n=a.max.subtract(a.min),r=a.min.add(n.scale(.5));this.setRadius(1.5*n.length()),this.wheelPrecision=100/this.radius,this.panningInertia=0,this.panningOriginTarget.copyFrom(r),this.panDenominator=n.length(),i.zoomOnBoundingInfo(a.min,a.max,void 0,(()=>{e&&e()})),i.framingTime=0}enableAutoRotationBehavior(e=5e3){this.useAutoRotationBehavior=!0;const t=this.getAutoRotationBehavior();t&&(t.idleRotationWaitTime=e)}disableAutoRotationBehavior(){this.useAutoRotationBehavior=!1}setRadius(e){this.radius=e,this.maxZ=1e3*this.radius,this.lowerRadiusLimit=.01*this.radius,this.upperRadiusLimit=1.5*this.radius,this.wheelPrecision=100/this.radius,this.pinchPrecision=300/this.radius}static create(e,t,i){const a=pe(e),n=a.max.subtract(a.min),r=a.min.add(n.scale(.5)),s=new ue("ProductCamera",-Math.PI/2,Math.PI/2,1.5*n.length(),r,e,t);return s.panningInertia=0,s.panningOriginTarget.copyFrom(r),s.panDenominator=n.length(),s.onAfterCheckInputsObservable.add((()=>{s.panningSensibility=1e3/s.panDenominator})),i&&(e.activeCamera=s),s}}function pe(e){if(0===e.meshes.length)return{min:new o(-1,-1,-1),max:new o(1,1,1)};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))))}function be(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class fe{constructor(e,t=!0,i=null){be(this,"renderingPipeline",void 0),be(this,"currentConfiguration",void 0),this.renderingPipeline=new F("default",t,e,i?[i]:void 0,!1),this.renderingPipeline.isSupported&&this.renderingPipeline.prepare()}dispose(){this.renderingPipeline.dispose()}addCamera(e){this.renderingPipeline.isSupported&&this.renderingPipeline.addCamera(e)}removeCamera(e){this.renderingPipeline.isSupported&&this.renderingPipeline.removeCamera(e)}getConfiguration(){return this.currentConfiguration}setConfiguration(e){if(this.renderingPipeline.isSupported){if(this.renderingPipeline.samples=e.antiAliasing?.samples??q.antiAliasing.samples,this.renderingPipeline.fxaaEnabled=e.antiAliasing?.fxaaEnabled??q.antiAliasing.fxaaEnabled,this.renderingPipeline.bloomEnabled=e.bloom?.enabled??q.bloom.enabled,this.renderingPipeline.bloomKernel=e.bloom?.kernel??q.bloom.kernel,this.renderingPipeline.bloomScale=e.bloom?.scale??q.bloom.scale,this.renderingPipeline.bloomThreshold=e.bloom?.threshold??q.bloom.threshold,this.renderingPipeline.bloomWeight=e.bloom?.weight??q.bloom.weight,this.renderingPipeline.chromaticAberrationEnabled=e.chromaticAberration?.enabled??q.chromaticAberration.enabled,this.renderingPipeline.chromaticAberration.aberrationAmount=e.chromaticAberration?.aberrationAmount??q.chromaticAberration.aberrationAmount,this.renderingPipeline.chromaticAberration.radialIntensity=e.chromaticAberration?.radialIntensity??q.chromaticAberration.radialIntensity,this.renderingPipeline.chromaticAberration.direction=e.chromaticAberration?.direction?new l(e.chromaticAberration.direction.x,e.chromaticAberration.direction.y):new l(q.chromaticAberration.direction.x,q.chromaticAberration.direction.y),this.renderingPipeline.imageProcessing.colorCurvesEnabled=e.colorCurves?.enabled??q.colorCurves.enabled,this.renderingPipeline.imageProcessing.colorCurves=e.colorCurves?this.updateColorCurve(e.colorCurves):new S,this.renderingPipeline.depthOfFieldEnabled=e.depthOfField?.enabled??q.depthOfField.enabled,e.depthOfField)switch(e.depthOfField.blurLevel??q.depthOfField.blurLevel){case"Low":this.renderingPipeline.depthOfFieldBlurLevel=D.Low;break;case"Medium":this.renderingPipeline.depthOfFieldBlurLevel=D.Medium;break;case"High":this.renderingPipeline.depthOfFieldBlurLevel=D.High}if(this.renderingPipeline.depthOfField.focalLength=e.depthOfField?.focalLength??q.depthOfField.focalLength,this.renderingPipeline.depthOfField.fStop=e.depthOfField?.fStop??q.depthOfField.fStop,this.renderingPipeline.depthOfField.focusDistance=e.depthOfField?.focusDistance??q.depthOfField.focusDistance,this.renderingPipeline.depthOfField.lensSize=e.depthOfField?.lensSize??q.depthOfField.lensSize,this.renderingPipeline.grainEnabled=e.grain?.enabled??q.grain.enabled,this.renderingPipeline.grain.animated=e.grain?.animated??q.grain.animated,this.renderingPipeline.grain.intensity=e.grain?.intensity??q.grain.intensity,this.renderingPipeline.imageProcessing.contrast=e.misc?.contrast??q.misc.contrast,this.renderingPipeline.imageProcessing.exposure=e.misc?.exposure??q.misc.exposure,this.renderingPipeline.imageProcessing.toneMappingEnabled=e.misc?.toneMappingEnabled??q.misc.toneMappingEnabled,this.renderingPipeline.imageProcessing.toneMappingEnabled)switch(e.misc.toneMappingType??q.misc.toneMappingType){case"Standard":this.renderingPipeline.imageProcessing.toneMappingType=I.TONEMAPPING_STANDARD;break;case"ACES":this.renderingPipeline.imageProcessing.toneMappingType=I.TONEMAPPING_ACES}if(this.renderingPipeline.sharpenEnabled=e.sharpen?.enabled??q.sharpen.enabled,this.renderingPipeline.sharpen.colorAmount=e.sharpen?.colorAmount??q.sharpen.colorAmount,this.renderingPipeline.sharpen.edgeAmount=e.sharpen?.edgeAmount??q.sharpen.edgeAmount,this.renderingPipeline.imageProcessing.vignetteEnabled=e.vignette?.enabled??q.vignette.enabled,e.vignette?.center?(this.renderingPipeline.imageProcessing.vignetteCenterX=e.vignette.center.x,this.renderingPipeline.imageProcessing.vignetteCenterY=e.vignette.center.y):(this.renderingPipeline.imageProcessing.vignetteCenterX=q.vignette.center.x,this.renderingPipeline.imageProcessing.vignetteCenterY=q.vignette.center.y),e.vignette)switch(e.vignette?.blendMode??q.vignette.blendMode){case"Multiply":this.renderingPipeline.imageProcessing.vignetteBlendMode=I.VIGNETTEMODE_MULTIPLY;break;case"Opaque":this.renderingPipeline.imageProcessing.vignetteBlendMode=I.VIGNETTEMODE_OPAQUE}e.vignette?.colorRgba?this.renderingPipeline.imageProcessing.vignetteColor=new s(e.vignette.colorRgba.r,e.vignette.colorRgba.g,e.vignette.colorRgba.b,e.vignette.colorRgba.a):e.vignette?.colorHex?this.renderingPipeline.imageProcessing.vignetteColor=s.FromHexString(e.vignette.colorHex):this.renderingPipeline.imageProcessing.vignetteColor=new s(q.vignette.colorRgba.r,q.vignette.colorRgba.g,q.vignette.colorRgba.b,q.vignette.colorRgba.a),this.renderingPipeline.imageProcessing.vignetteStretch=e.vignette?.stretch??q.vignette.stretch,this.renderingPipeline.imageProcessing.vignetteWeight=e.vignette?.weight??q.vignette.weight,this.renderingPipeline.prepare(),this.currentConfiguration=e}}updateColorCurve(e){const t=new S;return t.globalDensity=e.globalDensity??t.globalDensity,t.globalExposure=e.globalExposure??t.globalExposure,t.globalHue=e.globalHue??t.globalHue,t.globalSaturation=e.globalSaturation??t.globalSaturation,t.highlightsDensity=e.highlightsDensity??t.highlightsDensity,t.highlightsExposure=e.highlightsExposure??t.highlightsExposure,t.highlightsHue=e.highlightsHue??t.highlightsHue,t.highlightsSaturation=e.highlightsSaturation??t.highlightsSaturation,t.midtonesDensity=e.midtonesDensity??t.midtonesDensity,t.midtonesExposure=e.midtonesExposure??t.midtonesExposure,t.midtonesHue=e.midtonesHue??t.midtonesHue,t.midtonesSaturation=e.midtonesSaturation??t.midtonesSaturation,t.shadowsDensity=e.shadowsDensity??t.shadowsDensity,t.shadowsExposure=e.shadowsExposure??t.shadowsExposure,t.shadowsHue=e.shadowsHue??t.shadowsHue,t.shadowsSaturation=e.shadowsSaturation??t.shadowsSaturation,t}}function ve(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}g.GLTFLoader.RegisterExtension("glbPostProcessor",(function(e){return new Q(e)})),a.OnPluginActivatedObservable.add((e=>{if("gltf"===e.name){e.transparencyAsCoverage=!0}}));class ye{constructor(i){ve(this,"camera",void 0),ve(this,"configuration",void 0),ve(this,"engine",void 0),ve(this,"scene",void 0),ve(this,"loadProgress",new Map([["initialScene",0]])),ve(this,"queuedCameraAnimation",void 0),ve(this,"focusLostNotified",!1),ve(this,"loadObservable",new h),ve(this,"focusLostObservable",new h),ve(this,"initializedCallbacks",[]),ve(this,"isInitialized",!1),ve(this,"highlightLayer",void 0),ve(this,"renderingPipeline",void 0),ve(this,"modelContainers",new Map),ve(this,"plugins",[]);const a=i?.noRender?void 0:document.createElement("canvas");this.configuration=new _(i);c.Configuration={decoder:{wasmUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.6/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.6/draco_decoder_gltf.wasm",fallbackUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.6/draco_decoder_gltf.js"}},a&&(a.getContext("webgl2")||a.getContext("webgl"));const n=console.log;console.log=()=>{};const r=a?new e(a,!0,{adaptToDeviceRatio:!0,limitDeviceRatio:2,premultipliedAlpha:!1,preserveDrawingBuffer:!!i?.backgroundImage,audioEngine:!1,stencil:this.configuration.highlights.enabled,forceSRGBBufferSupportState:!0}):new t;console.log=n,r.hideLoadingUI(),window.addEventListener("resize",this.fireResizeEvent.bind(this)),this.engine=r,this.scene=new m(r),this.camera=ue.create(this.scene,this.configuration),this.renderingPipeline=new fe(this.scene,!0),this.renderingPipeline.addCamera(this.camera),this.scene.imageProcessingConfiguration.exposure=this.configuration.lighting.exposure,this.scene.imageProcessingConfiguration.contrast=this.configuration.lighting.contrast}getEngineContext(){return{engine:this.engine,scene:this.scene,camera:this.camera}}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)}registerInitializedListener(e){this.isInitialized||!this.isInitialized&&this.initializedCallbacks.push(e)}unregisterInitializedListener(e){if(this.isInitialized)return;const t=this.initializedCallbacks.indexOf(e);t>-1&&this.initializedCallbacks.splice(t,1)}getIsInitialized(){return this.isInitialized}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(z.Pan),this.reattachControls(e)}getNumViewports(){return this.engine.views?.length||0}unregisterView(e){this.engine.unRegisterView(e)}shutdown(){this.plugins.forEach((e=>e.dispose(!0))),this.renderingPipeline.dispose(),this.engine&&this.engine.dispose(),window.removeEventListener("resize",this.fireResizeEvent)}getSceneInitializationProgress(){return this.loadProgress.get("initialScene")}async initialize(e){let t;if(this.scene.clearColor=this.configuration.scene.clearColor,this.scene.environmentTexture=n.CreateFromPrefilteredData(this.configuration.scene.environmentFile,this.scene),e){const i=100;t=await this.loadModel(e,(e=>{this.loadProgress.set("initialScene",e.loaded*i/e.total),this.notifyLoadHandlers()}))}return this.loadProgress.set("initialScene",100),this.notifyLoadHandlers(),this.scene.activeCamera=this.camera,this.camera.rerunFramingBehavior(void 0,1),this.configuration.options?.renderingPipelineConfiguration&&this.renderingPipeline.setConfiguration(this.configuration.options.renderingPipelineConfiguration),te(this.scene.animationGroups),this.engine.views?.length>=1&&this.reattachControls(this.engine.views[this.engine.views.length-1].target),await this.processQueuedLoadEvents(),await Promise.all(this.initializedCallbacks.map((e=>e()))),this.initializedCallbacks=[],this.isInitialized=!0,this.engine.runRenderLoop((()=>{this.engine.views&&(this.modelContainers.forEach((e=>{e.updateDynamicTextures()})),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(),this.camera.target.equalsWithEpsilon(this.camera.lastFocus,.1)||this.focusLostNotified||(this.focusLostObservable.notifyObservers(void 0),this.focusLostNotified=!0))})),t}executeCameraAnimation(e){100===this.getSceneInitializationProgress()&&this.camera&&this.scene.activeCamera===this.camera?ie(this.scene,this.scene.activeCamera,e):this.queuedCameraAnimation=e}getCameraPose(){if(this.scene&&this.camera)return{lonDeg:Math.round(180*this.camera.alpha/Math.PI),latDeg:Math.round(180*this.camera.beta/Math.PI),radius:Math.round(1e4*(this.camera.radius+Number.EPSILON))/1e4,target:{x:this.camera.target.x,y:this.camera.target.y,z:this.camera.target.z}}}setCameraPose(e){this.scene&&this.camera&&(this.camera.target=new o(e.target.x,e.target.y,e.target.z),this.camera.radius=e.radius,this.camera.alpha=e.latDeg,this.camera.beta=e.lonDeg)}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===z.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.configuration;this.camera.rerunFramingBehavior((()=>{this.focusLostNotified=!1,t.camera.limits.min.radius&&(this.camera.lowerRadiusLimit=t.camera.limits.min.radius),t.camera.limits.max.radius&&(this.camera.upperRadiusLimit=t.camera.limits.max.radius),e()}))}))}setAutoRotation(e){this.configuration.camera.autoRotation.enabled&&this.camera&&(e?this.camera.enableAutoRotationBehavior(this.configuration.camera.autoRotation.idleTimeMs):this.camera.disableAutoRotationBehavior())}getCurrentConfiguration(){return this.configuration.options}async renderSceneScreenshot(e,t){if(!this.camera)throw new Error("Missing product camera, cannot render screenshot!");var i;(i=this.camera).getScene().stopAnimation(i),i.animations=[];const a=this.camera.alpha,n=this.camera.beta,r=this.camera.radius,s=t.latDeg*Math.PI/180,o=t.lonDeg*Math.PI/180;this.camera.alpha=o,this.camera.beta=s,this.camera.radius=t.radius||this.camera.radius;const l=await d.CreateScreenshotUsingRenderTargetAsync(this.engine,this.camera,e,"image/png",2,!0);return this.camera.alpha=a,this.camera.beta=n,this.camera.radius=r,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,n=e.camera.limits.max.beta;if(void 0===t||void 0===i||void 0===a||void 0===n)return!0;const r=[a,n],s=[t,i].every((e=>e===t)),o=r.every((e=>e===a));return!s&&!o}fireResizeEvent(){this.getNumViewports()>0&&this.engine.resize()}setHighlights(e,t){0===e.length&&(this.highlightLayer?.dispose(),this.highlightLayer=void 0),this.highlightLayer||(this.highlightLayer=new i("highlights",this.scene,{isStroke:!0,blurVerticalSize:.85,blurHorizontalSize:.85}),this.highlightLayer.innerGlow=!0,this.highlightLayer.outerGlow=!1),this.highlightLayer.removeAllMeshes();const a=t?new r(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||r.FromHexString("#fcba03"))))}))}setRenderingPipelineConfiguration(e){this.renderingPipeline&&this.renderingPipeline.setConfiguration(e)}async loadModel(e,t){const i=new me({modelDetails:e,scene:this.scene,previewService:this,progressHandler:t});return i.registerMaterialVariantListener((e=>this.handleMaterialProgressCallback(e.remainingCount,e.totalCount,e.taskName))),i.registerModelVariantListener((e=>this.handleModelProgressCallback(e,e.key))),this.configuration.highlights.enabled&&(i.registerMaterialSelectedCallback((e=>{this.setHighlights([e])})),i.registerMaterialDeselectedCallback((()=>{this.setHighlights([])}))),this.modelContainers.set(i.getId(),i),await i.getImportPromise(),i}getAllModels(){return Array.from(this.modelContainers.values())}getModelById(e){return this.modelContainers.get(e)}registerPlugin(e){this.plugins.push(e),e.initialize(this,{camera:this.camera,engine:this.engine,scene:this.scene})}unregisterPlugin(e){const t=this.plugins.indexOf(e);if(t>-1){this.plugins.splice(t,1).forEach((e=>e.dispose(!1)))}}handleMaterialProgressCallback(e,t,i){this.loadProgress.set(`key_${i}`,e/t*100),this.notifyLoadHandlers()}handleModelProgressCallback(e,t){this.loadProgress.set(t,100*e.loaded/e.total),this.notifyLoadHandlers()}reattachControls(e,t=2){if(this.scene.detachControl(),this.engine.inputElement=e,this.camera){this.camera.attachControl(!0,!1,t);this.camera.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 processQueuedLoadEvents(){this.queuedCameraAnimation&&(this.executeCameraAnimation(this.queuedCameraAnimation),this.queuedCameraAnimation=void 0)}}export{z as ProductCameraRig,j as MaterialEffectMode,ye as SpiffCommerce3DPreviewService,U as RenderingConfiguration,W as REFLECTION_PROBE_RESOLUTION,q as renderingPipelineDefaults};
2
2
  //# sourceMappingURL=module.js.map
package/dist/types.d.ts CHANGED
@@ -1,5 +1,11 @@
1
- import { ISceneLoaderProgressEvent } from "@babylonjs/core/Loading/sceneLoader";
1
+ import { Color4 } from "@babylonjs/core/Maths/math.color";
2
+ import { AutoRotationBehavior } from "@babylonjs/core/Behaviors/Cameras/autoRotationBehavior";
3
+ import { FramingBehavior } from "@babylonjs/core/Behaviors/Cameras/framingBehavior";
4
+ import { ArcRotateCamera } from "@babylonjs/core/Cameras/arcRotateCamera";
5
+ import { Vector3 } from "@babylonjs/core/Maths/math.vector";
2
6
  import { Scene } from "@babylonjs/core/scene";
7
+ import { Engine } from "@babylonjs/core/Engines/engine";
8
+ import { ISceneLoaderProgressEvent } from "@babylonjs/core/Loading/sceneLoader";
3
9
  /**
4
10
  * Defines the different behaviors supported by the camera system
5
11
  * for control when viewing a product.
@@ -12,8 +18,14 @@ export enum ProductCameraRig {
12
18
  * Details relating to a model for use in the preview.
13
19
  */
14
20
  export type ModelDetails = {
21
+ /**
22
+ * The source of the model to load.
23
+ */
15
24
  readonly model?: string;
16
- readonly contextService: RenderableContextService;
25
+ /**
26
+ * A reference to the renderable context service to use.
27
+ */
28
+ readonly contextService?: RenderableContextService;
17
29
  };
18
30
  /**
19
31
  * Identical to CameraAnimation typing, however the
@@ -55,6 +67,20 @@ export type ThreeDPreviewService = {
55
67
  * @param listener The listener to exclude from load progress.
56
68
  */
57
69
  unregisterLoadProgressListener(listener: (e: LoadProgressEventData) => void): void;
70
+ /**
71
+ * Provides a callback that will be called when the service has been initialized.
72
+ * @param listener The callback function to add.
73
+ */
74
+ registerInitializedListener(listener: () => void | Promise<void>): void;
75
+ /**
76
+ * Removes a callback from the observables that would be called when the service has been initialized.
77
+ * @param listener The function to remove.
78
+ */
79
+ unregisterInitializedListener(listener: () => void | Promise<void>): void;
80
+ /**
81
+ * Returns true if the service has been initialized.
82
+ */
83
+ getIsInitialized(): boolean;
58
84
  /**
59
85
  * Request that the scene renders to a given canvas
60
86
  * @param canvas The canvas we should render to.
@@ -71,18 +97,15 @@ export type ThreeDPreviewService = {
71
97
  */
72
98
  unregisterView(canvas: HTMLCanvasElement): void;
73
99
  /**
74
- * Shutdown the preview engine. Noop if the engine is not initialized.
100
+ * Shutdown the preview engine and all registered plugins. Noop if the engine is not initialized.
75
101
  */
76
102
  shutdown(): void;
77
103
  /**
78
104
  * Initialize the scene. Also initialize the engine, if it hasn't been done already.
105
+ * @param modelDetails Optional model details to load.
106
+ * @returns A promise that resolves with the model container, or undefined if no model was loaded.
79
107
  */
80
- initialize(src: string, contextService?: RenderableContextService): Promise<void>;
81
- /**
82
- * Executes an animation in the currently loaded scene.
83
- * @param animation The current animation track to run.
84
- */
85
- executeModelAnimation(animation: ModelAnimation): void;
108
+ initialize(modelDetails?: ModelDetails): Promise<ModelContainer | undefined>;
86
109
  /**
87
110
  * Executes an animation of the camera.
88
111
  * @param animation The animation to execute.
@@ -96,20 +119,6 @@ export type ThreeDPreviewService = {
96
119
  * Sets the values of the Arc Rotate Camera
97
120
  */
98
121
  setCameraPose(cameraPose: CameraPose): void;
99
- /**
100
- * Applies a given material modifier to a target material in the scene.
101
- * @param targetMaterial The material to target.
102
- * @param key A unique key used to identify this action.
103
- * @param material The material modifier to apply.
104
- */
105
- applyMaterialVariant(targetMaterial: string, key: string, material: MaterialResource, removeWhenUndefined?: boolean): Promise<void>;
106
- /**
107
- * Applies a given model variant to the scene.
108
- * @param key A unique key used to identify this action.
109
- * @param model modelDetails -> An asset containing a model file to be loaded into the scene.
110
- * @param layouts modelDetails -> The layouts of the workflow, used for applying dynamic textures.
111
- */
112
- applyModelVariant(key: string, modelDetails: ModelDetails, replaceProductModel: boolean): Promise<void>;
113
122
  /**
114
123
  * Controls the current control state of the camera.
115
124
  * @param rigType The control type to use.
@@ -153,15 +162,6 @@ export type ThreeDPreviewService = {
153
162
  * also prevents performance problems.
154
163
  */
155
164
  fireResizeEvent(): void;
156
- /**
157
- * A callback when the user clicks in the scene and a material is hit.
158
- */
159
- onMaterialSelected(cb: (material: MaterialHandle) => void): void;
160
- /**
161
- * Designed for use when utilizing the 3D preview in an editor format.
162
- * List named materials that are available in the scene.
163
- */
164
- listMaterials(): readonly MaterialHandle[];
165
165
  /**
166
166
  * Designed for use when utilizing the 3D preview in an editor format.
167
167
  * Given a list of material names, highlights the associated meshes in the scene.
@@ -172,6 +172,33 @@ export type ThreeDPreviewService = {
172
172
  * @param renderingPipelineConfiguration The configuration to apply. Empty values will be set to default.
173
173
  */
174
174
  setRenderingPipelineConfiguration(renderingPipelineConfiguration: RenderingPipelineConfiguration): void;
175
+ /**
176
+ * Loads a model into the scene.
177
+ * @param modelDetails The details of the model to load.
178
+ * @returns A promise that resolves with the model container.
179
+ */
180
+ loadModel(modelDetails: ModelDetails): Promise<ModelContainer>;
181
+ /**
182
+ * Returns all loaded models.
183
+ * @returns A map of id to model container.
184
+ */
185
+ getAllModels(): ReadonlyArray<ModelContainer>;
186
+ /**
187
+ * Retrieves a loaded model by it's id.
188
+ * @param id The id of the model to retrieve.
189
+ * @returns The model container if it exists, undefined otherwise.
190
+ */
191
+ getModelById(id: string): ModelContainer | undefined;
192
+ /**
193
+ * Registers a plugin with the preview service.
194
+ * @param plugin The plugin to register.
195
+ */
196
+ registerPlugin(plugin: PreviewServicePlugin): void;
197
+ /**
198
+ * Removes a plugin from the preview service.
199
+ * @param plugin The plugin to remove.
200
+ */
201
+ unregisterPlugin(plugin: PreviewServicePlugin): void;
175
202
  };
176
203
  /**
177
204
  * Represents a service capable of managing and returning contexts that
@@ -682,6 +709,165 @@ export interface Color4Configuration {
682
709
  b: number;
683
710
  a: number;
684
711
  }
712
+ export interface Vector {
713
+ x: number;
714
+ y: number;
715
+ z: number;
716
+ }
717
+ /**
718
+ * Wraps functionality for interacting with models in the scene.
719
+ */
720
+ export type ModelContainer = {
721
+ /**
722
+ * Applies a given material modifier to a target material in the scene.
723
+ * @param targetMaterial The material to target.
724
+ * @param key A unique key used to identify this action.
725
+ * @param material The material modifier to apply.
726
+ * @param removeWhenUndefined Whether or not to remove the material modifier when the material is undefined.
727
+ */
728
+ applyMaterialVariant(targetMaterial: string, key: string, material: Partial<MaterialResource>, removeWhenUndefined?: boolean): Promise<void>;
729
+ /**
730
+ * Applies a given model variant to the scene.
731
+ * @param key A unique key used to identify this action.
732
+ * @param model modelDetails -> An asset containing a model file to be loaded into the scene.
733
+ * If undefined, the model will be removed from the scene.
734
+ * @param replaceProductModel Whether or not to replace the product model with the new model.
735
+ */
736
+ applyModelVariant(key: string, modelDetails: ModelDetails | undefined, replaceProductModel: boolean): Promise<void>;
737
+ /**
738
+ * Executes an animation on the model.
739
+ * @param animation The animation track to run.
740
+ */
741
+ executeAnimation(animation: ModelAnimation): void;
742
+ /**
743
+ * Returns the unique ID of the model container.
744
+ */
745
+ getId(): string;
746
+ /**
747
+ * List named materials that are available on the model.
748
+ * Designed for use when utilizing the 3D preview in an editor format.
749
+ */
750
+ listMaterials(): readonly MaterialHandle[];
751
+ /**
752
+ * Registers a callback that will be invoked when a material is under the cursor.
753
+ * @param callback The callback to register.
754
+ */
755
+ registerMaterialSelectedCallback(callback: (material: MaterialHandle) => void): void;
756
+ /**
757
+ * Removes a callback that was previously registered to be invoked when a material is under the cursor.
758
+ * @param callback The callback to unregister.
759
+ */
760
+ unregisterMaterialSelectedCallback(callback: (material: MaterialHandle) => void): void;
761
+ /**
762
+ * Registers a callback that will be invoked when a material is no longer under the cursor.
763
+ * @param callback The callback to register.
764
+ */
765
+ registerMaterialDeselectedCallback(callback: (material: MaterialHandle) => void): void;
766
+ /**
767
+ * Removes a callback that was previously registered to be invoked when a material is no longer under the cursor.
768
+ * @param callback The callback to unregister.
769
+ */
770
+ unregisterMaterialDeselectedCallback(callback: (material: MaterialHandle) => void): void;
771
+ /**
772
+ * The position of the model, in scene space.
773
+ */
774
+ position: Vector;
775
+ /**
776
+ * The rotation of the model, in scene space.
777
+ */
778
+ rotation: Vector;
779
+ /**
780
+ * The scale of the model, in scene space.
781
+ */
782
+ scale: Vector;
783
+ };
784
+ /**
785
+ * Provides references to 3D preview engine objects.
786
+ * The types of these objects are dependent on the engine being used.
787
+ */
788
+ export type EngineContext = {
789
+ /**
790
+ * The camera being used by the ThreeDPreviewService.
791
+ */
792
+ camera: any;
793
+ /**
794
+ * The 3D engine.
795
+ */
796
+ engine: any;
797
+ /**
798
+ * The active scene.
799
+ */
800
+ scene: any;
801
+ };
802
+ /**
803
+ * A plugin that provides additional functionality to the preview service.
804
+ */
805
+ export type PreviewServicePlugin = {
806
+ /**
807
+ * Called when the plugin is first registered with the preview service.
808
+ * @param previewService A reference to the preview service.
809
+ * @param context A reference to the engine context.
810
+ */
811
+ initialize(previewService: ThreeDPreviewService, context: EngineContext): void;
812
+ /**
813
+ * Called when the plugin is unregistered from the preview service.
814
+ * Use this to cleanup any resources that have been allocated.
815
+ * This will be called automatically when the preview service is shutdown, or when the plugin is unregistered.
816
+ * @param isServiceShutdown True if the service is being shutdown, false if the plugin is being unregistered.
817
+ */
818
+ dispose(isServiceShutdown: boolean): void;
819
+ };
820
+ /**
821
+ * Configuration for the preview. Optionally, you can provide a custom configuration. (from a workflow for example) Sensible
822
+ * defaults will be specified for all properties otherwise.
823
+ */
824
+ declare class Configuration {
825
+ readonly customOptions?: PreviewOptions;
826
+ constructor(options?: PreviewOptions);
827
+ get options(): PreviewOptions;
828
+ /**
829
+ * Configuration related to the scene
830
+ */
831
+ get scene(): {
832
+ clearColor: Color4;
833
+ transparentBackground: string | true;
834
+ environmentFile: string;
835
+ };
836
+ /**
837
+ * Configuration related to the camera used to view and interact with the scene.
838
+ */
839
+ get camera(): {
840
+ autoOrientation: boolean;
841
+ autoRotation: {
842
+ enabled: boolean;
843
+ idleTimeMs: number;
844
+ };
845
+ limits: {
846
+ min: {
847
+ alpha: number;
848
+ beta: number;
849
+ radius: number;
850
+ };
851
+ max: {
852
+ alpha: number;
853
+ beta: number;
854
+ radius: number;
855
+ };
856
+ };
857
+ };
858
+ /**
859
+ * Configuration related to the highlighting system. Highlights are used to add
860
+ * a visual cue to the user that something is moused over in the preview.
861
+ */
862
+ get highlights(): {
863
+ enabled: boolean;
864
+ color: Color4;
865
+ };
866
+ get lighting(): {
867
+ exposure: number;
868
+ contrast: number;
869
+ };
870
+ }
685
871
  /**
686
872
  * Represents the dimensions of a texture, enforcing power of two numbers.
687
873
  */
@@ -713,6 +899,58 @@ export class RenderingConfiguration {
713
899
  export const REFLECTION_PROBE_RESOLUTION = 128;
714
900
  export type PowerOfTwoNumber = 128 | 256 | 512 | 1024 | 2048 | 4096 | 8192;
715
901
  export const renderingPipelineDefaults: RenderingPipelineConfiguration;
902
+ /**
903
+ * A slightly extended version of the ArcRotateCamera.
904
+ * Configures the camera in a way that best suites product visualization.
905
+ * Also provides some convenience functions for interacting with the camera at runtime.
906
+ */
907
+ declare class ProductCamera extends ArcRotateCamera {
908
+ constructor(name: string, alpha: number, beta: number, radius: number, target: Vector3, scene: Scene, configuration: Configuration, setActiveOnSceneIfNoneActive?: boolean);
909
+ /**
910
+ * Stores the current executed target point of the camera. If the camera target changes
911
+ * via panning we can notify ui about the fact to help users reset the camera.
912
+ */
913
+ readonly lastFocus: Vector3;
914
+ /**
915
+ * Returns the framing behavior of this camera.
916
+ */
917
+ getFramingBehavior(): FramingBehavior;
918
+ /**
919
+ * Returns the auto rotation behavior of this camera, this may
920
+ * not always be available.
921
+ */
922
+ getAutoRotationBehavior(): AutoRotationBehavior | undefined;
923
+ /**
924
+ * Activates framing on this camera causing the camera to focus on
925
+ * the scene and bound itself in a sensible fashion to the scene content.
926
+ */
927
+ enableFramingBehavior(): FramingBehavior;
928
+ /**
929
+ * Animates the camera back to the initial target when it has drifted to another position.
930
+ * @param onAnimationComplete A callback when the camera has finished animating.
931
+ * @param time The time in milliseconds the animation should take.
932
+ */
933
+ rerunFramingBehavior(onAnimationComplete?: () => void, time?: number): void;
934
+ /**
935
+ * Activates the auto rotation behavior causing the camera to rotate slowly around
936
+ * it's target.
937
+ * @param idleTime The number of milliseconds before the camera starts rotating after the user last interacted.
938
+ */
939
+ enableAutoRotationBehavior(idleTime?: number): void;
940
+ /**
941
+ * Stops the auto rotation functionality immediately.
942
+ */
943
+ disableAutoRotationBehavior(): void;
944
+ setRadius(radius: number): void;
945
+ /**
946
+ * A static function used to instantiate a single product camera instance on a scene. This camera will assume
947
+ * the active camera role on the scene and any existing active camera will be disposed.
948
+ * @param scene The scene to attach the camera to.
949
+ * @param configuration A configuration object to define the cameras limitations.
950
+ * @param assignActive If true the camera will be assigned as the active camera on the scene.
951
+ */
952
+ static create(scene: Scene, configuration: Configuration, assignActive?: boolean): ProductCamera;
953
+ }
716
954
  /**
717
955
  * An example implementation of the ThreeDPreviewService interface. The inclusion of 3D previews
718
956
  * is designed to be optional, anyone can come along and implement their own 3D preview service or
@@ -720,24 +958,27 @@ export const renderingPipelineDefaults: RenderingPipelineConfiguration;
720
958
  */
721
959
  export class SpiffCommerce3DPreviewService implements ThreeDPreviewService {
722
960
  constructor(options?: PreviewOptions);
961
+ getEngineContext(): {
962
+ engine: Engine;
963
+ scene: Scene;
964
+ camera: ProductCamera;
965
+ };
723
966
  registerFocusLostListener(listener: () => void): void;
724
967
  unregisterFocusLostListener(listener: () => void): void;
725
968
  registerLoadProgressListener(listener: (e: LoadProgressEventData) => void): void;
726
969
  unregisterLoadProgressListener(listener: (e: LoadProgressEventData) => void): void;
970
+ registerInitializedListener(listener: () => void | Promise<void>): void;
971
+ unregisterInitializedListener(listener: () => void | Promise<void>): void;
972
+ getIsInitialized(): boolean;
727
973
  registerView(canvas: HTMLCanvasElement): void;
728
974
  getNumViewports(): number;
729
975
  unregisterView(canvas: HTMLCanvasElement): void;
730
976
  shutdown(): void;
731
977
  getSceneInitializationProgress(): number;
732
- initialize(src?: string, contextService?: RenderableContextService): Promise<void>;
733
- executeModelAnimation(animation: ModelAnimation): void;
978
+ initialize(modelDetails?: ModelDetails): Promise<ModelContainer | undefined>;
734
979
  executeCameraAnimation(animation: CameraAnimation): void;
735
980
  getCameraPose(): CameraPose | undefined;
736
981
  setCameraPose(cameraPose: CameraPose): void;
737
- applyMaterialVariant(targetMaterial: string, key: string, material: MaterialResource, removeWhenUndefined?: boolean): Promise<void>;
738
- applyModelVariant(key: string, modelDetails: ModelDetails, replaceProductModel: boolean): Promise<void>;
739
- getQueuedMaterialVariants(): number;
740
- getQueuedModelVariants(): number;
741
982
  setCameraState(rigType: ProductCameraRig): void;
742
983
  animateToLastCameraFocus(): Promise<void>;
743
984
  setAutoRotation(shouldAutoRotate: boolean): void;
@@ -745,17 +986,13 @@ export class SpiffCommerce3DPreviewService implements ThreeDPreviewService {
745
986
  renderSceneScreenshot(resolution: number, camAnim: CameraAnimation): Promise<string>;
746
987
  orbitEnabled(): boolean;
747
988
  fireResizeEvent(): void;
748
- onMaterialSelected(cb: (material: MaterialHandle) => void): void;
749
- listMaterials(): readonly MaterialHandle[];
750
989
  setHighlights(materials: readonly MaterialHandle[], color?: readonly [number, number, number]): void;
751
990
  setRenderingPipelineConfiguration(renderingPipelineConfiguration: RenderingPipelineConfiguration): void;
991
+ loadModel(modelDetails: ModelDetails, progressHandler?: (event: ISceneLoaderProgressEvent) => void): Promise<ModelContainer>;
992
+ getAllModels(): ReadonlyArray<ModelContainer>;
993
+ getModelById(id: string): ModelContainer | undefined;
994
+ registerPlugin(plugin: PreviewServicePlugin): void;
995
+ unregisterPlugin(plugin: PreviewServicePlugin): void;
752
996
  }
753
- /**
754
- * Adds a tags a base mesh to the scene.
755
- * TODO: Move this to another file with other creation/initialization functionality?
756
- * @param src A url to a valid glb scene
757
- * @param progressHandler A handler for load progress events.
758
- */
759
- export function createBaseModel(src: string, scene: Scene, progressHandler?: (event: ISceneLoaderProgressEvent) => void): Promise<void>;
760
997
 
761
998
  //# sourceMappingURL=types.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spiffcommerce/preview",
3
- "version": "2.1.45",
3
+ "version": "3.0.0",
4
4
  "description": "An internal implementation of the ThreeDPreviewService interface used by Spiff Commerce",
5
5
  "source": "src/index.ts",
6
6
  "main": "dist/main.js",
@@ -29,10 +29,10 @@
29
29
  }
30
30
  },
31
31
  "dependencies": {
32
- "@babylonjs/core": "^5.51.0",
33
- "@babylonjs/loaders": "^5.51.0",
32
+ "@babylonjs/core": "^6.12.1",
33
+ "@babylonjs/loaders": "^6.12.1",
34
34
  "@swc/helpers": "^0.4.11",
35
- "babylonjs-gltf2interface": "^5.50.1"
35
+ "babylonjs-gltf2interface": "^6.12.1"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@babel/plugin-proposal-class-properties": "^7.18.6",