LCOV - code coverage report
Current view: top level - packages/viewport3d/src/load3d - SceneModelManager.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 48.1 % 293 141
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { SparkRenderer } from '@sparkjsdev/spark'
       2              : import * as THREE from 'three'
       3              : import type { GLTF } from 'three/examples/jsm/loaders/GLTFLoader'
       4              : 
       5              : import type { RendererViewState } from '#/three/sharedWebGLRenderer'
       6              : 
       7              : import { DEFAULT_MODEL_CAPABILITIES } from './ModelAdapter'
       8              : import type { ModelAdapterCapabilities } from './ModelAdapter'
       9              : import { buildPointCloudForMaterialMode } from './PointCloudModelAdapter'
      10              : import type {
      11              :   EventManagerInterface,
      12              :   MaterialMode,
      13              :   ModelManagerInterface,
      14              :   UpDirection
      15              : } from './interfaces'
      16              : import { QuadWireframeManager } from './quadWireframe/QuadWireframeManager'
      17              : import {
      18              :   faceSizesFor,
      19              :   registerFaceSizes
      20              : } from './quadWireframe/faceSizesRegistry'
      21              : 
      22              : type ResourceRenderable = THREE.Mesh | THREE.Points | THREE.Line
      23              : 
      24           32 : function isResourceRenderable(
      25              :   object: THREE.Object3D
      26              : ): object is ResourceRenderable {
      27           32 :   return (
      28              :     object instanceof THREE.Mesh ||
      29              :     object instanceof THREE.Points ||
      30              :     object instanceof THREE.Line
      31              :   )
      32              : }
      33              : 
      34           20 : export function disposeObject3D(
      35              :   object: THREE.Object3D,
      36              :   preservedMaterials: THREE.Material | ReadonlySet<THREE.Material>,
      37              :   preservedTextures: ReadonlySet<THREE.Texture> = new Set()
      38              : ): void {
      39           20 :   const preserved =
      40              :     preservedMaterials instanceof THREE.Material
      41              :       ? new Set([preservedMaterials])
      42              :       : preservedMaterials
      43           20 :   object.traverse((child) => {
      44           28 :     if (!isResourceRenderable(child)) return
      45            8 :     child.geometry.dispose()
      46           28 :     const materials = Array.isArray(child.material)
      47              :       ? child.material
      48              :       : [child.material]
      49           28 :     for (const material of materials) {
      50            8 :       if (preserved.has(material)) continue
      51            8 :       for (const [, texture] of materialTextures(material)) {
      52            0 :         if (!preservedTextures.has(texture)) {
      53            0 :           texture.dispose()
      54              :         }
      55              :       }
      56            8 :       material.dispose()
      57              :     }
      58              :   })
      59              : }
      60              : 
      61           10 : function materialTextures(
      62              :   material: THREE.Material
      63              : ): Array<[property: string, texture: THREE.Texture]> {
      64           10 :   return Object.entries(material).filter(
      65              :     (entry): entry is [string, THREE.Texture] =>
      66              :       entry[1] instanceof THREE.Texture
      67              :   )
      68              : }
      69              : 
      70            2 : function cloneMaterialResources(material: THREE.Material): THREE.Material {
      71            2 :   const clone = material.clone()
      72            2 :   for (const [property, texture] of materialTextures(clone)) {
      73              :     // Material subclasses expose texture slots dynamically; Reflect.set keeps
      74              :     // that boundary runtime-checked without pretending every slot is indexed.
      75            0 :     if (!Reflect.set(clone, property, texture.clone())) {
      76            0 :       throw new TypeError(`Unable to clone material resource ${property}`)
      77              :     }
      78              :   }
      79            2 :   return clone
      80              : }
      81              : 
      82              : /** Give a cloned renderable graph independent ownership of GPU resources. */
      83            2 : export function cloneObject3DResources(object: THREE.Object3D): void {
      84            2 :   object.traverse((child) => {
      85            4 :     if (!isResourceRenderable(child)) return
      86            2 :     const geometry = child.geometry.clone()
      87            2 :     const faceSizes = faceSizesFor(child.geometry)
      88            4 :     if (faceSizes) registerFaceSizes(geometry, faceSizes)
      89            2 :     child.geometry = geometry
      90            4 :     child.material = Array.isArray(child.material)
      91              :       ? child.material.map(cloneMaterialResources)
      92              :       : cloneMaterialResources(child.material)
      93              :   })
      94              : }
      95              : 
      96           24 : export class SceneModelManager implements ModelManagerInterface {
      97              :   currentModel: THREE.Object3D | null = null
      98              :   originalModel:
      99              :     | THREE.Object3D
     100              :     | THREE.Group
     101              :     | THREE.BufferGeometry
     102              :     | GLTF
     103              :     | null = null
     104              :   originalRotation: THREE.Euler | null = null
     105              :   currentUpDirection: UpDirection = 'original'
     106              :   materialMode: MaterialMode = 'original'
     107              :   originalMaterials: WeakMap<THREE.Mesh, THREE.Material | THREE.Material[]> =
     108              :     new WeakMap()
     109              :   normalMaterial: THREE.MeshNormalMaterial
     110              :   standardMaterial: THREE.MeshStandardMaterial
     111              :   wireframeMaterial: THREE.MeshBasicMaterial
     112              :   occluderMaterial: THREE.MeshBasicMaterial
     113              :   depthMaterial: THREE.MeshDepthMaterial
     114              :   clayMaterial: THREE.MeshStandardMaterial
     115              :   originalFileName: string | null = null
     116              :   originalURL: string | null = null
     117              :   appliedTexture: THREE.Texture | null = null
     118              :   private ownsAppliedTexture = true
     119              :   textureLoader: THREE.TextureLoader
     120              :   skeletonHelper: THREE.SkeletonHelper | null = null
     121              :   showSkeleton: boolean = false
     122              : 
     123              :   private scene: THREE.Scene
     124              :   private viewState: RendererViewState
     125              :   private eventManager: EventManagerInterface
     126              :   private activeCamera: THREE.Camera
     127              :   private setupCamera: (size: THREE.Vector3, center: THREE.Vector3) => void
     128              :   private setupGizmo: (model: THREE.Object3D) => void
     129              :   private getCurrentCapabilities: () => ModelAdapterCapabilities
     130              :   private getBoundsFromAdapter: (model: THREE.Object3D) => THREE.Box3 | null
     131              :   private disposeModelViaAdapter: (model: THREE.Object3D) => void
     132              :   private getDefaultCameraPose: () => {
     133              :     size: THREE.Vector3
     134              :     center: THREE.Vector3
     135              :   } | null
     136              :   private readonly quadWireframe = new QuadWireframeManager()
     137              : 
     138              :   private get preservedMaterials(): ReadonlySet<THREE.Material> {
     139           40 :     return new Set([
     140              :       this.normalMaterial,
     141              :       this.standardMaterial,
     142              :       this.wireframeMaterial,
     143              :       this.depthMaterial,
     144              :       this.clayMaterial,
     145              :       this.occluderMaterial
     146              :     ])
     147              :   }
     148              : 
     149              :   constructor(
     150              :     scene: THREE.Scene,
     151              :     viewState: RendererViewState,
     152              :     eventManager: EventManagerInterface,
     153              :     getActiveCamera: () => THREE.Camera,
     154              :     setupCamera: (size: THREE.Vector3, center: THREE.Vector3) => void,
     155              :     setupGizmo: (model: THREE.Object3D) => void,
     156              :     getCurrentCapabilities: () => ModelAdapterCapabilities = () =>
     157              :       DEFAULT_MODEL_CAPABILITIES,
     158              :     getBoundsFromAdapter: (model: THREE.Object3D) => THREE.Box3 | null = () =>
     159              :       null,
     160              :     disposeModelViaAdapter: (model: THREE.Object3D) => void = () => {},
     161              :     getDefaultCameraPose: () => {
     162              :       size: THREE.Vector3
     163              :       center: THREE.Vector3
     164              :     } | null = () => null
     165              :   ) {
     166           27 :     this.scene = scene
     167           27 :     this.viewState = viewState
     168           27 :     this.eventManager = eventManager
     169           27 :     this.activeCamera = getActiveCamera()
     170           27 :     this.setupCamera = setupCamera
     171           27 :     this.textureLoader = new THREE.TextureLoader()
     172           27 :     this.setupGizmo = setupGizmo
     173           27 :     this.getCurrentCapabilities = getCurrentCapabilities
     174           27 :     this.getBoundsFromAdapter = getBoundsFromAdapter
     175           27 :     this.disposeModelViaAdapter = disposeModelViaAdapter
     176           27 :     this.getDefaultCameraPose = getDefaultCameraPose
     177              : 
     178           27 :     this.normalMaterial = new THREE.MeshNormalMaterial({
     179              :       flatShading: false,
     180              :       side: THREE.DoubleSide,
     181              :       normalScale: new THREE.Vector2(1, 1),
     182              :       transparent: false,
     183              :       opacity: 1.0
     184              :     })
     185              : 
     186           27 :     this.wireframeMaterial = new THREE.MeshBasicMaterial({
     187              :       color: 0xffffff,
     188              :       wireframe: true,
     189              :       transparent: false,
     190              :       opacity: 1.0
     191              :     })
     192              : 
     193           27 :     this.occluderMaterial = new THREE.MeshBasicMaterial({
     194              :       colorWrite: false,
     195              :       side: THREE.DoubleSide,
     196              :       polygonOffset: true,
     197              :       polygonOffsetFactor: 1,
     198              :       polygonOffsetUnits: 1
     199              :     })
     200              : 
     201           27 :     this.depthMaterial = new THREE.MeshDepthMaterial({
     202              :       depthPacking: THREE.BasicDepthPacking,
     203              :       side: THREE.DoubleSide
     204              :     })
     205           27 :     this.depthMaterial.onBeforeCompile = (shader) => {
     206            0 :       shader.uniforms.cameraType = {
     207              :         value: this.activeCamera instanceof THREE.OrthographicCamera ? 1.0 : 0.0
     208              :       }
     209              : 
     210            0 :       shader.fragmentShader = `
     211              :                 uniform float cameraType;
     212              :                 ${shader.fragmentShader}
     213              :               `
     214              : 
     215            0 :       shader.fragmentShader = shader.fragmentShader.replace(
     216              :         /gl_FragColor\s*=\s*vec4\(\s*vec3\(\s*1.0\s*-\s*fragCoordZ\s*\)\s*,\s*opacity\s*\)\s*;/,
     217              :         `
     218              :                   float depth = 1.0 - fragCoordZ;
     219              :                   if (cameraType > 0.5) {
     220              :                     depth = pow(depth, 400.0);
     221              :                   } else {
     222              :                     depth = pow(depth, 0.6);
     223              :                   }
     224              :                   gl_FragColor = vec4(vec3(depth), opacity);
     225              :                 `
     226              :       )
     227              :     }
     228           27 :     this.depthMaterial.customProgramCacheKey = () => {
     229            0 :       return this.activeCamera instanceof THREE.OrthographicCamera
     230              :         ? 'ortho'
     231              :         : 'persp'
     232              :     }
     233              : 
     234           27 :     this.standardMaterial = this.createSTLMaterial()
     235              : 
     236           27 :     this.clayMaterial = new THREE.MeshStandardMaterial({
     237              :       color: 0x888888,
     238              :       metalness: 0.0,
     239              :       roughness: 0.9,
     240              :       flatShading: false,
     241              :       side: THREE.DoubleSide
     242              :     })
     243              :   }
     244              : 
     245              :   init(): void {}
     246              : 
     247              :   dispose(): void {
     248            1 :     this.clearModel()
     249            1 :     this.quadWireframe.dispose()
     250            1 :     this.normalMaterial.dispose()
     251            1 :     this.standardMaterial.dispose()
     252            1 :     this.wireframeMaterial.dispose()
     253            1 :     this.occluderMaterial.dispose()
     254            1 :     this.depthMaterial.dispose()
     255            1 :     this.clayMaterial.dispose()
     256              :   }
     257              : 
     258              :   createSTLMaterial(): THREE.MeshStandardMaterial {
     259           27 :     return new THREE.MeshStandardMaterial({
     260              :       color: 0x808080,
     261              :       metalness: 0.1,
     262              :       roughness: 0.8,
     263              :       flatShading: false,
     264              :       side: THREE.DoubleSide
     265              :     })
     266              :   }
     267              : 
     268              :   borrowAppliedTexture(texture: THREE.Texture, takeOwnership = false): void {
     269            0 :     if (this.ownsAppliedTexture) this.appliedTexture?.dispose()
     270            0 :     ;[this.appliedTexture, this.ownsAppliedTexture] = [texture, takeOwnership]
     271              :   }
     272              : 
     273              :   private appliedTexturesToPreserve(): ReadonlySet<THREE.Texture> {
     274           20 :     return this.ownsAppliedTexture || !this.appliedTexture
     275              :       ? new Set()
     276              :       : new Set([this.appliedTexture])
     277              :   }
     278              : 
     279              :   private removeAllMainModelsFromScene(): void {
     280            0 :     this.quadWireframe.clear()
     281            0 :     const oldMainModels: THREE.Object3D[] = []
     282            0 :     this.scene.traverse((obj) => {
     283            0 :       if (obj.name === 'MainModel') oldMainModels.push(obj)
     284              :     })
     285            0 :     oldMainModels.forEach((oldModel) => {
     286            0 :       this.restoreOriginalMaterials(oldModel)
     287            0 :       disposeObject3D(
     288              :         oldModel,
     289              :         this.preservedMaterials,
     290              :         this.appliedTexturesToPreserve()
     291              :       )
     292            0 :       this.disposeModelViaAdapter(oldModel)
     293            0 :       this.scene.remove(oldModel)
     294              :     })
     295              :   }
     296              : 
     297              :   private restoreOriginalMaterials(model: THREE.Object3D): void {
     298           20 :     const preserved = this.preservedMaterials
     299           20 :     model.traverse((child) => {
     300           28 :       if (!(child instanceof THREE.Mesh)) return
     301            8 :       const original = this.originalMaterials.get(child)
     302           28 :       if (!original || original === child.material) return
     303           28 :       const replaced = Array.isArray(child.material)
     304              :         ? child.material
     305              :         : [child.material]
     306           28 :       for (const material of replaced) {
     307            0 :         if (!preserved.has(material)) material.dispose()
     308              :       }
     309            0 :       child.material = original
     310              :     })
     311              :   }
     312              : 
     313              :   private rebuildForMaterialMode(mode: MaterialMode): void {
     314            0 :     if (!(this.originalModel instanceof THREE.BufferGeometry)) return
     315              : 
     316            0 :     this.removeAllMainModelsFromScene()
     317            0 :     this.currentModel = null
     318              : 
     319            0 :     const newModel = buildPointCloudForMaterialMode(
     320              :       this.originalModel,
     321              :       mode,
     322              :       this.standardMaterial,
     323              :       this.originalMaterials
     324              :     )
     325            0 :     newModel.name = 'MainModel'
     326              : 
     327            0 :     if (mode !== 'pointCloud') {
     328            0 :       const box = new THREE.Box3().setFromObject(newModel)
     329            0 :       const size = box.getSize(new THREE.Vector3())
     330            0 :       const center = box.getCenter(new THREE.Vector3())
     331            0 :       const maxDim = Math.max(size.x, size.y, size.z)
     332              :       const targetSize = this.getCurrentCapabilities().fitTargetSize
     333            0 :       const scale = targetSize / maxDim
     334            0 :       newModel.scale.multiplyScalar(scale)
     335              : 
     336            0 :       box.setFromObject(newModel)
     337            0 :       box.getCenter(center)
     338            0 :       box.getSize(size)
     339              : 
     340            0 :       newModel.position.set(-center.x, -box.min.y, -center.z)
     341              :     }
     342              : 
     343            0 :     this.scene.add(newModel)
     344            0 :     this.currentModel = newModel
     345            0 :     this.eventManager.emitEvent('materialModeChange', mode)
     346              :   }
     347              : 
     348              :   setMaterialMode(mode: MaterialMode): void {
     349           77 :     if (!this.currentModel || mode === this.materialMode) {
     350           77 :       return
     351              :     }
     352              : 
     353            0 :     this.materialMode = mode
     354              : 
     355            0 :     if (this.getCurrentCapabilities().requiresMaterialRebuild) {
     356            0 :       this.rebuildForMaterialMode(mode)
     357            0 :       return
     358              :     }
     359              : 
     360            0 :     if (mode === 'depth') {
     361            0 :       this.viewState.outputColorSpace = THREE.LinearSRGBColorSpace
     362              :     } else {
     363            0 :       this.viewState.outputColorSpace = THREE.SRGBColorSpace
     364              :     }
     365              : 
     366            0 :     this.currentModel.visible = true
     367              : 
     368            0 :     this.currentModel.traverse((child) => {
     369            0 :       if (child instanceof THREE.Mesh) {
     370            0 :         switch (mode) {
     371              :           case 'depth':
     372            0 :             if (!this.originalMaterials.has(child)) {
     373            0 :               this.originalMaterials.set(child, child.material)
     374              :             }
     375            0 :             child.material = this.depthMaterial
     376            0 :             break
     377              :           case 'normal':
     378            0 :             if (!this.originalMaterials.has(child)) {
     379            0 :               this.originalMaterials.set(child, child.material)
     380              :             }
     381            0 :             child.material = this.normalMaterial
     382            0 :             break
     383              :           case 'wireframe':
     384            0 :             if (!this.originalMaterials.has(child)) {
     385            0 :               this.originalMaterials.set(child, child.material)
     386              :             }
     387            0 :             child.material = this.wireframeMaterial
     388            0 :             break
     389              :           case 'clay':
     390            0 :             if (!this.originalMaterials.has(child)) {
     391            0 :               this.originalMaterials.set(child, child.material)
     392              :             }
     393            0 :             child.material = this.clayMaterial
     394            0 :             break
     395              :           case 'original':
     396              :           case 'pointCloud': {
     397            0 :             const originalMaterial = this.originalMaterials.get(child)
     398            0 :             if (originalMaterial) {
     399            0 :               child.material = originalMaterial
     400              :             } else {
     401            0 :               if (this.appliedTexture) {
     402            0 :                 child.material = new THREE.MeshStandardMaterial({
     403              :                   map: this.appliedTexture,
     404              :                   metalness: 0.1,
     405              :                   roughness: 0.8,
     406              :                   side: THREE.DoubleSide
     407              :                 })
     408              :               } else {
     409            0 :                 child.material = this.standardMaterial
     410              :               }
     411              :             }
     412            0 :             break
     413              :           }
     414              :         }
     415              :       }
     416              :     })
     417              : 
     418            0 :     this.syncQuadWireframe(mode)
     419            0 :     this.eventManager.emitEvent('materialModeChange', mode)
     420              :   }
     421              : 
     422              :   clearQuadWireframe(): void {
     423            0 :     this.quadWireframe.clear()
     424              :   }
     425              : 
     426              :   private syncQuadWireframe(mode: MaterialMode): void {
     427            0 :     if (mode !== 'wireframe') {
     428            0 :       this.quadWireframe.hide()
     429            0 :       return
     430              :     }
     431            0 :     if (!this.currentModel) return
     432            0 :     for (const mesh of this.quadWireframe.show(this.currentModel)) {
     433            0 :       mesh.material = this.occluderMaterial
     434              :     }
     435              :   }
     436              : 
     437              :   setupModelMaterials(model: THREE.Object3D): void {
     438           19 :     model.traverse((child) => {
     439           38 :       if (child instanceof THREE.Mesh) {
     440           19 :         this.originalMaterials.set(child, child.material)
     441              :       }
     442              :     })
     443              : 
     444           19 :     this.setMaterialMode('original')
     445              :   }
     446              : 
     447              :   disposeCurrentModel(): void {
     448            2 :     const model = this.currentModel
     449            2 :     if (!model) return
     450            2 :     const appliedTextures = this.appliedTexture
     451              :       ? new Set([this.appliedTexture])
     452              :       : new Set<THREE.Texture>()
     453              : 
     454            2 :     this.quadWireframe.clear()
     455            2 :     this.scene.remove(model)
     456            2 :     this.restoreOriginalMaterials(model)
     457            2 :     disposeObject3D(model, this.preservedMaterials, appliedTextures)
     458            2 :     this.disposeModelViaAdapter(model)
     459            2 :     const { originalFileName, originalURL } = this
     460            2 :     this.reset()
     461            2 :     this.originalFileName = originalFileName
     462            2 :     this.originalURL = originalURL
     463              :   }
     464              : 
     465              :   clearModel(): void {
     466           46 :     this.quadWireframe.clear()
     467           46 :     const objectsToRemove: THREE.Object3D[] = []
     468              : 
     469           46 :     for (const object of Array.from(this.scene.children)) {
     470              :       const isEnvironmentObject =
     471              :         object instanceof THREE.GridHelper ||
     472              :         object instanceof THREE.Light ||
     473              :         object instanceof THREE.Camera ||
     474              :         object instanceof SparkRenderer ||
     475              :         object.name === 'GizmoTransformControls'
     476              : 
     477          425 :       if (!isEnvironmentObject) {
     478           20 :         objectsToRemove.push(object)
     479              :       }
     480              :     }
     481              : 
     482           46 :     objectsToRemove.forEach((obj) => {
     483           20 :       this.scene.remove(obj)
     484              : 
     485           20 :       this.restoreOriginalMaterials(obj)
     486           20 :       disposeObject3D(
     487              :         obj,
     488              :         this.preservedMaterials,
     489              :         this.appliedTexturesToPreserve()
     490              :       )
     491           20 :       this.disposeModelViaAdapter(obj)
     492              :     })
     493              : 
     494           46 :     this.reset()
     495              :   }
     496              : 
     497              :   reset(): void {
     498           46 :     this.currentModel = null
     499           46 :     this.originalModel = null
     500           46 :     this.originalRotation = null
     501           46 :     this.currentUpDirection = 'original'
     502           46 :     this.setMaterialMode('original')
     503           46 :     this.originalFileName = null
     504           46 :     this.originalURL = null
     505              : 
     506           46 :     if (this.appliedTexture && this.ownsAppliedTexture) {
     507            0 :       this.appliedTexture.dispose()
     508              :     }
     509           46 :     this.appliedTexture = null
     510           46 :     this.ownsAppliedTexture = true
     511              : 
     512           46 :     if (this.skeletonHelper) {
     513            0 :       this.scene.remove(this.skeletonHelper)
     514            0 :       this.skeletonHelper.dispose()
     515            0 :       this.skeletonHelper = null
     516              :     }
     517           46 :     this.showSkeleton = false
     518              : 
     519           46 :     this.originalMaterials = new WeakMap()
     520              :   }
     521              : 
     522              :   hasSkeleton(): boolean {
     523           19 :     if (!this.currentModel) return false
     524           17 :     let found = false
     525           17 :     this.currentModel.traverse((child) => {
     526           34 :       if (child instanceof THREE.SkinnedMesh) {
     527            0 :         found = true
     528              :       }
     529              :     })
     530           17 :     return found
     531              :   }
     532              : 
     533              :   setShowSkeleton(show: boolean): void {
     534            2 :     this.showSkeleton = show
     535              : 
     536            2 :     if (show) {
     537            0 :       if (!this.skeletonHelper && this.currentModel) {
     538            0 :         const rootBones: THREE.Bone[] = []
     539            0 :         const skinnedMeshes: THREE.SkinnedMesh[] = []
     540            0 :         this.currentModel.traverse((child) => {
     541            0 :           if (
     542              :             child instanceof THREE.Bone &&
     543              :             !(child.parent instanceof THREE.Bone)
     544              :           ) {
     545            0 :             rootBones.push(child)
     546            0 :           } else if (child instanceof THREE.SkinnedMesh) {
     547            0 :             skinnedMeshes.push(child)
     548              :           }
     549              :         })
     550              : 
     551            0 :         const skeletonRoot = rootBones.at(0) ?? skinnedMeshes.at(0)
     552            0 :         if (skeletonRoot) {
     553            0 :           this.skeletonHelper = new THREE.SkeletonHelper(skeletonRoot)
     554            0 :           this.scene.add(this.skeletonHelper)
     555              :         }
     556            0 :       } else if (this.skeletonHelper) {
     557            0 :         this.skeletonHelper.visible = true
     558              :       }
     559              :     } else {
     560            2 :       if (this.skeletonHelper) {
     561            0 :         this.skeletonHelper.visible = false
     562              :       }
     563              :     }
     564              : 
     565            2 :     this.eventManager.emitEvent('skeletonVisibilityChange', show)
     566              :   }
     567              : 
     568              :   addModelToScene(model: THREE.Object3D): void {
     569            0 :     this.currentModel = model
     570            0 :     model.name = 'MainModel'
     571              : 
     572            0 :     this.scene.add(this.currentModel)
     573              :   }
     574              : 
     575              :   private computeWorldBounds(model: THREE.Object3D): THREE.Box3 {
     576           17 :     return (
     577              :       this.getBoundsFromAdapter(model) ?? new THREE.Box3().setFromObject(model)
     578              :     )
     579              :   }
     580              : 
     581              :   getCurrentBounds(): THREE.Box3 | null {
     582            0 :     if (!this.currentModel) return null
     583            0 :     return this.computeWorldBounds(this.currentModel)
     584              :   }
     585              : 
     586              :   async setupModel(model: THREE.Object3D): Promise<void> {
     587           17 :     this.currentModel = model
     588           17 :     model.name = 'MainModel'
     589              : 
     590           17 :     if (!this.getCurrentCapabilities().fitToViewer) {
     591            0 :       const pose = this.getDefaultCameraPose()
     592            0 :       if (pose) {
     593            0 :         this.scene.add(model)
     594            0 :         this.setupCamera(pose.size, pose.center)
     595            0 :         return
     596              :       }
     597              :     }
     598              : 
     599           17 :     this.scene.add(model)
     600           17 :     const pendingMaterialMode = this.materialMode
     601           17 :     this.setupModelMaterials(model)
     602              : 
     603           17 :     if (pendingMaterialMode !== 'original') {
     604            0 :       this.setMaterialMode(pendingMaterialMode)
     605              :     }
     606              : 
     607           17 :     const validModes = this.getCurrentCapabilities().materialModes
     608           17 :     if (validModes.length > 0 && !validModes.includes(this.materialMode)) {
     609            0 :       this.materialMode = validModes[0]
     610            0 :       this.eventManager.emitEvent('materialModeChange', this.materialMode)
     611              :     }
     612              : 
     613           17 :     if (this.currentUpDirection !== 'original') {
     614            0 :       this.setUpDirection(this.currentUpDirection)
     615              :     }
     616              : 
     617           17 :     const box = this.computeWorldBounds(model)
     618           17 :     const size = box.getSize(new THREE.Vector3())
     619           17 :     const center = box.getCenter(new THREE.Vector3())
     620              : 
     621           17 :     this.setupCamera(size, center)
     622              : 
     623           17 :     this.setupGizmo(model)
     624              :   }
     625              : 
     626              :   fitToViewer(): void {
     627            0 :     if (!this.currentModel || !this.getCurrentCapabilities().fitToViewer) return
     628            0 :     const model = this.currentModel
     629              : 
     630            0 :     model.scale.set(1, 1, 1)
     631            0 :     model.position.set(0, 0, 0)
     632            0 :     model.rotation.set(0, 0, 0)
     633              : 
     634            0 :     const box = this.computeWorldBounds(model)
     635            0 :     const size = box.getSize(new THREE.Vector3())
     636            0 :     const center = box.getCenter(new THREE.Vector3())
     637              : 
     638            0 :     const maxDim = Math.max(size.x, size.y, size.z)
     639            0 :     if (maxDim === 0) return
     640              : 
     641              :     const targetSize = this.getCurrentCapabilities().fitTargetSize
     642            0 :     const scale = targetSize / maxDim
     643            0 :     model.scale.set(scale, scale, scale)
     644              : 
     645            0 :     const scaledBox = this.computeWorldBounds(model)
     646            0 :     scaledBox.getCenter(center)
     647            0 :     scaledBox.getSize(size)
     648              : 
     649            0 :     model.position.set(-center.x, -scaledBox.min.y, -center.z)
     650              : 
     651              :     // fitToViewer resets rotation to (0,0,0), so originalRotation must be cleared
     652              :     // before reapplying currentUpDirection to avoid compounding rotations.
     653            0 :     this.originalRotation = null
     654            0 :     if (this.currentUpDirection !== 'original') {
     655            0 :       this.setUpDirection(this.currentUpDirection)
     656              :     }
     657              : 
     658            0 :     const newBox = this.computeWorldBounds(model)
     659            0 :     const newSize = newBox.getSize(new THREE.Vector3())
     660            0 :     const newCenter = newBox.getCenter(new THREE.Vector3())
     661              : 
     662            0 :     this.setupCamera(newSize, newCenter)
     663            0 :     this.setupGizmo(model)
     664              :   }
     665              : 
     666              :   setOriginalModel(model: THREE.Object3D | THREE.BufferGeometry | GLTF): void {
     667            2 :     this.originalModel = model
     668              :   }
     669              : 
     670              :   setUpDirection(direction: UpDirection): void {
     671           12 :     if (!this.currentModel) return
     672              : 
     673           12 :     const directionChanged = this.currentUpDirection !== direction
     674              : 
     675           12 :     this.originalRotation ??= this.currentModel.rotation.clone()
     676           12 :     this.currentUpDirection = direction
     677           12 :     this.currentModel.rotation.copy(this.originalRotation)
     678              : 
     679           12 :     switch (direction) {
     680              :       case 'original':
     681           12 :         break
     682              :       case '-x':
     683            0 :         this.currentModel.rotation.z = Math.PI / 2
     684            0 :         break
     685              :       case '+x':
     686            0 :         this.currentModel.rotation.z = -Math.PI / 2
     687            0 :         break
     688              :       case '-y':
     689            0 :         this.currentModel.rotation.x = Math.PI
     690            0 :         break
     691              :       case '+y':
     692            0 :         break
     693              :       case '-z':
     694            0 :         this.currentModel.rotation.x = Math.PI / 2
     695            0 :         break
     696              :       case '+z':
     697            0 :         this.currentModel.rotation.x = -Math.PI / 2
     698              :         break
     699              :     }
     700              : 
     701           12 :     this.eventManager.emitEvent('upDirectionChange', direction)
     702              : 
     703           12 :     if (directionChanged) {
     704            0 :       this.setupGizmo(this.currentModel)
     705              :     }
     706              :   }
     707              : }
        

Generated by: LCOV version 2.0-1