LCOV - code coverage report
Current view: top level - src/extensions/core/load3d/composables - useLoad3dViewer.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 43.3 % 335 145
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { ref, toRaw, watch } from 'vue'
       2              : import QuickLRU from '@alloc/quick-lru'
       3              : 
       4              : import type Load3d from '@comfyorg/viewport3d/load3d/Load3d'
       5              : import Load3dUtils from '@/extensions/core/load3d/Load3dUtils'
       6              : import { createLoad3d } from '@comfyorg/viewport3d/load3d/createLoad3d'
       7              : import { load3dHost } from '@/extensions/core/load3d/load3dHost'
       8              : import { isLoad3dResultViewerNode } from '@/extensions/core/load3d/nodeTypes'
       9              : import { reportLoadModelOutcome } from '@/extensions/core/load3d/reportLoadModelOutcome'
      10              : import {
      11              :   isAssetPreviewSupported,
      12              :   persistThumbnail
      13              : } from '@/platform/assets/utils/assetPreviewUtil'
      14              : import type {
      15              :   AnimationItem,
      16              :   BackgroundRenderModeType,
      17              :   CameraConfig,
      18              :   CameraState,
      19              :   CameraType,
      20              :   GizmoMode,
      21              :   LightConfig,
      22              :   MaterialMode,
      23              :   ModelConfig,
      24              :   SceneConfig,
      25              :   UpDirection
      26              : } from '@comfyorg/viewport3d/load3d/interfaces'
      27              : import { t } from '@/i18n'
      28              : import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
      29              : import { useToast } from '@/components/ui/toast/toastStore'
      30              : import { api } from '@/scripts/api'
      31              : import {
      32              :   copyLoad3dState,
      33              :   handleViewportRefresh
      34              : } from '@/extensions/core/load3d/load3dInstances'
      35              : 
      36              : interface Load3dViewerState {
      37              :   backgroundColor: string
      38              :   showGrid: boolean
      39              :   cameraType: CameraType
      40              :   fov: number
      41              :   lightIntensity: number
      42              :   cameraState: CameraState | null
      43              :   backgroundImage: string
      44              :   backgroundRenderMode: BackgroundRenderModeType
      45              :   upDirection: UpDirection
      46              :   materialMode: MaterialMode
      47              :   gizmoEnabled: boolean
      48              :   gizmoMode: GizmoMode
      49              : }
      50              : 
      51            0 : function standaloneAssetName(modelUrl: string): string | null {
      52            0 :   try {
      53            0 :     const url = new URL(modelUrl, window.location.origin)
      54              :     const filename =
      55              :       url.searchParams.get('filename') ??
      56              :       decodeURIComponent(url.pathname.split('/').pop() ?? '')
      57            0 :     return filename || null
      58              :   } catch {
      59            0 :     return null
      60              :   }
      61              : }
      62              : 
      63           24 : const DEFAULT_STANDALONE_CONFIG: Load3dViewerState = {
      64              :   backgroundColor: '#282828',
      65              :   showGrid: true,
      66              :   cameraType: 'perspective',
      67              :   fov: 75,
      68              :   lightIntensity: 1,
      69              :   cameraState: null,
      70              :   backgroundImage: '',
      71              :   backgroundRenderMode: 'tiled',
      72              :   upDirection: 'original',
      73              :   materialMode: 'original',
      74              :   gizmoEnabled: false,
      75              :   gizmoMode: 'translate'
      76              : }
      77              : 
      78           24 : const standaloneConfigCache = new QuickLRU<string, Load3dViewerState>({
      79              :   maxSize: 50
      80              : })
      81              : 
      82              : /**
      83              :  * Composable for managing a 3D viewer instance.
      84              :  * Supports both node-based mode (applied to a LiteGraph node)
      85              :  * and standalone mode (for asset previews).
      86              :  *
      87              :  * @param node Optional LiteGraph node to sync state with
      88              :  */
      89           24 : export const useLoad3dViewer = (node?: LGraphNode) => {
      90            2 :   const backgroundColor = ref('')
      91            2 :   const showGrid = ref(true)
      92            2 :   const cameraType = ref<CameraType>('perspective')
      93            2 :   const fov = ref(75)
      94            2 :   const lightIntensity = ref(1)
      95            2 :   const backgroundImage = ref('')
      96            2 :   const hasBackgroundImage = ref(false)
      97            2 :   const backgroundRenderMode = ref<BackgroundRenderModeType>('tiled')
      98            2 :   const upDirection = ref<UpDirection>('original')
      99            2 :   const materialMode = ref<MaterialMode>('original')
     100            2 :   const gizmoEnabled = ref(false)
     101            2 :   const gizmoMode = ref<GizmoMode>('translate')
     102            2 :   const needApplyChanges = ref(true)
     103            2 :   const isPreview = ref(false)
     104            2 :   const isStandaloneMode = ref(false)
     105            2 :   const isSplatModel = ref(false)
     106            2 :   const isPlyModel = ref(false)
     107            2 :   const sourceFormat = ref<string | null>(null)
     108            2 :   const canFitToViewer = ref(true)
     109            2 :   const canUseGizmo = ref(true)
     110            2 :   const canUseLighting = ref(true)
     111            2 :   const canExport = ref(true)
     112            2 :   const materialModes = ref<readonly MaterialMode[]>([
     113              :     'original',
     114              :     'normal',
     115              :     'wireframe'
     116              :   ])
     117              : 
     118            2 :   const captureAdapterFlags = (source: Load3d) => {
     119            2 :     isSplatModel.value =
     120              :       typeof source.isSplatModel === 'function' ? source.isSplatModel() : false
     121            2 :     isPlyModel.value =
     122              :       typeof source.isPlyModel === 'function' ? source.isPlyModel() : false
     123            2 :     sourceFormat.value =
     124              :       typeof source.getSourceFormat === 'function'
     125              :         ? source.getSourceFormat()
     126              :         : null
     127            2 :     const getCapabilities = source.getCurrentModelCapabilities
     128            2 :     const caps =
     129              :       typeof getCapabilities === 'function'
     130              :         ? getCapabilities.call(source)
     131              :         : undefined
     132            2 :     if (!caps) return
     133            2 :     canFitToViewer.value = caps.fitToViewer
     134            2 :     canUseGizmo.value = caps.gizmoTransform
     135            2 :     canUseLighting.value = caps.lighting
     136            2 :     canExport.value = caps.exportable
     137            2 :     materialModes.value = caps.materialModes
     138              :   }
     139              : 
     140              :   // Animation state
     141            2 :   const animations = ref<AnimationItem[]>([])
     142            2 :   const playing = ref(false)
     143            2 :   const selectedSpeed = ref(1)
     144            2 :   const selectedAnimation = ref(0)
     145            2 :   const animationProgress = ref(0)
     146            2 :   const animationDuration = ref(0)
     147              : 
     148            2 :   let load3d: Load3d | null = null
     149            2 :   let sourceLoad3d: Load3d | null = null
     150            2 :   let currentModelUrl: string | null = null
     151            2 :   let mouseOnViewer = false
     152              : 
     153            2 :   const initialState = ref<Load3dViewerState>({
     154              :     backgroundColor: '#282828',
     155              :     showGrid: true,
     156              :     cameraType: 'perspective',
     157              :     fov: 75,
     158              :     lightIntensity: 1,
     159              :     cameraState: null,
     160              :     backgroundImage: '',
     161              :     backgroundRenderMode: 'tiled',
     162              :     upDirection: 'original',
     163              :     materialMode: 'original',
     164              :     gizmoEnabled: false,
     165              :     gizmoMode: 'translate'
     166              :   })
     167              : 
     168            2 :   watch(backgroundColor, (newColor) => {
     169            2 :     if (!load3d) return
     170            2 :     try {
     171            2 :       load3d.setBackgroundColor(newColor)
     172              :     } catch (error) {
     173            0 :       console.error('Error updating background color:', error)
     174            0 :       useToast().warning(
     175              :         t('toastMessages.failedToUpdateBackgroundColor', {
     176              :           color: newColor
     177              :         })
     178              :       )
     179              :     }
     180              :   })
     181              : 
     182            2 :   watch(showGrid, (newValue) => {
     183            0 :     if (!load3d) return
     184            0 :     try {
     185            0 :       load3d.toggleGrid(newValue)
     186              :     } catch (error) {
     187            0 :       console.error('Error toggling grid:', error)
     188            0 :       useToast().warning(
     189              :         t('toastMessages.failedToToggleGrid', {
     190              :           show: newValue ? 'on' : 'off'
     191              :         })
     192              :       )
     193              :     }
     194              :   })
     195              : 
     196            2 :   watch(cameraType, (newCameraType) => {
     197            0 :     if (!load3d) return
     198            0 :     try {
     199            0 :       load3d.toggleCamera(newCameraType)
     200              :     } catch (error) {
     201            0 :       console.error('Error toggling camera:', error)
     202            0 :       useToast().warning(
     203              :         t('toastMessages.failedToToggleCamera', {
     204              :           camera: newCameraType
     205              :         })
     206              :       )
     207              :     }
     208              :   })
     209              : 
     210            2 :   watch(fov, (newFov) => {
     211            2 :     if (!load3d) return
     212            2 :     try {
     213            2 :       load3d.setFOV(newFov)
     214              :     } catch (error) {
     215            0 :       console.error('Error updating FOV:', error)
     216            0 :       useToast().warning(t('toastMessages.failedToUpdateFOV', { fov: newFov }))
     217              :     }
     218              :   })
     219              : 
     220            2 :   watch(lightIntensity, (newValue) => {
     221            2 :     if (!load3d) return
     222            2 :     try {
     223            2 :       load3d.setLightIntensity(newValue)
     224              :     } catch (error) {
     225            0 :       console.error('Error updating light intensity:', error)
     226            0 :       useToast().warning(
     227              :         t('toastMessages.failedToUpdateLightIntensity', {
     228              :           intensity: newValue
     229              :         })
     230              :       )
     231              :     }
     232              :   })
     233              : 
     234            2 :   watch(backgroundImage, async (newValue) => {
     235            0 :     if (!load3d) return
     236            0 :     try {
     237            0 :       await load3d.setBackgroundImage(newValue)
     238            0 :       hasBackgroundImage.value = !!newValue
     239              :     } catch (error) {
     240            0 :       console.error('Error updating background image:', error)
     241            0 :       useToast().warning(t('toastMessages.failedToUpdateBackgroundImage'))
     242              :     }
     243              :   })
     244              : 
     245            2 :   watch(backgroundRenderMode, (newValue) => {
     246            0 :     if (!load3d) return
     247            0 :     try {
     248            0 :       load3d.setBackgroundRenderMode(newValue)
     249              :     } catch (error) {
     250            0 :       console.error('Error updating background render mode:', error)
     251            0 :       useToast().warning(
     252              :         t('toastMessages.failedToUpdateBackgroundRenderMode', {
     253              :           mode: newValue
     254              :         })
     255              :       )
     256              :     }
     257              :   })
     258              : 
     259            2 :   watch(upDirection, (newValue) => {
     260            0 :     if (!load3d) return
     261            0 :     try {
     262            0 :       load3d.setUpDirection(newValue)
     263              :     } catch (error) {
     264            0 :       console.error('Error updating up direction:', error)
     265            0 :       useToast().warning(
     266              :         t('toastMessages.failedToUpdateUpDirection', {
     267              :           direction: newValue
     268              :         })
     269              :       )
     270              :     }
     271              :   })
     272              : 
     273            2 :   watch(materialMode, (newValue) => {
     274            0 :     if (!load3d) return
     275            0 :     try {
     276            0 :       load3d.setMaterialMode(newValue)
     277              :     } catch (error) {
     278            0 :       console.error('Error updating material mode:', error)
     279            0 :       useToast().warning(
     280              :         t('toastMessages.failedToUpdateMaterialMode', {
     281              :           mode: newValue
     282              :         })
     283              :       )
     284              :     }
     285              :   })
     286              : 
     287              :   // Animation watches
     288            2 :   watch(playing, (newValue) => {
     289            0 :     if (load3d) {
     290            0 :       load3d.toggleAnimation(newValue)
     291              :     }
     292              :   })
     293              : 
     294            2 :   watch(selectedSpeed, (newValue) => {
     295            0 :     if (load3d && newValue) {
     296            0 :       load3d.setAnimationSpeed(newValue)
     297              :     }
     298              :   })
     299              : 
     300            2 :   watch(selectedAnimation, (newValue) => {
     301            0 :     if (load3d) {
     302            0 :       load3d.updateSelectedAnimation(newValue)
     303              :     }
     304              :   })
     305              : 
     306              :   /**
     307              :    * Seeks to a specific progress point in the current animation.
     308              :    *
     309              :    * @param progress Progress percentage (0-100)
     310              :    */
     311            2 :   const handleSeek = (progress: number) => {
     312            0 :     if (load3d && animationDuration.value > 0) {
     313            0 :       const time = (progress / 100) * animationDuration.value
     314            0 :       load3d.setAnimationTime(time)
     315              :     }
     316              :   }
     317              : 
     318              :   /**
     319              :    * Sets up event listeners for animation-related events from the Load3d instance.
     320              :    */
     321            2 :   const setupAnimationEvents = () => {
     322            2 :     if (!load3d) return
     323              : 
     324            2 :     load3d.addEventListener(
     325              :       'animationListChange',
     326              :       (newValue: AnimationItem[]) => {
     327            1 :         animations.value = newValue
     328              :       }
     329              :     )
     330              : 
     331            2 :     load3d.addEventListener(
     332              :       'animationProgressChange',
     333              :       (data: { progress: number; currentTime: number; duration: number }) => {
     334            0 :         animationProgress.value = data.progress
     335            0 :         animationDuration.value = data.duration
     336              :       }
     337              :     )
     338              : 
     339              :     // Initialize animation list if animations already exist
     340            2 :     if (load3d.hasAnimations()) {
     341            0 :       const clips = load3d.animationManager.animationClips
     342            0 :       animations.value = clips.map((clip, index) => ({
     343              :         name: clip.name || `Animation ${index + 1}`,
     344              :         index
     345              :       }))
     346            0 :       animationDuration.value = load3d.getAnimationDuration()
     347              :     }
     348              :   }
     349              : 
     350            2 :   watch(gizmoEnabled, (newValue) => {
     351            0 :     if (load3d) {
     352            0 :       load3d.setGizmoEnabled(newValue)
     353              :     }
     354              :   })
     355              : 
     356            2 :   watch(gizmoMode, (newValue) => {
     357            0 :     if (load3d) {
     358            0 :       load3d.setGizmoMode(newValue)
     359              :     }
     360              :   })
     361              : 
     362              :   /**
     363              :    * Initializes the viewer in node mode using a source Load3d instance.
     364              :    *
     365              :    * @param containerRef The HTML element to mount the viewer in
     366              :    * @param source The source Load3d instance to copy state from
     367              :    */
     368            2 :   const initializeViewer = async (
     369              :     containerRef: HTMLElement,
     370              :     source: Load3d
     371              :   ) => {
     372            2 :     if (!node) return
     373              : 
     374            2 :     sourceLoad3d = source
     375              : 
     376            2 :     try {
     377            2 :       const width = node.widgets?.find((w) => w.name === 'width')
     378            2 :       const height = node.widgets?.find((w) => w.name === 'height')
     379              : 
     380            2 :       const hasTargetDimensions = !!(width && height)
     381              : 
     382            2 :       load3d = createLoad3d(containerRef, load3dHost, {
     383              :         width: width ? (toRaw(width).value as number) : undefined,
     384              :         height: height ? (toRaw(height).value as number) : undefined,
     385              :         getDimensions: hasTargetDimensions
     386              :           ? () => ({
     387              :               width: width.value as number,
     388              :               height: height.value as number
     389              :             })
     390              :           : undefined,
     391              :         isViewerMode: hasTargetDimensions
     392              :       })
     393              : 
     394            2 :       if (mouseOnViewer) {
     395            2 :         load3d.updateStatusMouseOnViewer(true)
     396              :       }
     397              : 
     398            2 :       await copyLoad3dState(source, load3d)
     399              : 
     400            2 :       const sourceCameraState = source.getCameraState()
     401              : 
     402            2 :       const sceneConfig = node.properties['Scene Config'] as
     403              :         | SceneConfig
     404              :         | undefined
     405            2 :       const modelConfig = node.properties['Model Config'] as
     406              :         | ModelConfig
     407              :         | undefined
     408            2 :       const cameraConfig = node.properties['Camera Config'] as
     409              :         | Partial<CameraConfig>
     410              :         | undefined
     411            2 :       const lightConfig = node.properties['Light Config'] as
     412              :         | LightConfig
     413              :         | undefined
     414              : 
     415            2 :       isPreview.value = isLoad3dResultViewerNode(node.type)
     416              : 
     417            2 :       if (sceneConfig) {
     418            2 :         backgroundColor.value =
     419              :           sceneConfig.backgroundColor ||
     420              :           source.sceneManager.currentBackgroundColor
     421            2 :         showGrid.value = sceneConfig.showGrid
     422            2 :         backgroundRenderMode.value =
     423              :           sceneConfig.backgroundRenderMode ||
     424              :           source.sceneManager.backgroundRenderMode
     425              : 
     426              :         const backgroundInfo = source.sceneManager.getCurrentBackgroundInfo()
     427            2 :         if (backgroundInfo.type === 'image' && sceneConfig.backgroundImage) {
     428            0 :           backgroundImage.value = sceneConfig.backgroundImage
     429            0 :           hasBackgroundImage.value = true
     430              :         } else {
     431            2 :           backgroundImage.value = ''
     432            2 :           hasBackgroundImage.value = false
     433              :         }
     434              :       }
     435              : 
     436            2 :       if (cameraConfig) {
     437            2 :         cameraType.value =
     438              :           cameraConfig.cameraType ?? source.getCurrentCameraType()
     439            2 :         fov.value =
     440              :           cameraConfig.fov || source.cameraManager.perspectiveCamera.fov
     441              :       }
     442              : 
     443            2 :       if (lightConfig) {
     444            2 :         lightIntensity.value = lightConfig.intensity || 1
     445              :       } else {
     446            0 :         lightIntensity.value = 1
     447              :       }
     448              : 
     449            2 :       if (modelConfig) {
     450            0 :         upDirection.value = modelConfig.upDirection
     451            0 :         materialMode.value = modelConfig.materialMode
     452            0 :         if (modelConfig.gizmo) {
     453            0 :           gizmoEnabled.value = modelConfig.gizmo.enabled
     454            0 :           gizmoMode.value = modelConfig.gizmo.mode
     455              :         }
     456              :       }
     457              : 
     458            2 :       captureAdapterFlags(source)
     459              : 
     460            2 :       initialState.value = {
     461              :         backgroundColor: backgroundColor.value,
     462              :         showGrid: showGrid.value,
     463              :         cameraType: cameraType.value,
     464              :         fov: fov.value,
     465              :         lightIntensity: lightIntensity.value,
     466              :         cameraState: sourceCameraState,
     467              :         backgroundImage: backgroundImage.value,
     468              :         backgroundRenderMode: backgroundRenderMode.value,
     469              :         upDirection: upDirection.value,
     470              :         materialMode: materialMode.value,
     471              :         gizmoEnabled: gizmoEnabled.value,
     472              :         gizmoMode: gizmoMode.value
     473              :       }
     474              : 
     475            2 :       setupAnimationEvents()
     476              :     } catch (error) {
     477            0 :       console.error('Error initializing Load3d viewer:', error)
     478            0 :       useToast().warning(t('toastMessages.failedToInitializeLoad3dViewer'))
     479              :     }
     480              :   }
     481              : 
     482              :   /**
     483              :    * Initializes the viewer in standalone mode for asset preview.
     484              :    * Creates the Load3d instance once; subsequent calls reuse it.
     485              :    *
     486              :    * @param containerRef The HTML element to mount the viewer in
     487              :    * @param modelUrl URL of the model to load
     488              :    */
     489            2 :   const initializeStandaloneViewer = async (
     490              :     containerRef: HTMLElement,
     491              :     modelUrl: string
     492              :   ) => {
     493            0 :     try {
     494            0 :       if (load3d) {
     495            0 :         await loadStandaloneModel(modelUrl)
     496            0 :         return
     497              :       }
     498              : 
     499            0 :       isStandaloneMode.value = true
     500              : 
     501            0 :       load3d = createLoad3d(containerRef, load3dHost, {
     502              :         width: 800,
     503              :         height: 600,
     504              :         isViewerMode: true
     505              :       })
     506              : 
     507            0 :       if (mouseOnViewer) {
     508            0 :         load3d.updateStatusMouseOnViewer(true)
     509              :       }
     510              : 
     511              :       // Viewer-lifetime setup belongs to instance creation, not to this
     512              :       // request: a concurrent initializeStandaloneViewer() call reuses the
     513              :       // instance through loadStandaloneModel() and can supersede this load.
     514            0 :       isPreview.value = true
     515            0 :       setupAnimationEvents()
     516              : 
     517            0 :       const outcome = await load3d.loadModel(modelUrl)
     518            0 :       reportLoadModelOutcome(outcome)
     519            0 :       if (outcome !== 'loaded') return
     520            0 :       currentModelUrl = modelUrl
     521            0 :       restoreStandaloneConfig(modelUrl)
     522            0 :       captureAdapterFlags(load3d)
     523            0 :       persistStandaloneThumbnail(modelUrl)
     524              :     } catch (error) {
     525            0 :       console.error('Error initializing standalone 3D viewer:', error)
     526            0 :       useToast().warning(t('toastMessages.failedToLoadModel'))
     527              :     }
     528              :   }
     529              : 
     530            2 :   const persistStandaloneThumbnail = (modelUrl: string) => {
     531            0 :     if (!load3d || !isAssetPreviewSupported()) return
     532            0 :     const name = standaloneAssetName(modelUrl)
     533            0 :     if (!name) return
     534            0 :     void load3d
     535              :       .captureThumbnail(256, 256)
     536              :       .then((dataUrl) => fetch(dataUrl))
     537              :       .then((response) => response.blob())
     538              :       .then((blob) => persistThumbnail(name, blob))
     539              :       .catch(() => {})
     540              :   }
     541              : 
     542              :   /**
     543              :    * Load a new model into an existing standalone viewer,
     544              :    * reusing the same WebGLRenderer.
     545              :    */
     546            2 :   const loadStandaloneModel = async (modelUrl: string) => {
     547            0 :     if (!load3d) return
     548              : 
     549            0 :     try {
     550            0 :       saveStandaloneConfig()
     551            0 :       const outcome = await load3d.loadModel(modelUrl)
     552            0 :       reportLoadModelOutcome(outcome)
     553            0 :       if (outcome !== 'loaded') return
     554            0 :       currentModelUrl = modelUrl
     555            0 :       restoreStandaloneConfig(modelUrl)
     556            0 :       captureAdapterFlags(load3d)
     557            0 :       persistStandaloneThumbnail(modelUrl)
     558              :     } catch (error) {
     559            0 :       console.error('Error loading model in standalone viewer:', error)
     560            0 :       useToast().warning(t('toastMessages.failedToLoadModel'))
     561              :     }
     562              :   }
     563              : 
     564              :   /**
     565              :    * Saves the current viewer configuration to the standalone cache.
     566              :    */
     567            0 :   function saveStandaloneConfig() {
     568            0 :     if (!currentModelUrl) return
     569            0 :     standaloneConfigCache.set(currentModelUrl, {
     570              :       backgroundColor: backgroundColor.value,
     571              :       showGrid: showGrid.value,
     572              :       cameraType: cameraType.value,
     573              :       fov: fov.value,
     574              :       lightIntensity: lightIntensity.value,
     575              :       cameraState: load3d?.getCameraState() ?? null,
     576              :       backgroundImage: backgroundImage.value,
     577              :       backgroundRenderMode: backgroundRenderMode.value,
     578              :       upDirection: upDirection.value,
     579              :       materialMode: materialMode.value,
     580              :       gizmoEnabled: gizmoEnabled.value,
     581              :       gizmoMode: gizmoMode.value
     582              :     })
     583              :   }
     584              : 
     585              :   /**
     586              :    * Restores the viewer configuration from the standalone cache for the given model URL.
     587              :    *
     588              :    * @param modelUrl URL of the model to restore config for
     589              :    */
     590            0 :   function restoreStandaloneConfig(modelUrl: string) {
     591            0 :     const cached = standaloneConfigCache.get(modelUrl)
     592            0 :     const config = cached ?? DEFAULT_STANDALONE_CONFIG
     593            0 :     backgroundColor.value = config.backgroundColor
     594            0 :     showGrid.value = config.showGrid
     595            0 :     cameraType.value = config.cameraType
     596            0 :     fov.value = config.fov
     597            0 :     lightIntensity.value = config.lightIntensity
     598            0 :     backgroundImage.value = config.backgroundImage
     599            0 :     hasBackgroundImage.value = !!config.backgroundImage
     600            0 :     backgroundRenderMode.value = config.backgroundRenderMode
     601            0 :     upDirection.value = config.upDirection
     602            0 :     materialMode.value = config.materialMode
     603            0 :     gizmoEnabled.value = config.gizmoEnabled
     604            0 :     gizmoMode.value = config.gizmoMode
     605            0 :     if (cached?.cameraState && load3d) {
     606            0 :       load3d.setCameraState(cached.cameraState)
     607              :     }
     608              :   }
     609              : 
     610              :   /**
     611              :    * Exports the current model in the specified format.
     612              :    *
     613              :    * @param format The export format (e.g., 'glb', 'obj')
     614              :    */
     615            2 :   const exportModel = async (format: string) => {
     616            0 :     if (!load3d) return
     617              : 
     618            0 :     try {
     619            0 :       await load3d.exportModel(format)
     620              :     } catch (error) {
     621            0 :       console.error('Error exporting model:', error)
     622            0 :       useToast().warning(
     623              :         t('toastMessages.failedToExportModel', {
     624              :           format: format.toUpperCase()
     625              :         })
     626              :       )
     627              :     }
     628              :   }
     629              : 
     630              :   /**
     631              :    * Handles resizing the 3D viewer.
     632              :    */
     633            2 :   const handleResize = () => {
     634            0 :     load3d?.handleResize()
     635              :   }
     636              : 
     637              :   /**
     638              :    * Notifies the viewer that the mouse has entered the viewer area.
     639              :    */
     640            2 :   const handleMouseEnter = () => {
     641            2 :     mouseOnViewer = true
     642            2 :     load3d?.updateStatusMouseOnViewer(true)
     643              :   }
     644              : 
     645              :   /**
     646              :    * Notifies the viewer that the mouse has left the viewer area.
     647              :    */
     648            2 :   const handleMouseLeave = () => {
     649            0 :     mouseOnViewer = false
     650            0 :     load3d?.updateStatusMouseOnViewer(false)
     651              :   }
     652              : 
     653              :   /**
     654              :    * Restores the viewer state to its initial values when the viewer was opened.
     655              :    */
     656            2 :   const restoreInitialState = () => {
     657            1 :     if (!node) return
     658              : 
     659            1 :     const nodeValue = node
     660              : 
     661            1 :     needApplyChanges.value = false
     662              : 
     663            1 :     nodeValue.properties['Scene Config'] = {
     664              :       showGrid: initialState.value.showGrid,
     665              :       backgroundColor: initialState.value.backgroundColor,
     666              :       backgroundImage: initialState.value.backgroundImage,
     667              :       backgroundRenderMode: initialState.value.backgroundRenderMode
     668              :     }
     669              : 
     670            1 :     nodeValue.properties['Camera Config'] = {
     671              :       cameraType: initialState.value.cameraType,
     672              :       fov: initialState.value.fov
     673              :     }
     674              : 
     675            1 :     nodeValue.properties['Light Config'] = {
     676              :       intensity: initialState.value.lightIntensity
     677              :     }
     678              : 
     679            1 :     const existingModelConfig = nodeValue.properties['Model Config'] as
     680              :       | ModelConfig
     681              :       | undefined
     682            1 :     nodeValue.properties['Model Config'] = {
     683              :       ...existingModelConfig,
     684              :       upDirection: initialState.value.upDirection,
     685              :       materialMode: initialState.value.materialMode,
     686              :       gizmo: {
     687              :         enabled: initialState.value.gizmoEnabled,
     688              :         mode: initialState.value.gizmoMode,
     689              :         position: { x: 0, y: 0, z: 0 },
     690              :         rotation: { x: 0, y: 0, z: 0 },
     691              :         scale: { x: 1, y: 1, z: 1 }
     692              :       }
     693              :     }
     694              : 
     695            1 :     const currentCameraConfig = nodeValue.properties['Camera Config'] as
     696              :       | CameraConfig
     697              :       | undefined
     698            1 :     nodeValue.properties['Camera Config'] = {
     699              :       ...currentCameraConfig,
     700              :       state: initialState.value.cameraState
     701              :     }
     702              :   }
     703              : 
     704              :   /**
     705              :    * Applies the current viewer changes back to the source node and its properties.
     706              :    *
     707              :    * @returns Promise resolving to true if changes were applied successfully
     708              :    */
     709            2 :   const applyChanges = async () => {
     710            0 :     if (!node || !sourceLoad3d || !load3d) return false
     711              : 
     712            0 :     const viewerCameraState = load3d.getCameraState()
     713            0 :     const nodeValue = node
     714              : 
     715            0 :     nodeValue.properties['Scene Config'] = {
     716              :       showGrid: showGrid.value,
     717              :       backgroundColor: backgroundColor.value,
     718              :       backgroundImage: backgroundImage.value,
     719              :       backgroundRenderMode: backgroundRenderMode.value
     720              :     }
     721              : 
     722            0 :     nodeValue.properties['Camera Config'] = {
     723              :       cameraType: cameraType.value,
     724              :       fov: fov.value,
     725              :       state: viewerCameraState
     726              :     }
     727              : 
     728            0 :     nodeValue.properties['Light Config'] = {
     729              :       intensity: lightIntensity.value
     730              :     }
     731              : 
     732            0 :     const gizmoTransform = load3d.getGizmoTransform()
     733            0 :     const existingModelConfig = nodeValue.properties['Model Config'] as
     734              :       | ModelConfig
     735              :       | undefined
     736            0 :     nodeValue.properties['Model Config'] = {
     737              :       ...existingModelConfig,
     738              :       upDirection: upDirection.value,
     739              :       materialMode: materialMode.value,
     740              :       gizmo: {
     741              :         enabled: gizmoEnabled.value,
     742              :         mode: gizmoMode.value,
     743              :         position: gizmoTransform.position,
     744              :         rotation: gizmoTransform.rotation,
     745              :         scale: gizmoTransform.scale
     746              :       }
     747              :     }
     748              : 
     749            0 :     await copyLoad3dState(load3d, sourceLoad3d)
     750              : 
     751            0 :     await sourceLoad3d.setBackgroundImage(backgroundImage.value)
     752            0 :     sourceLoad3d.setBackgroundRenderMode(backgroundRenderMode.value)
     753              : 
     754            0 :     sourceLoad3d.forceRender()
     755              : 
     756            0 :     if (nodeValue.graph) {
     757            0 :       nodeValue.graph.setDirtyCanvas(true, true)
     758              :     }
     759              : 
     760            0 :     return true
     761              :   }
     762              : 
     763              :   /**
     764              :    * Refreshes the viewport of the current Load3d instance.
     765              :    */
     766            2 :   const refreshViewport = () => {
     767            0 :     handleViewportRefresh(load3d)
     768              :   }
     769              : 
     770              :   /**
     771              :    * Returns the subfolder path for file uploads based on the node properties.
     772              :    *
     773              :    * @returns The subfolder string
     774              :    */
     775            2 :   const getUploadSubfolder = () => {
     776            0 :     const resourceFolder = String(
     777              :       node?.properties['Resource Folder'] ?? ''
     778              :     ).trim()
     779            0 :     return resourceFolder ? `3d/${resourceFolder}` : '3d'
     780              :   }
     781              : 
     782              :   /**
     783              :    * Handles updating the background image either by clearing it or uploading a new file.
     784              :    *
     785              :    * @param file The image file to upload, or null to clear the background
     786              :    */
     787            2 :   const handleBackgroundImageUpdate = async (file: File | null) => {
     788            0 :     if (!file) {
     789            0 :       backgroundImage.value = ''
     790            0 :       hasBackgroundImage.value = false
     791            0 :       return
     792              :     }
     793              : 
     794            0 :     if (!load3d) {
     795            0 :       useToast().warning(t('toastMessages.no3dScene'))
     796            0 :       return
     797              :     }
     798              : 
     799            0 :     try {
     800            0 :       const uploadPath = await Load3dUtils.uploadFile(
     801              :         file,
     802              :         getUploadSubfolder()
     803              :       )
     804              : 
     805            0 :       if (uploadPath) {
     806            0 :         backgroundRenderMode.value = 'tiled'
     807            0 :         backgroundImage.value = uploadPath
     808            0 :         hasBackgroundImage.value = true
     809              :       }
     810              :     } catch (error) {
     811            0 :       console.error('Error uploading background image:', error)
     812            0 :       useToast().warning(t('toastMessages.failedToUploadBackgroundImage'))
     813              :     }
     814              :   }
     815              : 
     816              :   /**
     817              :    * Handles dropping a new model file into the viewer.
     818              :    *
     819              :    * @param file The 3D model file to load
     820              :    */
     821            2 :   const handleModelDrop = async (file: File) => {
     822            0 :     if (!load3d) {
     823            0 :       useToast().warning(t('toastMessages.no3dScene'))
     824            0 :       return
     825              :     }
     826              : 
     827            0 :     try {
     828            0 :       const uploadedPath = await Load3dUtils.uploadFile(
     829              :         file,
     830              :         getUploadSubfolder()
     831              :       )
     832              : 
     833            0 :       if (!uploadedPath) {
     834            0 :         useToast().warning(t('toastMessages.fileUploadFailed'))
     835            0 :         return
     836              :       }
     837              : 
     838            0 :       const modelUrl = api.apiURL(
     839              :         Load3dUtils.getResourceURL(
     840              :           ...Load3dUtils.splitFilePath(uploadedPath),
     841              :           'input'
     842              :         )
     843              :       )
     844              : 
     845            0 :       const outcome = await load3d.loadModel(modelUrl)
     846            0 :       reportLoadModelOutcome(outcome)
     847            0 :       if (outcome !== 'loaded') return
     848              : 
     849            0 :       captureAdapterFlags(load3d)
     850              : 
     851            0 :       const modelWidget = node?.widgets?.find((w) => w.name === 'model_file')
     852            0 :       if (modelWidget) {
     853            0 :         const options = modelWidget.options as { values?: string[] } | undefined
     854            0 :         if (options?.values && !options.values.includes(uploadedPath)) {
     855            0 :           options.values.push(uploadedPath)
     856              :         }
     857            0 :         modelWidget.value = uploadedPath
     858              :       }
     859              :     } catch (error) {
     860            0 :       console.error('Model drop failed:', error)
     861            0 :       useToast().warning(t('toastMessages.failedToLoadModel'))
     862              :     }
     863              :   }
     864              : 
     865              :   /**
     866              :    * Cleans up the viewer resources and saves the current standalone config if applicable.
     867              :    */
     868            2 :   const cleanup = () => {
     869            1 :     if (isStandaloneMode.value) {
     870            0 :       saveStandaloneConfig()
     871              :     }
     872            1 :     mouseOnViewer = false
     873            1 :     load3d?.remove()
     874            1 :     load3d = null
     875            1 :     sourceLoad3d = null
     876            1 :     currentModelUrl = null
     877              :   }
     878              : 
     879            2 :   return {
     880              :     // State
     881              :     backgroundColor,
     882              :     showGrid,
     883              :     cameraType,
     884              :     fov,
     885              :     lightIntensity,
     886              :     backgroundImage,
     887              :     hasBackgroundImage,
     888              :     backgroundRenderMode,
     889              :     upDirection,
     890              :     materialMode,
     891              :     gizmoEnabled,
     892              :     gizmoMode,
     893              :     needApplyChanges,
     894              :     isPreview,
     895              :     isStandaloneMode,
     896              :     isSplatModel,
     897              :     isPlyModel,
     898              :     sourceFormat,
     899              :     canFitToViewer,
     900              :     canUseGizmo,
     901              :     canUseLighting,
     902              :     canExport,
     903              :     materialModes,
     904              : 
     905              :     // Animation state
     906              :     animations,
     907              :     playing,
     908              :     selectedSpeed,
     909              :     selectedAnimation,
     910              :     animationProgress,
     911              :     animationDuration,
     912              : 
     913              :     // Methods
     914              :     initializeViewer,
     915              :     initializeStandaloneViewer,
     916              :     exportModel,
     917              :     handleResize,
     918              :     handleMouseEnter,
     919              :     handleMouseLeave,
     920              :     restoreInitialState,
     921              :     applyChanges,
     922              :     refreshViewport,
     923              :     handleBackgroundImageUpdate,
     924              :     handleModelDrop,
     925              :     handleSeek,
     926              :     resetGizmoTransform: () => {
     927            0 :       load3d?.resetGizmoTransform()
     928              :     },
     929              :     cleanup,
     930              : 
     931              :     hasSkeleton: false,
     932              :     intensity: lightIntensity,
     933              :     showSkeleton: false
     934              :   }
     935              : }
        

Generated by: LCOV version 2.0-1