import { Material } from '@babylonjs/core/Materials/material.js' ; import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh.js' ; import { Scene } from '@babylonjs/core/scene.js' ; import { CreatedInstance } from '../CreatedInstance' ; import { MaterialCustomProps } from '../CustomProps' ; import { FiberMaterialProps } from '../generatedProps' ; import { assignProperty } from '../helper/property' ; import BaseLifecycleListener from './BaseLifecycleListener' ; export default class MaterialsLifecycleListener extends BaseLifecycleListener < Material , FiberMaterialProps > { onCreated ( instance , scene ) { if ( ( instance . customProps as MaterialCustomProps ) . attachToMeshesByName ) { if ( ! Array . isArray ( ( instance . customProps as MaterialCustomProps ) . attachToMeshesByName ) ) { console . error ( 'AttachToMeshesByName must be an array (of strings).' , ( instance . customProps as MaterialCustomProps ) . attachToMeshesByName ) ; return ; } if ( instance . hostInstance === undefined ) { console . error ( 'instance not assigned' ) ; return ; } const meshNamesToAttachTo = ( instance . customProps as MaterialCustomProps ) . attachToMeshesByName ! . slice ( 0 ) ; scene . onNewMeshAddedObservable . add ( ( mesh ) => { if ( meshNamesToAttachTo . indexOf ( mesh . name ) >= 0 ) { setTimeout ( ( ) => { mesh . material = instance . hostInstance ! ; } , 0 ) ; } } ) ; scene . meshes . forEach ( ( mesh ) => { if ( meshNamesToAttachTo . indexOf ( mesh . name ) >= 0 ) { mesh . material = instance . hostInstance ! ; } } ) ; } } onMount ( instance ? ) { if ( instance === undefined ) { console . error ( 'Missing instance' ) ; return ; } if ( ! ( instance . customProps as MaterialCustomProps ) . attachToMeshesByName ) { const material = instance . hostInstance ; let tmp = instance . parent ; while ( tmp !== null ) { if ( tmp . metadata && tmp . metadata . acceptsMaterials === true ) { if ( instance . customProps . assignTo ) { assignProperty ( material , tmp . hostInstance , instance . customProps . assignTo ) ; } else { tmp . hostInstance . material = material ; } break ; } tmp = tmp . parent ; } } } }