@fps-games/editor-deployment 0.2.3-beta.10
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/bin/fps-editor-agent.mjs +5 -0
- package/bin/fps-editor-prepare.mjs +5 -0
- package/bin/fps-editor-project.mjs +18 -0
- package/bin/fps-editor-server.mjs +2 -0
- package/licenses/THIRD_PARTY_NOTICES.txt +7 -0
- package/manifest.json +2688 -0
- package/npm-shrinkwrap.json +21 -0
- package/package.json +44 -0
- package/public/assets/abstractAudioBus-BRAC2GY2.js +1 -0
- package/public/assets/animation-C6iNAO1g.js +1 -0
- package/public/assets/animation-C6iNAO1g.js.br +0 -0
- package/public/assets/animation-C6iNAO1g.js.gz +0 -0
- package/public/assets/animationGroup-C74XVFRE.js +1 -0
- package/public/assets/animationGroup-C74XVFRE.js.br +0 -0
- package/public/assets/animationGroup-C74XVFRE.js.gz +0 -0
- package/public/assets/arcRotateCamera-CIQYNBBJ.js +1 -0
- package/public/assets/arcRotateCamera-CIQYNBBJ.js.br +0 -0
- package/public/assets/arcRotateCamera-CIQYNBBJ.js.gz +0 -0
- package/public/assets/babylon-core-PuGyjHMj.js +13882 -0
- package/public/assets/babylon-core-PuGyjHMj.js.br +0 -0
- package/public/assets/babylon-core-PuGyjHMj.js.gz +0 -0
- package/public/assets/babylon-core-S0gBQJVe.js +1 -0
- package/public/assets/babylon-core-S0gBQJVe.js.br +0 -0
- package/public/assets/babylon-core-S0gBQJVe.js.gz +0 -0
- package/public/assets/basisTextureLoader-BdapVvhf.js +1 -0
- package/public/assets/basisTextureLoader-BdapVvhf.js.br +0 -0
- package/public/assets/basisTextureLoader-BdapVvhf.js.gz +0 -0
- package/public/assets/bumpVertex-DMhnr4dz.js +173 -0
- package/public/assets/bumpVertex-DMhnr4dz.js.br +0 -0
- package/public/assets/bumpVertex-DMhnr4dz.js.gz +0 -0
- package/public/assets/bumpVertex-DpGOKCkn.js +177 -0
- package/public/assets/bumpVertex-DpGOKCkn.js.br +0 -0
- package/public/assets/bumpVertex-DpGOKCkn.js.gz +0 -0
- package/public/assets/chromaticAberration.fragment-BgX-2zxS.js +7 -0
- package/public/assets/chromaticAberration.fragment-BgX-2zxS.js.br +0 -0
- package/public/assets/chromaticAberration.fragment-BgX-2zxS.js.gz +0 -0
- package/public/assets/chromaticAberration.fragment-D7t6Txg4.js +6 -0
- package/public/assets/chromaticAberration.fragment-D7t6Txg4.js.br +0 -0
- package/public/assets/chromaticAberration.fragment-D7t6Txg4.js.gz +0 -0
- package/public/assets/circleOfConfusion.fragment-D1RtHaPm.js +17 -0
- package/public/assets/circleOfConfusion.fragment-D1RtHaPm.js.br +0 -0
- package/public/assets/circleOfConfusion.fragment-D1RtHaPm.js.gz +0 -0
- package/public/assets/circleOfConfusion.fragment-D8geMRma.js +17 -0
- package/public/assets/circleOfConfusion.fragment-D8geMRma.js.br +0 -0
- package/public/assets/circleOfConfusion.fragment-D8geMRma.js.gz +0 -0
- package/public/assets/clipPlaneFragment-Bgl3Usc4.js +46 -0
- package/public/assets/clipPlaneFragment-Bgl3Usc4.js.br +0 -0
- package/public/assets/clipPlaneFragment-Bgl3Usc4.js.gz +0 -0
- package/public/assets/clipPlaneVertex-BxK9aoI2.js +177 -0
- package/public/assets/clipPlaneVertex-BxK9aoI2.js.br +0 -0
- package/public/assets/clipPlaneVertex-BxK9aoI2.js.gz +0 -0
- package/public/assets/color.fragment-BUdIBar6.js +20 -0
- package/public/assets/color.fragment-BUdIBar6.js.br +0 -0
- package/public/assets/color.fragment-BUdIBar6.js.gz +0 -0
- package/public/assets/color.fragment-CDn4ZgkT.js +21 -0
- package/public/assets/color.fragment-CDn4ZgkT.js.br +0 -0
- package/public/assets/color.fragment-CDn4ZgkT.js.gz +0 -0
- package/public/assets/color.vertex-CaMOSKlC.js +39 -0
- package/public/assets/color.vertex-CaMOSKlC.js.br +5 -0
- package/public/assets/color.vertex-CaMOSKlC.js.gz +0 -0
- package/public/assets/color.vertex-dgbB6mhK.js +32 -0
- package/public/assets/color.vertex-dgbB6mhK.js.br +0 -0
- package/public/assets/color.vertex-dgbB6mhK.js.gz +0 -0
- package/public/assets/dds-3J0FZYX1.js +1 -0
- package/public/assets/dds-3J0FZYX1.js.br +0 -0
- package/public/assets/dds-3J0FZYX1.js.gz +0 -0
- package/public/assets/ddsTextureLoader-s5HptTVZ.js +1 -0
- package/public/assets/ddsTextureLoader-s5HptTVZ.js.br +0 -0
- package/public/assets/ddsTextureLoader-s5HptTVZ.js.gz +0 -0
- package/public/assets/default.fragment-C4xg7O-P.js +526 -0
- package/public/assets/default.fragment-C4xg7O-P.js.br +0 -0
- package/public/assets/default.fragment-C4xg7O-P.js.gz +0 -0
- package/public/assets/default.fragment-C4zjkcFb.js +468 -0
- package/public/assets/default.fragment-C4zjkcFb.js.br +0 -0
- package/public/assets/default.fragment-C4zjkcFb.js.gz +0 -0
- package/public/assets/default.vertex-A8wQopNr.js +193 -0
- package/public/assets/default.vertex-A8wQopNr.js.br +0 -0
- package/public/assets/default.vertex-A8wQopNr.js.gz +0 -0
- package/public/assets/default.vertex-YrvIUn4x.js +181 -0
- package/public/assets/default.vertex-YrvIUn4x.js.br +0 -0
- package/public/assets/default.vertex-YrvIUn4x.js.gz +0 -0
- package/public/assets/defaultUboDeclaration-C8GCosBM.js +5 -0
- package/public/assets/defaultUboDeclaration-C8GCosBM.js.br +0 -0
- package/public/assets/defaultUboDeclaration-C8GCosBM.js.gz +0 -0
- package/public/assets/defaultUboDeclaration-D26o_DDO.js +7 -0
- package/public/assets/defaultUboDeclaration-D26o_DDO.js.br +0 -0
- package/public/assets/defaultUboDeclaration-D26o_DDO.js.gz +0 -0
- package/public/assets/depth.fragment-Bn8G24s-.js +40 -0
- package/public/assets/depth.fragment-Bn8G24s-.js.br +4 -0
- package/public/assets/depth.fragment-Bn8G24s-.js.gz +0 -0
- package/public/assets/depth.vertex-B2lrdlJh.js +57 -0
- package/public/assets/depth.vertex-B2lrdlJh.js.br +0 -0
- package/public/assets/depth.vertex-B2lrdlJh.js.gz +0 -0
- package/public/assets/depthBoxBlur.fragment-BtTv8wid.js +5 -0
- package/public/assets/depthBoxBlur.fragment-BtTv8wid.js.br +0 -0
- package/public/assets/depthBoxBlur.fragment-BtTv8wid.js.gz +0 -0
- package/public/assets/depthBoxBlur.fragment-DViDG6Vb.js +6 -0
- package/public/assets/depthBoxBlur.fragment-DViDG6Vb.js.br +0 -0
- package/public/assets/depthBoxBlur.fragment-DViDG6Vb.js.gz +0 -0
- package/public/assets/depthOfFieldMerge.fragment-DCspcdWZ.js +26 -0
- package/public/assets/depthOfFieldMerge.fragment-DCspcdWZ.js.br +0 -0
- package/public/assets/depthOfFieldMerge.fragment-DCspcdWZ.js.gz +0 -0
- package/public/assets/depthOfFieldMerge.fragment-Ds-g4Ln8.js +21 -0
- package/public/assets/depthOfFieldMerge.fragment-Ds-g4Ln8.js.br +0 -0
- package/public/assets/depthOfFieldMerge.fragment-Ds-g4Ln8.js.gz +0 -0
- package/public/assets/dynamicTexture-Cuby-VOT.js +1329 -0
- package/public/assets/dynamicTexture-Cuby-VOT.js.br +0 -0
- package/public/assets/dynamicTexture-Cuby-VOT.js.gz +0 -0
- package/public/assets/easing-DbzzrXOl.js +1 -0
- package/public/assets/easing-DbzzrXOl.js.br +0 -0
- package/public/assets/easing-DbzzrXOl.js.gz +0 -0
- package/public/assets/editor-core-plugin-host-c2002442.js +1 -0
- package/public/assets/editor-core-plugin-host-c2002442.js.br +0 -0
- package/public/assets/editor-core-plugin-host-c2002442.js.gz +0 -0
- package/public/assets/exrTextureLoader-D39k4eK_.js +1 -0
- package/public/assets/exrTextureLoader-D39k4eK_.js.br +0 -0
- package/public/assets/exrTextureLoader-D39k4eK_.js.gz +0 -0
- package/public/assets/flowGraphArrayIndexBlock-C8nTWR8h.js +1 -0
- package/public/assets/flowGraphArrayIndexBlock-C8nTWR8h.js.br +0 -0
- package/public/assets/flowGraphArrayIndexBlock-C8nTWR8h.js.gz +0 -0
- package/public/assets/flowGraphBezierCurveEasingBlock-Izh7s0Zh.js +1 -0
- package/public/assets/flowGraphBezierCurveEasingBlock-Izh7s0Zh.js.br +0 -0
- package/public/assets/flowGraphBezierCurveEasingBlock-Izh7s0Zh.js.gz +0 -0
- package/public/assets/flowGraphBinaryOperationBlock-BRfalQP5.js +1 -0
- package/public/assets/flowGraphBinaryOperationBlock-BRfalQP5.js.br +0 -0
- package/public/assets/flowGraphBinaryOperationBlock-BRfalQP5.js.gz +0 -0
- package/public/assets/flowGraphBranchBlock-CV_leJX3.js +1 -0
- package/public/assets/flowGraphBranchBlock-CV_leJX3.js.br +0 -0
- package/public/assets/flowGraphBranchBlock-CV_leJX3.js.gz +0 -0
- package/public/assets/flowGraphCachedOperationBlock-BysRM-Ha.js +1 -0
- package/public/assets/flowGraphCachedOperationBlock-BysRM-Ha.js.br +2 -0
- package/public/assets/flowGraphCachedOperationBlock-BysRM-Ha.js.gz +0 -0
- package/public/assets/flowGraphCancelDelayBlock-BK6tDTGy.js +1 -0
- package/public/assets/flowGraphCancelDelayBlock-BK6tDTGy.js.br +0 -0
- package/public/assets/flowGraphCancelDelayBlock-BK6tDTGy.js.gz +0 -0
- package/public/assets/flowGraphCodeExecutionBlock-CQABvaP8.js +1 -0
- package/public/assets/flowGraphCodeExecutionBlock-CQABvaP8.js.br +0 -0
- package/public/assets/flowGraphCodeExecutionBlock-CQABvaP8.js.gz +0 -0
- package/public/assets/flowGraphConditionalDataBlock-D7OU_UOM.js +1 -0
- package/public/assets/flowGraphConditionalDataBlock-D7OU_UOM.js.br +0 -0
- package/public/assets/flowGraphConditionalDataBlock-D7OU_UOM.js.gz +0 -0
- package/public/assets/flowGraphConsoleLogBlock-BBxVDGOV.js +1 -0
- package/public/assets/flowGraphConsoleLogBlock-BBxVDGOV.js.br +0 -0
- package/public/assets/flowGraphConsoleLogBlock-BBxVDGOV.js.gz +0 -0
- package/public/assets/flowGraphConstantBlock-Cn3ZMGR0.js +1 -0
- package/public/assets/flowGraphConstantBlock-Cn3ZMGR0.js.br +0 -0
- package/public/assets/flowGraphConstantBlock-Cn3ZMGR0.js.gz +0 -0
- package/public/assets/flowGraphContextBlock-BS3b2XbE.js +1 -0
- package/public/assets/flowGraphContextBlock-BS3b2XbE.js.br +0 -0
- package/public/assets/flowGraphContextBlock-BS3b2XbE.js.gz +0 -0
- package/public/assets/flowGraphCounterBlock-xdcRCw4l.js +1 -0
- package/public/assets/flowGraphCounterBlock-xdcRCw4l.js.br +0 -0
- package/public/assets/flowGraphCounterBlock-xdcRCw4l.js.gz +0 -0
- package/public/assets/flowGraphDataSwitchBlock-dY8TSZtd.js +1 -0
- package/public/assets/flowGraphDataSwitchBlock-dY8TSZtd.js.br +0 -0
- package/public/assets/flowGraphDataSwitchBlock-dY8TSZtd.js.gz +0 -0
- package/public/assets/flowGraphDebounceBlock-Q_f2x-ID.js +1 -0
- package/public/assets/flowGraphDebounceBlock-Q_f2x-ID.js.br +0 -0
- package/public/assets/flowGraphDebounceBlock-Q_f2x-ID.js.gz +0 -0
- package/public/assets/flowGraphDoNBlock-COo31G00.js +1 -0
- package/public/assets/flowGraphDoNBlock-COo31G00.js.br +0 -0
- package/public/assets/flowGraphDoNBlock-COo31G00.js.gz +0 -0
- package/public/assets/flowGraphEasingBlock-jGW-fKIB.js +1 -0
- package/public/assets/flowGraphEasingBlock-jGW-fKIB.js.br +0 -0
- package/public/assets/flowGraphEasingBlock-jGW-fKIB.js.gz +0 -0
- package/public/assets/flowGraphFlipFlopBlock-B8znf-3o.js +1 -0
- package/public/assets/flowGraphFlipFlopBlock-B8znf-3o.js.br +0 -0
- package/public/assets/flowGraphFlipFlopBlock-B8znf-3o.js.gz +0 -0
- package/public/assets/flowGraphForLoopBlock-UxZSh8US.js +1 -0
- package/public/assets/flowGraphForLoopBlock-UxZSh8US.js.br +0 -0
- package/public/assets/flowGraphForLoopBlock-UxZSh8US.js.gz +0 -0
- package/public/assets/flowGraphFunctionReferenceBlock-c3ZQWBhk.js +1 -0
- package/public/assets/flowGraphFunctionReferenceBlock-c3ZQWBhk.js.br +0 -0
- package/public/assets/flowGraphFunctionReferenceBlock-c3ZQWBhk.js.gz +0 -0
- package/public/assets/flowGraphGetAssetBlock-B3zYUZmJ.js +1 -0
- package/public/assets/flowGraphGetAssetBlock-B3zYUZmJ.js.br +0 -0
- package/public/assets/flowGraphGetAssetBlock-B3zYUZmJ.js.gz +0 -0
- package/public/assets/flowGraphGetPropertyBlock-D--vcmMS.js +1 -0
- package/public/assets/flowGraphGetPropertyBlock-D--vcmMS.js.br +0 -0
- package/public/assets/flowGraphGetPropertyBlock-D--vcmMS.js.gz +0 -0
- package/public/assets/flowGraphGetVariableBlock-BkCEyiL6.js +1 -0
- package/public/assets/flowGraphGetVariableBlock-BkCEyiL6.js.br +0 -0
- package/public/assets/flowGraphGetVariableBlock-BkCEyiL6.js.gz +0 -0
- package/public/assets/flowGraphIndexOfBlock-C4ipR7YB.js +1 -0
- package/public/assets/flowGraphIndexOfBlock-C4ipR7YB.js.br +0 -0
- package/public/assets/flowGraphIndexOfBlock-C4ipR7YB.js.gz +0 -0
- package/public/assets/flowGraphInterpolationBlock-DuRc3LX7.js +1 -0
- package/public/assets/flowGraphInterpolationBlock-DuRc3LX7.js.br +0 -0
- package/public/assets/flowGraphInterpolationBlock-DuRc3LX7.js.gz +0 -0
- package/public/assets/flowGraphJsonPointerParserBlock-urEWktqi.js +1 -0
- package/public/assets/flowGraphJsonPointerParserBlock-urEWktqi.js.br +0 -0
- package/public/assets/flowGraphJsonPointerParserBlock-urEWktqi.js.gz +0 -0
- package/public/assets/flowGraphMathBlocks-CGTCQVqz.js +1 -0
- package/public/assets/flowGraphMathBlocks-CGTCQVqz.js.br +0 -0
- package/public/assets/flowGraphMathBlocks-CGTCQVqz.js.gz +0 -0
- package/public/assets/flowGraphMathCombineExtractBlocks-DDHGbRPt.js +1 -0
- package/public/assets/flowGraphMathCombineExtractBlocks-DDHGbRPt.js.br +0 -0
- package/public/assets/flowGraphMathCombineExtractBlocks-DDHGbRPt.js.gz +0 -0
- package/public/assets/flowGraphMatrixMathBlocks-Bwp1BysB.js +1 -0
- package/public/assets/flowGraphMatrixMathBlocks-Bwp1BysB.js.br +0 -0
- package/public/assets/flowGraphMatrixMathBlocks-Bwp1BysB.js.gz +0 -0
- package/public/assets/flowGraphMeshPickEventBlock-2wkqhQCG.js +1 -0
- package/public/assets/flowGraphMeshPickEventBlock-2wkqhQCG.js.br +0 -0
- package/public/assets/flowGraphMeshPickEventBlock-2wkqhQCG.js.gz +0 -0
- package/public/assets/flowGraphMultiGateBlock-BuKmvqC8.js +1 -0
- package/public/assets/flowGraphMultiGateBlock-BuKmvqC8.js.br +0 -0
- package/public/assets/flowGraphMultiGateBlock-BuKmvqC8.js.gz +0 -0
- package/public/assets/flowGraphPauseAnimationBlock-T_-VP-t5.js +1 -0
- package/public/assets/flowGraphPauseAnimationBlock-T_-VP-t5.js.br +0 -0
- package/public/assets/flowGraphPauseAnimationBlock-T_-VP-t5.js.gz +0 -0
- package/public/assets/flowGraphPlayAnimationBlock-DDVrE__n.js +1 -0
- package/public/assets/flowGraphPlayAnimationBlock-DDVrE__n.js.br +0 -0
- package/public/assets/flowGraphPlayAnimationBlock-DDVrE__n.js.gz +0 -0
- package/public/assets/flowGraphPointerOutEventBlock-Cx15Sf5R.js +1 -0
- package/public/assets/flowGraphPointerOutEventBlock-Cx15Sf5R.js.br +0 -0
- package/public/assets/flowGraphPointerOutEventBlock-Cx15Sf5R.js.gz +0 -0
- package/public/assets/flowGraphPointerOverEventBlock-DzzHa-dN.js +1 -0
- package/public/assets/flowGraphPointerOverEventBlock-DzzHa-dN.js.br +0 -0
- package/public/assets/flowGraphPointerOverEventBlock-DzzHa-dN.js.gz +0 -0
- package/public/assets/flowGraphReceiveCustomEventBlock-DKfLODu3.js +1 -0
- package/public/assets/flowGraphReceiveCustomEventBlock-DKfLODu3.js.br +0 -0
- package/public/assets/flowGraphReceiveCustomEventBlock-DKfLODu3.js.gz +0 -0
- package/public/assets/flowGraphSceneReadyEventBlock-ClJu3s64.js +1 -0
- package/public/assets/flowGraphSceneReadyEventBlock-ClJu3s64.js.br +0 -0
- package/public/assets/flowGraphSceneReadyEventBlock-ClJu3s64.js.gz +0 -0
- package/public/assets/flowGraphSceneTickEventBlock-3ZNr4eqw.js +1 -0
- package/public/assets/flowGraphSceneTickEventBlock-3ZNr4eqw.js.br +0 -0
- package/public/assets/flowGraphSceneTickEventBlock-3ZNr4eqw.js.gz +0 -0
- package/public/assets/flowGraphSendCustomEventBlock-CdKQeuma.js +1 -0
- package/public/assets/flowGraphSendCustomEventBlock-CdKQeuma.js.br +0 -0
- package/public/assets/flowGraphSendCustomEventBlock-CdKQeuma.js.gz +0 -0
- package/public/assets/flowGraphSequenceBlock-D0-_bFV3.js +1 -0
- package/public/assets/flowGraphSequenceBlock-D0-_bFV3.js.br +0 -0
- package/public/assets/flowGraphSequenceBlock-D0-_bFV3.js.gz +0 -0
- package/public/assets/flowGraphSetDelayBlock-B8946WOc.js +1 -0
- package/public/assets/flowGraphSetDelayBlock-B8946WOc.js.br +0 -0
- package/public/assets/flowGraphSetDelayBlock-B8946WOc.js.gz +0 -0
- package/public/assets/flowGraphSetPropertyBlock-Cx0IyW-a.js +1 -0
- package/public/assets/flowGraphSetPropertyBlock-Cx0IyW-a.js.br +0 -0
- package/public/assets/flowGraphSetPropertyBlock-Cx0IyW-a.js.gz +0 -0
- package/public/assets/flowGraphSetVariableBlock-0dns_CH6.js +1 -0
- package/public/assets/flowGraphSetVariableBlock-0dns_CH6.js.br +0 -0
- package/public/assets/flowGraphSetVariableBlock-0dns_CH6.js.gz +0 -0
- package/public/assets/flowGraphStopAnimationBlock-z4ou311H.js +1 -0
- package/public/assets/flowGraphStopAnimationBlock-z4ou311H.js.br +0 -0
- package/public/assets/flowGraphStopAnimationBlock-z4ou311H.js.gz +0 -0
- package/public/assets/flowGraphSwitchBlock-E7meS39u.js +1 -0
- package/public/assets/flowGraphSwitchBlock-E7meS39u.js.br +0 -0
- package/public/assets/flowGraphSwitchBlock-E7meS39u.js.gz +0 -0
- package/public/assets/flowGraphThrottleBlock-CldHJDs6.js +1 -0
- package/public/assets/flowGraphThrottleBlock-CldHJDs6.js.br +0 -0
- package/public/assets/flowGraphThrottleBlock-CldHJDs6.js.gz +0 -0
- package/public/assets/flowGraphTransformCoordinatesSystemBlock-pYdpcwK7.js +1 -0
- package/public/assets/flowGraphTransformCoordinatesSystemBlock-pYdpcwK7.js.br +0 -0
- package/public/assets/flowGraphTransformCoordinatesSystemBlock-pYdpcwK7.js.gz +0 -0
- package/public/assets/flowGraphTypeToTypeBlocks-CYfvLPJ-.js +1 -0
- package/public/assets/flowGraphTypeToTypeBlocks-CYfvLPJ-.js.br +0 -0
- package/public/assets/flowGraphTypeToTypeBlocks-CYfvLPJ-.js.gz +0 -0
- package/public/assets/flowGraphUnaryOperationBlock-s-kJ99D8.js +1 -0
- package/public/assets/flowGraphUnaryOperationBlock-s-kJ99D8.js.br +0 -0
- package/public/assets/flowGraphUnaryOperationBlock-s-kJ99D8.js.gz +0 -0
- package/public/assets/flowGraphVectorMathBlocks-D7iofIoY.js +1 -0
- package/public/assets/flowGraphVectorMathBlocks-D7iofIoY.js.br +0 -0
- package/public/assets/flowGraphVectorMathBlocks-D7iofIoY.js.gz +0 -0
- package/public/assets/flowGraphWaitAllBlock-CAW7HgUP.js +1 -0
- package/public/assets/flowGraphWaitAllBlock-CAW7HgUP.js.br +0 -0
- package/public/assets/flowGraphWaitAllBlock-CAW7HgUP.js.gz +0 -0
- package/public/assets/flowGraphWhileLoopBlock-DRP9_Zd1.js +1 -0
- package/public/assets/flowGraphWhileLoopBlock-DRP9_Zd1.js.br +0 -0
- package/public/assets/flowGraphWhileLoopBlock-DRP9_Zd1.js.gz +0 -0
- package/public/assets/fogFragmentDeclaration-CzUy86ul.js +22 -0
- package/public/assets/fogFragmentDeclaration-CzUy86ul.js.br +0 -0
- package/public/assets/fogFragmentDeclaration-CzUy86ul.js.gz +0 -0
- package/public/assets/fogFragmentDeclaration-kfcrkpgB.js +23 -0
- package/public/assets/fogFragmentDeclaration-kfcrkpgB.js.br +0 -0
- package/public/assets/fogFragmentDeclaration-kfcrkpgB.js.gz +0 -0
- package/public/assets/glowBlurPostProcess.fragment-CS_rTtUL.js +7 -0
- package/public/assets/glowBlurPostProcess.fragment-CS_rTtUL.js.br +0 -0
- package/public/assets/glowBlurPostProcess.fragment-CS_rTtUL.js.gz +0 -0
- package/public/assets/glowBlurPostProcess.fragment-G_xfSiIr.js +7 -0
- package/public/assets/glowBlurPostProcess.fragment-G_xfSiIr.js.br +0 -0
- package/public/assets/glowBlurPostProcess.fragment-G_xfSiIr.js.gz +0 -0
- package/public/assets/glowMapGeneration.fragment-DwJ3bpr6.js +63 -0
- package/public/assets/glowMapGeneration.fragment-DwJ3bpr6.js.br +0 -0
- package/public/assets/glowMapGeneration.fragment-DwJ3bpr6.js.gz +0 -0
- package/public/assets/glowMapGeneration.fragment-mDEHNZRi.js +63 -0
- package/public/assets/glowMapGeneration.fragment-mDEHNZRi.js.br +0 -0
- package/public/assets/glowMapGeneration.fragment-mDEHNZRi.js.gz +0 -0
- package/public/assets/glowMapGeneration.vertex-BACa9-r4.js +75 -0
- package/public/assets/glowMapGeneration.vertex-BACa9-r4.js.br +0 -0
- package/public/assets/glowMapGeneration.vertex-BACa9-r4.js.gz +0 -0
- package/public/assets/glowMapGeneration.vertex-mAWUJxSB.js +75 -0
- package/public/assets/glowMapGeneration.vertex-mAWUJxSB.js.br +3 -0
- package/public/assets/glowMapGeneration.vertex-mAWUJxSB.js.gz +0 -0
- package/public/assets/glowMapMerge.fragment-0Im35OVD.js +23 -0
- package/public/assets/glowMapMerge.fragment-0Im35OVD.js.br +0 -0
- package/public/assets/glowMapMerge.fragment-0Im35OVD.js.gz +0 -0
- package/public/assets/glowMapMerge.fragment-BXHfrWgL.js +25 -0
- package/public/assets/glowMapMerge.fragment-BXHfrWgL.js.br +0 -0
- package/public/assets/glowMapMerge.fragment-BXHfrWgL.js.gz +0 -0
- package/public/assets/glowMapMerge.vertex-8A2ntYoS.js +7 -0
- package/public/assets/glowMapMerge.vertex-8A2ntYoS.js.br +0 -0
- package/public/assets/glowMapMerge.vertex-8A2ntYoS.js.gz +0 -0
- package/public/assets/glowMapMerge.vertex-Cnm-5WLT.js +8 -0
- package/public/assets/glowMapMerge.vertex-Cnm-5WLT.js.br +0 -0
- package/public/assets/glowMapMerge.vertex-Cnm-5WLT.js.gz +0 -0
- package/public/assets/grain.fragment-BMGi-Hgp.js +6 -0
- package/public/assets/grain.fragment-BMGi-Hgp.js.br +0 -0
- package/public/assets/grain.fragment-BMGi-Hgp.js.gz +0 -0
- package/public/assets/grain.fragment-CH9zg05c.js +5 -0
- package/public/assets/grain.fragment-CH9zg05c.js.br +0 -0
- package/public/assets/grain.fragment-CH9zg05c.js.gz +0 -0
- package/public/assets/harmonicsFunctions-BQTTvws3.js +192 -0
- package/public/assets/harmonicsFunctions-BQTTvws3.js.br +0 -0
- package/public/assets/harmonicsFunctions-BQTTvws3.js.gz +0 -0
- package/public/assets/harmonicsFunctions-DtIiYWL1.js +189 -0
- package/public/assets/harmonicsFunctions-DtIiYWL1.js.br +0 -0
- package/public/assets/harmonicsFunctions-DtIiYWL1.js.gz +0 -0
- package/public/assets/hdrTextureLoader-Dqvpv0kr.js +2 -0
- package/public/assets/hdrTextureLoader-Dqvpv0kr.js.br +0 -0
- package/public/assets/hdrTextureLoader-Dqvpv0kr.js.gz +0 -0
- package/public/assets/iesTextureLoader-B8AoKSG2.js +2 -0
- package/public/assets/iesTextureLoader-B8AoKSG2.js.br +0 -0
- package/public/assets/iesTextureLoader-B8AoKSG2.js.gz +0 -0
- package/public/assets/index-CiIoJ8v1.js +4 -0
- package/public/assets/index-CiIoJ8v1.js.br +0 -0
- package/public/assets/index-CiIoJ8v1.js.gz +0 -0
- package/public/assets/index-Dhf9rSmv.js +1 -0
- package/public/assets/index-Dhf9rSmv.js.br +0 -0
- package/public/assets/index-Dhf9rSmv.js.gz +0 -0
- package/public/assets/instancesDeclaration-B2a0VuuR.js +23 -0
- package/public/assets/instancesDeclaration-B2a0VuuR.js.br +0 -0
- package/public/assets/instancesDeclaration-B2a0VuuR.js.gz +0 -0
- package/public/assets/ktxTextureLoader-DTr7AKqG.js +1 -0
- package/public/assets/ktxTextureLoader-DTr7AKqG.js.br +0 -0
- package/public/assets/ktxTextureLoader-DTr7AKqG.js.gz +0 -0
- package/public/assets/lazy-Cj-01uhW.js +2 -0
- package/public/assets/lazy-Cj-01uhW.js.br +0 -0
- package/public/assets/lazy-Cj-01uhW.js.gz +0 -0
- package/public/assets/lod.fragment-BuvQbBhE.js +3 -0
- package/public/assets/lod.fragment-BuvQbBhE.js.br +0 -0
- package/public/assets/lod.fragment-BuvQbBhE.js.gz +0 -0
- package/public/assets/lod.fragment-Cp0eqGjl.js +3 -0
- package/public/assets/lod.fragment-Cp0eqGjl.js.br +3 -0
- package/public/assets/lod.fragment-Cp0eqGjl.js.gz +0 -0
- package/public/assets/lodCube.fragment-CI1eTppS.js +22 -0
- package/public/assets/lodCube.fragment-CI1eTppS.js.br +2 -0
- package/public/assets/lodCube.fragment-CI1eTppS.js.gz +0 -0
- package/public/assets/lodCube.fragment-yDzV1teg.js +22 -0
- package/public/assets/lodCube.fragment-yDzV1teg.js.br +0 -0
- package/public/assets/lodCube.fragment-yDzV1teg.js.gz +0 -0
- package/public/assets/logDepthDeclaration-CeLLOhuK.js +4 -0
- package/public/assets/logDepthDeclaration-XDsVKoT0.js +4 -0
- package/public/assets/logDepthFragment-BPP-rBiT.js +4 -0
- package/public/assets/logDepthFragment-BPP-rBiT.js.br +0 -0
- package/public/assets/logDepthFragment-BPP-rBiT.js.gz +0 -0
- package/public/assets/logDepthFragment-CDaMyvfH.js +4 -0
- package/public/assets/logDepthVertex-CkFa6uAf.js +4 -0
- package/public/assets/logDepthVertex-CkFa6uAf.js.br +0 -0
- package/public/assets/logDepthVertex-CkFa6uAf.js.gz +0 -0
- package/public/assets/logDepthVertex-H6E8NLz1.js +4 -0
- package/public/assets/logDepthVertex-H6E8NLz1.js.br +1 -0
- package/public/assets/logDepthVertex-H6E8NLz1.js.gz +0 -0
- package/public/assets/mainUVVaryingDeclaration-DdwP8xi_.js +4 -0
- package/public/assets/mainUVVaryingDeclaration-OBB3LR8s.js +4 -0
- package/public/assets/mesh.vertexData.functions-BXkNVxNr.js +1 -0
- package/public/assets/mesh.vertexData.functions-BXkNVxNr.js.br +0 -0
- package/public/assets/mesh.vertexData.functions-BXkNVxNr.js.gz +0 -0
- package/public/assets/meshUboDeclaration-Cr5YhBB1.js +13 -0
- package/public/assets/meshUboDeclaration-Cr5YhBB1.js.br +0 -0
- package/public/assets/meshUboDeclaration-Cr5YhBB1.js.gz +0 -0
- package/public/assets/meshUboDeclaration-Uj1CsoJP.js +13 -0
- package/public/assets/meshUboDeclaration-Uj1CsoJP.js.br +0 -0
- package/public/assets/meshUboDeclaration-Uj1CsoJP.js.gz +0 -0
- package/public/assets/morphTargetsVertex-B9xWvV_u.js +100 -0
- package/public/assets/morphTargetsVertex-B9xWvV_u.js.br +0 -0
- package/public/assets/morphTargetsVertex-B9xWvV_u.js.gz +0 -0
- package/public/assets/oitFinalSimpleBlend.fragment-4NtZHGOG.js +3 -0
- package/public/assets/oitFinalSimpleBlend.fragment-4NtZHGOG.js.br +0 -0
- package/public/assets/oitFinalSimpleBlend.fragment-4NtZHGOG.js.gz +0 -0
- package/public/assets/oitFinalSimpleBlend.fragment-D8T6jyS0.js +2 -0
- package/public/assets/oitFinalSimpleBlend.fragment-D8T6jyS0.js.br +3 -0
- package/public/assets/oitFinalSimpleBlend.fragment-D8T6jyS0.js.gz +0 -0
- package/public/assets/oitFragment-CK8Y-Z-q.js +1202 -0
- package/public/assets/oitFragment-CK8Y-Z-q.js.br +0 -0
- package/public/assets/oitFragment-CK8Y-Z-q.js.gz +0 -0
- package/public/assets/oitFragment-ZUHesxAg.js +1077 -0
- package/public/assets/oitFragment-ZUHesxAg.js.br +0 -0
- package/public/assets/oitFragment-ZUHesxAg.js.gz +0 -0
- package/public/assets/openpbrMaterial-Dc7VVRl6.js +2 -0
- package/public/assets/openpbrMaterial-Dc7VVRl6.js.br +0 -0
- package/public/assets/openpbrMaterial-Dc7VVRl6.js.gz +0 -0
- package/public/assets/outline.fragment-BK0vgcx7.js +21 -0
- package/public/assets/outline.fragment-BK0vgcx7.js.br +0 -0
- package/public/assets/outline.fragment-BK0vgcx7.js.gz +0 -0
- package/public/assets/outline.fragment-DQK2JikO.js +18 -0
- package/public/assets/outline.fragment-DQK2JikO.js.br +0 -0
- package/public/assets/outline.fragment-DQK2JikO.js.gz +0 -0
- package/public/assets/outline.vertex-CHR7GZYH.js +47 -0
- package/public/assets/outline.vertex-CHR7GZYH.js.br +0 -0
- package/public/assets/outline.vertex-CHR7GZYH.js.gz +0 -0
- package/public/assets/outline.vertex-CKcILDiL.js +47 -0
- package/public/assets/outline.vertex-CKcILDiL.js.br +0 -0
- package/public/assets/outline.vertex-CKcILDiL.js.gz +0 -0
- package/public/assets/passCube.fragment-Ch6aeybh.js +23 -0
- package/public/assets/passCube.fragment-Ch6aeybh.js.br +0 -0
- package/public/assets/passCube.fragment-Ch6aeybh.js.gz +0 -0
- package/public/assets/passCube.fragment-wvJ8mb6_.js +23 -0
- package/public/assets/passCube.fragment-wvJ8mb6_.js.br +0 -0
- package/public/assets/passCube.fragment-wvJ8mb6_.js.gz +0 -0
- package/public/assets/pbr.fragment-Bo4XM7Ct.js +3277 -0
- package/public/assets/pbr.fragment-Bo4XM7Ct.js.br +0 -0
- package/public/assets/pbr.fragment-Bo4XM7Ct.js.gz +0 -0
- package/public/assets/pbr.fragment-T2xKI2J0.js +3327 -0
- package/public/assets/pbr.fragment-T2xKI2J0.js.br +0 -0
- package/public/assets/pbr.fragment-T2xKI2J0.js.gz +0 -0
- package/public/assets/pbr.vertex-BezAbBHx.js +357 -0
- package/public/assets/pbr.vertex-BezAbBHx.js.br +0 -0
- package/public/assets/pbr.vertex-BezAbBHx.js.gz +0 -0
- package/public/assets/pbr.vertex-w2ZWBdHy.js +227 -0
- package/public/assets/pbr.vertex-w2ZWBdHy.js.br +0 -0
- package/public/assets/pbr.vertex-w2ZWBdHy.js.gz +0 -0
- package/public/assets/playable-sdk-zAYuBOLj.js +8 -0
- package/public/assets/playable-sdk-zAYuBOLj.js.br +0 -0
- package/public/assets/playable-sdk-zAYuBOLj.js.gz +0 -0
- package/public/assets/playable-standard-project-Brbyn9c4.js +5140 -0
- package/public/assets/playable-standard-project-Brbyn9c4.js.br +0 -0
- package/public/assets/playable-standard-project-Brbyn9c4.js.gz +0 -0
- package/public/assets/rgbdDecode.fragment-BQ16CsAv.js +5 -0
- package/public/assets/rgbdDecode.fragment-BQ16CsAv.js.br +4 -0
- package/public/assets/rgbdDecode.fragment-BQ16CsAv.js.gz +0 -0
- package/public/assets/rgbdDecode.fragment-D_2CJy2O.js +5 -0
- package/public/assets/rgbdDecode.fragment-D_2CJy2O.js.br +0 -0
- package/public/assets/rgbdDecode.fragment-D_2CJy2O.js.gz +0 -0
- package/public/assets/rgbdEncode.fragment-CmDv6yEZ.js +5 -0
- package/public/assets/rgbdEncode.fragment-CmDv6yEZ.js.br +3 -0
- package/public/assets/rgbdEncode.fragment-CmDv6yEZ.js.gz +0 -0
- package/public/assets/rgbdEncode.fragment-QRg2h8KC.js +5 -0
- package/public/assets/rgbdEncode.fragment-QRg2h8KC.js.br +1 -0
- package/public/assets/rgbdEncode.fragment-QRg2h8KC.js.gz +0 -0
- package/public/assets/sceneLoader-CDreObGG.js +1 -0
- package/public/assets/sceneLoader-CDreObGG.js.br +0 -0
- package/public/assets/sceneLoader-CDreObGG.js.gz +0 -0
- package/public/assets/screenSpaceCurvature.fragment-BWdr_4iW.js +15 -0
- package/public/assets/screenSpaceCurvature.fragment-BWdr_4iW.js.br +0 -0
- package/public/assets/screenSpaceCurvature.fragment-BWdr_4iW.js.gz +0 -0
- package/public/assets/selection.fragment-CVXAuXcC.js +35 -0
- package/public/assets/selection.fragment-CVXAuXcC.js.br +0 -0
- package/public/assets/selection.fragment-CVXAuXcC.js.gz +0 -0
- package/public/assets/selection.fragment-DobH4NRw.js +35 -0
- package/public/assets/selection.fragment-DobH4NRw.js.br +0 -0
- package/public/assets/selection.fragment-DobH4NRw.js.gz +0 -0
- package/public/assets/selection.vertex-BUBv8X1j.js +74 -0
- package/public/assets/selection.vertex-BUBv8X1j.js.br +0 -0
- package/public/assets/selection.vertex-BUBv8X1j.js.gz +0 -0
- package/public/assets/selection.vertex-DlADXBtf.js +73 -0
- package/public/assets/selection.vertex-DlADXBtf.js.br +0 -0
- package/public/assets/selection.vertex-DlADXBtf.js.gz +0 -0
- package/public/assets/selectionOutline.fragment-CWpNrg8m.js +47 -0
- package/public/assets/selectionOutline.fragment-CWpNrg8m.js.br +0 -0
- package/public/assets/selectionOutline.fragment-CWpNrg8m.js.gz +0 -0
- package/public/assets/selectionOutline.fragment-DoKuUf2L.js +48 -0
- package/public/assets/selectionOutline.fragment-DoKuUf2L.js.br +0 -0
- package/public/assets/selectionOutline.fragment-DoKuUf2L.js.gz +0 -0
- package/public/assets/shadowMap.fragment-BEwhnKOg.js +78 -0
- package/public/assets/shadowMap.fragment-BEwhnKOg.js.br +0 -0
- package/public/assets/shadowMap.fragment-BEwhnKOg.js.gz +0 -0
- package/public/assets/shadowMap.fragment-CVar4C4N.js +79 -0
- package/public/assets/shadowMap.fragment-CVar4C4N.js.br +0 -0
- package/public/assets/shadowMap.fragment-CVar4C4N.js.gz +0 -0
- package/public/assets/shadowMap.vertex-ImOoSjTb.js +109 -0
- package/public/assets/shadowMap.vertex-ImOoSjTb.js.br +0 -0
- package/public/assets/shadowMap.vertex-ImOoSjTb.js.gz +0 -0
- package/public/assets/shadowMap.vertex-Q2d15P5z.js +119 -0
- package/public/assets/shadowMap.vertex-Q2d15P5z.js.br +0 -0
- package/public/assets/shadowMap.vertex-Q2d15P5z.js.gz +0 -0
- package/public/assets/shadowMapFragmentSoftTransparentShadow-BmxybqRD.js +4 -0
- package/public/assets/shadowMapFragmentSoftTransparentShadow-BmxybqRD.js.br +0 -0
- package/public/assets/shadowMapFragmentSoftTransparentShadow-BmxybqRD.js.gz +0 -0
- package/public/assets/shadowMapFragmentSoftTransparentShadow-D6ZvWsNy.js +4 -0
- package/public/assets/shadowMapFragmentSoftTransparentShadow-D6ZvWsNy.js.br +0 -0
- package/public/assets/shadowMapFragmentSoftTransparentShadow-D6ZvWsNy.js.gz +0 -0
- package/public/assets/sharpen.fragment-CI40r28S.js +8 -0
- package/public/assets/sharpen.fragment-CI40r28S.js.br +0 -0
- package/public/assets/sharpen.fragment-CI40r28S.js.gz +0 -0
- package/public/assets/textureMerger.fragment-BGsvQGn5.js +84 -0
- package/public/assets/textureMerger.fragment-BGsvQGn5.js.br +0 -0
- package/public/assets/textureMerger.fragment-BGsvQGn5.js.gz +0 -0
- package/public/assets/textureMerger.fragment-Q7yPwkGt.js +76 -0
- package/public/assets/textureMerger.fragment-Q7yPwkGt.js.br +0 -0
- package/public/assets/textureMerger.fragment-Q7yPwkGt.js.gz +0 -0
- package/public/assets/tgaTextureLoader-D7Pjisvo.js +1 -0
- package/public/assets/tgaTextureLoader-D7Pjisvo.js.br +0 -0
- package/public/assets/tgaTextureLoader-D7Pjisvo.js.gz +0 -0
- package/public/assets/vertexColorMixing-CwuEx4gP.js +20 -0
- package/public/assets/vertexColorMixing-CwuEx4gP.js.br +0 -0
- package/public/assets/vertexColorMixing-CwuEx4gP.js.gz +0 -0
- package/public/assets/vertexColorMixing-DRlcGbEu.js +24 -0
- package/public/assets/vertexColorMixing-DRlcGbEu.js.br +2 -0
- package/public/assets/vertexColorMixing-DRlcGbEu.js.gz +0 -0
- package/public/assets/volumetricLightingBlendVolume.fragment-0VKaEyya.js +12 -0
- package/public/assets/volumetricLightingBlendVolume.fragment-0VKaEyya.js.br +0 -0
- package/public/assets/volumetricLightingBlendVolume.fragment-0VKaEyya.js.gz +0 -0
- package/public/assets/volumetricLightingBlendVolume.fragment-BZLjMggm.js +11 -0
- package/public/assets/volumetricLightingBlendVolume.fragment-BZLjMggm.js.br +0 -0
- package/public/assets/volumetricLightingBlendVolume.fragment-BZLjMggm.js.gz +0 -0
- package/public/assets/volumetricLightingRenderVolume.fragment-6GAsdyvE.js +15 -0
- package/public/assets/volumetricLightingRenderVolume.fragment-6GAsdyvE.js.br +0 -0
- package/public/assets/volumetricLightingRenderVolume.fragment-6GAsdyvE.js.gz +0 -0
- package/public/assets/volumetricLightingRenderVolume.fragment-Da_DpfG1.js +13 -0
- package/public/assets/volumetricLightingRenderVolume.fragment-Da_DpfG1.js.br +0 -0
- package/public/assets/volumetricLightingRenderVolume.fragment-Da_DpfG1.js.gz +0 -0
- package/public/assets/volumetricLightingRenderVolume.vertex-BdVFX-tC.js +4 -0
- package/public/assets/volumetricLightingRenderVolume.vertex-BdVFX-tC.js.br +0 -0
- package/public/assets/volumetricLightingRenderVolume.vertex-BdVFX-tC.js.gz +0 -0
- package/public/assets/volumetricLightingRenderVolume.vertex-DO-VIhJn.js +5 -0
- package/public/assets/volumetricLightingRenderVolume.vertex-DO-VIhJn.js.br +0 -0
- package/public/assets/volumetricLightingRenderVolume.vertex-DO-VIhJn.js.gz +0 -0
- package/public/assets/webAudioBus-BkMWEG1L.js +1 -0
- package/public/assets/webAudioBus-BkMWEG1L.js.br +0 -0
- package/public/assets/webAudioBus-BkMWEG1L.js.gz +0 -0
- package/public/assets/webAudioMainBus-DYcQXAkm.js +1 -0
- package/public/assets/webAudioMainBus-DYcQXAkm.js.br +0 -0
- package/public/assets/webAudioMainBus-DYcQXAkm.js.gz +0 -0
- package/public/assets/workerPool-H9Ji3mCo.js +1 -0
- package/public/assets/workerPool-H9Ji3mCo.js.br +2 -0
- package/public/assets/workerPool-H9Ji3mCo.js.gz +0 -0
- package/public/index.html +21 -0
- package/public/index.html.br +0 -0
- package/public/index.html.gz +0 -0
- package/runtime/editor-control-plane.mjs +5 -0
- package/runtime/runtime-debug-authoring-bridge.mjs +1 -0
- package/worker/editor-service-worker.mjs +27 -0
|
@@ -0,0 +1,1329 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ddsTextureLoader-s5HptTVZ.js","./dds-3J0FZYX1.js","./ktxTextureLoader-DTr7AKqG.js","./workerPool-H9Ji3mCo.js","./glowMapGeneration.vertex-BACa9-r4.js","./clipPlaneVertex-BxK9aoI2.js","./morphTargetsVertex-B9xWvV_u.js","./instancesDeclaration-B2a0VuuR.js","./glowMapGeneration.fragment-mDEHNZRi.js","./clipPlaneFragment-Bgl3Usc4.js","./depth.vertex-B2lrdlJh.js","./depth.fragment-Bn8G24s-.js","./shadowMap.fragment-BEwhnKOg.js","./shadowMap.vertex-ImOoSjTb.js","./meshUboDeclaration-Uj1CsoJP.js","./shadowMap.vertex-Q2d15P5z.js","./meshUboDeclaration-Cr5YhBB1.js","./color.vertex-dgbB6mhK.js","./vertexColorMixing-DRlcGbEu.js","./color.fragment-CDn4ZgkT.js","./fogFragmentDeclaration-CzUy86ul.js","./color.vertex-CaMOSKlC.js","./vertexColorMixing-CwuEx4gP.js","./color.fragment-BUdIBar6.js","./fogFragmentDeclaration-kfcrkpgB.js","./outline.fragment-DQK2JikO.js","./logDepthDeclaration-XDsVKoT0.js","./logDepthFragment-BPP-rBiT.js","./outline.vertex-CKcILDiL.js","./logDepthVertex-CkFa6uAf.js","./outline.fragment-BK0vgcx7.js","./logDepthDeclaration-CeLLOhuK.js","./logDepthFragment-CDaMyvfH.js","./outline.vertex-CHR7GZYH.js","./logDepthVertex-H6E8NLz1.js","./default.vertex-YrvIUn4x.js","./defaultUboDeclaration-C8GCosBM.js","./bumpVertex-DpGOKCkn.js","./mainUVVaryingDeclaration-OBB3LR8s.js","./default.fragment-C4zjkcFb.js","./oitFragment-ZUHesxAg.js","./default.vertex-A8wQopNr.js","./bumpVertex-DMhnr4dz.js","./defaultUboDeclaration-D26o_DDO.js","./mainUVVaryingDeclaration-DdwP8xi_.js","./default.fragment-C4xg7O-P.js","./oitFragment-CK8Y-Z-q.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
function M(o,e,t,i){var s=arguments.length,r=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,n;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,e,t,i);else for(var a=o.length-1;a>=0;a--)(n=o[a])&&(r=(s<3?n(r):s>3?n(e,t,r):n(e,t))||r);return s>3&&r&&Object.defineProperty(e,t,r),r}const xr={},Pr={};function lu(o){const e=o.getClassName();return Pr[e]||(Pr[e]={}),Pr[e]}function Cn(o){const e=o.getClassName();if(xr[e])return xr[e];xr[e]={};const t=xr[e];let i=o,s=e;for(;s;){const r=Pr[s];for(const h in r)t[h]=r[h];let n,a=!1;do{if(n=Object.getPrototypeOf(i),!n.getClassName){a=!0;break}if(n.getClassName()!==s)break;i=n}while(n);if(a)break;s=n.getClassName(),i=n}return t}function Nt(o,e){return(t,i)=>{const s=lu(t);s[i]||(s[i]={type:o,sourceName:e})}}function cu(o,e=null){return(t,i)=>{const s=e||"_"+i;Object.defineProperty(t,i,{get:function(){return this[s]},set:function(r){typeof this[s]?.equals=="function"&&this[s].equals(r)||this[s]!==r&&(this[s]=r,t[o].apply(this))},enumerable:!0,configurable:!0})}}function ze(o,e=null){return cu(o,e)}function C(o){return Nt(0,o)}function qt(o){return Nt(1,o)}function ss(o){return Nt(2,o)}function rr(o){return Nt(3,o)}function uu(o){return Nt(4,o)}function Ut(o){return Nt(5,o)}function fu(o){return Nt(6,o)}function du(o){return Nt(7,o)}function La(o){return Nt(8,o)}function _u(o){return Nt(9,o)}function gu(o){return Nt(10,o)}function Gh(o){return Nt(12,o)}function pu(o){return Nt(11,o)}function _i(o,e,t,i){const s=t.value;t.value=(...r)=>{let n=s;if(typeof _native<"u"&&_native[e]){const a=_native[e];i?n=(...h)=>i(...h)?a(...h):s(...h):n=a}return o[e]=n,n(...r)}}_i.filter=function(o){return(e,t,i)=>_i(e,t,i,o)};function vp(o,e=null){return(t,i)=>{const s=i;Object.defineProperty(t,e||"",{get:function(){return this[s].value},set:function(n){typeof this[s]?.value?.equals=="function"&&this[s].value.equals(n)||this[s].value!==n&&(this[s].value=n,t[o].apply(this))},enumerable:!0,configurable:!0})}}const mu=typeof WeakRef<"u";class Tu{constructor(e,t=!1,i,s){this.initialize(e,t,i,s)}initialize(e,t=!1,i,s){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=s,this}}class Eu{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(e=!1){this._remove&&this._remove(e)}}class z{static FromPromise(e,t){const i=new z;return e.then(s=>{i.notifyObservers(s)}).catch(s=>{if(t)t.notifyObservers(s);else throw s}),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new Tu(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,r=!1){if(!e)return null;const n=new Eu(e,t,s);n.unregisterOnNextCall=r,i?this._observers.unshift(n):this._observers.push(n),this._onObserverAdded&&this._onObserverAdded(n),this._hasNotified&&this.notifyIfTriggered&&this._lastNotifiedValue!==void 0&&this.notifyObserver(n,this._lastNotifiedValue);const a=mu?new WeakRef(this):{deref:()=>this};return n._remove=(h=!1)=>{const l=a.deref();l&&(h?l.remove(n):l._remove(n))},n}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return e?(e._remove=null,this._observers.indexOf(e)!==-1?(this._deferUnregister(e),!0):!1):!1}removeCallback(e,t){for(let i=0;i<this._observers.length;i++){const s=this._observers[i];if(!s._willBeUnregistered&&s.callback===e&&(!t||t===s.scope))return this._deferUnregister(s),!0}return!1}_deferUnregister(e){e._willBeUnregistered||(this._numObserversMarkedAsDeleted++,e.unregisterOnNextCall=!1,e._willBeUnregistered=!0,setTimeout(()=>{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;const i=this._observers.indexOf(e);return i!==-1?(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0):!1}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,s,r){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const n=this._eventState;n.mask=t,n.target=i,n.currentTarget=s,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=r;for(const a of this._observers)if(!a._willBeUnregistered&&(a.mask&t&&(a.unregisterOnNextCall&&this._deferUnregister(a),a.scope?n.lastReturnValue=a.callback.apply(a.scope,[e,n]):n.lastReturnValue=a.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const s=this._eventState;s.mask=i,s.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,s)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new z;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}function mt(){return typeof window<"u"}function Ji(){return typeof navigator<"u"}function ls(){return typeof document<"u"}function Ba(o){let e="",t=o.firstChild;for(;t;)t.nodeType===3&&(e+=t.textContent),t=t.nextSibling;return e}const Cp={IsWindowObjectExist:mt,IsNavigatorAvailable:Ji,IsDocumentAvailable:ls,GetDOMTextContent:Ba};class W{static _CheckLimit(e,t){let i=W._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},W._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){const i=W._LogLimitOutputs[e];if(!i||!W.MessageLimitReached)return;const s=this._Levels[t];i.current===i.limit&&W[s.name](W.MessageLimitReached.replace(/%LIMIT%/g,""+i.limit).replace(/%TYPE%/g,s.name??""))}static _AddLogEntry(e){W._LogCache=e+W._LogCache,W.OnNewCacheEntry&&W.OnNewCacheEntry(e)}static _FormatMessage(e){const t=s=>s<10?"0"+s:""+s,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){const s=Array.isArray(t)?t[0]:t;if(i!==void 0&&!W._CheckLimit(s,i))return;const r=W._FormatMessage(s),n=this._Levels[e],a=Array.isArray(t)?t.slice(1):[];n.logFunc&&n.logFunc("BJS - "+r,...a);const h=`<div style='color:${n.color}'>${r}</div><br>`;W._AddLogEntry(h),W._GenerateLimitMessage(s,e)}static get LogCache(){return W._LogCache}static ClearLogCache(){W._LogCache="",W._LogLimitOutputs={},W.errorsCount=0}static set LogLevels(e){W.Log=W._LogDisabled,W.Warn=W._LogDisabled,W.Error=W._LogDisabled;const t=[W.MessageLogLevel,W.WarningLogLevel,W.ErrorLogLevel];for(const i of t)if((e&i)===i){const s=this._Levels[i];W[s.name]=W._LogEnabled.bind(W,i)}}}W.NoneLogLevel=0;W.MessageLogLevel=1;W.WarningLogLevel=2;W.ErrorLogLevel=4;W.AllLogLevel=7;W.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";W._LogCache="";W._LogLimitOutputs={};W._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}];W.errorsCount=0;W.Log=W._LogEnabled.bind(W,W.MessageLogLevel);W.Warn=W._LogEnabled.bind(W,W.WarningLogLevel);W.Error=W._LogEnabled.bind(W,W.ErrorLogLevel);const Fo=(o,e,t)=>!o||o.getClassName&&o.getClassName()==="Mesh"?null:o.getClassName&&(o.getClassName()==="SubMesh"||o.getClassName()==="PhysicsBody")?o.clone(e):o.clone?o.clone():Array.isArray(o)?o.slice():t&&typeof o=="object"?{...o}:null;function xu(o){const e=[];do{const t=Object.getOwnPropertyNames(o);for(const i of t)e.indexOf(i)===-1&&e.push(i)}while(o=Object.getPrototypeOf(o));return e}class Na{static DeepCopy(e,t,i,s,r=!1){const n=xu(e);for(const a of n){if(a[0]==="_"&&(!s||s.indexOf(a)===-1)||a.endsWith("Observable")||i&&i.indexOf(a)!==-1)continue;const h=e[a],l=typeof h;if(l!=="function")try{if(l==="object")if(h instanceof Uint8Array)t[a]=Uint8Array.from(h);else if(h instanceof Array){if(t[a]=[],h.length>0)if(typeof h[0]=="object")for(let c=0;c<h.length;c++){const u=Fo(h[c],t,r);t[a].indexOf(u)===-1&&t[a].push(u)}else t[a]=h.slice(0)}else t[a]=Fo(h,t,r);else t[a]=h}catch(c){W.Warn(c.message)}}}}class Si{static get Now(){return mt()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}const wo={};function pe(o,e=!1){if(!(e&&wo[o]))return wo[o]=!0,`${o} needs to be imported before as it contains a side-effect required by your code.`}function bu(){return typeof _native<"u"&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}class at{constructor(){this._xhr=bu(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(at.CustomRequestHeaders).length>0||at.CustomRequestModifiers.length>0}static _CleanUrl(e){return e=e.replace("file:http:","http:"),e=e.replace("file:https:","https:"),e}static _ShouldSkipRequestModifications(e){return at.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}static _CollectCustomizations(e,t={}){const i={...t};if(at._ShouldSkipRequestModifications(e))return{url:e,headers:i};for(const r in at.CustomRequestHeaders){const n=at.CustomRequestHeaders[r];n&&(i[r]=n)}const s={setRequestHeader:(r,n)=>{i[r]=n}};for(const r of at.CustomRequestModifiers){if(at._ShouldSkipRequestModifications(e))break;const n=r(s,e);typeof n=="string"&&(e=n)}return{url:e,headers:i}}static async FetchAsync(e,t={}){const i=t.method??"GET";if(typeof fetch<"u"){const{url:s,headers:r}=at._CollectCustomizations(at._CleanUrl(e),t.headers??{});return await fetch(s,{method:i,headers:r,body:t.body??void 0})}return await new Promise((s,r)=>{const n=new at;n.responseType="arraybuffer",n.addEventListener("readystatechange",()=>{if(n.readyState===4)if(n.status>=200&&n.status<300){const a=typeof Headers<"u"?new Headers:void 0,h=n.getResponseHeader("Content-Type");h&&a&&a.set("Content-Type",h),s(typeof Response<"u"?new Response(n.response,{status:n.status,statusText:n.statusText,headers:a}):{ok:!0,status:n.status,statusText:n.statusText,headers:{get:l=>n.getResponseHeader(l)},arrayBuffer:async()=>await Promise.resolve(n.response)})}else r(new Error(`HTTP ${n.status} loading '${n.requestURL}': ${n.statusText}`))}),n.open(i,e,t.headers),n.send(t.body??null)})}get requestURL(){return this._requestURL}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){this._xhr.send(e)}open(e,t,i){const{url:s,headers:r}=at._CollectCustomizations(t,i);this._requestURL=at._CleanUrl(s),this._xhr.open(e,this._requestURL,!0);for(const n in r)this._xhr.setRequestHeader(n,r[n])}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}at.CustomRequestHeaders={};at.CustomRequestModifiers=new Array;at.SkipRequestModificationForBabylonCDN=!0;class ye{static get LastCreatedEngine(){return this.Instances.length===0?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}ye.Instances=[];ye.OnEnginesDisposedObservable=new z;ye._LastCreatedScene=null;ye.UseFallbackTexture=!0;ye.FallbackTexture="";class Us{}Us.FilesToLoad={};class Ru{static ExponentialBackoff(e=3,t=500){return(i,s,r)=>s.status!==0||r>=e||i.indexOf("file:")!==-1?-1:Math.pow(2,r)*t}}class Ui extends Error{}Ui._setPrototypeOf=Object.setPrototypeOf||((o,e)=>(o.__proto__=e,o));const Xr={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class Ss extends Ui{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",Ui._setPrototypeOf(this,Ss.prototype)}}class Hh extends Ui{constructor(e="Operation aborted"){super(e),this.name="AbortError",Ui._setPrototypeOf(this,Hh.prototype)}}const Su=(o,e)=>o.endsWith(e),yu=(o,e)=>o?o.startsWith(e):!1,Au=o=>{if(typeof TextDecoder<"u")return new TextDecoder().decode(o);let e="";for(let t=0;t<o.byteLength;t++)e+=String.fromCharCode(o[t]);return e},Kr=o=>{const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",i,s,r,n,a,h,l,c=0;const u=ArrayBuffer.isView(o)?new Uint8Array(o.buffer,o.byteOffset,o.byteLength):new Uint8Array(o);for(;c<u.length;)i=u[c++],s=c<u.length?u[c++]:Number.NaN,r=c<u.length?u[c++]:Number.NaN,n=i>>2,a=(i&3)<<4|s>>4,h=(s&15)<<2|r>>6,l=r&63,isNaN(s)?h=l=64:isNaN(r)&&(l=64),t+=e.charAt(n)+e.charAt(a)+e.charAt(h)+e.charAt(l);return t},Ua=o=>atob(o),Xh=o=>{const e=Ua(o),t=e.length,i=new Uint8Array(new ArrayBuffer(t));for(let s=0;s<t;s++)i[s]=e.charCodeAt(s);return i.buffer},Mu=(o,e)=>{let t=String(o);for(;t.length<e;)t="0"+t;return t},Dp={EndsWith:Su,StartsWith:yu,Decode:Au,EncodeArrayBufferToBase64:Kr,DecodeBase64ToString:Ua,DecodeBase64ToBinary:Xh,PadNumber:Mu},Pu="attribute",Iu="varying";class nr{constructor(){this.children=[]}isValid(e){return!0}process(e,t,i){let s="";if(this.line){let r=this.line;const n=t.processor;if(n){n.lineProcessor&&(r=n.lineProcessor(r,t.isFragment,t.processingContext));const a=t.processor?.attributeKeywordName??Pu,h=t.isFragment&&t.processor?.varyingFragmentKeywordName?t.processor?.varyingFragmentKeywordName:!t.isFragment&&t.processor?.varyingVertexKeywordName?t.processor?.varyingVertexKeywordName:Iu;!t.isFragment&&n.attributeProcessor&&this.line.startsWith(a)?r=n.attributeProcessor(this.line,e,t.processingContext):n.varyingProcessor&&(n.varyingCheck?.(this.line,t.isFragment)||!n.varyingCheck&&this.line.startsWith(h))?r=n.varyingProcessor(this.line,t.isFragment,e,t.processingContext):n.uniformProcessor&&n.uniformRegexp&&n.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(r=n.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):n.uniformBufferProcessor&&n.uniformBufferRegexp&&n.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(r=n.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):n.textureProcessor&&n.textureRegexp&&n.textureRegexp.test(this.line)?r=n.textureProcessor(this.line,t.isFragment,e,t.processingContext):(n.uniformProcessor||n.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?n.uniformProcessor&&(r=n.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):n.uniformBufferProcessor&&(r=n.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&this.line.indexOf("}")!==-1&&(t.lookForClosingBracketForUniformBuffer=!1,n.endOfUniformBufferProcessor&&(r=n.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}s+=r+`
|
|
3
|
+
`}for(const r of this.children)s+=r.process(e,t,i);return this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true",i[this.additionalDefineKey]=e[this.additionalDefineKey]),s}}class vu{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex<this._lines.length-1}set lines(e){this._lines.length=0;for(const t of e){if(!t||t==="\r")continue;if(t[0]==="#"){this._lines.push(t);continue}const i=t.trim();if(!i)continue;if(i.startsWith("//")){this._lines.push(t);continue}const s=i.indexOf(";");if(s===-1)this._lines.push(i);else if(s===i.length-1)i.length>1&&this._lines.push(i);else{const r=t.split(";");for(let n=0;n<r.length;n++){let a=r[n];a&&(a=a.trim(),a&&this._lines.push(a+(n!==r.length-1?";":"")))}}}}}class pn extends nr{process(e,t,i){for(let s=0;s<this.children.length;s++){const r=this.children[s];if(r.isValid(e))return r.process(e,t,i)}return""}}class Cu extends nr{isValid(e){return this.testExpression.isTrue(e)}}class Je{isTrue(e){return!0}static postfixToInfix(e){const t=[];for(const i of e)if(Je._OperatorPriority[i]===void 0)t.push(i);else{const s=t[t.length-1],r=t[t.length-2];t.length-=2,t.push(`(${r}${i}${s})`)}return t[t.length-1]}static infixToPostfix(e){const t=Je._InfixToPostfixCache.get(e);if(t)return t.accessTime=Date.now(),t.result;if(!e.includes("&&")&&!e.includes("||")&&!e.includes(")")&&!e.includes("("))return[e];const i=[];let s=-1;const r=()=>{c=c.trim(),c!==""&&(i.push(c),c="")},n=u=>{s<Je._Stack.length-1&&(Je._Stack[++s]=u)},a=()=>Je._Stack[s],h=()=>s===-1?"!!INVALID EXPRESSION!!":Je._Stack[s--];let l=0,c="";for(;l<e.length;){const u=e.charAt(l),f=l<e.length-1?e.substring(l,2+l):"";if(u==="(")c="",n(u);else if(u===")"){for(r();s!==-1&&a()!=="(";)i.push(h());h()}else if(Je._OperatorPriority[f]>1){for(r();s!==-1&&Je._OperatorPriority[a()]>=Je._OperatorPriority[f];)i.push(h());n(f),l++}else c+=u;l++}for(r();s!==-1;)a()==="("?h():i.push(h());return Je._InfixToPostfixCache.size>=Je.InfixToPostfixCacheLimitSize&&Je.ClearCache(),Je._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(Je._InfixToPostfixCache.entries()).sort((t,i)=>t[1].accessTime-i[1].accessTime);for(let t=0;t<Je.InfixToPostfixCacheCleanupSize;t++)Je._InfixToPostfixCache.delete(e[t][0])}}Je.InfixToPostfixCacheLimitSize=5e4;Je.InfixToPostfixCacheCleanupSize=25e3;Je._InfixToPostfixCache=new Map;Je._OperatorPriority={")":0,"(":1,"||":2,"&&":3};Je._Stack=["","","","","","","","","","","","","","","","","","","",""];class Cr extends Je{constructor(e,t=!1){super(),this.define=e,this.not=t}isTrue(e){let t=e[this.define]!==void 0;return this.not&&(t=!t),t}}class Du extends Je{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}}class Ou extends Je{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}}class Fu extends Je{constructor(e,t,i){super(),this.define=e,this.operand=t,this.testValue=i}toString(){return`${this.define} ${this.operand} ${this.testValue}`}isTrue(e){let t=!1;const i=parseInt(e[this.define]!=null?e[this.define]:this.define),s=parseInt(e[this.testValue]!=null?e[this.testValue]:this.testValue);if(isNaN(i)||isNaN(s))return!1;switch(this.operand){case">":t=i>s;break;case"<":t=i<s;break;case"<=":t=i<=s;break;case">=":t=i>=s;break;case"==":t=i===s;break;case"!=":t=i!==s;break}return t}}const Dr={};function Kh(o,e,t=""){return t+(e?e+`
|
|
4
|
+
`:"")+o}function Yh(o,e,t,i,s,r,n){const a=n||Dr.loadFile;if(a)return a(o,e,t,i,s,r);throw pe("FileTools")}function jh(o,e,t,i){if(o){e?o.IS_NDC_HALF_ZRANGE="":delete o.IS_NDC_HALF_ZRANGE,t?o.USE_REVERSE_DEPTHBUFFER="":delete o.USE_REVERSE_DEPTHBUFFER,i?o.USE_EXACT_SRGB_CONVERSIONS="":delete o.USE_EXACT_SRGB_CONVERSIONS;return}else{let s="";return e&&(s+="#define IS_NDC_HALF_ZRANGE"),t&&(s&&(s+=`
|
|
5
|
+
`),s+="#define USE_REVERSE_DEPTHBUFFER"),i&&(s&&(s+=`
|
|
6
|
+
`),s+="#define USE_EXACT_SRGB_CONVERSIONS"),s}}function wu(o,e,t=!1,i){switch(o){case 3:{const r=new Int8Array(e);return i&&r.set(new Int8Array(i)),r}case 0:{const r=new Uint8Array(e);return i&&r.set(new Uint8Array(i)),r}case 4:{const r=typeof e!="number"?new Int16Array(e):new Int16Array(t?e/2:e);return i&&r.set(new Int16Array(i)),r}case 5:case 8:case 9:case 10:case 2:{const r=typeof e!="number"?new Uint16Array(e):new Uint16Array(t?e/2:e);return i&&r.set(new Uint16Array(i)),r}case 6:{const r=typeof e!="number"?new Int32Array(e):new Int32Array(t?e/4:e);return i&&r.set(new Int32Array(i)),r}case 7:case 11:case 12:case 13:case 14:case 15:{const r=typeof e!="number"?new Uint32Array(e):new Uint32Array(t?e/4:e);return i&&r.set(new Uint32Array(i)),r}case 1:{const r=typeof e!="number"?new Float32Array(e):new Float32Array(t?e/4:e);return i&&r.set(new Float32Array(i)),r}}const s=new Uint8Array(e);return i&&s.set(new Uint8Array(i)),s}const Lu=/defined\s*?\((.+?)\)/g,mn=/defined\s*?\[(.+?)\]/g,Bu=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,Nu=/__decl__/,Lo=/light\{X\}.(\w*)/g,Bo=/\{X\}/g,br=[],Uu=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function ku(o){o.processor&&o.processor.initializeShaders&&o.processor.initializeShaders(o.processingContext)}function No(o,e,t,i){e.processor?.preProcessShaderCode&&(o=e.processor.preProcessShaderCode(o,e.isFragment)),Ws(o,e,s=>{e.processCodeAfterIncludes&&(s=e.processCodeAfterIncludes(e.isFragment?"fragment":"vertex",s,e.defines));const r=Gu(s,e,i);t(r,s)})}function Op(o,e,t,i){e.processor?.preProcessShaderCode&&(o=e.processor.preProcessShaderCode(o,e.isFragment)),Ws(o,e,s=>{e.processCodeAfterIncludes&&(s=e.processCodeAfterIncludes(e.isFragment?"fragment":"vertex",s,e.defines));const r=Hu(s,e,i);t(r,s)})}function Vu(o,e,t){return!t.processor||!t.processor.finalizeShaders?{vertexCode:o,fragmentCode:e}:t.processor.finalizeShaders(o,e,t.processingContext)}function zu(o,e){if(e.processor?.noPrecision)return o;const t=e.shouldUseHighPrecisionShader;return o.indexOf("precision highp float")===-1?t?o=`precision highp float;
|
|
7
|
+
`+o:o=`precision mediump float;
|
|
8
|
+
`+o:t||(o=o.replace("precision highp float","precision mediump float")),o}function Tn(o){const t=/defined\((.+)\)/.exec(o);if(t&&t.length)return new Cr(t[1].trim(),o[0]==="!");const i=["==","!=",">=","<=","<",">"];let s="",r=0;for(s of i)if(r=o.indexOf(s),r>-1)break;if(r===-1)return new Cr(o);const n=o.substring(0,r).trim(),a=o.substring(r+s.length).trim();return new Fu(n,s,a)}function Wu(o){o=o.replace(Lu,"defined[$1]");const e=Je.infixToPostfix(o),t=[];for(const s of e)if(s!=="||"&&s!=="&&")t.push(s);else if(t.length>=2){let r=t[t.length-1],n=t[t.length-2];t.length-=2;const a=s=="&&"?new Ou:new Du;typeof r=="string"&&(r=r.replace(mn,"defined($1)")),typeof n=="string"&&(n=n.replace(mn,"defined($1)")),a.leftOperand=typeof n=="string"?Tn(n):n,a.rightOperand=typeof r=="string"?Tn(r):r,t.push(a)}let i=t[t.length-1];return typeof i=="string"&&(i=i.replace(mn,"defined($1)")),typeof i=="string"?Tn(i):i}function Ir(o,e){const t=new Cu,i=o.substring(0,e);let s=o.substring(e);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),i==="#ifdef"?t.testExpression=new Cr(s):i==="#ifndef"?t.testExpression=new Cr(s,!0):t.testExpression=Wu(s),t}function En(o,e,t,i){let s;for(;Dn(o,t);){s=o.currentLine;const r=s.substring(0,5).toLowerCase();if(r==="#else"){const n=new nr;e.children.push(n),Dn(o,n);return}else if(r==="#elif"){const n=Ir(s,5);e.children.push(n),t=n}}}function Dn(o,e,t){for(;o.canRead;){o.lineIndex++;const i=o.currentLine;if(i.indexOf("#")>=0){const r=Uu.exec(i);if(r&&r.length){switch(r[0]){case"#ifdef":{const a=new pn;e.children.push(a);const h=Ir(i,6);a.children.push(h),En(o,a,h);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const a=new pn;e.children.push(a);const h=Ir(i,7);a.children.push(h),En(o,a,h);break}case"#if":{const a=new pn,h=Ir(i,3);e.children.push(a),a.children.push(h),En(o,a,h);break}}continue}}const s=new nr;if(s.line=i,e.children.push(s),i[0]==="#"&&i[1]==="d"){const r=i.replace(";","").split(" ");s.additionalDefineKey=r[1],r.length===3&&(s.additionalDefineValue=r[2])}}return!1}function Zh(o,e,t,i){const s=new nr,r=new vu;return r.lineIndex=-1,r.lines=o.split(`
|
|
9
|
+
`),Dn(r,s),s.process(e,t,i)}function qh(o,e){const t=o.defines,i={};for(const s of t){const n=s.replace("#define","").replace(";","").trim().split(" ");i[n[0]]=n.length>1?n[1]:""}return o.processor?.shaderLanguage===0&&(i.GL_ES="true"),i.__VERSION__=o.version,i[o.platformName]="true",jh(i,e?.isNDCHalfZRange,e?.useReverseDepthBuffer,e?.useExactSrgbConversions),i}function Gu(o,e,t){let i=zu(o,e);if(!e.processor||e.processor.shaderLanguage===0&&i.indexOf("#version 3")!==-1&&(i=i.replace("#version 300 es",""),!e.processor.parseGLES3))return i;const s=e.defines,r=qh(e,t);e.processor.preProcessor&&(i=e.processor.preProcessor(i,s,r,e.isFragment,e.processingContext));const n={};return i=Zh(i,r,e,n),e.processor.postProcessor&&(i=e.processor.postProcessor(i,s,e.isFragment,e.processingContext,t?{drawBuffersExtensionDisabled:!t.getCaps().drawBuffersExtension}:{},r,n)),t?._features.needShaderCodeInlining&&(i=t.inlineShaderCode(i)),i}function Hu(o,e,t){let i=o;const s=e.defines,r=qh(e,t);e.processor?.preProcessor&&(i=e.processor.preProcessor(i,s,r,e.isFragment,e.processingContext));const n={};return i=Zh(i,r,e,n),e.processor?.postProcessor&&(i=e.processor.postProcessor(i,s,e.isFragment,e.processingContext,t?{drawBuffersExtensionDisabled:!t.getCaps().drawBuffersExtension}:{},r,n)),t._features.needShaderCodeInlining&&(i=t.inlineShaderCode(i)),i}function Ws(o,e,t){br.length=0;let i;for(;(i=Bu.exec(o))!==null;)br.push(i);let s=[o],r=!1;for(const a of br){let h=a[1];if(h.indexOf("__decl__")!==-1&&(h=h.replace(Nu,""),e.supportsUniformBuffers&&(h=h.replace("Vertex","Ubo").replace("Fragment","Ubo")),h=h+"Declaration"),e.includesShadersStore[h]){let l=e.includesShadersStore[h];if(a[2]){const u=a[3].split(",");for(let f=0;f<u.length;f+=2){const d=new RegExp(u[f],"g"),_=u[f+1];l=l.replace(d,_)}}if(a[4]){const u=a[5];if(u.indexOf("..")!==-1){const f=u.split(".."),d=parseInt(f[0]);let _=parseInt(f[1]),m=l.slice(0);l="",isNaN(_)&&(_=e.indexParameters[f[1]]);for(let g=d;g<_;g++)e.supportsUniformBuffers||(m=m.replace(Lo,(T,R)=>R+"{X}")),l+=m.replace(Bo,g.toString())+`
|
|
10
|
+
`}else e.supportsUniformBuffers||(l=l.replace(Lo,(f,d)=>d+"{X}")),l=l.replace(Bo,u)}const c=[];for(const u of s){const f=u.split(a[0]);for(let d=0;d<f.length-1;d++)c.push(f[d]),c.push(l);c.push(f[f.length-1])}s=c,r=r||l.indexOf("#include<")>=0||l.indexOf("#include <")>=0}else{const l=e.shadersRepository+"ShadersInclude/"+h+".fx";Qh.loadFile(l,c=>{e.includesShadersStore[h]=c,Ws(s.join(""),e,t)});return}}br.length=0;const n=s.join("");r?Ws(n.toString(),e,t):t(n)}const Qh={loadFile:(o,e,t,i,s,r)=>{throw pe("FileTools")}};let Rr=[];class Gs{static SetImmediate(e){Rr.length===0&&setTimeout(()=>{const t=Rr;Rr=[];for(const i of t)i()},1),Rr.push(e)}}function Uo(o,e,t){try{if(o())return e(),!0}catch(i){return t?.(i),!0}return!1}const Yr=(o,e,t,i=16,s=3e4,r=!0,n)=>{if(r&&Uo(o,e,t))return null;const a=setInterval(()=>{Uo(o,e,t)?clearInterval(a):(s-=i,s<0&&(clearInterval(a),t?.(new Error("Operation timed out after maximum retries. "+(n||"")),!0)))},i);return()=>clearInterval(a)};class Z{static GetShadersRepository(e=0){return e===0?Z.ShadersRepository:Z.ShadersRepositoryWGSL}static GetShadersStore(e=0){return e===0?Z.ShadersStore:Z.ShadersStoreWGSL}static GetIncludesShadersStore(e=0){return e===0?Z.IncludesShadersStore:Z.IncludesShadersStoreWGSL}}Z.ShadersRepository="src/Shaders/";Z.ShadersStore={};Z.IncludesShadersStore={};Z.ShadersRepositoryWGSL="src/ShadersWGSL/";Z.ShadersStoreWGSL={};Z.IncludesShadersStoreWGSL={};class Xu{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return this.program?this.isParallelCompiled?this.engine._isRenderingStateCompiled(this):!0:!1}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,i,s,r,n,a,h){const l=this.engine;if(l.supportsUniformBuffers)for(const f in t)e.bindUniformBlock(f,t[f]);this.engine.getUniforms(this,i).forEach((f,d)=>{s[i[d]]=f}),this._uniforms=s;let u;for(u=0;u<r.length;u++)e.getUniform(r[u])==null&&(r.splice(u,1),u--);r.forEach((f,d)=>{n[f]=d});for(const f of l.getAttributes(this,a))h.push(f)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return i!==void 0&&i===s?!1:(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s||s.length!==2)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r||r.length!==3)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n||n.length!==4)return n=[t,i,s,r],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==s&&(n[2]=s,a=!0),n[3]!==r&&(n[3]=r,a=!0),a}setInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}const On=new WeakMap,Ku={_webGLVersion:2,cachedPipelines:{}};function Ft(o){let e=On.get(o);if(!e){if(!o)return Ku;e={_webGLVersion:o.TEXTURE_BINDING_3D?2:1,_context:o,parallelShaderCompile:o.getExtension("KHR_parallel_shader_compile")||void 0,cachedPipelines:{}},On.set(o,e)}return e}function xn(o){On.delete(o)}function $h(o,e,t,i,s,r){const n=Ft(i);r||(r=n._createShaderProgramInjection??ka);const a=Fn(e,"vertex",i,n._contextWasLost),h=Fn(t,"fragment",i,n._contextWasLost);return r(o,a,h,i,s,n.validateShaderPrograms)}function Jh(o,e,t,i,s,r=null,n){const a=Ft(s);n||(n=a._createShaderProgramInjection??ka);const h=a._webGLVersion>1?`#version 300 es
|
|
11
|
+
#define WEBGL2
|
|
12
|
+
`:"",l=ko(e,"vertex",i,h,s,a._contextWasLost),c=ko(t,"fragment",i,h,s,a._contextWasLost);return n(o,l,c,s,r,a.validateShaderPrograms)}function Yu(o,e){const t=new Xu,i=Ft(o);return i.parallelShaderCompile&&!i.disableParallelShaderCompile&&(t.isParallelCompiled=!0),t.context=i._context,t}function ka(o,e,t,i,s=null,r){const n=i.createProgram();if(o.program=n,!n)throw new Error("Unable to create program");return i.attachShader(n,e),i.attachShader(n,t),i.linkProgram(n),o.context=i,o.vertexShader=e,o.fragmentShader=t,o.isParallelCompiled||Va(o,i,r),n}function ju(o,e,t){const i=o;if(i._isDisposed)return!1;const s=Ft(e);return s&&s.parallelShaderCompile&&s.parallelShaderCompile.COMPLETION_STATUS_KHR&&i.program&&e.getProgramParameter(i.program,s.parallelShaderCompile.COMPLETION_STATUS_KHR)?(Va(i,e,t),!0):!1}function Va(o,e,t){const i=o.context,s=o.vertexShader,r=o.fragmentShader,n=o.program;if(!i.getProgramParameter(n,i.LINK_STATUS)){if(!e.getShaderParameter(s,e.COMPILE_STATUS)){const l=e.getShaderInfoLog(s);if(l)throw o.vertexCompilationError=l,new Error("VERTEX SHADER "+l)}if(!e.getShaderParameter(r,e.COMPILE_STATUS)){const l=e.getShaderInfoLog(r);if(l)throw o.fragmentCompilationError=l,new Error("FRAGMENT SHADER "+l)}const h=i.getProgramInfoLog(n);if(h)throw o.programLinkError=h,new Error(h)}if(t&&(i.validateProgram(n),!i.getProgramParameter(n,i.VALIDATE_STATUS))){const l=i.getProgramInfoLog(n);if(l)throw o.programValidationError=l,new Error(l)}i.deleteShader(s),i.deleteShader(r),o.vertexShader=void 0,o.fragmentShader=void 0,o.onCompiled&&(o.onCompiled(),o.onCompiled=void 0)}function Zu(o,e,t,i,s,r,n,a,h,l="",c,u,f){const d=Ft(o.context);u||(u=d.createRawShaderProgramInjection??$h),f||(f=d.createShaderProgramInjection??Jh);const _=o;i?_.program=u(_,e,t,_.context,h):_.program=f(_,e,t,a,_.context,h),_.program.__SPECTOR_rebuildProgram=n,c()}function ko(o,e,t,i,s,r){return Fn(Kh(o,t,i),e,s,r)}function Fn(o,e,t,i){const s=t.createShader(e==="vertex"?t.VERTEX_SHADER:t.FRAGMENT_SHADER);if(!s){let r=t.NO_ERROR,n;for(;(n=t.getError())!==t.NO_ERROR;)r=n;throw new Error(`Something went wrong while creating a gl ${e} shader object. gl error=${r}, gl isContextLost=${t.isContextLost()}, _contextWasLost=${i}`)}return t.shaderSource(s,o),t.compileShader(s),s}function qu(o,e){e.useProgram(o)}function Qu(o,e){const t=o;if(!t.isParallelCompiled){e(o);return}const i=t.onCompiled;t.onCompiled=()=>{i?.(),e(o)}}function $u(o,e){return Ft(e).cachedPipelines[o]}function el(o){const e=o._name,t=o.context;if(e&&t){const i=Ft(t);i.cachedPipelines[e]?.dispose(),delete i.cachedPipelines[e]}}function Ju(o,e,t,i,s,r,n){let a,h;const l=mt()?r?.getHostDocument():null;typeof e=="string"?a=e:e.vertexSource?a="source:"+e.vertexSource:e.vertexElement?a=l?.getElementById(e.vertexElement)||e.vertexElement:a=e.vertex||e,typeof e=="string"?h=e:e.fragmentSource?h="source:"+e.fragmentSource:e.fragmentElement?h=l?.getElementById(e.fragmentElement)||e.fragmentElement:h=e.fragment||e;const c=[void 0,void 0],u=()=>{if(c[0]&&c[1]){const[f,d]=c;ku(o),No(f,o,(_,m)=>{n&&(n._vertexSourceCodeBeforeMigration=m),t&&(_=t("vertex",_)),o.isFragment=!0,No(d,o,(g,T)=>{n&&(n._fragmentSourceCodeBeforeMigration=T),t&&(g=t("fragment",g));const R=Vu(_,g,o);o=null;const A=ef(R.vertexCode,R.fragmentCode,e,s);i?.(A.vertexSourceCode,A.fragmentSourceCode)},r)},r)}};Vo(a,"Vertex","",f=>{n&&(n._rawVertexSourceCode=f),c[0]=f,u()},s),Vo(h,"Fragment","Pixel",f=>{n&&(n._rawFragmentSourceCode=f),c[1]=f,u()},s)}function Vo(o,e,t,i,s,r){if(typeof HTMLElement<"u"&&o instanceof HTMLElement){const h=Ba(o);i(h);return}if(o.substring(0,7)==="source:"){i(o.substring(7));return}if(o.substring(0,7)==="base64:"){const h=window.atob(o.substring(7));i(h);return}const n=Z.GetShadersStore(s);if(n[o+e+"Shader"]){i(n[o+e+"Shader"]);return}if(t&&n[o+t+"Shader"]){i(n[o+t+"Shader"]);return}let a;if(o[0]==="."||o[0]==="/"||o.indexOf("http")>-1?a=o:a=Z.GetShadersRepository(s)+o,r=r||Yh,!r)throw new Error("loadFileInjection is not defined");r(a+"."+e.toLowerCase()+".fx",i)}function ef(o,e,t,i){if(t){const s=t.vertexElement||t.vertex||t.spectorName||t,r=t.fragmentElement||t.fragment||t.spectorName||t;return{vertexSourceCode:(i===1?"//":"")+"#define SHADER_NAME vertex:"+s+`
|
|
13
|
+
`+o,fragmentSourceCode:(i===1?"//":"")+"#define SHADER_NAME fragment:"+r+`
|
|
14
|
+
`+e}}else return{vertexSourceCode:o,fragmentSourceCode:e}}const tf=(o,e,t,i)=>{try{const s=o.context?Ft(o.context):null;s&&(s.disableParallelShaderCompile=o.disableParallelCompilation);const r=o.existingPipelineContext||e(o.shaderProcessingContext);return r._name=o.name,o.name&&s&&(s.cachedPipelines[o.name]=r),t(r,o.vertex,o.fragment,!!o.createAsRaw,"","",o.rebuildRebind,o.defines,o.transformFeedbackVaryings,"",()=>{i(r,()=>{o.onRenderingStateCompiled?.(r)})}),r}catch(s){throw W.Error("Error compiling effect"),s}};class it{static get ShadersRepository(){return Z.ShadersRepository}static set ShadersRepository(e){Z.ShadersRepository=e}get isDisposed(){return this._isDisposed}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new z),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,s=null,r,n=null,a=null,h=null,l=null,c,u="",f=0,d){this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new z,this.onErrorObservable=new z,this._onBindObservable=null,this._isDisposed=!1,this._refCount=1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._disableParallelShaderCompilation=!1,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this._onReleaseEffectsObserver=null,this.name=e,this._key=u;const _=this._key.replace(/\r/g,"").replace(/\n/g,"|");let m;if(t.attributes){const g=t;if(this._engine=i,this._attributesNames=g.attributes,this._uniformsNames=g.uniformsNames.concat(g.samplers),this._samplerList=g.samplers.slice(),this.defines=g.defines,this.onError=g.onError,this.onCompiled=g.onCompiled,this._fallbacks=g.fallbacks,this._indexParameters=g.indexParameters,this._transformFeedbackVaryings=g.transformFeedbackVaryings||null,this._multiTarget=!!g.multiTarget,this._shaderLanguage=g.shaderLanguage??0,this._disableParallelShaderCompilation=!!g.disableParallelShaderCompilation,g.uniformBuffersNames){this._uniformBuffersNamesList=g.uniformBuffersNames.slice();for(let T=0;T<g.uniformBuffersNames.length;T++)this._uniformBuffersNames[g.uniformBuffersNames[T]]=T}this._processFinalCode=g.processFinalCode??null,this._processCodeAfterIncludes=g.processCodeAfterIncludes??void 0,d=g.extraInitializationsAsync,m=g.existingPipelineContext}else this._engine=r,this.defines=n??"",this._uniformsNames=i.concat(s),this._samplerList=s?s.slice():[],this._attributesNames=t,this._uniformBuffersNamesList=[],this._shaderLanguage=f,this.onError=l,this.onCompiled=h,this._indexParameters=c,this._fallbacks=a;this._engine.shaderPlatformName==="WEBGL2"&&(m=$u(_,this._engine._gl)??m),this._attributeLocationByName={},this.uniqueId=it._UniqueIdSeed++,m?(this._pipelineContext=m,this._pipelineContext.setEngine(this._engine),this._onRenderingStateCompiled(this._pipelineContext),this._pipelineContext.program&&(this._pipelineContext.program.__SPECTOR_rebuildProgram=this._rebuildProgram.bind(this))):this._processShaderCodeAsync(null,!1,null,d),this._onReleaseEffectsObserver=this._engine.onReleaseEffectsObservable.addOnce(()=>{this._onReleaseEffectsObserver=null,!this.isDisposed&&this.dispose(!0)})}async _processShaderCodeAsync(e=null,t=!1,i=null,s){s&&await s(),this._processingContext=i||this._engine._getShaderProcessingContext(this._shaderLanguage,!1);const r={defines:this.defines.split(`
|
|
15
|
+
`),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:e??this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Z.GetShadersRepository(this._shaderLanguage),includesShadersStore:Z.GetIncludesShadersStore(this._shaderLanguage),version:(this._engine.version*100).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:this._processCodeAfterIncludes};Ju(r,this.name,this._processFinalCode,(n,a)=>{this._vertexSourceCode=n,this._fragmentSourceCode=a,this._prepareEffect(t)},this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return this._engine.isDisposed||this._isReady?!0:this._pipelineContext?this._pipelineContext.isReady:!1}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getAttributesNames(){return this._attributesNames}getAttributeLocation(e){return this._attributes[e]}getAttributeLocationByName(e){return this._attributeLocationByName[e]}getAttributesCount(){return this._attributes.length}getUniformIndex(e){return this._uniformsNames.indexOf(e)}getUniform(e){return this._uniforms[e]}getSamplers(){return this._samplerList}getUniformNames(){return this._uniformsNames}getUniformBuffersNames(){return this._uniformBuffersNamesList}getIndexParameters(){return this._indexParameters}getCompilationError(){return this._compilationError}allFallbacksProcessed(){return this._allFallbacksProcessed}async whenCompiledAsync(){return await new Promise(e=>{this.executeWhenCompiled(e)})}executeWhenCompiled(e){if(this.isReady()){e(this);return}this.onCompileObservable.add(t=>{e(t)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&this._checkIsReady(null)}_checkIsReady(e){Yr(()=>this._isReadyInternal()||this._isDisposed,()=>{},t=>{this._processCompilationErrors(t,e)},16,12e4,!0,` - Effect: ${typeof this.name=="string"?this.name:this.key}`)}get vertexSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:this._pipelineContext?._getVertexShaderCode()??this._vertexSourceCode}get fragmentSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:this._pipelineContext?._getFragmentShaderCode()??this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}getPipelineGenerationOptions(){return{platformName:this._engine.shaderPlatformName,shaderLanguage:this._shaderLanguage,shaderNameOrContent:this.name,key:this._key,defines:this.defines.split(`
|
|
16
|
+
`),addGlobalDefines:!1,extendedProcessingOptions:{indexParameters:this._indexParameters,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,supportsUniformBuffers:this._engine.supportsUniformBuffers},extendedCreatePipelineOptions:{transformFeedbackVaryings:this._transformFeedbackVaryings,createAsRaw:!!(this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride)}}}_rebuildProgram(e,t,i,s){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(r,n)=>{s&&s(n)},this.onCompiled=()=>{const r=this.getEngine().scenes;if(r)for(let n=0;n<r.length;n++)r[n].markAllMaterialsAsDirty(127);this._pipelineContext._handlesSpectorRebuildCallback?.(i)},this._fallbacks=null,this._prepareEffect()}_onRenderingStateCompiled(e){if(this._pipelineContext=e,this._pipelineContext.setEngine(this._engine),this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,this._attributesNames,this._attributes),this._attributesNames)for(let t=0;t<this._attributesNames.length;t++){const i=this._attributesNames[t];this._attributeLocationByName[i]=this._attributes[t]}this._engine.bindSamplers(this),this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh(),it.AutomaticallyClearCodeCache&&this.clearCodeCache()}_prepareEffect(e=!1){const t=this._pipelineContext;this._isReady=!1;try{const i=!!(this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride),s=i?null:this.defines,r=i?this._vertexSourceCodeOverride:this._vertexSourceCode,n=i?this._fragmentSourceCodeOverride:this._fragmentSourceCode,a=this._engine;this._pipelineContext=tf({existingPipelineContext:e?t:null,vertex:r,fragment:n,context:a.shaderPlatformName==="WEBGL2"||a.shaderPlatformName==="WEBGL1"?a._gl:void 0,rebuildRebind:(h,l,c,u)=>this._rebuildProgram(h,l,c,u),defines:s,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:i,disableParallelCompilation:this._disableParallelShaderCompilation,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:h=>{t&&!e&&this._engine._deletePipelineContext(t),h&&this._onRenderingStateCompiled(h)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContextAsync.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(i){this._processCompilationErrors(i,t)}}_getShaderCodeAndErrorLine(e,t,i){const s=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let r=null;if(t&&e){const n=t.match(s);if(n&&n.length===2){const a=parseInt(n[1]),h=e.split(`
|
|
17
|
+
`,-1);h.length>=a&&(r=`Offending line [${a}] in ${i?"fragment":"vertex"} code: ${h[a-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){this._compilationError=e.message;const i=this._attributesNames,s=this._fallbacks;if(W.Error("Unable to compile effect:"),W.Error(`Uniforms: ${this._uniformsNames.join(" ")}`),W.Error(`Attributes: ${i.join(" ")}`),W.Error(`Defines:
|
|
18
|
+
`+this.defines),it.LogShaderCodeOnCompilationError){let n=null,a=null,h;this._pipelineContext?._getVertexShaderCode()&&([h,n]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),h&&(W.Error("Vertex code:"),W.Error(h))),this._pipelineContext?._getFragmentShaderCode()&&([h,a]=this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(),this._compilationError,!0),h&&(W.Error("Fragment code:"),W.Error(h))),n&&W.Error(n),a&&W.Error(a)}W.Error("Error: "+this._compilationError);const r=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this),this._engine.onEffectErrorObservable.notifyObservers({effect:this,errors:this._compilationError})};t&&(this._pipelineContext=t,this._isReady=!0,r()),s?(this._pipelineContext=null,s.hasMoreFallbacks?(this._allFallbacksProcessed=!1,W.Error("Trying next fallback."),this.defines=s.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,r(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||r())}get isSupported(){return this._compilationError===""}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(this._samplerList.indexOf(i+"0")===-1){const s=this._samplerList.indexOf(e);for(let n=1;n<t.length;n++){const a=i+(n-1).toString();this._samplerList.splice(s+n,0,a)}let r=0;for(const n of this._samplerList)this._samplers[n]=r,r+=1}this._engine.setTextureArray(this._samplers[e],this._uniforms[e],t,e)}bindUniformBuffer(e,t){const i=this._uniformBuffersNames[t];i===void 0||it._BaseCache[i]===e&&this._engine._features.useUBOBindingCache||(it._BaseCache[i]=e,this._engine.bindUniformBufferBase(e,i,t))}bindUniformBlock(e,t){this._engine.bindUniformBlock(this._pipelineContext,e,t)}setInt(e,t){return this._pipelineContext.setInt(e,t),this}setInt2(e,t,i){return this._pipelineContext.setInt2(e,t,i),this}setInt3(e,t,i,s){return this._pipelineContext.setInt3(e,t,i,s),this}setInt4(e,t,i,s,r){return this._pipelineContext.setInt4(e,t,i,s,r),this}setIntArray(e,t){return this._pipelineContext.setIntArray(e,t),this}setIntArray2(e,t){return this._pipelineContext.setIntArray2(e,t),this}setIntArray3(e,t){return this._pipelineContext.setIntArray3(e,t),this}setIntArray4(e,t){return this._pipelineContext.setIntArray4(e,t),this}setUInt(e,t){return this._pipelineContext.setUInt(e,t),this}setUInt2(e,t,i){return this._pipelineContext.setUInt2(e,t,i),this}setUInt3(e,t,i,s){return this._pipelineContext.setUInt3(e,t,i,s),this}setUInt4(e,t,i,s,r){return this._pipelineContext.setUInt4(e,t,i,s,r),this}setUIntArray(e,t){return this._pipelineContext.setUIntArray(e,t),this}setUIntArray2(e,t){return this._pipelineContext.setUIntArray2(e,t),this}setUIntArray3(e,t){return this._pipelineContext.setUIntArray3(e,t),this}setUIntArray4(e,t){return this._pipelineContext.setUIntArray4(e,t),this}setFloatArray(e,t){return this._pipelineContext.setArray(e,t),this}setFloatArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setFloatArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setFloatArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setArray(e,t){return this._pipelineContext.setArray(e,t),this}setArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setMatrices(e,t){return this._pipelineContext.setMatrices(e,t),this}setMatrix(e,t){return this._pipelineContext.setMatrix(e,t),this}setMatrix3x3(e,t){return this._pipelineContext.setMatrix3x3(e,t),this}setMatrix2x2(e,t){return this._pipelineContext.setMatrix2x2(e,t),this}setFloat(e,t){return this._pipelineContext.setFloat(e,t),this}setBool(e,t){return this._pipelineContext.setInt(e,t?1:0),this}setVector2(e,t){return this._pipelineContext.setVector2(e,t),this}setFloat2(e,t,i){return this._pipelineContext.setFloat2(e,t,i),this}setVector3(e,t){return this._pipelineContext.setVector3(e,t),this}setFloat3(e,t,i,s){return this._pipelineContext.setFloat3(e,t,i,s),this}setVector4(e,t){return this._pipelineContext.setVector4(e,t),this}setQuaternion(e,t){return this._pipelineContext.setQuaternion(e,t),this}setFloat4(e,t,i,s,r){return this._pipelineContext.setFloat4(e,t,i,s,r),this}setColor3(e,t){return this._pipelineContext.setColor3(e,t),this}setColor4(e,t,i){return this._pipelineContext.setColor4(e,t,i),this}setDirectColor4(e,t){return this._pipelineContext.setDirectColor4(e,t),this}clearCodeCache(){this._vertexSourceCode="",this._fragmentSourceCode="",this._fragmentSourceCodeBeforeMigration="",this._vertexSourceCodeBeforeMigration=""}dispose(e=!1){if(e)this._refCount=0;else{if(it.PersistentMode)return;this._refCount--}this._refCount>0||this._isDisposed||(this._onReleaseEffectsObserver&&(this._engine.onReleaseEffectsObservable.remove(this._onReleaseEffectsObserver),this._onReleaseEffectsObserver=null),this._pipelineContext&&el(this._pipelineContext),this._engine._releaseEffect(this),this.clearCodeCache(),this._isDisposed=!0)}static RegisterShader(e,t,i,s=0){t&&(Z.GetShadersStore(s)[`${e}PixelShader`]=t),i&&(Z.GetShadersStore(s)[`${e}VertexShader`]=i)}static ResetCache(){it._BaseCache={}}}it.LogShaderCodeOnCompilationError=!0;it.PersistentMode=!1;it.AutomaticallyClearCodeCache=!1;it._UniqueIdSeed=0;it._BaseCache={};it.ShadersStore=Z.ShadersStore;it.IncludesShadersStore=Z.IncludesShadersStore;class dt{static SetMatrixPrecision(e){if(dt.MatrixTrackPrecisionChange=!1,e&&!dt.MatrixUse64Bits&&dt.MatrixTrackedMatrices)for(let t=0;t<dt.MatrixTrackedMatrices.length;++t){const i=dt.MatrixTrackedMatrices[t],s=i._m;i._m=new Array(16);for(let r=0;r<16;++r)i._m[r]=s[r]}dt.MatrixUse64Bits=e,dt.MatrixCurrentType=dt.MatrixUse64Bits?Array:Float32Array,dt.MatrixTrackedMatrices=null}}dt.MatrixUse64Bits=!1;dt.MatrixTrackPrecisionChange=!0;dt.MatrixCurrentType=Float32Array;dt.MatrixTrackedMatrices=[];class sf{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}class rf{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get backFunc(){return this._func}set backFunc(e){this._backFunc!==e&&(this._backFunc=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get backOpStencilFail(){return this._backOpStencilFail}set backOpStencilFail(e){this._backOpStencilFail!==e&&(this._backOpStencilFail=e,this._isStencilOpDirty=!0)}get backOpDepthFail(){return this._backOpDepthFail}set backOpDepthFail(e){this._backOpDepthFail!==e&&(this._backOpDepthFail=e,this._isStencilOpDirty=!0)}get backOpStencilDepthPass(){return this._backOpStencilDepthPass}set backOpStencilDepthPass(e){this._backOpStencilDepthPass!==e&&(this._backOpStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){this.stencilMaterial=void 0,this.stencilGlobal?.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){if(!e)return;const t=!this.useStencilGlobalOnly&&!!this.stencilMaterial?.enabled;this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.backFunc=t?this.stencilMaterial.backFunc:this.stencilGlobal.backFunc,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.backOpStencilFail=t?this.stencilMaterial.backOpStencilFail:this.stencilGlobal.backOpStencilFail,this.backOpDepthFail=t?this.stencilMaterial.backOpDepthFail:this.stencilGlobal.backOpDepthFail,this.backOpStencilDepthPass=t?this.stencilMaterial.backOpStencilDepthPass:this.stencilGlobal.backOpStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFuncSeparate(e.FRONT,this.func,this.funcRef,this.funcMask),e.stencilFuncSeparate(e.BACK,this.backFunc,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOpSeparate(e.FRONT,this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),e.stencilOpSeparate(e.BACK,this.backOpStencilFail,this.backOpDepthFail,this.backOpStencilDepthPass),this._isStencilOpDirty=!1))}}class Lt{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.funcRef=1,this.funcMask=255,this.func=Lt.ALWAYS,this.opStencilFail=Lt.KEEP,this.opDepthFail=Lt.KEEP,this.opStencilDepthPass=Lt.REPLACE,this.backFunc=Lt.ALWAYS,this.backOpStencilFail=Lt.KEEP,this.backOpDepthFail=Lt.KEEP,this.backOpStencilDepthPass=Lt.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilBackFunc(){return this.backFunc}set stencilBackFunc(e){this.backFunc=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilBackOpStencilFail(){return this.backOpStencilFail}set stencilBackOpStencilFail(e){this.backOpStencilFail=e}get stencilBackOpDepthFail(){return this.backOpDepthFail}set stencilBackOpDepthFail(e){this.backOpDepthFail=e}get stencilBackOpStencilDepthPass(){return this.backOpStencilDepthPass}set stencilBackOpStencilDepthPass(e){this.backOpStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}}Lt.ALWAYS=519;Lt.KEEP=7680;Lt.REPLACE=7681;class tl{constructor(e){this._supportBlendParametersPerTarget=e,this._blendFunctionParameters=new Array(4*8),this._blendEquationParameters=new Array(2*8),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=Array(8).fill(!1),this._numTargetEnabled=0,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._numTargetEnabled>0}set alphaBlend(e){this.setAlphaBlend(e)}setAlphaBlend(e,t=0){this._alphaBlend[t]!==e&&(e?this._numTargetEnabled++:this._numTargetEnabled--,this._alphaBlend[t]=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,s){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===s||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=s,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,s,r=0){const n=r*4;this._blendFunctionParameters[n+0]===e&&this._blendFunctionParameters[n+1]===t&&this._blendFunctionParameters[n+2]===i&&this._blendFunctionParameters[n+3]===s||(this._blendFunctionParameters[n+0]=e,this._blendFunctionParameters[n+1]=t,this._blendFunctionParameters[n+2]=i,this._blendFunctionParameters[n+3]=s,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t,i=0){const s=i*2;this._blendEquationParameters[s+0]===e&&this._blendEquationParameters[s+1]===t||(this._blendEquationParameters[s+0]=e,this._blendEquationParameters[s+1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend.fill(!1),this._numTargetEnabled=0,this._blendFunctionParameters.fill(null),this._blendEquationParameters.fill(null),this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e,t=1){if(!this.isDirty)return;if(this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1),t===1||!this._supportBlendParametersPerTarget){this._isAlphaBlendDirty&&(this._alphaBlend[0]?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1);return}const i=e;if(this._isAlphaBlendDirty){for(let s=0;s<t;s++){const r=s<this._numTargetEnabled?s:0;this._alphaBlend[r]?i.enableIndexed(e.BLEND,s):i.disableIndexed(e.BLEND,s)}this._isAlphaBlendDirty=!1}if(this._isBlendFunctionParametersDirty){for(let s=0;s<t;s++){const r=s<this._numTargetEnabled?s*4:0;i.blendFuncSeparateIndexed(s,this._blendFunctionParameters[r+0],this._blendFunctionParameters[r+1],this._blendFunctionParameters[r+2],this._blendFunctionParameters[r+3])}this._isBlendFunctionParametersDirty=!1}if(this._isBlendEquationParametersDirty){for(let s=0;s<t;s++){const r=s<this._numTargetEnabled?s*2:0;i.blendEquationSeparateIndexed(s,this._blendEquationParameters[r+0],this._blendEquationParameters[r+1])}this._isBlendEquationParametersDirty=!1}}setAlphaMode(e,t){let i=32774;switch(e){case 0:break;case 7:this.setAlphaBlendFunctionParameters(1,771,1,1,t);break;case 8:this.setAlphaBlendFunctionParameters(1,771,1,771,t);break;case 2:this.setAlphaBlendFunctionParameters(770,771,1,1,t);break;case 6:this.setAlphaBlendFunctionParameters(1,1,0,1,t);break;case 1:this.setAlphaBlendFunctionParameters(770,1,0,1,t);break;case 3:this.setAlphaBlendFunctionParameters(0,769,1,1,t);break;case 4:this.setAlphaBlendFunctionParameters(774,0,1,1,t);break;case 5:this.setAlphaBlendFunctionParameters(770,769,1,1,t);break;case 9:this.setAlphaBlendFunctionParameters(32769,32770,32771,32772,t);break;case 10:this.setAlphaBlendFunctionParameters(1,769,1,771,t);break;case 11:this.setAlphaBlendFunctionParameters(1,1,1,1,t);break;case 12:this.setAlphaBlendFunctionParameters(772,1,0,0,t);break;case 13:this.setAlphaBlendFunctionParameters(775,769,773,771,t);break;case 14:this.setAlphaBlendFunctionParameters(1,771,1,771,t);break;case 15:this.setAlphaBlendFunctionParameters(1,1,1,0,t);break;case 16:this.setAlphaBlendFunctionParameters(775,769,0,1,t);break;case 17:this.setAlphaBlendFunctionParameters(770,771,1,771,t);break;case 18:this.setAlphaBlendFunctionParameters(1,1,1,1,t),i=32775;break;case 19:this.setAlphaBlendFunctionParameters(1,1,1,1,t),i=32776;break;case 20:this.setAlphaBlendFunctionParameters(1,35065,0,1,t);break}this.setAlphaEquationParameters(i,i,t)}}class nf{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,s=1,r=2,n=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=s,this.samplingMode=r,this._comparisonFunction=n,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}var zo;(function(o){o[o.Unknown=0]="Unknown",o[o.Url=1]="Url",o[o.Temp=2]="Temp",o[o.Raw=3]="Raw",o[o.Dynamic=4]="Dynamic",o[o.RenderTarget=5]="RenderTarget",o[o.MultiRenderTarget=6]="MultiRenderTarget",o[o.Cube=7]="Cube",o[o.CubeRaw=8]="CubeRaw",o[o.CubePrefiltered=9]="CubePrefiltered",o[o.Raw3D=10]="Raw3D",o[o.Raw2DArray=11]="Raw2DArray",o[o.DepthStencil=12]="DepthStencil",o[o.CubeRawRGBD=13]="CubeRawRGBD",o[o.Depth=14]="Depth"})(zo||(zo={}));class xt extends nf{get useMipMaps(){return this._useMipMaps===null?this.generateMipMaps:this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,i=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this._useMipMaps=null,this.mipLevelCount=1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new z,this.onErrorObservable=new z,this.onRebuildCallback=null,this.width=0,this.height=0,this.depth=0,this.baseWidth=0,this.baseHeight=0,this.baseDepth=0,this.invertY=!1,this._invertVScale=!1,this._associatedChannel=-1,this._source=0,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._creationFlags=0,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._hardwareTexture=null,this._maxLodLevel=null,this._references=1,this._gammaSpace=null,this._premulAlpha=!1,this._dynamicTextureSource=null,this._autoMSAAManagement=!1,this._engine=e,this._source=t,this._uniqueId=xt._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){const t=this.onRebuildCallback(this),i=s=>{s._swapAndDie(this,!1),this.isReady=t.isReady};t.isAsync?t.proxy.then(i):i(t.proxy);return}let e;switch(this.source){case 2:break;case 1:e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,t=>{t._swapAndDie(this,!1),this.isReady=!0},null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer);return;case 3:if(e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer,this.mipLevelCount),e._swapAndDie(this,!1),this._bufferViewArray)for(let t=0;t<this._bufferViewArray.length;t++){const i=this._bufferViewArray[t];i&&this._engine.updateRawTexture(this,i,this.format,this.invertY,this._compression,this.type,this._useSRGBBuffer,t)}this.isReady=!0;break;case 10:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case 11:if(e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this.mipLevelCount),e._swapAndDie(this,!1),this._bufferViewArray)for(let t=0;t<this._bufferViewArray.length;t++){const i=this._bufferViewArray[t];i&&this._engine.updateRawTexture2DArray(this,i,this.format,this.invertY,this._compression,this.type,t)}this.isReady=!0;break;case 4:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case 7:e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,()=>{e._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer,ArrayBuffer.isView(this._buffer)?this._buffer:null);return;case 8:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case 13:return;case 9:e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,t=>{t&&t._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension),e._sphericalPolynomial=this._sphericalPolynomial;return}}_swapAndDie(e,t=!0){this._hardwareTexture?.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const i=this._engine.getLoadedTexturesCache();let s=i.indexOf(this);s!==-1&&i.splice(s,1),s=i.indexOf(e),s===-1&&i.push(e)}dispose(){this._references--,this._references===0&&(this.onLoadedObservable.clear(),this.onErrorObservable.clear(),this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}xt._Counter=0;function il(o,e){if(mt()){const{requestAnimationFrame:t}=e||window;if(typeof t=="function")return t(o)}else if(typeof requestAnimationFrame=="function")return requestAnimationFrame(o);return setTimeout(o,16)}class J{get frameId(){return this._frameId}get isWebGPU(){return this._isWebGPU}_getShaderProcessor(e){return this._shaderProcessor}_resetAlphaMode(){this._alphaMode.fill(-1),this._alphaEquation.fill(-1)}get shaderPlatformName(){return this._shaderPlatformName}_clearEmptyResources(){this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,e?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}_getGlobalDefines(e){if(e){this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS;return}else{let t="";return this.isNDCHalfZRange&&(t+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(t&&(t+=`
|
|
19
|
+
`),t+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(t&&(t+=`
|
|
20
|
+
`),t+="#define USE_EXACT_SRGB_CONVERSIONS"),t}}_rebuildInternalTextures(){const e=this._internalTexturesCache.slice();for(const t of e)t._rebuild()}_rebuildRenderTargetWrappers(){const e=this._renderTargetWrapperCache.slice();for(const t of e)t._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}it.ResetCache()}_rebuildGraphicsResources(){this.wipeCaches(!0),this._rebuildEffects(),this._rebuildComputeEffects?.(),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){W.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout(()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=r,this._flagContextRestored()},0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return 0}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){const e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get activeRenderLoops(){return this._activeRenderLoops}stopRenderLoop(e){if(!e){this._activeRenderLoops.length=0,this._cancelFrame();return}const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),this._activeRenderLoops.length==0&&this._cancelFrame())}_cancelFrame(){if(this._frameHandler!==0){const e=this._frameHandler;if(this._frameHandler=0,mt()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if(typeof t=="function")return t(e)}else if(typeof cancelAnimationFrame=="function")return cancelAnimationFrame(e);return clearTimeout(e)}}beginFrame(){this.onBeginFrameObservable.notifyObservers(this)}endFrame(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)}get maxFPS(){return this._maxFPS}set maxFPS(e){if(this._maxFPS=e,e!==void 0){if(e<=0){this._minFrameTime=Number.MAX_VALUE;return}this._minFrameTime=1e3/e}}_isOverFrameTime(e){if(!e||this._maxFPS===void 0)return!1;const t=e-this._lastFrameTime;return this._lastFrameTime=e,this._renderAccumulator+=t,this._renderAccumulator<this._minFrameTime?!0:(this._renderAccumulator-=this._minFrameTime,this._renderAccumulator>this._minFrameTime&&(this._renderAccumulator=this._minFrameTime),!1)}_processFrame(e){if(this._frameHandler=0,!this._contextWasLost&&!this._isOverFrameTime(e)){let t=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(t=!1),t&&(this.beginFrame(),!this.skipFrameRender&&!this._renderViews()&&this._renderFrame(),this.endFrame())}}_renderLoop(e){this._processFrame(e),this._activeRenderLoops.length>0&&this._frameHandler===0&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e<this._activeRenderLoops.length;e++){const t=this._activeRenderLoops[e];t()}}_renderViews(){return!1}_queueNewFrame(e,t){return il(e,t)}runRenderLoop(e){this._activeRenderLoops.indexOf(e)===-1&&(this._activeRenderLoops.push(e),this._activeRenderLoops.length===1&&this._frameHandler===0&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){const e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){const e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}getHostWindow(){return mt()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=!0}_rebuildTextures(){for(const e of this.scenes)e._rebuildTextures();for(const e of this._virtualScenes)e._rebuildTextures()}_releaseRenderTargetWrapper(e){const t=this._renderTargetWrapperCache.indexOf(e);t!==-1&&this._renderTargetWrapperCache.splice(t,1)}get currentViewport(){return this._cachedViewport}setViewport(e,t,i){const s=t||this.getRenderWidth(),r=i||this.getRenderHeight(),n=e.x||0,a=e.y||0;this._cachedViewport=e,this._viewport(n*s,a*r,s*e.width,r*e.height)}createCanvasImage(){return document.createElement("img")}createCanvasPath2D(e){return new Path2D(e)}get description(){let e=this.name+this.version;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}_createTextureBase(e,t,i,s,r=3,n=null,a=null,h,l,c=null,u=null,f=null,d=null,_,m,g){e=e||"";const T=e.substring(0,5)==="data:",R=e.substring(0,5)==="blob:",A=T&&e.indexOf(";base64,")!==-1,y=u||new xt(this,1);y!==u&&(y.label=e.substring(0,60));const E=e;this._transformTextureUrl&&!A&&!u&&!c&&(e=this._transformTextureUrl(e)),E!==e&&(y._originalUrl=E);const x=e.lastIndexOf(".");let b=d||(x>-1?e.substring(x).toLowerCase():"");b.indexOf("?")>-1&&(b=b.split("?")[0]);const v=J.GetCompatibleTextureLoader(b,_);s&&s.addPendingData(y),y.url=e,y.generateMipMaps=!t,y.samplingMode=r,y.invertY=i,y._useSRGBBuffer=this._getUseSRGBBuffer(!!g,t),this._doNotHandleContextLost||(y._buffer=c);let O=null;n&&!u&&(O=y.onLoadedObservable.add(n)),u||this._internalTexturesCache.push(y);const k=(Y,q)=>{s&&s.removePendingData(y),e===E?(O&&y.onLoadedObservable.remove(O),ye.UseFallbackTexture&&e!==ye.FallbackTexture&&this._createTextureBase(ye.FallbackTexture,t,y.invertY,s,r,null,a,h,l,c,y),Y=(Y||"Unknown error")+(ye.UseFallbackTexture?" - Fallback texture was used":""),y.onErrorObservable.notifyObservers({message:Y,exception:q}),a&&a(Y,q)):(W.Warn(`Failed to load ${e}, falling back to ${E}`),this._createTextureBase(E,t,y.invertY,s,r,n,a,h,l,c,y,f,d,_,m,g))};if(v){const Y=async q=>{(await v).loadData(q,y,(ee,Q,se,le,H,K)=>{K?k("TextureLoader failed to load data"):h(y,b,s,{width:ee,height:Q},y.invertY,!se,le,()=>(H(),!1),r)},m)};if(!c)this._loadFile(e,async q=>{try{await Y(new Uint8Array(q))}catch(L){k("Failed to parse texture data",L)}},void 0,s?s.offlineProvider:void 0,!0,(q,L)=>{k("Unable to load "+(q&&q.responseURL,L))});else{const q=async L=>{try{await Y(L)}catch(ee){k("Failed to parse texture data",ee)}};c instanceof ArrayBuffer?q(new Uint8Array(c)):ArrayBuffer.isView(c)?q(c):a&&a("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null)}}else{const Y=q=>{R&&!this._doNotHandleContextLost&&(y._buffer=q),h(y,b,s,q,y.invertY,t,!1,l,r)};!T||A?c&&(typeof c.decoding=="string"||c.close)?Y(c):J._FileToolsLoadImage(e||"",Y,k,s?s.offlineProvider:null,_,y.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0,this):typeof c=="string"||c instanceof ArrayBuffer||ArrayBuffer.isView(c)||c instanceof Blob?J._FileToolsLoadImage(c,Y,k,s?s.offlineProvider:null,_,y.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0,this):c&&Y(c)}return y}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuildAfterContextLost()}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:ls()?document:null}getLoadedTexturesCache(){return this._internalTexturesCache}clearInternalTexturesCache(){this._internalTexturesCache.length=0}getCaps(){return this._caps}resetTextureCache(){for(const e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}get name(){return this._name}set name(e){this._name=e}static get NpmPackage(){return"babylonjs@8.56.2"}static get Version(){return"8.56.2"}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get isStencilEnable(){return this._isStencilEnable}getCreationOptions(){return this._creationOptions}constructor(e,t,i){this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new sf,this._stencilStateComposer=new rf,this._stencilState=new Lt,this._alphaState=new tl(!1),this._alphaMode=Array(8).fill(-1),this._alphaEquation=Array(8).fill(-1),this._activeRequests=[],this._badOS=!1,this._badDesktopOS=!1,this._compatibilityMode=!0,this._internalTexturesCache=new Array,this._currentRenderTarget=null,this._boundTexturesCache={},this._activeChannel=0,this._currentTextureChannel=-1,this._viewportCached={x:0,y:0,z:0,w:0},this._isWebGPU=!1,this._enableGPUDebugMarkers=!1,this.onCanvasBlurObservable=new z,this.onCanvasFocusObservable=new z,this.onNewSceneAddedObservable=new z,this.onResizeObservable=new z,this.onCanvasPointerOutObservable=new z,this.onEffectErrorObservable=new z,this.disablePerformanceMonitorInBackground=!1,this.disableVertexArrayObjects=!1,this._frameId=0,this.hostInformation={isMobile:!1},this.isFullscreen=!1,this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.currentRenderPassId=0,this.isPointerLock=!1,this.postProcesses=[],this.canvasTabIndex=1,this._contextWasLost=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this._renderTargetWrapperCache=new Array,this._compiledEffects={},this._isDisposed=!1,this.scenes=[],this._virtualScenes=new Array,this.onBeforeTextureInitObservable=new z,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=n=>this._renderLoop(n),this._lastFrameTime=0,this._renderAccumulator=0,this.skipFrameRender=!1,this.onBeforeShaderCompilationObservable=new z,this.onAfterShaderCompilationObservable=new z,this.onBeginFrameObservable=new z,this.onEndFrameObservable=new z,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new z,this.onContextRestoredObservable=new z,this._name="",this.premultipliedAlpha=!0,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._doNotHandleContextLost=!1,this.cullBackFaces=null,this._renderPassNames=["main"],this._fps=60,this._deltaTime=0,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this.onDisposeObservable=new z,this.onReleaseEffectsObservable=new z,ye.Instances.push(this),this.startTime=Si.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,dt.SetMatrixPrecision(!!t.useLargeWorldRendering||!!t.useHighPrecisionMatrix),Ji()&&navigator.userAgent&&(this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),this.adaptToDeviceRatio=i??!1,t.antialias=e??t.antialias,t.deterministicLockstep=t.deterministicLockstep??!1,t.lockstepMaxSteps=t.lockstepMaxSteps??4,t.timeStep=t.timeStep??1/60,t.stencil=t.stencil??!0,this._audioContext=t.audioEngineOptions?.audioContext??null,this._audioDestination=t.audioEngineOptions?.audioDestination??null,this.premultipliedAlpha=t.premultipliedAlpha??!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=t.useExactSrgbConversions??!1;const s=mt()&&window.devicePixelRatio||1,r=t.limitDeviceRatio||s;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(r,s):1,this._lastDevicePixelRatio=s,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const s=mt()&&window.devicePixelRatio||1,r=this._lastDevicePixelRatio/s;this._lastDevicePixelRatio=s,this._hardwareScalingLevel*=r}if(mt()&&ls())if(this._renderingCanvas){const s=this._renderingCanvas.getBoundingClientRect?.();t=this._renderingCanvas.clientWidth||s?.width||this._renderingCanvas.width*this._hardwareScalingLevel||100,i=this._renderingCanvas.clientHeight||s?.height||this._renderingCanvas.height*this._hardwareScalingLevel||100}else t=window.innerWidth,i=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){if(!this._renderingCanvas||(e=e|0,t=t|0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t))return!1;if(this._renderingCanvas.width=e,this._renderingCanvas.height=t,this.scenes){for(let s=0;s<this.scenes.length;s++){const r=this.scenes[s];for(let n=0;n<r.cameras.length;n++){const a=r.cameras[n];a._currentRenderId=0}}this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this)}return!0}createRawTexture(e,t,i,s,r,n,a,h,l,c,u,f){throw pe("engine.rawTexture")}createRawCubeTexture(e,t,i,s,r,n,a,h){throw pe("engine.rawTexture")}createRawTexture3D(e,t,i,s,r,n,a,h,l,c,u){throw pe("engine.rawTexture")}createRawTexture2DArray(e,t,i,s,r,n,a,h,l,c,u,f){throw pe("engine.rawTexture")}_sharedInit(e){this._renderingCanvas=e}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{const e=navigator.userAgent;this.hostInformation.isMobile=e.indexOf("Mobile")!==-1||e.indexOf("Mac")!==-1&&ls()&&"ontouchend"in document},this._checkForMobile(),mt()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){this._drawCalls?.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return this._timeStep*1e3}_createImageBitmapFromSource(e,t){throw new Error("createImageBitmapFromSource is not implemented")}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){throw new Error("resizeImageBitmap is not implemented")}getFontOffset(e){throw new Error("getFontOffset is not implemented")}static _CreateCanvas(e,t){if(typeof document>"u")return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return J._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,s,r,n,a){throw pe("FileTools")}_loadFile(e,t,i,s,r,n){const a=Yh(e,t,i,s,r,n);return this._activeRequests.push(a),a.onCompleteObservable.add(()=>{const h=this._activeRequests.indexOf(a);h!==-1&&this._activeRequests.splice(h,1)}),a}static _FileToolsLoadFile(e,t,i,s,r,n){if(Dr.loadFile)return Dr.loadFile(e,t,i,s,r,n);throw pe("FileTools")}dispose(){for(this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();this.releaseComputeEffects?.(),it.ResetCache();for(const t of this._activeRequests)t.abort();this._boundRenderFunction=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onNewSceneAddedObservable.clear(),this.onEffectErrorObservable.clear(),mt()&&window.removeEventListener("resize",this._checkForMobile);const e=ye.Instances.indexOf(this);e>=0&&ye.Instances.splice(e,1),ye.Instances.length||(ye.OnEnginesDisposedObservable.notifyObservers(this),ye.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw pe("LoadingScreen")}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i<ye.Instances.length;i++){const s=ye.Instances[i];for(let r=0;r<s.scenes.length;r++)s.scenes[r].markAllMaterialsAsDirty(e,t)}}static GetCompatibleTextureLoader(e,t){return null}}J._RenderPassIdCounter=0;J._RescalePostProcessFactory=null;J.CollisionsEpsilon=.001;J.QueueNewFrame=il;function af(o,e,t,i){switch(e){case 5120:{let s=o.getInt8(t);return i&&(s=Math.max(s/127,-1)),s}case 5121:{let s=o.getUint8(t);return i&&(s=s/255),s}case 5122:{let s=o.getInt16(t,!0);return i&&(s=Math.max(s/32767,-1)),s}case 5123:{let s=o.getUint16(t,!0);return i&&(s=s/65535),s}case 5124:return o.getInt32(t,!0);case 5125:return o.getUint32(t,!0);case 5126:return o.getFloat32(t,!0);default:throw new Error(`Invalid component type ${e}`)}}function of(o,e,t,i,s){switch(e){case 5120:{i&&(s=Math.round(s*127)),o.setInt8(t,s);break}case 5121:{i&&(s=Math.round(s*255)),o.setUint8(t,s);break}case 5122:{i&&(s=Math.round(s*32767)),o.setInt16(t,s,!0);break}case 5123:{i&&(s=Math.round(s*65535)),o.setUint16(t,s,!0);break}case 5124:{o.setInt32(t,s,!0);break}case 5125:{o.setUint32(t,s,!0);break}case 5126:{o.setFloat32(t,s,!0);break}default:throw new Error(`Invalid component type ${e}`)}}function xi(o){switch(o){case 5120:case 5121:return 1;case 5122:case 5123:return 2;case 5124:case 5125:case 5126:return 4;default:throw new Error(`Invalid type '${o}'`)}}function hf(o){switch(o){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5124:return Int32Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`Invalid component type '${o}'`)}}function ps(o,e,t,i,s,r,n,a){const h=new Array(i),l=new Array(i);if(o instanceof Array){let c=e/4;const u=t/4;for(let f=0;f<r;f+=i){for(let d=0;d<i;d++)h[d]=l[d]=o[c+d];a(l,f);for(let d=0;d<i;d++)h[d]!==l[d]&&(o[c+d]=l[d]);c+=u}}else{const c=ArrayBuffer.isView(o)?new DataView(o.buffer,o.byteOffset,o.byteLength):new DataView(o),u=xi(s);for(let f=0;f<r;f+=i){for(let d=0,_=e;d<i;d++,_+=u)h[d]=l[d]=af(c,s,_,n);a(l,f);for(let d=0,_=e;d<i;d++,_+=u)h[d]!==l[d]&&of(c,s,_,n,l[d]);e+=t}}}function Wo(o,e,t,i,s,r,n,a){const h=e*xi(t),l=n*e;if(t!==5126||s!==h){const c=new Float32Array(l);return ps(o,i,s,e,t,l,r,(u,f)=>{for(let d=0;d<e;d++)c[f+d]=u[d]}),c}if(!(o instanceof Array||o instanceof Float32Array)||i!==0||o.length!==l)if(o instanceof Array){const c=i/4;return o.slice(c,c+l)}else if(ArrayBuffer.isView(o)){const c=o.byteOffset+i;return c&3&&(W.Warn("Float array must be aligned to 4-bytes border"),a=!0),a?new Float32Array(o.buffer.slice(c,c+l*Float32Array.BYTES_PER_ELEMENT)):new Float32Array(o.buffer,c,l)}else return new Float32Array(o,i,l);return a?o.slice():o}function lf(o,e,t,i,s,r,n){const a=xi(t),h=hf(t),l=r*e;if(Array.isArray(o)){if(i&3||s&3)throw new Error("byteOffset and byteStride must be a multiple of 4 for number[] data.");const _=i/4,m=s/4;if(_+(r-1)*m+e>o.length)throw new Error("Last accessed index is out of bounds.");if(m<e)throw new Error("Data stride cannot be smaller than the component size.");if(m!==e){const T=new h(l);return ps(o,i,s,e,t,l,!1,(R,A)=>{for(let y=0;y<e;y++)T[A+y]=R[y]}),T}return new h(o.slice(_,_+l))}let c,u=i;if(ArrayBuffer.isView(o)?(c=o.buffer,u+=o.byteOffset):c=o,u+(r-1)*s+e*a>c.byteLength)throw new Error("Last accessed byte is out of bounds.");const d=e*a;if(s<d)throw new Error("Byte stride cannot be smaller than the component's byte size.");if(s!==d){const _=new h(l);return ps(c,u,s,e,t,l,!1,(m,g)=>{for(let T=0;T<e;T++)_[g+T]=m[T]}),_}return a!==1&&u&a-1&&(W.Warn("Array must be aligned to border of element size. Data will be copied."),n=!0),n?new h(c.slice(u,u+l*a)):new h(c,u,l)}function cf(o,e,t,i,s,r,n,a){const h=e*xi(t),l=n*e;if(a.length!==l)throw new Error("Output length is not valid");if(t!==5126||s!==h){ps(o,i,s,e,t,l,r,(c,u)=>{for(let f=0;f<e;f++)a[u+f]=c[f]});return}if(o instanceof Array){const c=i/4;a.set(o,c)}else if(ArrayBuffer.isView(o)){const c=o.byteOffset+i;if(c&3){W.Warn("Float array must be aligned to 4-bytes border"),a.set(new Float32Array(o.buffer.slice(c,c+l*Float32Array.BYTES_PER_ELEMENT)));return}const u=new Float32Array(o.buffer,c,l);a.set(u)}else{const c=new Float32Array(o,i,l);a.set(c)}}function Fp(o,e,t=0,i=0){if(Array.isArray(o)){for(let s=0;s<e;s++)if(o[t+s]-i>65535)return!0;return!1}return o.BYTES_PER_ELEMENT===4}function wp(o,e){let t=e*o.BYTES_PER_ELEMENT;if(!(t&3))return new o(e);t=t+3&-4;const i=new ArrayBuffer(t);return new o(i,0,e)}function sl(o){const e=o.buffer;if(e instanceof ArrayBuffer)return o;const t=new ArrayBuffer(o.byteLength);return new Uint8Array(t).set(new Uint8Array(e,o.byteOffset,o.byteLength)),t}const rl=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class Or extends Ss{constructor(e,t){super(e,Xr.LoadFileError),this.name="LoadFileError",Ui._setPrototypeOf(this,Or.prototype),t instanceof at?this.request=t:this.file=t}}class Fr extends Ss{constructor(e,t){super(e,Xr.RequestFileError),this.request=t,this.name="RequestFileError",Ui._setPrototypeOf(this,Fr.prototype)}}class za extends Ss{constructor(e,t){super(e,Xr.ReadFileError),this.file=t,this.name="ReadFileError",Ui._setPrototypeOf(this,za.prototype)}}const uf=o=>(o=o.replace(/#/gm,"%23"),o),et={DefaultRetryStrategy:Ru.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:o=>o,ScriptBaseUrl:"",ScriptPreprocessUrl:o=>o,CleanUrl:uf},Wa=(o,e)=>{if(!(o&&o.indexOf("data:")===0)&&et.CorsBehavior)if(typeof et.CorsBehavior=="string"||et.CorsBehavior instanceof String)e.crossOrigin=et.CorsBehavior;else{const t=et.CorsBehavior(o);t&&(e.crossOrigin=t)}},Go={getRequiredSize:null},jr=(o,e,t,i,s="",r,n=ye.LastCreatedEngine)=>{if(typeof HTMLImageElement>"u"&&!n?._features.forceBitmapOverHTMLImageElement)return t("LoadImage is only supported in web or BabylonNative environments."),null;let a,h=!1;if(o instanceof ArrayBuffer||ArrayBuffer.isView(o))if(typeof Blob<"u"&&typeof URL<"u"){let E;o instanceof ArrayBuffer?E=o:E=sl(o),a=URL.createObjectURL(new Blob([E],{type:s})),h=!0}else a=`data:${s};base64,`+Kr(o);else o instanceof Blob?(a=URL.createObjectURL(o),h=!0):(a=et.CleanUrl(o),a=et.PreprocessUrl(a));const l=E=>{if(t){const x=a||o.toString();t(`Error while trying to load image: ${x.indexOf("http")===0||x.length<=128?x:x.slice(0,128)+"..."}`,E)}};if(n?._features.forceBitmapOverHTMLImageElement)return ki(a,E=>{n.createImageBitmap(new Blob([E],{type:s}),{premultiplyAlpha:"none",colorSpaceConversion:"none",...r}).then(x=>{e(x),h&&URL.revokeObjectURL(a)}).catch(x=>{t&&t("Error while trying to load image: "+o,x)})},void 0,i||void 0,!0,(E,x)=>{l(x)}),null;const c=new Image;if(Go.getRequiredSize){const E=Go.getRequiredSize(o);E.width&&(c.width=E.width),E.height&&(c.height=E.height)}Wa(a,c);const u=[],f=()=>{for(const E of u)E.target.addEventListener(E.name,E.handler)},d=()=>{for(const E of u)E.target.removeEventListener(E.name,E.handler);u.length=0},_=()=>{d(),e(c),h&&c.src&&URL.revokeObjectURL(c.src)},m=E=>{d(),l(E),h&&c.src&&URL.revokeObjectURL(c.src)},g=E=>{if(E.blockedURI!==c.src||E.disposition==="report")return;d();const x=new Error(`CSP violation of policy ${E.effectiveDirective} ${E.blockedURI}. Current policy is ${E.originalPolicy}`);ye.UseFallbackTexture=!1,l(x),h&&c.src&&URL.revokeObjectURL(c.src),c.src=""};u.push({target:c,name:"load",handler:_}),u.push({target:c,name:"error",handler:m}),u.push({target:document,name:"securitypolicyviolation",handler:g}),f();const T=a.substring(0,5)==="blob:",R=a.substring(0,5)==="data:",A=()=>{T||R||!at.IsCustomRequestAvailable?c.src=a:ki(a,(E,x,b)=>{const P=!s&&b?b:s,v=new Blob([E],{type:P}),O=URL.createObjectURL(v);h=!0,c.src=O},void 0,i||void 0,!0,(E,x)=>{l(x)})},y=()=>{i&&i.loadImage(a,c)};if(!T&&!R&&i&&i.enableTexturesOffline)i.open(y,A);else{if(a.indexOf("file:")!==-1){const E=decodeURIComponent(a.substring(5).toLowerCase());if(Us.FilesToLoad[E]&&typeof URL<"u"){try{let x;try{x=URL.createObjectURL(Us.FilesToLoad[E])}catch{x=URL.createObjectURL(Us.FilesToLoad[E])}c.src=x,h=!0}catch{c.src=""}return c}}A()}return c},Hs=(o,e,t,i,s)=>{const r=new FileReader,n={onCompleteObservable:new z,abort:()=>r.abort()};return r.onloadend=()=>n.onCompleteObservable.notifyObservers(n),s&&(r.onerror=()=>{s(new za(`Unable to read ${o.name}`,o))}),r.onload=a=>{e(a.target.result)},t&&(r.onprogress=t),i?r.readAsArrayBuffer(o):r.readAsText(o),n},ki=(o,e,t,i,s,r,n)=>{if(o.name)return Hs(o,e,t,s,r?c=>{r(void 0,c)}:void 0);const a=o;if(a.indexOf("file:")!==-1){let c=decodeURIComponent(a.substring(5).toLowerCase());c.indexOf("./")===0&&(c=c.substring(2));const u=Us.FilesToLoad[c];if(u)return Hs(u,e,t,s,r?f=>r(void 0,new Or(f.message,f.file)):void 0)}const{match:h,type:l}=ol(a);if(h){const c={onCompleteObservable:new z,abort:()=>()=>{}};try{const u=s?Ha(a):hl(a);e(u,void 0,l)}catch(u){r?r(void 0,u):W.Error(u.message||"Failed to parse the Data URL")}return Gs.SetImmediate(()=>{c.onCompleteObservable.notifyObservers(c)}),c}return Ga(a,(c,u)=>{e(c,u?.responseURL,u?.getResponseHeader("content-type"))},t,i,s,r?c=>{r(c.request,new Or(c.message,c.request))}:void 0,n)},Ga=(o,e,t,i,s,r,n)=>{i!==null&&(i??(i=ye.LastCreatedScene?.offlineProvider)),o=et.CleanUrl(o),o=et.PreprocessUrl(o);const a=et.BaseUrl+o;let h=!1;const l={onCompleteObservable:new z,abort:()=>h=!0},c=()=>{let u=new at,f=null,d;const _=()=>{u&&(t&&u.removeEventListener("progress",t),d&&u.removeEventListener("readystatechange",d),u.removeEventListener("loadend",m))};let m=()=>{_(),l.onCompleteObservable.notifyObservers(l),l.onCompleteObservable.clear(),t=void 0,d=null,m=null,r=void 0,n=void 0,e=void 0};l.abort=()=>{h=!0,m&&m(),u&&u.readyState!==(XMLHttpRequest.DONE||4)&&u.abort(),f!==null&&(clearTimeout(f),f=null),u=null};const g=R=>{const A=R.message||"Unknown error";r&&u?r(new Fr(A,u)):W.Error(A)},T=R=>{if(u){if(u.open("GET",a),n)try{n(u)}catch(A){g(A);return}s&&(u.responseType="arraybuffer"),t&&u.addEventListener("progress",t),m&&u.addEventListener("loadend",m),d=()=>{if(!(h||!u)&&u.readyState===(XMLHttpRequest.DONE||4)){if(d&&u.removeEventListener("readystatechange",d),u.status>=200&&u.status<300||u.status===0&&(!mt()||nl())){const E=s?u.response:u.responseText;if(E!==null){try{e&&e(E,u)}catch(x){g(x)}return}}const A=et.DefaultRetryStrategy;if(A){const E=A(a,u,R);if(E!==-1){_(),u=new at,f=setTimeout(()=>T(R+1),E);return}}const y=new Fr("Error status: "+u.status+" "+u.statusText+" - Unable to load "+a,u);r&&r(y)}},u.addEventListener("readystatechange",d),u.send()}};T(0)};if(i&&i.enableSceneOffline&&!o.startsWith("blob:")){const u=d=>{d&&d.status>400?r&&r(d):c()},f=()=>{i&&i.loadFile(et.BaseUrl+o,d=>{!h&&e&&e(d),l.onCompleteObservable.notifyObservers(l)},t?d=>{!h&&t&&t(d)}:void 0,u,s)};i.open(f,u)}else c();return l},Lp=o=>{const{match:e,type:t}=ol(o);if(e)return t||void 0;const i=o.lastIndexOf(".");switch(o.substring(i+1).toLowerCase()){case"glb":return"model/gltf-binary";case"bin":return"application/octet-stream";case"gltf":return"model/gltf+json";case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"ktx":return"image/ktx";case"ktx2":return"image/ktx2";case"avif":return"image/avif";default:return}},nl=()=>typeof location<"u"&&location.protocol==="file:",al=o=>rl.test(o),ol=o=>{const e=rl.exec(o);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace(";base64,","")}};function Ha(o){return Xh(o.split(",")[1])}const hl=o=>Ua(o.split(",")[1]),ff=()=>{J._FileToolsLoadImage=jr,Dr.loadFile=ki,Qh.loadFile=ki};ff();let Ns;const df=(o,e,t,i,s,r,n,a,h,l)=>{Ns={DecodeBase64UrlToBinary:o,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:s,LoadFile:r,LoadImage:n,ReadFile:a,RequestFile:h,SetCorsBehavior:l},Object.defineProperty(Ns,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(c){t.DefaultRetryStrategy=c}}),Object.defineProperty(Ns,"BaseUrl",{get:function(){return t.BaseUrl},set:function(c){t.BaseUrl=c}}),Object.defineProperty(Ns,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(c){t.PreprocessUrl=c}}),Object.defineProperty(Ns,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(c){t.CorsBehavior=c}})};df(Ha,hl,et,al,nl,ki,jr,Hs,Ga,Wa);const wr={};function Ye(o,e){wr[o]=e}function Pi(o){return wr[o]}function Bp(o){for(const e in wr)if(o instanceof wr[e]&&!e.includes("Abstract"))return e;return"Unknown"}class ks{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=Pi(e);if(t)return t;W.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let r=0,n=i.length;r<n;r++)s=s[i[r]];return typeof s!="function"?null:s}}ks.RegisteredExternalClasses={};function Zr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{const e=Math.random()*16|0;return(o==="x"?e:e&3|8).toString(16)})}const Np={RandomId:Zr};function Xs(o){let e=1;do e*=2;while(e<o);return e===o}function wn(o,e,t){return o*(1-t)+e*t}function ll(o){const e=cl(o),t=Xa(o);return e-o>o-t?t:e}function cl(o){return o--,o|=o>>1,o|=o>>2,o|=o>>4,o|=o>>8,o|=o>>16,o++,o}function Xa(o){return o=o|o>>1,o=o|o>>2,o=o|o>>4,o=o|o>>8,o=o|o>>16,o-(o>>1)}function ni(o,e,t=2){let i;switch(t){case 1:i=Xa(o);break;case 2:i=ll(o);break;case 3:default:i=cl(o);break}return Math.min(i,e)}var ge;class fe{static get BaseUrl(){return et.BaseUrl}static set BaseUrl(e){et.BaseUrl=e}static get CleanUrl(){return et.CleanUrl}static set CleanUrl(e){et.CleanUrl=e}static IsAbsoluteUrl(e){return e.indexOf("//")===0?!0:e.indexOf("://")===-1||e.indexOf(".")===-1||e.indexOf("/")===-1||e.indexOf(":")>e.indexOf("/")?!1:e.indexOf("://")<e.indexOf(".")||e.indexOf("data:")===0||e.indexOf("blob:")===0}static set ScriptBaseUrl(e){et.ScriptBaseUrl=e}static get ScriptBaseUrl(){return et.ScriptBaseUrl}static set CDNBaseUrl(e){ge.ScriptBaseUrl=e,ge.AssetBaseUrl=e}static set ScriptPreprocessUrl(e){et.ScriptPreprocessUrl=e}static get ScriptPreprocessUrl(){return et.ScriptPreprocessUrl}static get DefaultRetryStrategy(){return et.DefaultRetryStrategy}static set DefaultRetryStrategy(e){et.DefaultRetryStrategy=e}static get CorsBehavior(){return et.CorsBehavior}static set CorsBehavior(e){et.CorsBehavior=e}static get UseFallbackTexture(){return ye.UseFallbackTexture}static set UseFallbackTexture(e){ye.UseFallbackTexture=e}static get RegisteredExternalClasses(){return ks.RegisteredExternalClasses}static set RegisteredExternalClasses(e){ks.RegisteredExternalClasses=e}static get fallbackTexture(){return ye.FallbackTexture}static set fallbackTexture(e){ye.FallbackTexture=e}static FetchToRef(e,t,i,s,r,n){const a=Math.abs(e)*i%i|0,h=Math.abs(t)*s%s|0,l=(a+h*i)*4;n.r=r[l]/255,n.g=r[l+1]/255,n.b=r[l+2]/255,n.a=r[l+3]/255}static Mix(e,t,i){return 0}static Instantiate(e){return ks.Instantiate(e)}static SetImmediate(e){Gs.SetImmediate(e)}static IsExponentOfTwo(e){return!0}static FloatRound(e){return Math.fround(e)}static GetFilename(e){const t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)}static GetFolderPath(e,t=!1){const i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)}static ToDegrees(e){return e*180/Math.PI}static ToRadians(e){return e*Math.PI/180}static SmoothAngleChange(e,t,i=.9){const s=this.ToRadians(e),r=this.ToRadians(t);return this.ToDegrees(Math.atan2((1-i)*Math.sin(r)+i*Math.sin(s),(1-i)*Math.cos(r)+i*Math.cos(s)))}static MakeArray(e,t){return t!==!0&&(e===void 0||e==null)?null:Array.isArray(e)?e:[e]}static GetPointerPrefix(e){return mt()&&!window.PointerEvent?"mouse":"pointer"}static SetCorsBehavior(e,t){Wa(e,t)}static SetReferrerPolicyBehavior(e,t){t.referrerPolicy=e}static get PreprocessUrl(){return et.PreprocessUrl}static set PreprocessUrl(e){et.PreprocessUrl=e}static LoadImage(e,t,i,s,r,n){return jr(e,t,i,s,r,n)}static LoadFile(e,t,i,s,r,n){return ki(e,t,i,s,r,n)}static async LoadFileAsync(e,t=!0){return await new Promise((i,s)=>{ki(e,r=>{i(r)},void 0,void 0,t,(r,n)=>{s(n)})})}static GetAssetUrl(e){if(!e)return"";if(ge.AssetBaseUrl&&e.startsWith(ge._DefaultAssetsUrl)){const t=ge.AssetBaseUrl.endsWith("/")?ge.AssetBaseUrl.slice(0,-1):ge.AssetBaseUrl;return e.replace(ge._DefaultAssetsUrl,t)}return e}static GetBabylonScriptURL(e,t){if(!e)return"";if(e.startsWith(ge._DefaultCdnUrl)){if(ge.ScriptBaseUrl){const i=ge.ScriptBaseUrl.endsWith("/")?ge.ScriptBaseUrl.slice(0,-1):ge.ScriptBaseUrl;e=e.replace(ge._DefaultCdnUrl,i)}else if(ge._CdnVersion){const i=`${ge._DefaultCdnUrl}/v${ge._CdnVersion}`;e.startsWith(i)||(e=e.replace(ge._DefaultCdnUrl,i))}}return e=ge.ScriptPreprocessUrl(e),t&&!ge.IsAbsoluteUrl(e)&&(e=ge.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=ge.GetBabylonScriptURL(e),ge.LoadScript(e,t,i)}static async LoadBabylonScriptAsync(e){return e=ge.GetBabylonScriptURL(e),await ge.LoadScriptAsync(e)}static _LoadScriptNative(e,t,i){_native&&ge.LoadFile(e,s=>{Function(s).apply(null),t&&t()},void 0,void 0,!1,(s,r)=>{i&&i("LoadScript Error",r)})}static _LoadScriptWeb(e,t,i,s,r=!1){if(typeof importScripts=="function"){try{importScripts(e),t&&t()}catch(h){i?.(`Unable to load script '${e}' in worker`,h)}return}else if(!mt()){i?.(`Cannot load script '${e}' outside of a window or a worker`);return}const n=document.getElementsByTagName("head")[0],a=document.createElement("script");r?(a.setAttribute("type","module"),a.innerText=e):(a.setAttribute("type","text/javascript"),a.setAttribute("src",e)),s&&(a.id=s),a.onload=()=>{t&&t()},a.onerror=h=>{i&&i(`Unable to load script '${e}'`,h)},n.appendChild(a)}static async LoadScriptAsync(e,t){return await new Promise((i,s)=>{this.LoadScript(e,()=>{i()},(r,n)=>{s(n||new Error(r))},t)})}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new z,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=n=>{t(n.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,s,r){return Hs(e,t,i,s,r)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,s){Na.DeepCopy(e,t,i,s)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){const s=t[i];e.addEventListener(s.name,s.handler,!1);try{window.parent&&window.parent.addEventListener(s.name,s.handler,!1)}catch{}}}static UnregisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){const s=t[i];e.removeEventListener(s.name,s.handler);try{e.parent&&e.parent.removeEventListener(s.name,s.handler)}catch{}}}static async DumpFramebuffer(e,t,i,s,r="image/png",n,a){throw pe("DumpTools")}static DumpData(e,t,i,s,r="image/png",n,a=!1,h=!1,l){throw pe("DumpTools")}static async DumpDataAsync(e,t,i,s="image/png",r,n=!1,a=!1,h){throw pe("DumpTools")}static _IsOffScreenCanvas(e){return e.convertToBlob!==void 0}static ToBlob(e,t,i="image/png",s){!ge._IsOffScreenCanvas(e)&&!e.toBlob&&(e.toBlob=function(r,n,a){setTimeout(()=>{const h=atob(this.toDataURL(n,a).split(",")[1]),l=h.length,c=new Uint8Array(l);for(let u=0;u<l;u++)c[u]=h.charCodeAt(u);r(new Blob([c]))})}),ge._IsOffScreenCanvas(e)?e.convertToBlob({type:i,quality:s}).then(r=>t(r)):e.toBlob(function(r){t(r)},i,s)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const i=new Date;t="screenshot_"+((i.getFullYear()+"-"+(i.getMonth()+1)).slice(2)+"-"+i.getDate()+"_"+i.getHours()+"-"+("0"+i.getMinutes()).slice(-2))+".png"}ge.Download(e,t)}else if(e&&typeof URL<"u"){const i=URL.createObjectURL(e),s=window.open("");if(!s)return;const r=s.document.createElement("img");r.onload=function(){URL.revokeObjectURL(i)},r.src=i,s.document.body.appendChild(r)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,r){if(typeof s=="string"||!t)this.ToBlob(e,function(n){n&&ge.DownloadBlob(n,s),t&&t("")},i,r);else if(t){if(ge._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:r}).then(a=>{const h=new FileReader;h.readAsDataURL(a),h.onloadend=()=>{const l=h.result;t(l)}});return}const n=e.toDataURL(i,r);t(n)}}static Download(e,t){if(typeof URL>"u")return;const i=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.style.display="none",s.href=i,s.download=t,s.addEventListener("click",()=>{s.parentElement&&s.parentElement.removeChild(s)}),s.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return typeof e[0]=="boolean"?e[0]:typeof e[1]=="boolean"?e[1]:!1}static CreateScreenshot(e,t,i,s,r="image/png",n=!1,a){throw pe("ScreenshotTools")}static async CreateScreenshotAsync(e,t,i,s="image/png",r){throw pe("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,a=!1,h,l=!1,c=!1,u=!0,f,d){throw pe("ScreenshotTools")}static async CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,a,h=!1,l=!1,c=!0,u,f){throw pe("ScreenshotTools")}static RandomId(){return Zr()}static IsBase64(e){return al(e)}static DecodeBase64(e){return Ha(e)}static get errorsCount(){return W.errorsCount}static Log(e){W.Log(e)}static Warn(e){W.Warn(e)}static Error(e){W.Error(e)}static get LogCache(){return W.LogCache}static ClearLogCache(){W.ClearLogCache()}static set LogLevels(e){W.LogLevels=e}static set PerformanceLogLevel(e){if((e&ge.PerformanceUserMarkLogLevel)===ge.PerformanceUserMarkLogLevel){_native?.enablePerformanceLogging?(_native.enablePerformanceLogging(1),ge.StartPerformanceCounter=ge._StartMarkNative,ge.EndPerformanceCounter=ge._EndMarkNative):(ge.StartPerformanceCounter=ge._StartUserMark,ge.EndPerformanceCounter=ge._EndUserMark);return}if((e&ge.PerformanceConsoleLogLevel)===ge.PerformanceConsoleLogLevel){_native?.enablePerformanceLogging?(_native.enablePerformanceLogging(2),ge.StartPerformanceCounter=ge._StartMarkNative,ge.EndPerformanceCounter=ge._EndMarkNative):(ge.StartPerformanceCounter=ge._StartPerformanceConsole,ge.EndPerformanceCounter=ge._EndPerformanceConsole);return}ge.StartPerformanceCounter=ge._StartPerformanceCounterDisabled,ge.EndPerformanceCounter=ge._EndPerformanceCounterDisabled,_native?.disablePerformanceLogging?.()}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!ge._Performance){if(!mt())return;ge._Performance=window.performance}!t||!ge._Performance.mark||ge._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!ge._Performance.mark||(ge._Performance.mark(e+"-End"),ge._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(ge._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(ge._EndUserMark(e,t),console.timeEnd(e))}static _StartMarkNative(e,t=!0){if(t&&_native?.startPerformanceCounter)if(ge._NativePerformanceCounterHandles.has(e))ge.Warn(`Performance counter with name ${e} is already started.`);else{const i=_native.startPerformanceCounter(e);ge._NativePerformanceCounterHandles.set(e,i)}}static _EndMarkNative(e,t=!0){if(t&&_native?.endPerformanceCounter){const i=ge._NativePerformanceCounterHandles.get(e);i?(_native.endPerformanceCounter(i),ge._NativePerformanceCounterHandles.delete(e)):ge.Warn(`Performance counter with name ${e} was not started.`)}}static get Now(){return Si.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,s=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,s=r.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(s!=null?s+".":"")+i:null}static async DelayAsync(e){await new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return Ji()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}}ge=fe;fe.AssetBaseUrl="";fe.UseCustomRequestHeaders=!1;fe.CustomRequestHeaders=at.CustomRequestHeaders;fe.GetDOMTextContent=Ba;fe._DefaultCdnUrl="https://cdn.babylonjs.com";fe._CdnVersion="8.56.2";fe._DefaultAssetsUrl="https://assets.babylonjs.com/core";fe.LoadScript=typeof _native>"u"?ge._LoadScriptWeb:ge._LoadScriptNative;fe.GetAbsoluteUrl=typeof document=="object"?o=>{const e=document.createElement("a");return e.href=o,e.href}:typeof URL=="function"&&typeof location=="object"?o=>new URL(o,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")};fe.NoneLogLevel=W.NoneLogLevel;fe.MessageLogLevel=W.MessageLogLevel;fe.WarningLogLevel=W.WarningLogLevel;fe.ErrorLogLevel=W.ErrorLogLevel;fe.AllLogLevel=W.AllLogLevel;fe.IsWindowObjectExist=mt;fe.PerformanceNoneLogLevel=0;fe.PerformanceUserMarkLogLevel=1;fe.PerformanceConsoleLogLevel=2;fe._NativePerformanceCounterHandles=new Map;fe.StartPerformanceCounter=ge._StartPerformanceCounterDisabled;fe.EndPerformanceCounter=ge._EndPerformanceCounterDisabled;function Up(o,e){return t=>{t.__bjsclassName__=o,t.__bjsmoduleName__=e??null}}class Lr{constructor(e,t,i,s=0){this.iterations=e,this.index=s-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())}breakLoop(){this._done=!0,this._successCallback()}static Run(e,t,i,s=0){const r=new Lr(e,t,i,s);return r.executeNext(),r}static SyncAsyncForLoop(e,t,i,s,r,n=0){return Lr.Run(Math.ceil(e/t),a=>{r&&r()?a.breakLoop():setTimeout(()=>{for(let h=0;h<t;++h){const l=a.index*t+h;if(l>=e)break;if(i(l),r&&r()){a.breakLoop();break}}a.executeNext()},n)},s)}}fe.Mix=wn;fe.IsExponentOfTwo=Xs;ye.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";const ul=1/2.2,vr=2.2,ot=(1+Math.sqrt(5))/2;let Ke=.001;function yi(o,e){const t=[];for(let i=0;i<o;++i)t.push(e());return t}function Ki(o,e){return yi(o,e)}function _f(o,e,t){const i=o[e];if(typeof i!="function")return null;const s=function(){const r=o.length,n=s.previous.apply(o,arguments);return t(e,r),n};return i.next=s,s.previous=i,o[e]=s,()=>{const r=s.previous;if(!r)return;const n=s.next;n?(r.next=n,n.previous=r):(r.next=void 0,o[e]=r),s.next=void 0,s.previous=void 0}}const gf=["push","splice","pop","shift","unshift"];function fl(o,e){const t=gf.map(i=>_f(o,i,e));return()=>{for(const i of t)i?.()}}function pf(o){return parseInt(o.toString().replace(/\W/g,""))}function Ue(o,e,t=1401298e-51){return Math.abs(o-e)<=t}function mf(o,e,t,i=1401298e-51){return o<e-i||o>t+i}function tt(o,e){return o===e?o:Math.random()*(e-o)+o}function Br(o,e,t){return o+(e-o)*t}function Tf(o,e,t){let i=qr(e-o,360);return i>180&&(i-=360),o+i*ke(t)}function Ef(o,e,t){let i;return o!=e?i=ke((t-o)/(e-o)):i=0,i}function xf(o,e,t,i,s){const r=s*s,n=s*r,a=2*n-3*r+1,h=-2*n+3*r,l=n-2*r+s,c=n-r;return o*a+t*h+e*l+i*c}function bf(o,e,t,i,s){const r=s*s;return(r-s)*6*o+(3*r-4*s+1)*e+(-r+s)*6*t+(3*r-2*s)*i}function ke(o,e=0,t=1){return Math.min(t,Math.max(e,o))}function dl(o){return o-=Math.PI*2*Math.floor((o+Math.PI)/(Math.PI*2)),o}function ii(o){const e=o.toString(16);return o<=15?("0"+e).toUpperCase():e.toUpperCase()}function Ka(o){if(Math.log2)return Math.floor(Math.log2(o));if(o<0)return NaN;if(o===0)return-1/0;let e=0;if(o<1){for(;o<1;)e++,o=o*2;e=-e}else if(o>1)for(;o>1;)e++,o=Math.floor(o/2);return e}function qr(o,e){return o-Math.floor(o/e)*e}function Rf(o,e,t){return(o-e)/(t-e)}function Sf(o,e,t){return o*(t-e)+e}function _l(o,e){let t=qr(e-o,360);return t>180&&(t-=360),t}function yf(o,e){const t=qr(o,e*2);return e-Math.abs(t-e)}function Af(o,e,t){let i=ke(t);return i=-2*i*i*i+3*i*i,e*i+o*(1-i)}function gl(o,e,t){let i;return Math.abs(e-o)<=t?i=e:i=o+Math.sign(e-o)*t,i}function Mf(o,e,t){const i=_l(o,e);let s;return-t<i&&i<t?s=e:(e=o+i,s=gl(o,e,t)),s}function Pf(o,e,t){return(o-e)/(t-e)}function If(o,e,t){return(t-e)*o+e}function Nr(o,e){const t=o%e;return t===0?e:Nr(e,t)}const kp=Object.freeze(Object.defineProperty({__proto__:null,Clamp:ke,DeltaAngle:_l,Denormalize:Sf,ExtractAsInt:pf,Hermite:xf,Hermite1stDerivative:bf,HighestCommonFactor:Nr,ILog2:Ka,InverseLerp:Ef,Lerp:Br,LerpAngle:Tf,MoveTowards:gl,MoveTowardsAngle:Mf,Normalize:Rf,NormalizeRadians:dl,OutsideRange:mf,PercentToRange:If,PingPong:yf,RandomRange:tt,RangeToPercent:Pf,Repeat:qr,SmoothStep:Af,ToHex:ii,WithinEpsilon:Ue},Symbol.toStringTag,{value:"Module"}));class Ya{}Ya._UpdateFlagSeed=0;function ja(o,e,t,i,s,r,n,a,h,l,c,u,f,d,_,m,g){const T=o.asArray();T[0]=e,T[1]=t,T[2]=i,T[3]=s,T[4]=r,T[5]=n,T[6]=a,T[7]=h,T[8]=l,T[9]=c,T[10]=u,T[11]=f,T[12]=d,T[13]=_,T[14]=m,T[15]=g,Qr(o)}function Qr(o){o.updateFlag=Ya._UpdateFlagSeed++}function Vp(o){ja(o,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)}function zp(o,e,t,i){ja(i,1,0,0,0,0,1,0,0,0,0,1,0,o,e,t,1)}function Wp(o,e,t,i){ja(i,o,0,0,0,0,e,0,0,0,0,t,0,0,0,0,1)}function pl(o,e,t,i=0){const s=o.asArray(),r=e.asArray(),n=s[0],a=s[1],h=s[2],l=s[3],c=s[4],u=s[5],f=s[6],d=s[7],_=s[8],m=s[9],g=s[10],T=s[11],R=s[12],A=s[13],y=s[14],E=s[15],x=r[0],b=r[1],P=r[2],v=r[3],O=r[4],k=r[5],Y=r[6],q=r[7],L=r[8],ee=r[9],Q=r[10],se=r[11],le=r[12],H=r[13],K=r[14],w=r[15];t[i]=n*x+a*O+h*L+l*le,t[i+1]=n*b+a*k+h*ee+l*H,t[i+2]=n*P+a*Y+h*Q+l*K,t[i+3]=n*v+a*q+h*se+l*w,t[i+4]=c*x+u*O+f*L+d*le,t[i+5]=c*b+u*k+f*ee+d*H,t[i+6]=c*P+u*Y+f*Q+d*K,t[i+7]=c*v+u*q+f*se+d*w,t[i+8]=_*x+m*O+g*L+T*le,t[i+9]=_*b+m*k+g*ee+T*H,t[i+10]=_*P+m*Y+g*Q+T*K,t[i+11]=_*v+m*q+g*se+T*w,t[i+12]=R*x+A*O+y*L+E*le,t[i+13]=R*b+A*k+y*ee+E*H,t[i+14]=R*P+A*Y+y*Q+E*K,t[i+15]=R*v+A*q+y*se+E*w}function ms(o,e,t,i=0){pl(o,e,t.asArray(),i),Qr(t)}function Gp(o,e){ml(o,e.asArray()),Qr(e)}function ml(o,e,t=0){const i=o.asArray();e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15]}function Ur(o,e){const t=Tl(o,e.asArray());return t&&Qr(e),t}function Tl(o,e){const t=o.asArray(),i=t[0],s=t[1],r=t[2],n=t[3],a=t[4],h=t[5],l=t[6],c=t[7],u=t[8],f=t[9],d=t[10],_=t[11],m=t[12],g=t[13],T=t[14],R=t[15],A=d*R-T*_,y=f*R-g*_,E=f*T-g*d,x=u*R-m*_,b=u*T-d*m,P=u*g-m*f,v=+(h*A-l*y+c*E),O=-(a*A-l*x+c*b),k=+(a*y-h*x+c*P),Y=-(a*E-h*b+l*P),q=i*v+s*O+r*k+n*Y;if(q===0)return!1;const L=1/q,ee=l*R-T*c,Q=h*R-g*c,se=h*T-g*l,le=a*R-m*c,H=a*T-m*l,K=a*g-m*h,w=l*_-d*c,B=h*_-f*c,N=h*d-f*l,X=a*_-u*c,Ee=a*d-u*l,ae=a*f-u*h,Se=-(s*A-r*y+n*E),We=+(i*A-r*x+n*b),nt=-(i*y-s*x+n*P),ct=+(i*E-s*b+r*P),Ge=+(s*ee-r*Q+n*se),_e=-(i*ee-r*le+n*H),Fe=+(i*Q-s*le+n*K),Xe=-(i*se-s*H+r*K),Ae=-(s*w-r*B+n*N),$e=+(i*w-r*X+n*Ee),zt=-(i*B-s*X+n*ae),bt=+(i*N-s*Ee+r*ae);return e[0]=v*L,e[1]=Se*L,e[2]=Ge*L,e[3]=Ae*L,e[4]=O*L,e[5]=We*L,e[6]=_e*L,e[7]=$e*L,e[8]=k*L,e[9]=nt*L,e[10]=Fe*L,e[11]=zt*L,e[12]=Y*L,e[13]=ct*L,e[14]=Xe*L,e[15]=bt*L,!0}const vt=o=>parseInt(o.toString().replace(/\W/g,""));class ie{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){const e=vt(this.x),t=vt(this.y);let i=e;return i=i*397^t,i}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return ie.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new ie(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new ie(this.x+e.x,this.y+e.y)}subtract(e){return new ie(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new ie(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new ie(this.x*e,this.y*t)}divide(e){return new ie(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new ie(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.x=this.x-e,i.y=this.y-t,i}negate(){return new ie(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new ie(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=Ke){return e&&Ue(this.x,e.x,t)&&Ue(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new ie(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new ie(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotate(e){return this.rotateToRef(e,new ie)}rotateToRef(e,t){const i=Math.cos(e),s=Math.sin(e);return t.x=i*this.x-s*this.y,t.y=s*this.x+i*this.y,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new ie;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new ie(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new ie(0,0)}static One(){return new ie(1,1)}static Random(e=0,t=1){return new ie(tt(e,t),tt(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(tt(e,t),tt(e,t))}static get ZeroReadOnly(){return ie._ZeroReadOnly}static FromArray(e,t=0){return new ie(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,s,r){const n=r*r,a=r*n,h=.5*(2*t.x+(-e.x+i.x)*r+(2*e.x-5*t.x+4*i.x-s.x)*n+(-e.x+3*t.x-3*i.x+s.x)*a),l=.5*(2*t.y+(-e.y+i.y)*r+(2*e.y-5*t.y+4*i.y-s.y)*n+(-e.y+3*t.y-3*i.y+s.y)*a);return new ie(h,l)}static ClampToRef(e,t,i,s){return s.x=ke(e.x,t.x,i.x),s.y=ke(e.y,t.y,i.y),s}static Clamp(e,t,i){const s=ke(e.x,t.x,i.x),r=ke(e.y,t.y,i.y);return new ie(s,r)}static Hermite(e,t,i,s,r){const n=r*r,a=r*n,h=2*a-3*n+1,l=-2*a+3*n,c=a-2*n+r,u=a-n,f=e.x*h+i.x*l+t.x*c+s.x*u,d=e.y*h+i.y*l+t.y*c+s.y*u;return new ie(f,d)}static Hermite1stDerivative(e,t,i,s,r){return this.Hermite1stDerivativeToRef(e,t,i,s,r,new ie)}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;return n.x=(a-r)*6*e.x+(3*a-4*r+1)*t.x+(-a+r)*6*i.x+(3*a-2*r)*s.x,n.y=(a-r)*6*e.y+(3*a-4*r+1)*t.y+(-a+r)*6*i.y+(3*a-2*r)*s.y,n}static Lerp(e,t,i){return ie.LerpToRef(e,t,i,new ie)}static LerpToRef(e,t,i,s){return s.x=e.x+(t.x-e.x)*i,s.y=e.y+(t.y-e.y)*i,s}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return ie.NormalizeToRef(e,new ie)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.x<t.x?e.x:t.x,s=e.y<t.y?e.y:t.y;return new ie(i,s)}static Maximize(e,t){const i=e.x>t.x?e.x:t.x,s=e.y>t.y?e.y:t.y;return new ie(i,s)}static Transform(e,t){return ie.TransformToRef(e,t,new ie)}static TransformToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+s[12],n=e.x*s[1]+e.y*s[5]+s[13];return i.x=r,i.y=n,i}static PointInTriangle(e,t,i,s){const r=.5*(-i.y*s.x+t.y*(-i.x+s.x)+t.x*(i.y-s.y)+i.x*s.y),n=r<0?-1:1,a=(t.y*s.x-t.x*s.y+(s.y-t.y)*e.x+(t.x-s.x)*e.y)*n,h=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*n;return a>0&&h>0&&a+h<2*r*n}static Distance(e,t){return Math.sqrt(ie.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y;return i*i+s*s}static Center(e,t){return ie.CenterToRef(e,t,new ie)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const s=ie.DistanceSquared(t,i);if(s===0)return ie.Distance(e,t);const r=i.subtract(t),n=Math.max(0,Math.min(1,ie.Dot(e.subtract(t),r)/s)),a=t.add(r.multiplyByFloats(n,n));return ie.Distance(e,a)}}ie._V8PerformanceHack=new ie(.5,.5);ie._ZeroReadOnly=ie.Zero();Object.defineProperties(ie.prototype,{dimension:{value:[2]},rank:{value:1}});class p{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){const e=vt(this._x),t=vt(this._y),i=vt(this._z);let s=e;return s=s*397^t,s=s*397^i,s}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return p.FromArrayToRef(e,t,this),this}toQuaternion(){return re.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new p(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._isDirty=!0,t}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new p(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new p(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,s){return s._x=this._x-e,s._y=this._y-t,s._z=this._z-i,s._isDirty=!0,s}negate(){return new p(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e._x=this._x*-1,e._y=this._y*-1,e._z=this._z*-1,e._isDirty=!0,e}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new p(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._isDirty=!0,t}getNormalToRef(e){const t=this.length();let i=Math.acos(this._y/t);const s=Math.atan2(this._z,this._x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const r=t*Math.sin(i)*Math.cos(s),n=t*Math.cos(i),a=t*Math.sin(i)*Math.sin(s);return e.set(r,n,a),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,r=this._z,n=e._x,a=e._y,h=e._z,l=e._w,c=2*(a*r-h*s),u=2*(h*i-n*r),f=2*(n*s-a*i);return t._x=i+l*c+a*f-h*u,t._y=s+l*u+h*c-n*f,t._z=r+l*f+n*u-a*c,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new p)}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._isDirty=!0,t}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new p)}projectOnPlaneToRef(e,t,i){const s=e.normal,r=e.d,n=ne.Vector3[0];this.subtractToRef(t,n),n.normalize();const a=p.Dot(n,s);if(Math.abs(a)<1e-10)i.setAll(1/0);else{const h=-(p.Dot(t,s)+r)/a,l=n.scaleInPlace(h);t.addToRef(l,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=Ke){return e&&Ue(this._x,e._x,t)&&Ue(this._y,e._y,t)&&Ue(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t._x=this._x*e._x,t._y=this._y*e._y,t._z=this._z*e._z,t._isDirty=!0,t}multiplyByFloats(e,t,i){return new p(this._x*e,this._y*t,this._z*i)}divide(e){return new p(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t._x=this._x/e._x,t._y=this._y/e._y,t._z=this._z/e._z,t._isDirty=!0,t}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return e<this._x&&(this.x=e),t<this._y&&(this.y=t),i<this._z&&(this.z=i),this}maximizeInPlaceFromFloats(e,t,i){return e>this._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!Ue(t,i,e))return!0;const s=Math.abs(this._z);return!Ue(t,s,e)||!Ue(i,s,e)}get isNonUniform(){const e=Math.abs(this._x),t=Math.abs(this._y);if(e!==t)return!0;const i=Math.abs(this._z);return e!==i}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new p(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fractToRef(e){return e._x=this._x-Math.floor(this._x),e._y=this._y-Math.floor(this._y),e._z=this._z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new p(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z===0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if(e=e.toLowerCase(),e==="xyz")return this;const t=ne.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(ne.Matrix[0]),p.TransformCoordinatesToRef(this,ne.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,ne.Vector3[0]),ne.Vector3[0].rotateByQuaternionToRef(e,ne.Vector3[0]),t.addToRef(ne.Vector3[0],i),i}cross(e){return p.CrossToRef(this,e,new p)}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new p)}normalizeToRef(e){const t=this.length();return t===0||t===1?(e._x=this._x,e._y=this._y,e._z=this._z,e._isDirty=!0,e):this.scaleToRef(1/t,e)}clone(){return new p(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,s){const r=p.Dot(e,i),n=p.Dot(t,i);return(r-s)/(r-n)}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(ne.Vector3[1]),r=t.normalizeToRef(ne.Vector3[2]);let n=p.Dot(s,r);n=ke(n,-1,1);const a=Math.acos(n),h=ne.Vector3[3];return p.CrossToRef(s,r,h),p.Dot(h,i)>0?isNaN(a)?0:a:isNaN(a)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){ne.Vector3[0].copyFrom(e);const s=ne.Vector3[0];ne.Vector3[1].copyFrom(t);const r=ne.Vector3[1];ne.Vector3[2].copyFrom(i);const n=ne.Vector3[2],a=ne.Vector3[3],h=ne.Vector3[4];s.normalize(),r.normalize(),n.normalize(),p.CrossToRef(n,s,a),p.CrossToRef(a,n,h);const l=Math.atan2(p.Dot(r,a),p.Dot(r,h));return dl(l)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=U.Vector3[0];return t.subtractToRef(e,s),i._y=Math.atan2(s.x,s.z)||0,i._x=Math.atan2(Math.sqrt(s.x**2+s.z**2),s.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=p.Zero();return p.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=ke(i,0,1);const r=ne.Vector3[0],n=ne.Vector3[1];r.copyFrom(e);const a=r.length();r.normalizeFromLength(a),n.copyFrom(t);const h=n.length();n.normalizeFromLength(h);const l=p.Dot(r,n);let c,u;if(l<1-Ke){const f=Math.acos(l),d=1/Math.sin(f);c=Math.sin((1-i)*f)*d,u=Math.sin(i*f)*d}else c=1-i,u=i;return r.scaleInPlace(c),n.scaleInPlace(u),s.copyFrom(r).addInPlace(n),s.scaleInPlace(Br(a,h,i)),s}static SmoothToRef(e,t,i,s,r){return p.SlerpToRef(e,t,s===0?1:i/s,r),r}static FromArray(e,t=0){return new p(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return p.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return p.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new p(0,0,0)}static One(){return new p(1,1,1)}static Up(){return new p(0,1,0)}static get UpReadOnly(){return p._UpReadOnly}static get DownReadOnly(){return p._DownReadOnly}static get RightReadOnly(){return p._RightReadOnly}static get LeftReadOnly(){return p._LeftReadOnly}static get LeftHandedForwardReadOnly(){return p._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return p._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return p._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return p._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return p._ZeroReadOnly}static get OneReadOnly(){return p._OneReadOnly}static Down(){return new p(0,-1,0)}static Forward(e=!1){return new p(0,0,e?-1:1)}static Backward(e=!1){return new p(0,0,e?1:-1)}static Right(){return new p(1,0,0)}static Left(){return new p(-1,0,0)}static Random(e=0,t=1){return new p(tt(e,t),tt(e,t),tt(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(tt(e,t),tt(e,t),tt(e,t))}static TransformCoordinates(e,t){const i=p.Zero();return p.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return p.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,a=e*n[0]+t*n[4]+i*n[8]+n[12],h=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],c=1/(e*n[3]+t*n[7]+i*n[11]+n[15]);return r._x=a*c,r._y=h*c,r._z=l*c,r._isDirty=!0,r}static TransformNormal(e,t){const i=p.Zero();return p.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,s,r){const n=s.m;return r._x=e*n[0]+t*n[4]+i*n[8],r._y=e*n[1]+t*n[5]+i*n[9],r._z=e*n[2]+t*n[6]+i*n[10],r._isDirty=!0,r}static CatmullRom(e,t,i,s,r){const n=r*r,a=r*n,h=.5*(2*t._x+(-e._x+i._x)*r+(2*e._x-5*t._x+4*i._x-s._x)*n+(-e._x+3*t._x-3*i._x+s._x)*a),l=.5*(2*t._y+(-e._y+i._y)*r+(2*e._y-5*t._y+4*i._y-s._y)*n+(-e._y+3*t._y-3*i._y+s._y)*a),c=.5*(2*t._z+(-e._z+i._z)*r+(2*e._z-5*t._z+4*i._z-s._z)*n+(-e._z+3*t._z-3*i._z+s._z)*a);return new p(h,l,c)}static Clamp(e,t,i){const s=new p;return p.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let r=e._x;r=r>i._x?i._x:r,r=r<t._x?t._x:r;let n=e._y;n=n>i._y?i._y:n,n=n<t._y?t._y:n;let a=e._z;return a=a>i._z?i._z:a,a=a<t._z?t._z:a,s.copyFromFloats(r,n,a),s}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static Hermite(e,t,i,s,r){const n=r*r,a=r*n,h=2*a-3*n+1,l=-2*a+3*n,c=a-2*n+r,u=a-n,f=e._x*h+i._x*l+t._x*c+s._x*u,d=e._y*h+i._y*l+t._y*c+s._y*u,_=e._z*h+i._z*l+t._z*c+s._z*u;return new p(f,d,_)}static Hermite1stDerivative(e,t,i,s,r){const n=new p;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;return n._x=(a-r)*6*e._x+(3*a-4*r+1)*t._x+(-a+r)*6*i._x+(3*a-2*r)*s._x,n._y=(a-r)*6*e._y+(3*a-4*r+1)*t._y+(-a+r)*6*i._y+(3*a-2*r)*s._y,n._z=(a-r)*6*e._z+(3*a-4*r+1)*t._z+(-a+r)*6*i._z+(3*a-2*r)*s._z,n._isDirty=!0,n}static Lerp(e,t,i){const s=new p(0,0,0);return p.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){return s._x=e._x+(t._x-e._x)*i,s._y=e._y+(t._y-e._y)*i,s._z=e._z+(t._z-e._z)*i,s._isDirty=!0,s}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z}static Cross(e,t){const i=new p;return p.CrossToRef(e,t,i),i}static CrossToRef(e,t,i){const s=e._y*t._z-e._z*t._y,r=e._z*t._x-e._x*t._z,n=e._x*t._y-e._y*t._x;return i.copyFromFloats(s,r,n),i}static Normalize(e){const t=p.Zero();return p.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Project(e,t,i,s){const r=new p;return p.ProjectToRef(e,t,i,s,r),r}static ProjectToRef(e,t,i,s,r){const n=s.width,a=s.height,h=s.x,l=s.y,c=ne.Matrix[1],u=ye.LastCreatedEngine?.isNDCHalfZRange,f=u?1:.5,d=u?0:.5;D.FromValuesToRef(n/2,0,0,0,0,-a/2,0,0,0,0,f,0,h+n/2,a/2+l,d,1,c);const _=ne.Matrix[0];return t.multiplyToRef(i,_),_.multiplyToRef(c,_),p.TransformCoordinatesToRef(e,_,r),r}static Reflect(e,t){return this.ReflectToRef(e,t,new p)}static ReflectToRef(e,t,i){const s=U.Vector3[0];return s.copyFrom(t).scaleInPlace(2*p.Dot(e,t)),i.copyFrom(e).subtractInPlace(s)}static UnprojectFromTransform(e,t,i,s,r){return this.Unproject(e,t,i,s,r,D.IdentityReadOnly)}static Unproject(e,t,i,s,r,n){const a=new p;return p.UnprojectToRef(e,t,i,s,r,n,a),a}static UnprojectToRef(e,t,i,s,r,n,a){return p.UnprojectFloatsToRef(e._x,e._y,e._z,t,i,s,r,n,a),a}static UnprojectFloatsToRef(e,t,i,s,r,n,a,h,l){const c=ne.Matrix[0];n.multiplyToRef(a,c),c.multiplyToRef(h,c),c.invert();const u=ne.Vector3[0];return u.x=e/s*2-1,u.y=-(t/r*2-1),ye.LastCreatedEngine?.isNDCHalfZRange?u.z=i:u.z=2*i-1,p.TransformCoordinatesToRef(u,c,l),l}static Minimize(e,t){const i=new p;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new p;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(p.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e._x-t._x,s=e._y-t._y,r=e._z-t._z;return i*i+s*s+r*r}static ProjectOnTriangleToRef(e,t,i,s,r){const n=ne.Vector3[0],a=ne.Vector3[1],h=ne.Vector3[2],l=ne.Vector3[3],c=ne.Vector3[4];i.subtractToRef(t,n),s.subtractToRef(t,a),s.subtractToRef(i,h);const u=n.length(),f=a.length(),d=h.length();if(u<Ke||f<Ke||d<Ke)return r.copyFrom(t),p.Distance(e,t);e.subtractToRef(t,c),p.CrossToRef(n,a,l);const _=l.length();if(_<Ke)return r.copyFrom(t),p.Distance(e,t);l.normalizeFromLength(_);let m=c.length();if(m<Ke)return r.copyFrom(t),0;c.normalizeFromLength(m);const g=p.Dot(l,c),T=ne.Vector3[5],R=ne.Vector3[6];T.copyFrom(l).scaleInPlace(-m*g),R.copyFrom(e).addInPlace(T);const A=ne.Vector3[4],y=ne.Vector3[5],E=ne.Vector3[7],x=ne.Vector3[8];A.copyFrom(n).scaleInPlace(1/u),x.copyFrom(a).scaleInPlace(1/f),A.addInPlace(x).scaleInPlace(-1),y.copyFrom(n).scaleInPlace(-1/u),x.copyFrom(h).scaleInPlace(1/d),y.addInPlace(x).scaleInPlace(-1),E.copyFrom(h).scaleInPlace(-1/d),x.copyFrom(a).scaleInPlace(-1/f),E.addInPlace(x).scaleInPlace(-1);const b=ne.Vector3[9];let P;b.copyFrom(R).subtractInPlace(t),p.CrossToRef(A,b,x),P=p.Dot(x,l);const v=P;b.copyFrom(R).subtractInPlace(i),p.CrossToRef(y,b,x),P=p.Dot(x,l);const O=P;b.copyFrom(R).subtractInPlace(s),p.CrossToRef(E,b,x),P=p.Dot(x,l);const k=P,Y=ne.Vector3[10];let q,L;v>0&&O<0?(Y.copyFrom(n),q=t,L=i):O>0&&k<0?(Y.copyFrom(h),q=i,L=s):(Y.copyFrom(a).scaleInPlace(-1),q=s,L=t);const ee=ne.Vector3[9],Q=ne.Vector3[4];if(q.subtractToRef(R,x),L.subtractToRef(R,ee),p.CrossToRef(x,ee,Q),!(p.Dot(Q,l)<0))return r.copyFrom(R),Math.abs(m*g);const le=ne.Vector3[5];p.CrossToRef(Y,Q,le),le.normalize();const H=ne.Vector3[9];H.copyFrom(q).subtractInPlace(R);const K=H.length();if(K<Ke)return r.copyFrom(q),p.Distance(e,q);H.normalizeFromLength(K);const w=p.Dot(le,H),B=ne.Vector3[7];B.copyFrom(R).addInPlace(le.scaleInPlace(K*w)),x.copyFrom(B).subtractInPlace(q),m=Y.length(),Y.normalizeFromLength(m);let N=p.Dot(x,Y)/Math.max(m,Ke);return N=ke(N,0,1),B.copyFrom(q).addInPlace(Y.scaleInPlace(N*m)),r.copyFrom(B),p.Distance(e,B)}static Center(e,t){return p.CenterToRef(e,t,p.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e._x+t._x)/2,(e._y+t._y)/2,(e._z+t._z)/2)}static RotationFromAxis(e,t,i){const s=new p;return p.RotationFromAxisToRef(e,t,i,s),s}static RotationFromAxisToRef(e,t,i,s){const r=ne.Quaternion[0];return re.RotationQuaternionFromAxisToRef(e,t,i,r),r.toEulerAnglesToRef(s),s}}p._V8PerformanceHack=new p(.5,.5,.5);p._UpReadOnly=p.Up();p._DownReadOnly=p.Down();p._LeftHandedForwardReadOnly=p.Forward(!1);p._RightHandedForwardReadOnly=p.Forward(!0);p._LeftHandedBackwardReadOnly=p.Backward(!1);p._RightHandedBackwardReadOnly=p.Backward(!0);p._RightReadOnly=p.Right();p._LeftReadOnly=p.Left();p._ZeroReadOnly=p.Zero();p._OneReadOnly=p.One();Object.defineProperties(p.prototype,{dimension:{value:[3]},rank:{value:1}});class Me{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,s=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Vector4"}getHashCode(){const e=vt(this._x),t=vt(this._y),i=vt(this._z),s=vt(this._w);let r=e;return r=r*397^t,r=r*397^i,r=r*397^s,r}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t){return t===void 0&&(t=0),e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return Me.FromArrayToRef(e,t,this),this}addInPlace(e){return this.x+=e._x,this.y+=e._y,this.z+=e._z,this.w+=e._w,this}addInPlaceFromFloats(e,t,i,s){return this.x+=e,this.y+=t,this.z+=i,this.w+=s,this}add(e){return new Me(this._x+e.x,this._y+e.y,this._z+e.z,this._w+e.w)}addToRef(e,t){return t.x=this._x+e.x,t.y=this._y+e.y,t.z=this._z+e.z,t.w=this._w+e.w,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subtract(e){return new Me(this._x-e.x,this._y-e.y,this._z-e.z,this._w-e.w)}subtractToRef(e,t){return t.x=this._x-e.x,t.y=this._y-e.y,t.z=this._z-e.z,t.w=this._w-e.w,t}subtractFromFloats(e,t,i,s){return new Me(this._x-e,this._y-t,this._z-i,this._w-s)}subtractFromFloatsToRef(e,t,i,s,r){return r.x=this._x-e,r.y=this._y-t,r.z=this._z-i,r.w=this._w-s,r}negate(){return new Me(-this._x,-this._y,-this._z,-this._w)}negateInPlace(){return this.x*=-1,this.y*=-1,this.z*=-1,this.w*=-1,this}negateToRef(e){return e.x=-this._x,e.y=-this._y,e.z=-this._z,e.w=-this._w,e}scaleInPlace(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}scale(e){return new Me(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t.x=this._x*e,t.y=this._y*e,t.z=this._z*e,t.w=this._w*e,t}scaleAndAddToRef(e,t){return t.x+=this._x*e,t.y+=this._y*e,t.z+=this._z*e,t.w+=this._w*e,t}equals(e){return e&&this._x===e.x&&this._y===e.y&&this._z===e.z&&this._w===e.w}equalsWithEpsilon(e,t=Ke){return e&&Ue(this._x,e.x,t)&&Ue(this._y,e.y,t)&&Ue(this._z,e.z,t)&&Ue(this._w,e.w,t)}equalsToFloats(e,t,i,s){return this._x===e&&this._y===t&&this._z===i&&this._w===s}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiply(e){return new Me(this._x*e.x,this._y*e.y,this._z*e.z,this._w*e.w)}multiplyToRef(e,t){return t.x=this._x*e.x,t.y=this._y*e.y,t.z=this._z*e.z,t.w=this._w*e.w,t}multiplyByFloats(e,t,i,s){return new Me(this._x*e,this._y*t,this._z*i,this._w*s)}divide(e){return new Me(this._x/e.x,this._y/e.y,this._z/e.z,this._w/e.w)}divideToRef(e,t){return t.x=this._x/e.x,t.y=this._y/e.y,t.z=this._z/e.z,t.w=this._w/e.w,t}divideInPlace(e){return this.divideToRef(e,this)}minimizeInPlace(e){return e.x<this._x&&(this.x=e.x),e.y<this._y&&(this.y=e.y),e.z<this._z&&(this.z=e.z),e.w<this._w&&(this.w=e.w),this}maximizeInPlace(e){return e.x>this._x&&(this.x=e.x),e.y>this._y&&(this.y=e.y),e.z>this._z&&(this.z=e.z),e.w>this._w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,s){return this.x=Math.min(e,this._x),this.y=Math.min(t,this._y),this.z=Math.min(i,this._z),this.w=Math.min(s,this._w),this}maximizeInPlaceFromFloats(e,t,i,s){return this.x=Math.max(e,this._x),this.y=Math.max(t,this._y),this.z=Math.max(i,this._z),this.w=Math.max(s,this._w),this}floorToRef(e){return e.x=Math.floor(this._x),e.y=Math.floor(this._y),e.z=Math.floor(this._z),e.w=Math.floor(this._w),e}floor(){return new Me(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z),Math.floor(this._w))}fractToRef(e){return e.x=this._x-Math.floor(this._x),e.y=this._y-Math.floor(this._y),e.z=this._z-Math.floor(this._z),e.w=this._w-Math.floor(this._w),e}fract(){return new Me(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z),this._w-Math.floor(this._w))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new Me)}normalizeToRef(e){const t=this.length();return t===0||t===1?(e.x=this._x,e.y=this._y,e.z=this._z,e.w=this._w,e):this.scaleToRef(1/t,e)}toVector3(){return new p(this._x,this._y,this._z)}clone(){return new Me(this._x,this._y,this._z,this._w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this._x*e.x+this._y*e.y+this._z*e.z+this._w*e.w}static FromArray(e,t){return t||(t=0),new Me(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return Me.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,s,r){return r.x=e,r.y=t,r.z=i,r.w=s,r}static Zero(){return new Me(0,0,0,0)}static One(){return new Me(1,1,1,1)}static Random(e=0,t=1){return new Me(tt(e,t),tt(e,t),tt(e,t),tt(e,t))}static RandomToRef(e=0,t=1,i){return i.x=tt(e,t),i.y=tt(e,t),i.z=tt(e,t),i.w=tt(e,t),i}static Clamp(e,t,i){return Me.ClampToRef(e,t,i,new Me)}static ClampToRef(e,t,i,s){return s.x=ke(e.x,t.x,i.x),s.y=ke(e.y,t.y,i.y),s.z=ke(e.z,t.z,i.z),s.w=ke(e.w,t.w,i.w),s}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return Me._ZeroReadOnly}static Normalize(e){return Me.NormalizeToRef(e,new Me)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new Me;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new Me;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(Me.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return Me.CenterToRef(e,t,new Me)}static CenterToRef(e,t,i){return i.x=(e.x+t.x)/2,i.y=(e.y+t.y)/2,i.z=(e.z+t.z)/2,i.w=(e.w+t.w)/2,i}static TransformCoordinates(e,t){return Me.TransformCoordinatesToRef(e,t,new Me)}static TransformCoordinatesToRef(e,t,i){return Me.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,a=e*n[0]+t*n[4]+i*n[8]+n[12],h=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],c=e*n[3]+t*n[7]+i*n[11]+n[15];return r.x=a,r.y=h,r.z=l,r.w=c,r}static TransformNormal(e,t){return Me.TransformNormalToRef(e,t,new Me)}static TransformNormalToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+e.z*s[8],n=e.x*s[1]+e.y*s[5]+e.z*s[9],a=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=r,i.y=n,i.z=a,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,r,n){const a=r.m;return n.x=e*a[0]+t*a[4]+i*a[8],n.y=e*a[1]+t*a[5]+i*a[9],n.z=e*a[2]+t*a[6]+i*a[10],n.w=s,n}static FromVector3(e,t=0){return new Me(e._x,e._y,e._z,t)}static Dot(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w}}Me._V8PerformanceHack=new Me(.5,.5,.5,.5);Me._ZeroReadOnly=Me.Zero();Object.defineProperties(Me.prototype,{dimension:{value:[4]},rank:{value:1}});class re{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,s=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){const e=vt(this._x),t=vt(this._y),i=vt(this._z),s=vt(this._w);let r=e;return r=r*397^t,r=r*397^i,r=r*397^s,r}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return re.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=Ke){return e&&Ue(this._x,e._x,t)&&Ue(this._y,e._y,t)&&Ue(this._z,e._z,t)&&Ue(this._w,e._w,t)}isApprox(e,t=Ke){return e&&(Ue(this._x,e._x,t)&&Ue(this._y,e._y,t)&&Ue(this._z,e._z,t)&&Ue(this._w,e._w,t)||Ue(this._x,-e._x,t)&&Ue(this._y,-e._y,t)&&Ue(this._z,-e._z,t)&&Ue(this._w,-e._w,t))}clone(){return new re(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._isDirty=!0,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new re(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,s){return this._x+=e,this._y+=t,this._z+=i,this._w+=s,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,s){return this.subtractFromFloatsToRef(e,t,i,s,new re)}subtractFromFloatsToRef(e,t,i,s,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._w=this._w-s,r._isDirty=!0,r}subtract(e){return new re(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new re(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){const t=new re(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,s=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,n=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,s,r,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,s){return this._x*=e,this._y*=t,this._z*=i,this._w*=s,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new re)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,s){return this._x===e&&this._y===t&&this._z===i&&this._w===s}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new re(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return t==0||t==1||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return e==0||e==1?this:(this.scaleInPlace(1/e),this)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new re(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0||t===1?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=p.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,s=this._y,r=this._w,n=s*t-i*r,a=.4999999;if(n<-a)e._y=2*Math.atan2(s,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>a)e._y=2*Math.atan2(s,r),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const h=r*r,l=t*t,c=i*i,u=s*s;e._z=Math.atan2(2*(i*s+t*r),-l-c+u+h),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*i+s*r),l-c-u+h),e._isDirty=!0}return e}toAlphaBetaGammaToRef(e){const t=this._z,i=this._x,s=this._y,r=this._w,n=Math.sqrt(i*i+s*s),a=Math.sqrt(t*t+r*r),h=2*Math.atan2(n,a),l=2*Math.atan2(t,r),c=2*Math.atan2(s,i),u=(l+c)/2,f=(l-c)/2;return e.set(f,h,u),e}toRotationMatrix(e){return D.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return re.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}toAxisAngle(){const e=p.Zero(),t=this.toAxisAngleToRef(e);return{axis:e,angle:t}}toAxisAngleToRef(e){let t;const i=Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z),s=this._w;return i>0?(t=2*Math.atan2(i,s),e.set(this._x/i,this._y/i,this._z/i)):(t=0,e.set(1,0,0)),t}static FromRotationMatrix(e){const t=new re;return re.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],a=i[1],h=i[5],l=i[9],c=i[2],u=i[6],f=i[10],d=s+h+f;let _;return d>0?(_=.5/Math.sqrt(d+1),t._w=.25/_,t._x=(u-l)*_,t._y=(n-c)*_,t._z=(a-r)*_,t._isDirty=!0):s>h&&s>f?(_=2*Math.sqrt(1+s-h-f),t._w=(u-l)/_,t._x=.25*_,t._y=(r+a)/_,t._z=(n+c)/_,t._isDirty=!0):h>f?(_=2*Math.sqrt(1+h-s-f),t._w=(n-c)/_,t._x=(r+a)/_,t._y=.25*_,t._z=(l+u)/_,t._isDirty=!0):(_=2*Math.sqrt(1+f-s-h),t._w=(a-r)/_,t._x=(n+c)/_,t._y=(l+u)/_,t._z=.25*_,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const s=re.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,r){let n=s===0?1:i/s;return n=ke(n,0,1),re.SlerpToRef(e,t,n,r),r}static Zero(){return new re(0,0,0,0)}static Inverse(e){return new re(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new re(0,0,0,1)}static IsIdentity(e){return e&&e._x===0&&e._y===0&&e._z===0&&e._w===1}static RotationAxis(e,t){return re.RotationAxisToRef(e,t,new re)}static RotationAxisToRef(e,t,i){i._w=Math.cos(t/2);const s=Math.sin(t/2)/e.length();return i._x=e._x*s,i._y=e._y*s,i._z=e._z*s,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new re(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,s,r){return r.copyFromFloats(e,t,i,s),r}static FromEulerAngles(e,t,i){const s=new re;return re.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return re.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new re;return re.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return re.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=Ke){const r=p.Dot(e,t)+1;return r<s?Math.abs(e.x)>Math.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(p.CrossToRef(e,t,U.Vector3[0]),i.set(U.Vector3[0].x,U.Vector3[0].y,U.Vector3[0].z,r)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new re;return re.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const r=i*.5,n=t*.5,a=e*.5,h=Math.sin(r),l=Math.cos(r),c=Math.sin(n),u=Math.cos(n),f=Math.sin(a),d=Math.cos(a);return s._x=d*c*l+f*u*h,s._y=f*u*l-d*c*h,s._z=d*u*h-f*c*l,s._w=d*u*l+f*c*h,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new re;return re.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const r=(i+e)*.5,n=(i-e)*.5,a=t*.5;return s._x=Math.cos(n)*Math.sin(a),s._y=Math.sin(n)*Math.sin(a),s._z=Math.sin(r)*Math.cos(a),s._w=Math.cos(r)*Math.cos(a),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new re(0,0,0,0);return re.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const r=ne.Matrix[0];return e=e.normalizeToRef(ne.Vector3[0]),t=t.normalizeToRef(ne.Vector3[1]),i=i.normalizeToRef(ne.Vector3[2]),D.FromXYZAxesToRef(e,t,i,r),re.FromRotationMatrixToRef(r,s),s}static FromLookDirectionLH(e,t){const i=new re;return re.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=ne.Matrix[0];return D.LookDirectionLHToRef(e,t,s),re.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new re;return re.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=ne.Matrix[0];return D.LookDirectionRHToRef(e,t,s),re.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=re.Identity();return re.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let r,n,a=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,h=!1;if(a<0&&(h=!0,a=-a),a>.999999)n=1-i,r=h?-i:i;else{const l=Math.acos(a),c=1/Math.sin(l);n=Math.sin((1-i)*l)*c,r=h?-Math.sin(i*l)*c:Math.sin(i*l)*c}return s._x=n*e._x+r*t._x,s._y=n*e._y+r*t._y,s._z=n*e._z+r*t._z,s._w=n*e._w+r*t._w,s._isDirty=!0,s}static Hermite(e,t,i,s,r){const n=r*r,a=r*n,h=2*a-3*n+1,l=-2*a+3*n,c=a-2*n+r,u=a-n,f=e._x*h+i._x*l+t._x*c+s._x*u,d=e._y*h+i._y*l+t._y*c+s._y*u,_=e._z*h+i._z*l+t._z*c+s._z*u,m=e._w*h+i._w*l+t._w*c+s._w*u;return new re(f,d,_,m)}static Hermite1stDerivative(e,t,i,s,r){const n=new re;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;return n._x=(a-r)*6*e._x+(3*a-4*r+1)*t._x+(-a+r)*6*i._x+(3*a-2*r)*s._x,n._y=(a-r)*6*e._y+(3*a-4*r+1)*t._y+(-a+r)*6*i._y+(3*a-2*r)*s._y,n._z=(a-r)*6*e._z+(3*a-4*r+1)*t._z+(-a+r)*6*i._z+(3*a-2*r)*s._z,n._w=(a-r)*6*e._w+(3*a-4*r+1)*t._w+(-a+r)*6*i._w+(3*a-2*r)*s._w,n._isDirty=!0,n}static Normalize(e){const t=re.Zero();return re.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const s=new re;return re.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(ke(e.x,t.x,i.x),ke(e.y,t.y,i.y),ke(e.z,t.z,i.z),ke(e.w,t.w,i.w))}static Random(e=0,t=1){return new re(tt(e,t),tt(e,t),tt(e,t),tt(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(tt(e,t),tt(e,t),tt(e,t),tt(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(re.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return re.CenterToRef(e,t,re.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}re._V8PerformanceHack=new re(.5,.5,.5,.5);Object.defineProperties(re.prototype,{dimension:{value:[4]},rank:{value:1}});class D{static get Use64Bits(){return dt.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=Ya._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,s=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=this._isIdentity?!1:t,this._isIdentity3x2Dirty=this._isIdentity3x2?!1:s}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,dt.MatrixTrackPrecisionChange&&dt.MatrixTrackedMatrices.push(this),this._m=new dt.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=e[0]===1&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===1&&e[6]===0&&e[7]===0&&e[8]===0&&e[9]===0&&e[10]===1&&e[11]===0&&e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,this._m[0]!==1||this._m[5]!==1||this._m[15]!==1?this._isIdentity3x2=!1:this._m[1]!==0||this._m[2]!==0||this._m[3]!==0||this._m[4]!==0||this._m[6]!==0||this._m[7]!==0||this._m[8]!==0||this._m[9]!==0||this._m[10]!==0||this._m[11]!==0||this._m[12]!==0||this._m[13]!==0||this._m[14]!==0?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(this._isIdentity===!0)return 1;const e=this._m,t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],a=e[5],h=e[6],l=e[7],c=e[8],u=e[9],f=e[10],d=e[11],_=e[12],m=e[13],g=e[14],T=e[15],R=f*T-g*d,A=u*T-m*d,y=u*g-m*f,E=c*T-_*d,x=c*g-f*_,b=c*m-_*u,P=+(a*R-h*A+l*y),v=-(n*R-h*E+l*x),O=+(n*A-a*E+l*b),k=-(n*y-a*x+h*b);return t*P+i*v+s*O+r*k}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}
|
|
21
|
+
${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}
|
|
22
|
+
${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}
|
|
23
|
+
${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let s=0;s<16;s++)e[t+s]=i[s];return this}asArray(){return this._m}fromArray(e,t=0){return D.FromArrayToRef(e,t,this)}copyFromFloats(...e){return D.FromArrayToRef(e,0,this)}set(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){const t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return D.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){const t=new D;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,s=t._m,r=e.m;for(let n=0;n<16;n++)s[n]=i[n]+r[n];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;return t[0]+=i[0],t[1]+=i[1],t[2]+=i[2],t[3]+=i[3],t[4]+=i[4],t[5]+=i[5],t[6]+=i[6],t[7]+=i[7],t[8]+=i[8],t[9]+=i[9],t[10]+=i[10],t[11]+=i[11],t[12]+=i[12],t[13]+=i[13],t[14]+=i[14],t[15]+=i[15],this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]+=i[s];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]-=i[s];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let n=0;n<16;n++)r[n]=i[n]-s[n];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]-=i[s];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new D)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let n=0;n<16;n++)s[n]=i[n]-r[n];return t.markAsUpdated(),t}invertToRef(e){return this._isIdentity===!0?(D.IdentityToRef(e),e):(Tl(this,e.asArray())?e.markAsUpdated():e.copyFrom(this),e)}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new p(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){const e=this.m;return D.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1),this}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){return ml(this,e,t),this}multiply(e){const t=new D;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]*=i[s];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let n=0;n<16;n++)s[n]=i[n]*r[n];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){return pl(this,e,t,i),this}divide(e){return this.divideToRef(e,new D)}divideToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let n=0;n<16;n++)r[n]=i[n]/s[n];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]/=i[s];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]=Math.min(t[s],i[s]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]=Math.min(t[s],i[s]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new D)}negateInPlace(){const e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){const t=this._m,i=e._m;for(let s=0;s<16;s++)i[s]=-t[s];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,s=t.m;return i[0]===s[0]&&i[1]===s[1]&&i[2]===s[2]&&i[3]===s[3]&&i[4]===s[4]&&i[5]===s[5]&&i[6]===s[6]&&i[7]===s[7]&&i[8]===s[8]&&i[9]===s[9]&&i[10]===s[10]&&i[11]===s[11]&&i[12]===s[12]&&i[13]===s[13]&&i[14]===s[14]&&i[15]===s[15]}equalsWithEpsilon(e,t=0){const i=this._m,s=e.m;for(let r=0;r<16;r++)if(!Ue(i[r],s[r],t))return!1;return!0}equalsToFloats(...e){const t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new D)}floorToRef(e){const t=this._m,i=e._m;for(let s=0;s<16;s++)i[s]=Math.floor(t[s]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new D)}fractToRef(e){const t=this._m,i=e._m;for(let s=0;s<16;s++)i[s]=t[s]-Math.floor(t[s]);return e.markAsUpdated(),e}clone(){const e=new D;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=vt(this._m[0]);for(let t=1;t<16;t++)e=e*397^vt(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new re,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,s,r=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const n=this._m;if(i&&i.copyFromFloats(n[12],n[13],n[14]),e=e||ne.Vector3[0],e.x=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),e.y=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),e.z=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]),s){const a=(r?s.absoluteScaling.x:s.scaling.x)<0?-1:1,h=(r?s.absoluteScaling.y:s.scaling.y)<0?-1:1,l=(r?s.absoluteScaling.z:s.scaling.z)<0?-1:1;e.x*=a,e.y*=h,e.z*=l}else this.determinant()<=0&&(e.y*=-1);if(e._x===0||e._y===0||e._z===0)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const a=1/e._x,h=1/e._y,l=1/e._z;D.FromValuesToRef(n[0]*a,n[1]*a,n[2]*a,0,n[4]*h,n[5]*h,n[6]*h,0,n[8]*l,n[9]*l,n[10]*l,0,0,0,0,1,ne.Matrix[0]),re.FromRotationMatrixToRef(ne.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=e*4;return new Me(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){const i=e*4;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){const e=new D;return D.TransposeToRef(this,e),e}transposeToRef(e){return D.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,s,r){if(e<0||e>3)return this;const n=e*4;return this._m[n+0]=t,this._m[n+1]=i,this._m[n+2]=s,this._m[n+3]=r,this.markAsUpdated(),this}scale(e){const t=new D;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){const t=ne.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return D.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){const e=new D;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=ne.Vector3[0];if(!this.decompose(t))return D.IdentityToRef(e),e;const i=this._m,s=1/t._x,r=1/t._y,n=1/t._z;return D.FromValuesToRef(i[0]*s,i[1]*s,i[2]*s,0,i[4]*r,i[5]*r,i[6]*r,0,i[8]*n,i[9]*n,i[10]*n,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){const i=new D;return D.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let s=0;s<16;s++)i._m[s]=e[s+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,s){return s._m[0]=e[0+t]*i,s._m[1]=e[1+t]*i,s._m[2]=e[2+t]*i,s._m[3]=e[3+t]*i,s._m[4]=e[4+t]*i,s._m[5]=e[5+t]*i,s._m[6]=e[6+t]*i,s._m[7]=e[7+t]*i,s._m[8]=e[8+t]*i,s._m[9]=e[9+t]*i,s._m[10]=e[10+t]*i,s._m[11]=e[11+t]*i,s._m[12]=e[12+t]*i,s._m[13]=e[13+t]*i,s._m[14]=e[14+t]*i,s._m[15]=e[15+t]*i,s.markAsUpdated(),s}static get IdentityReadOnly(){return D._IdentityReadOnly}static FromValuesToRef(e,t,i,s,r,n,a,h,l,c,u,f,d,_,m,g,T){const R=T._m;R[0]=e,R[1]=t,R[2]=i,R[3]=s,R[4]=r,R[5]=n,R[6]=a,R[7]=h,R[8]=l,R[9]=c,R[10]=u,R[11]=f,R[12]=d,R[13]=_,R[14]=m,R[15]=g,T.markAsUpdated()}static FromValues(e,t,i,s,r,n,a,h,l,c,u,f,d,_,m,g){const T=new D,R=T._m;return R[0]=e,R[1]=t,R[2]=i,R[3]=s,R[4]=r,R[5]=n,R[6]=a,R[7]=h,R[8]=l,R[9]=c,R[10]=u,R[11]=f,R[12]=d,R[13]=_,R[14]=m,R[15]=g,T.markAsUpdated(),T}static Compose(e,t,i){const s=new D;return D.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const r=s._m,n=t._x,a=t._y,h=t._z,l=t._w,c=n+n,u=a+a,f=h+h,d=n*c,_=n*u,m=n*f,g=a*u,T=a*f,R=h*f,A=l*c,y=l*u,E=l*f,x=e._x,b=e._y,P=e._z;return r[0]=(1-(g+R))*x,r[1]=(_+E)*x,r[2]=(m-y)*x,r[3]=0,r[4]=(_-E)*b,r[5]=(1-(d+R))*b,r[6]=(T+A)*b,r[7]=0,r[8]=(m+y)*P,r[9]=(T-A)*P,r[10]=(1-(d+g))*P,r[11]=0,r[12]=i._x,r[13]=i._y,r[14]=i._z,r[15]=1,s.markAsUpdated(),s}static Identity(){const e=D.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return D.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){const e=D.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){const t=new D;return D.RotationXToRef(e,t),t}static Invert(e){const t=new D;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return D.FromValuesToRef(1,0,0,0,0,s,i,0,0,-i,s,0,0,0,0,1,t),t._updateIdentityStatus(s===1&&i===0),t}static RotationY(e){const t=new D;return D.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return D.FromValuesToRef(s,0,-i,0,0,1,0,0,i,0,s,0,0,0,0,1,t),t._updateIdentityStatus(s===1&&i===0),t}static RotationZ(e){const t=new D;return D.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return D.FromValuesToRef(s,i,0,0,-i,s,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(s===1&&i===0),t}static RotationAxis(e,t){const i=new D;return D.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),r=Math.cos(-t),n=1-r;e=e.normalizeToRef(ne.Vector3[0]);const a=i._m;return a[0]=e._x*e._x*n+r,a[1]=e._x*e._y*n-e._z*s,a[2]=e._x*e._z*n+e._y*s,a[3]=0,a[4]=e._y*e._x*n+e._z*s,a[5]=e._y*e._y*n+r,a[6]=e._y*e._z*n-e._x*s,a[7]=0,a[8]=e._z*e._x*n-e._y*s,a[9]=e._z*e._y*n+e._x*s,a[10]=e._z*e._z*n+r,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const r=p.Dot(t,e),n=i._m;if(r<-1+Ke)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=s?1:-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=s?-1:1,n[11]=0;else{const a=p.Cross(t,e),h=1/(1+r);n[0]=a._x*a._x*h+r,n[1]=a._y*a._x*h-a._z,n[2]=a._z*a._x*h+a._y,n[3]=0,n[4]=a._x*a._y*h+a._z,n[5]=a._y*a._y*h+r,n[6]=a._z*a._y*h-a._x,n[7]=0,n[8]=a._x*a._z*h-a._y,n[9]=a._y*a._z*h+a._x,n[10]=a._z*a._z*h+r,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const s=new D;return D.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return re.RotationYawPitchRollToRef(e,t,i,ne.Quaternion[0]),ne.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new D;return D.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return D.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,s),s._updateIdentityStatus(e===1&&t===1&&i===1),s}static Translation(e,t,i){const s=new D;return D.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return D.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,s),s._updateIdentityStatus(e===0&&t===0&&i===0),s}static Lerp(e,t,i){const s=new D;return D.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const r=s._m,n=e.m,a=t.m;for(let h=0;h<16;h++)r[h]=n[h]*(1-i)+a[h]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new D;return D.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const r=ne.Vector3[0],n=ne.Quaternion[0],a=ne.Vector3[1];e.decompose(r,n,a);const h=ne.Vector3[2],l=ne.Quaternion[1],c=ne.Vector3[3];t.decompose(h,l,c);const u=ne.Vector3[4];p.LerpToRef(r,h,i,u);const f=ne.Quaternion[2];re.SlerpToRef(n,l,i,f);const d=ne.Vector3[5];return p.LerpToRef(a,c,i,d),D.ComposeToRef(u,f,d,s),s}static LookAtLH(e,t,i){const s=new D;return D.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const r=ne.Vector3[0],n=ne.Vector3[1],a=ne.Vector3[2];t.subtractToRef(e,a),a.normalize(),p.CrossToRef(i,a,r);const h=r.lengthSquared();h===0?r.x=1:r.normalizeFromLength(Math.sqrt(h)),p.CrossToRef(a,r,n),n.normalize();const l=-p.Dot(r,e),c=-p.Dot(n,e),u=-p.Dot(a,e);return D.FromValuesToRef(r._x,n._x,a._x,0,r._y,n._y,a._y,0,r._z,n._z,a._z,0,l,c,u,1,s),s}static LookAtRH(e,t,i){const s=new D;return D.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const r=ne.Vector3[0],n=ne.Vector3[1],a=ne.Vector3[2];e.subtractToRef(t,a),a.normalize(),p.CrossToRef(i,a,r);const h=r.lengthSquared();h===0?r.x=1:r.normalizeFromLength(Math.sqrt(h)),p.CrossToRef(a,r,n),n.normalize();const l=-p.Dot(r,e),c=-p.Dot(n,e),u=-p.Dot(a,e);return D.FromValuesToRef(r._x,n._x,a._x,0,r._y,n._y,a._y,0,r._z,n._z,a._z,0,l,c,u,1,s),s}static LookDirectionLH(e,t){const i=new D;return D.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=ne.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const r=ne.Vector3[1];return p.CrossToRef(t,s,r),D.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new D;return D.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=ne.Vector3[2];return p.CrossToRef(t,e,s),D.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,s,r){const n=new D;return D.OrthoLHToRef(e,t,i,s,n,r),n}static OrthoLHToRef(e,t,i,s,r,n){const a=i,h=s,l=2/e,c=2/t,u=2/(h-a),f=-(h+a)/(h-a);return D.FromValuesToRef(l,0,0,0,0,c,0,0,0,0,u,0,0,0,f,1,r),n&&r.multiplyToRef(ji,r),r._updateIdentityStatus(l===1&&c===1&&u===1&&f===0),r}static OrthoOffCenterLH(e,t,i,s,r,n,a){const h=new D;return D.OrthoOffCenterLHToRef(e,t,i,s,r,n,h,a),h}static OrthoOffCenterLHToRef(e,t,i,s,r,n,a,h){const l=r,c=n,u=2/(t-e),f=2/(s-i),d=2/(c-l),_=-(c+l)/(c-l),m=(e+t)/(e-t),g=(s+i)/(i-s);return D.FromValuesToRef(u,0,0,0,0,f,0,0,0,0,d,0,m,g,_,1,a),h&&a.multiplyToRef(ji,a),a.markAsUpdated(),a}static ObliqueOffCenterLHToRef(e,t,i,s,r,n,a,h,l,c,u){const f=-a*Math.cos(h),d=-a*Math.sin(h);return D.TranslationToRef(0,0,-l,ne.Matrix[1]),D.FromValuesToRef(1,0,0,0,0,1,0,0,f,d,1,0,0,0,0,1,ne.Matrix[0]),ne.Matrix[1].multiplyToRef(ne.Matrix[0],ne.Matrix[0]),D.TranslationToRef(0,0,l,ne.Matrix[1]),ne.Matrix[0].multiplyToRef(ne.Matrix[1],ne.Matrix[0]),D.OrthoOffCenterLHToRef(e,t,i,s,r,n,c,u),ne.Matrix[0].multiplyToRef(c,c),c}static OrthoOffCenterRH(e,t,i,s,r,n,a){const h=new D;return D.OrthoOffCenterRHToRef(e,t,i,s,r,n,h,a),h}static OrthoOffCenterRHToRef(e,t,i,s,r,n,a,h){return D.OrthoOffCenterLHToRef(e,t,i,s,r,n,a,h),a._m[10]*=-1,a}static ObliqueOffCenterRHToRef(e,t,i,s,r,n,a,h,l,c,u){const f=a*Math.cos(h),d=a*Math.sin(h);return D.TranslationToRef(0,0,l,ne.Matrix[1]),D.FromValuesToRef(1,0,0,0,0,1,0,0,f,d,1,0,0,0,0,1,ne.Matrix[0]),ne.Matrix[1].multiplyToRef(ne.Matrix[0],ne.Matrix[0]),D.TranslationToRef(0,0,-l,ne.Matrix[1]),ne.Matrix[0].multiplyToRef(ne.Matrix[1],ne.Matrix[0]),D.OrthoOffCenterRHToRef(e,t,i,s,r,n,c,u),ne.Matrix[0].multiplyToRef(c,c),c}static PerspectiveLH(e,t,i,s,r,n=0){const a=new D,h=i,l=s,c=2*h/e,u=2*h/t,f=(l+h)/(l-h),d=-2*l*h/(l-h),_=Math.tan(n);return D.FromValuesToRef(c,0,0,0,0,u,0,_,0,0,f,1,0,0,d,0,a),r&&a.multiplyToRef(ji,a),a._updateIdentityStatus(!1),a}static PerspectiveFovLH(e,t,i,s,r,n=0,a=!1){const h=new D;return D.PerspectiveFovLHToRef(e,t,i,s,h,!0,r,n,a),h}static PerspectiveFovLHToRef(e,t,i,s,r,n=!0,a,h=0,l=!1){const c=i,u=s,f=1/Math.tan(e*.5),d=n?f/t:f,_=n?f:f*t,m=l&&c===0?-1:u!==0?(u+c)/(u-c):1,g=l&&c===0?2*u:u!==0?-2*u*c/(u-c):-2*c,T=Math.tan(h);return D.FromValuesToRef(d,0,0,0,0,_,0,T,0,0,m,1,0,0,g,0,r),a&&r.multiplyToRef(ji,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,s,r,n=!0,a,h=0){const l=1/Math.tan(e*.5),c=n?l/t:l,u=n?l:l*t,f=Math.tan(h);return D.FromValuesToRef(c,0,0,0,0,u,0,f,0,0,-i,1,0,0,1,0,r),a&&r.multiplyToRef(ji,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,s,r,n=0,a=!1){const h=new D;return D.PerspectiveFovRHToRef(e,t,i,s,h,!0,r,n,a),h}static PerspectiveFovRHToRef(e,t,i,s,r,n=!0,a,h=0,l=!1){const c=i,u=s,f=1/Math.tan(e*.5),d=n?f/t:f,_=n?f:f*t,m=l&&c===0?1:u!==0?-(u+c)/(u-c):-1,g=l&&c===0?2*u:u!==0?-2*u*c/(u-c):-2*c,T=Math.tan(h);return D.FromValuesToRef(d,0,0,0,0,_,0,T,0,0,m,-1,0,0,g,0,r),a&&r.multiplyToRef(ji,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,s,r,n=!0,a,h=0){const l=1/Math.tan(e*.5),c=n?l/t:l,u=n?l:l*t,f=Math.tan(h);return D.FromValuesToRef(c,0,0,0,0,u,0,f,0,0,-i,-1,0,0,-1,0,r),a&&r.multiplyToRef(ji,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,i,s,r,n){const a=e.width,h=e.height,l=e.x,c=e.y,u=D.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,n-r,0,l+a/2,h/2+c,r,1),f=new D;return t.multiplyToRef(i,f),f.multiplyToRef(s,f),f.multiplyToRef(u,f)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return dt.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){const t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return dt.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new D;return D.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],a=i[12],h=i[1],l=i[5],c=i[9],u=i[13],f=i[2],d=i[6],_=i[10],m=i[14],g=i[3],T=i[7],R=i[11],A=i[15],y=t._m;return y[0]=s,y[1]=r,y[2]=n,y[3]=a,y[4]=h,y[5]=l,y[6]=c,y[7]=u,y[8]=f,y[9]=d,y[10]=_,y[11]=m,y[12]=g,y[13]=T,y[14]=R,y[15]=A,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new D;return D.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,s=e.normal.y,r=e.normal.z,n=-2*i,a=-2*s,h=-2*r;return D.FromValuesToRef(n*i+1,a*i,h*i,0,n*s,a*s+1,h*s,0,n*r,a*r,h*r+1,0,n*e.d,a*e.d,h*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return D.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,s),s}static FromQuaternionToRef(e,t){const i=e._x*e._x,s=e._y*e._y,r=e._z*e._z,n=e._x*e._y,a=e._z*e._w,h=e._z*e._x,l=e._y*e._w,c=e._y*e._z,u=e._x*e._w;return t._m[0]=1-2*(s+r),t._m[1]=2*(n+a),t._m[2]=2*(h-l),t._m[3]=0,t._m[4]=2*(n-a),t._m[5]=1-2*(r+i),t._m[6]=2*(c+u),t._m[7]=0,t._m[8]=2*(h+l),t._m[9]=2*(c-u),t._m[10]=1-2*(s+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}D._IdentityReadOnly=D.Identity();Object.defineProperties(D.prototype,{dimension:{value:[4,4]},rank:{value:2}});class ne{}ne.Vector3=Ki(11,p.Zero);ne.Matrix=Ki(2,D.Identity);ne.Quaternion=Ki(3,re.Zero);class U{}U.Vector2=Ki(3,ie.Zero);U.Vector3=Ki(13,p.Zero);U.Vector4=Ki(3,Me.Zero);U.Quaternion=Ki(3,re.Zero);U.Matrix=Ki(8,D.Identity);Ye("BABYLON.Vector2",ie);Ye("BABYLON.Vector3",p);Ye("BABYLON.Vector4",Me);Ye("BABYLON.Matrix",D);const ji=D.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1),Hp=Object.freeze(Object.defineProperty({__proto__:null,Matrix:D,Quaternion:re,TmpVectors:U,Vector2:ie,Vector3:p,Vector4:Me},Symbol.toStringTag,{value:"Module"}));class ui{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=this.width|0;return e=e*397^(this.height|0),e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new ui(this.width*e,this.height*t)}clone(){return new ui(this.width,this.height)}equals(e){return e?this.width===e.width&&this.height===e.height:!1}get surface(){return this.width*this.height}static Zero(){return new ui(0,0)}add(e){return new ui(this.width+e.width,this.height+e.height)}subtract(e){return new ui(this.width-e.width,this.height-e.height)}scale(e){return new ui(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,r=e.height+(t.height-e.height)*i;return new ui(s,r)}}class Za{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return this._texture?this._texture.isCube:!1}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return e?.shareDepth!==void 0}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=ui.Zero(),this._cachedBaseSize=ui.Zero(),this._initialSamplingMode=2,this._texture=Za._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine(),this.wrapU=this._texture._cachedWrapU??this.wrapU,this.wrapV=this._texture._cachedWrapV??this.wrapV,this.wrapR=this._texture._cachedWrapR??this.wrapR)}isReady(){return this.delayLoadState===4?(this.delayLoad(),!1):this._texture?this._texture.isReady:!1}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return!this.isReady()||!this._texture?(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize):this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e,t=!1){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture,this._texture.generateMipMaps&&t)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}class Qi{static Eval(e,t){return e.match(/\([^()]*\)/g)?e=e.replace(/\([^()]*\)/g,i=>(i=i.slice(1,i.length-1),Qi._HandleParenthesisContent(i,t))):e=Qi._HandleParenthesisContent(e,t),e==="true"?!0:e==="false"?!1:Qi.Eval(e,t)}static _HandleParenthesisContent(e,t){t=t||(r=>r==="true");let i;const s=e.split("||");for(const r in s)if(Object.prototype.hasOwnProperty.call(s,r)){let n=Qi._SimplifyNegation(s[r].trim());const a=n.split("&&");if(a.length>1)for(let h=0;h<a.length;++h){const l=Qi._SimplifyNegation(a[h].trim());if(l!=="true"&&l!=="false"?l[0]==="!"?i=!t(l.substring(1)):i=t(l):i=l==="true",!i){n="false";break}}if(i||n==="true"){i=!0;break}n!=="true"&&n!=="false"?n[0]==="!"?i=!t(n.substring(1)):i=t(n):i=n==="true"}return i?"true":"false"}static _SimplifyNegation(e){return e=e.replace(/^[\s!]+/,t=>(t=t.replace(/[\s]/g,()=>""),t.length%2?"!":"")),e=e.trim(),e==="!true"?e="false":e==="!false"&&(e="true"),e}}class Le{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>Le.HasTags(e),e.addTags=t=>Le.AddTagsTo(e,t),e.removeTags=t=>Le.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>Le.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;const t=e._tags;for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const i=[];for(const s in e._tags)Object.prototype.hasOwnProperty.call(e._tags,s)&&e._tags[s]===!0&&i.push(s);return i.join(" ")}else return e._tags}static AddTagsTo(e,t){if(!t||typeof t!="string")return;const i=t.split(" ");for(const s of i)Le._AddTagTo(e,s)}static _AddTagTo(e,t){t=t.trim(),!(t===""||t==="true"||t==="false")&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(Le.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!Le.HasTags(e))return;const i=t.split(" ");for(const s in i)Le._RemoveTagFrom(e,i[s])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return t===void 0?!0:t===""?Le.HasTags(e):Qi.Eval(t,i=>Le.HasTags(e)&&e._tags[i])}}function cs(o){return Math.pow(o,vr)}function us(o){return o<=.04045?.0773993808*o:Math.pow(.947867299*(o+.055),2.4)}function fs(o){return Math.pow(o,ul)}function ds(o){return o<=.0031308?12.92*o:1.055*Math.pow(o,.41666)-.055}class Re{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return Re.FromArrayToRef(e,t,this),this}toColor4(e=1){return new Ce(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return this.r*.3+this.g*.59+this.b*.11}multiply(e){return new Re(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,i){return new Re(this.r*e,this.g*t,this.b*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=Ke){return Ue(this.r,e.r,t)&&Ue(this.g,e.g,t)&&Ue(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new Re(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,i){return i.r=ke(this.r,e,t),i.g=ke(this.g,e,t),i.b=ke(this.b,e,t),i}add(e){return new Re(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new Re(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,i){return new Re(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,s){return s.r=this.r-e,s.g=this.g-t,s.b=this.b-i,s}clone(){return new Re(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){const e=Math.round(this.r*255),t=Math.round(this.g*255),i=Math.round(this.b*255);return"#"+ii(e)+ii(t)+ii(i)}fromHexString(e){return e.substring(0,1)!=="#"||e.length!==7?this:(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255,this)}toHSV(){return this.toHSVToRef(new Re)}toHSVToRef(e){const t=this.r,i=this.g,s=this.b,r=Math.max(t,i,s),n=Math.min(t,i,s);let a=0,h=0;const l=r,c=r-n;return r!==0&&(h=c/r),r!=n&&(r==t?(a=(i-s)/c,i<s&&(a+=6)):r==i?a=(s-t)/c+2:r==s&&(a=(t-i)/c+4),a*=60),e.r=a,e.g=h,e.b=l,e}toLinearSpace(e=!1){const t=new Re;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=us(this.r),e.g=us(this.g),e.b=us(this.b)):(e.r=cs(this.r),e.g=cs(this.g),e.b=cs(this.b)),this}toGammaSpace(e=!1){const t=new Re;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=ds(this.r),e.g=ds(this.g),e.b=ds(this.b)):(e.r=fs(this.r),e.g=fs(this.g),e.b=fs(this.b)),this}static HSVtoRGBToRef(e,t,i,s){const r=i*t,n=e/60,a=r*(1-Math.abs(n%2-1));let h=0,l=0,c=0;n>=0&&n<=1?(h=r,l=a):n>=1&&n<=2?(h=a,l=r):n>=2&&n<=3?(l=r,c=a):n>=3&&n<=4?(l=a,c=r):n>=4&&n<=5?(h=a,c=r):n>=5&&n<=6&&(h=r,c=a);const u=i-r;return s.r=h+u,s.g=l+u,s.b=c+u,s}static FromHSV(e,t,i){const s=new Re(0,0,0);return Re.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){return new Re(0,0,0).fromHexString(e)}static FromArray(e,t=0){return new Re(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new Re(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new Re(0,0,0);return Re.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,s,r){const n=r*r,a=r*n,h=2*a-3*n+1,l=-2*a+3*n,c=a-2*n+r,u=a-n,f=e.r*h+i.r*l+t.r*c+s.r*u,d=e.g*h+i.g*l+t.g*c+s.g*u,_=e.b*h+i.b*l+t.b*c+s.b*u;return new Re(f,d,_)}static Hermite1stDerivative(e,t,i,s,r){const n=Re.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;n.r=(a-r)*6*e.r+(3*a-4*r+1)*t.r+(-a+r)*6*i.r+(3*a-2*r)*s.r,n.g=(a-r)*6*e.g+(3*a-4*r+1)*t.g+(-a+r)*6*i.g+(3*a-2*r)*s.g,n.b=(a-r)*6*e.b+(3*a-4*r+1)*t.b+(-a+r)*6*i.b+(3*a-2*r)*s.b}static Red(){return new Re(1,0,0)}static Green(){return new Re(0,1,0)}static Blue(){return new Re(0,0,1)}static Black(){return new Re(0,0,0)}static get BlackReadOnly(){return Re._BlackReadOnly}static White(){return new Re(1,1,1)}static Purple(){return new Re(.5,0,.5)}static Magenta(){return new Re(1,0,1)}static Yellow(){return new Re(1,1,0)}static Gray(){return new Re(.5,.5,.5)}static Teal(){return new Re(0,1,1)}static Random(){return new Re(Math.random(),Math.random(),Math.random())}}Re._V8PerformanceHack=new Re(.5,.5,.5);Re._BlackReadOnly=Re.Black();Object.defineProperties(Re.prototype,{dimension:{value:[3]},rank:{value:1}});class Ce{constructor(e=0,t=0,i=0,s=1){this.r=e,this.g=t,this.b=i,this.a=s}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new Ce(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,s){return this.r+=e,this.g+=t,this.b+=i,this.a+=s,this}subtract(e){return new Ce(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,s){return new Ce(this.r-e,this.g-t,this.b-i,this.a-s)}subtractFromFloatsToRef(e,t,i,s,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r.a=this.a-s,r}scale(e){return new Ce(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,i){return i.r=ke(this.r,e,t),i.g=ke(this.g,e,t),i.b=ke(this.b,e,t),i.a=ke(this.a,e,t),i}multiply(e){return new Ce(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,s){return new Ce(this.r*e,this.g*t,this.b*i,this.a*s)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,s){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(s,this.a),this}maximizeInPlaceFromFloats(e,t,i,s){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(s,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=Ke){return Ue(this.r,e.r,t)&&Ue(this.g,e.g,t)&&Ue(this.b,e.b,t)&&Ue(this.a,e.a,t)}equalsToFloats(e,t,i,s){return this.r===e&&this.g===t&&this.b===i&&this.a===s}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e=e*397^(this.a*255|0),e}clone(){return new Ce().copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,s){return this.r=e,this.g=t,this.b=i,this.a=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(this.r*255),i=Math.round(this.g*255),s=Math.round(this.b*255);if(e)return"#"+ii(t)+ii(i)+ii(s);const r=Math.round(this.a*255);return"#"+ii(t)+ii(i)+ii(s)+ii(r)}fromHexString(e){return e.substring(0,1)!=="#"||e.length!==9&&e.length!==7?this:(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255,e.length===9&&(this.a=parseInt(e.substring(7,9),16)/255),this)}toLinearSpace(e=!1){const t=new Ce;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=us(this.r),e.g=us(this.g),e.b=us(this.b)):(e.r=cs(this.r),e.g=cs(this.g),e.b=cs(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new Ce;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=ds(this.r),e.g=ds(this.g),e.b=ds(this.b)):(e.r=fs(this.r),e.g=fs(this.g),e.b=fs(this.b)),e.a=this.a,this}static FromHexString(e){return e.substring(0,1)!=="#"||e.length!==9&&e.length!==7?new Ce(0,0,0,0):new Ce(0,0,0,1).fromHexString(e)}static Lerp(e,t,i){return Ce.LerpToRef(e,t,i,new Ce)}static LerpToRef(e,t,i,s){return s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i,s.a=e.a+(t.a-e.a)*i,s}static Hermite(e,t,i,s,r){const n=r*r,a=r*n,h=2*a-3*n+1,l=-2*a+3*n,c=a-2*n+r,u=a-n,f=e.r*h+i.r*l+t.r*c+s.r*u,d=e.g*h+i.g*l+t.g*c+s.g*u,_=e.b*h+i.b*l+t.b*c+s.b*u,m=e.a*h+i.a*l+t.a*c+s.a*u;return new Ce(f,d,_,m)}static Hermite1stDerivative(e,t,i,s,r){const n=new Ce;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;n.r=(a-r)*6*e.r+(3*a-4*r+1)*t.r+(-a+r)*6*i.r+(3*a-2*r)*s.r,n.g=(a-r)*6*e.g+(3*a-4*r+1)*t.g+(-a+r)*6*i.g+(3*a-2*r)*s.g,n.b=(a-r)*6*e.b+(3*a-4*r+1)*t.b+(-a+r)*6*i.b+(3*a-2*r)*s.b,n.a=(a-r)*6*e.a+(3*a-4*r+1)*t.a+(-a+r)*6*i.a+(3*a-2*r)*s.a}static FromColor3(e,t=1){return new Ce(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new Ce(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,s){return new Ce(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===t*3){const i=[];for(let s=0;s<e.length;s+=3){const r=s/3*4;i[r]=e[s],i[r+1]=e[s+1],i[r+2]=e[s+2],i[r+3]=1}return i}return e}}Ce._V8PerformanceHack=new Ce(.5,.5,.5,.5);Object.defineProperties(Ce.prototype,{dimension:{value:[4]},rank:{value:1}});class es{}es.Color3=yi(3,Re.Black);es.Color4=yi(3,()=>new Ce(0,0,0,0));Ye("BABYLON.Color3",Re);Ye("BABYLON.Color4",Ce);const Xp=Object.freeze(Object.defineProperty({__proto__:null,Color3:Re,Color4:Ce,TmpColors:es},Symbol.toStringTag,{value:"Module"})),Ho=function(o,e,t,i={}){const s=o();Le&&Le.HasTags(e)&&Le.AddTagsTo(s,Le.GetTags(e,!0));const r=Cn(s),n={};for(const a in r){const h=r[a],l=e[a],c=h.type;if(l!=null&&(a!=="uniqueId"||me.AllowLoadingUniqueId))switch(c){case 0:case 6:case 9:case 11:typeof l.slice=="function"?s[a]=l.slice():s[a]=l;break;case 1:i.cloneTexturesOnlyOnce&&n[l.uniqueId]?s[a]=n[l.uniqueId]:(s[a]=t||l.isRenderTarget?l:l.clone(),n[l.uniqueId]=s[a]);break;case 2:case 3:case 4:case 5:case 7:case 8:case 10:case 12:s[a]=t?l:l.clone();break}}return s};class me{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i<e.animations.length;i++){const s=e.animations[i];t.animations.push(s.serialize())}}}static Serialize(e,t){t||(t={}),Le&&(t.tags=Le.GetTags(e));const i=Cn(e);for(const s in i){const r=i[s],n=r.sourceName||s,a=r.type,h=e[s];if(h!=null&&(s!=="uniqueId"||me.AllowLoadingUniqueId))switch(a){case 0:Array.isArray(h)?t[n]=h.slice():t[n]=h;break;case 1:t[n]=h.serialize();break;case 2:t[n]=h.asArray();break;case 3:t[n]=h.serialize();break;case 4:t[n]=h.asArray();break;case 5:t[n]=h.asArray();break;case 6:t[n]=h.id;break;case 7:t[n]=h.serialize();break;case 8:t[n]=h.asArray();break;case 9:t[n]=h.serialize();break;case 10:t[n]=h.asArray();break;case 11:t[n]=h.id;break;case 12:t[n]=h.asArray();break}}return t}static ParseProperties(e,t,i,s){s||(s="");const r=Cn(t);for(const n in r){const a=r[n],h=e[a.sourceName||n],l=a.type;if(h!=null&&(n!=="uniqueId"||me.AllowLoadingUniqueId)){const c=t;switch(l){case 0:c[n]=h;break;case 1:i&&(c[n]=me._TextureParser(h,i,s));break;case 2:c[n]=Re.FromArray(h);break;case 3:c[n]=me._FresnelParametersParser(h);break;case 4:c[n]=ie.FromArray(h);break;case 5:c[n]=p.FromArray(h);break;case 6:i&&(c[n]=i.getLastMeshById(h));break;case 7:c[n]=me._ColorCurvesParser(h);break;case 8:c[n]=Ce.FromArray(h);break;case 9:c[n]=me._ImageProcessingConfigurationParser(h);break;case 10:c[n]=re.FromArray(h);break;case 11:i&&(c[n]=i.getCameraById(h));break;case 12:c[n]=D.FromArray(h);break}}}}static Parse(e,t,i,s=null){const r=e();return Le&&Le.AddTagsTo(r,t.tags),me.ParseProperties(t,r,i,s),r}static Clone(e,t,i={}){return Ho(e,t,!1,i)}static Instanciate(e,t){return Ho(e,t,!0)}}me.AllowLoadingUniqueId=!1;me._ImageProcessingConfigurationParser=o=>{throw pe("ImageProcessingConfiguration")};me._FresnelParametersParser=o=>{throw pe("FresnelParameters")};me._ColorCurvesParser=o=>{throw pe("ColorCurves")};me._TextureParser=(o,e,t)=>{throw pe("Texture")};class Ve extends Za{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){if(this._texture)this._texture._gammaSpace===null&&(this._texture._gammaSpace=this._gammaSpace);else return this._gammaSpace;return this._texture._gammaSpace&&!this._texture._useSRGBBuffer}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this.getScene()?.markAllMaterialsAsDirty(1,t=>t.hasTexture(this))}get isRGBD(){return this._texture!=null&&this._texture._isRGBD}set isRGBD(e){e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),this.getScene()?.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return this._texture?this._texture._linearSpecularLOD:!1}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=Zr()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=Ve.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this._dominantDirection=null,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new z,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?Ve._IsScene(e)?this._scene=e:this._engine=e:this._scene=ye.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}getTextureMatrix(){return D.IdentityReadOnly}getReflectionTextureMatrix(){return D.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,s,r,n){const a=this._getEngine();if(!a)return null;const h=a._getUseSRGBBuffer(!!r,t),l=a.getLoadedTexturesCache();for(let c=0;c<l.length;c++){const u=l[c];if((r===void 0||h===u._useSRGBBuffer)&&(s===void 0||s===u.invertY)&&u.url===e&&u.generateMipMaps===!t&&(!i||i===u.samplingMode)&&(n===void 0||n===u.isCube))return u.incrementReferences(),u}return null}_rebuild(e=!1){}clone(){return null}get textureType(){return this._texture&&this._texture.type!==void 0?this._texture.type:0}get textureFormat(){return this._texture&&this._texture.format!==void 0?this._texture.format:5}_markAllSubMeshesAsTexturesDirty(){const e=this.getScene();e&&e.markAllMaterialsAsDirty(1)}readPixels(e=0,t=0,i=null,s=!0,r=!1,n=0,a=0,h=Number.MAX_VALUE,l=Number.MAX_VALUE){if(!this._texture)return null;const c=this._getEngine();if(!c)return null;const u=this.getSize();let f=u.width,d=u.height;t!==0&&(f=f/Math.pow(2,t),d=d/Math.pow(2,t),f=Math.round(f),d=Math.round(d)),h=Math.min(f,h),l=Math.min(d,l);try{return this._texture.isCube||this._texture.is2DArray?c._readTexturePixels(this._texture,h,l,e,t,i,s,r,n,a):c._readTexturePixels(this._texture,h,l,-1,t,i,s,r,n,a)}catch{return null}}_readPixelsSync(e=0,t=0,i=null,s=!0,r=!1){if(!this._texture)return null;const n=this.getSize();let a=n.width,h=n.height;const l=this._getEngine();if(!l)return null;t!=0&&(a=a/Math.pow(2,t),h=h/Math.pow(2,t),a=Math.round(a),h=Math.round(h));try{return this._texture.isCube?l._readTexturePixelsSync(this._texture,a,h,e,t,i,s,r):l._readTexturePixelsSync(this._texture,a,h,-1,t,i,s,r)}catch{return null}}get _lodTextureHigh(){return this._texture?this._texture._lodTextureHigh:null}get _lodTextureMid(){return this._texture?this._texture._lodTextureMid:null}get _lodTextureLow(){return this._texture?this._texture._lodTextureLow:null}dispose(){if(this._scene){this._scene.stopAnimation&&this._scene.stopAnimation(this),this._scene.removePendingData(this);const e=this._scene.textures.indexOf(this);if(e>=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const t=this._parentContainer.textures.indexOf(this);t>-1&&this._parentContainer.textures.splice(t,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;const t=me.Serialize(this);return me.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(i===0){t();return}for(let s=0;s<e.length;s++){const r=e[s];if(r.isReady())--i===0&&t();else{const n=r.onLoadObservable;n?n.addOnce(()=>{--i===0&&t()}):--i===0&&t()}}}static _IsScene(e){return e.getClassName()==="Scene"}}Ve.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4;M([C()],Ve.prototype,"uniqueId",void 0);M([C()],Ve.prototype,"name",void 0);M([C()],Ve.prototype,"displayName",void 0);M([C()],Ve.prototype,"metadata",void 0);M([C("hasAlpha")],Ve.prototype,"_hasAlpha",void 0);M([C("getAlphaFromRGB")],Ve.prototype,"_getAlphaFromRGB",void 0);M([C()],Ve.prototype,"level",void 0);M([C("coordinatesIndex")],Ve.prototype,"_coordinatesIndex",void 0);M([C()],Ve.prototype,"optimizeUVAllocation",void 0);M([C("coordinatesMode")],Ve.prototype,"_coordinatesMode",void 0);M([C()],Ve.prototype,"wrapU",null);M([C()],Ve.prototype,"wrapV",null);M([C()],Ve.prototype,"wrapR",void 0);M([C()],Ve.prototype,"anisotropicFilteringLevel",void 0);M([C()],Ve.prototype,"isCube",null);M([C()],Ve.prototype,"is3D",null);M([C()],Ve.prototype,"is2DArray",null);M([C()],Ve.prototype,"gammaSpace",null);M([C()],Ve.prototype,"invertZ",void 0);M([C()],Ve.prototype,"lodLevelInAlpha",void 0);M([C()],Ve.prototype,"lodGenerationOffset",null);M([C()],Ve.prototype,"lodGenerationScale",null);M([C()],Ve.prototype,"linearSpecularLOD",null);M([qt()],Ve.prototype,"irradianceTexture",null);M([C()],Ve.prototype,"isRenderTarget",void 0);class si{constructor(e,t,i,s){this.normal=new p(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new si(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=e*397^(this.d|0),e}normalize(){const e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z);let t=0;return e!==0&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=si._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,a=this.d,h=s*i[0]+r*i[1]+n*i[2]+a*i[3],l=s*i[4]+r*i[5]+n*i[6]+a*i[7],c=s*i[8]+r*i[9]+n*i[10]+a*i[11],u=s*i[12]+r*i[13]+n*i[14]+a*i[15];return new si(h,l,c,u)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const s=t.x-e.x,r=t.y-e.y,n=t.z-e.z,a=i.x-e.x,h=i.y-e.y,l=i.z-e.z,c=r*l-n*h,u=n*a-s*l,f=s*h-r*a,d=Math.sqrt(c*c+u*u+f*f);let _;return d!==0?_=1/d:_=0,this.normal.x=c*_,this.normal.y=u*_,this.normal.z=f*_,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return p.Dot(this.normal,e)<=t}signedDistanceTo(e){return p.Dot(e,this.normal)+this.d}static FromArray(e){return new si(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new si(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new si(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return p.Dot(i,t)+s}}si._TmpMatrix=D.Identity();function qa(o,e,t=!1){const i=e.width,s=e.height;if(o instanceof Float32Array){let l=o.byteLength/o.BYTES_PER_ELEMENT;const c=new Uint8Array(l);for(;--l>=0;){let u=o[l];u<0?u=0:u>1&&(u=1),c[l]=u*255}o=c}const r=document.createElement("canvas");r.width=i,r.height=s;const n=r.getContext("2d");if(!n)return null;const a=n.createImageData(i,s);if(a.data.set(o),n.putImageData(a,0,0),t){const l=document.createElement("canvas");l.width=i,l.height=s;const c=l.getContext("2d");return c?(c.translate(0,s),c.scale(1,-1),c.drawImage(r,0,0),l.toDataURL("image/png")):null}return r.toDataURL("image/png")}function El(o,e=0,t=0){const i=o.getInternalTexture();if(!i)return null;const s=o._readPixelsSync(e,t);return s?qa(s,o.getSize(),i.invertY):null}async function xl(o,e=0,t=0){const i=o.getInternalTexture();if(!i)return null;const s=await o.readPixels(e,t);return s?qa(s,o.getSize(),i.invertY):null}const Kp={GenerateBase64StringFromPixelData:qa,GenerateBase64StringFromTexture:El,GenerateBase64StringFromTextureAsync:xl};let we=!1;function Yp(o){we=o}const jp={get UseOpenGLOrientationForUV(){return we},set UseOpenGLOrientationForUV(o){we=o}};class G extends Ve{static _CreateVideoTexture(e,t,i,s=!1,r=!1,n=G.TRILINEAR_SAMPLINGMODE,a={},h,l=5){throw pe("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,s,r=G.TRILINEAR_SAMPLINGMODE,n=null,a=null,h=null,l=!1,c,u,f,d,_){super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=null,this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedIdentity3x2=!0,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new z,this._isBlocking=!0,this.name=e||"",this.url=e;let m,g=!1,T=null,R=!0;typeof i=="object"&&i!==null?(m=i.noMipmap??!1,s=i.invertY??!we,r=i.samplingMode??G.TRILINEAR_SAMPLINGMODE,n=i.onLoad??null,a=i.onError??null,h=i.buffer??null,l=i.deleteBuffer??!1,c=i.format,u=i.mimeType,f=i.loaderOptions,d=i.creationFlags,g=i.useSRGBBuffer??!1,T=i.internalTexture??null,R=i.gammaSpace??R,_=i.forcedExtension??_):m=!!i,this._gammaSpace=R,this._noMipmap=m,this._invertY=s===void 0?!we:s,this._initialSamplingMode=r,this._buffer=h,this._deleteBuffer=l,this._mimeType=u,this._loaderOptions=f,this._creationFlags=d,this._useSRGBBuffer=g,this._forcedExtension=_,c!==void 0&&(this._format=c);const A=this.getScene(),y=this._getEngine();if(!y)return;y.onBeforeTextureInitObservable.notifyObservers(this);const E=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),this._texture._cachedWrapU!==null&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),this._texture._cachedWrapV!==null&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),this._texture._cachedWrapR!==null&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),n&&n(),!this.isBlocking&&A&&A.resetCachedMaterial()},x=(b,P)=>{this._loadingError=!0,this._errorObject={message:b,exception:P},a&&a(b,P),G.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!T){this._delayedOnLoad=E,this._delayedOnError=x;return}if(this._texture=T??this._getFromCache(this.url,m,r,this._invertY,g,this.isCube),this._texture)if(this._texture.isReady)Gs.SetImmediate(()=>E());else{const b=this._texture.onLoadedObservable.add(E);this._texture.onErrorObservable.add(P=>{x(P.message,P.exception),this._texture?.onLoadedObservable.remove(b)})}else if(!A||!A.useDelayedTextureLoading){try{this._texture=y.createTexture(this.url,m,this._invertY,A,r,E,x,this._buffer,void 0,this._format,this._forcedExtension,u,f,d,g)}catch(b){throw x("error loading",b),b}l&&(this._buffer=null)}else this.delayLoadState=4,this._delayedOnLoad=E,this._delayedOnError=x}updateURL(e,t=null,i,s){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,a=>a.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=s,this.delayLoadState=4;const r=this._delayedOnLoad,n=()=>{r?r():this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),i&&i()};this._delayedOnLoad=n,this.delayLoad()}delayLoad(){if(this.delayLoadState!==4)return;const e=this.getScene();if(!e)return;let t=this.url;!t&&(this.name.indexOf("://")>0||this.name.startsWith("data:"))&&(t=this.name),this.delayLoadState=1,this._texture=this._getFromCache(t,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?Gs.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(t,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null}_prepareRowForTextureGeneration(e,t,i,s){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,p.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,s),s.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,s.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,s.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,(!this._cachedTextureMatrix||!this._rowGenerationMatrix)&&(this._cachedTextureMatrix=D.Zero(),this._rowGenerationMatrix=new D,this._t0=p.Zero(),this._t1=p.Zero(),this._t2=p.Zero()),D.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(D.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,U.Matrix[0]),D.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,U.Matrix[1]),D.ScalingToRef(this._cachedUScale,this._cachedVScale,0,U.Matrix[2]),D.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,U.Matrix[3]),U.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(U.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(U.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(U.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),D.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));const t=this.getScene();if(!t)return this._cachedTextureMatrix;const i=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&i!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(1,s=>s.hasTexture(this)),this._cachedTextureMatrix}getReflectionTextureMatrix(){const e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode)if(this.coordinatesMode===G.PROJECTION_MODE){if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}else return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=D.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=D.Zero());const t=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case G.PLANAR_MODE:{D.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break}case G.PROJECTION_MODE:{D.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const i=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=i.updateFlag,i.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:D.IdentityToRef(this._cachedReflectionTextureMatrix);break}return t&&e.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){const e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return me.Clone(()=>new G(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){const e=this.name;G.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(G._SerializeInternalTextureUniqueId);if(!t)return null;if(G.SerializeBuffers||G.ForceSerializeBuffers)if(typeof this._buffer=="string"&&this._buffer.startsWith("data:"))t.base64String=this._buffer,t.name=t.name.replace("data:","");else if(this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array){const i=this.mimeType||"image/png";t.base64String=`data:${i};base64,${Kr(this._buffer)}`}else(G.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?El(this):xl(this));return t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,G._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=this._texture?.uniqueId),t.internalTextureLabel=this._texture?.label,t.noMipmap=this._noMipmap,this.name=e,t}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const l=ks.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&l.updateSamplingMode&&l._samplingMode&&l._samplingMode!==e.samplingMode&&l.updateSamplingMode(e.samplingMode),l}if(e.isCube&&!e.isRenderTarget)return G._CubeTextureParser(e,t,i);const s=e.internalTextureUniqueId!==void 0;if(!e.name&&!e.isRenderTarget&&!s)return null;let r;if(s){const h=t.getEngine().getLoadedTexturesCache();for(const l of h)if(l.uniqueId===e.internalTextureUniqueId){r=l;break}}const n=h=>{if(h&&h._texture&&(h._texture._cachedWrapU=null,h._texture._cachedWrapV=null,h._texture._cachedWrapR=null),e.samplingMode){const l=e.samplingMode;h&&h.samplingMode!==l&&h.updateSamplingMode(l)}if(h&&e.animations)for(let l=0;l<e.animations.length;l++){const c=e.animations[l],u=Pi("BABYLON.Animation");u&&h.animations.push(u.Parse(c))}h&&h._texture&&(s&&!r&&h._texture._setUniqueId(e.internalTextureUniqueId),h._texture.label=e.internalTextureLabel)};return me.Parse(()=>{let h=!0;if(e.noMipmap&&(h=!1),e.mirrorPlane){const l=G._CreateMirror(e.name,e.renderTargetSize,t,h);return l._waitingRenderList=e.renderList,l.mirrorPlane=si.FromArray(e.mirrorPlane),n(l),l}else if(e.isRenderTarget&&!e.base64String){let l=null;if(e.isCube){if(t.reflectionProbes)for(let c=0;c<t.reflectionProbes.length;c++){const u=t.reflectionProbes[c];if(u.name===e.name)return u.cubeTexture}}else l=G._CreateRenderTargetTexture(e.name,e.renderTargetSize,t,h,e._creationFlags??0),l._waitingRenderList=e.renderList;return n(l),l}else if(e.isVideo){const l=G._CreateVideoTexture(i+(e.url||e.name),i+(e.src||e.url),t,h,e.invertY,e.samplingMode,e.settings||{});return n(l),l}else{let l;if(typeof e.base64String=="string"&&e.base64String&&!r){const c={buffer:e.base64String,noMipmap:!h,invertY:e.invertY,samplingMode:e.samplingMode,useSRGBBuffer:e._useSRGBBuffer??!1,creationFlags:e._creationFlags??0,onLoad:()=>{n(l)}},u=e.base64String,f=u.startsWith("data:")?u.substring(5):u;l=G.CreateFromBase64String("",f,t,c),l.name=e.name}else{let c;e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?c=e.name:c=i+e.name,e.url&&(e.url.startsWith("data:")||G.UseSerializedUrlIfAny)&&(c=e.url);const u={noMipmap:!h,invertY:e.invertY,samplingMode:e.samplingMode,useSRGBBuffer:e._useSRGBBuffer??!1,creationFlags:e._creationFlags??0,onLoad:()=>{n(l)},internalTexture:r};l=new G(c,t,u)}return l}},e,t)}static CreateFromBase64String(e,t,i,s,r,n=G.TRILINEAR_SAMPLINGMODE,a=null,h=null,l=5,c,u){return new G("data:"+t,i,s,r,n,a,h,e,!1,l,void 0,void 0,c,u)}static LoadFromDataString(e,t,i,s=!1,r,n=!0,a=G.TRILINEAR_SAMPLINGMODE,h=null,l=null,c=5,u,f){return e.substring(0,5)!=="data:"&&(e="data:"+e),new G(e,i,r,n,a,h,l,t,s,c,void 0,void 0,u,f)}}G.SerializeBuffers=!0;G.ForceSerializeBuffers=!1;G.OnTextureLoadErrorObservable=new z;G._SerializeInternalTextureUniqueId=!1;G._CubeTextureParser=(o,e,t)=>{throw pe("CubeTexture")};G._CreateMirror=(o,e,t,i)=>{throw pe("MirrorTexture")};G._CreateRenderTargetTexture=(o,e,t,i,s)=>{throw pe("RenderTargetTexture")};G.NEAREST_SAMPLINGMODE=1;G.NEAREST_NEAREST_MIPLINEAR=8;G.BILINEAR_SAMPLINGMODE=2;G.LINEAR_LINEAR_MIPNEAREST=11;G.TRILINEAR_SAMPLINGMODE=3;G.LINEAR_LINEAR_MIPLINEAR=3;G.NEAREST_NEAREST_MIPNEAREST=4;G.NEAREST_LINEAR_MIPNEAREST=5;G.NEAREST_LINEAR_MIPLINEAR=6;G.NEAREST_LINEAR=7;G.NEAREST_NEAREST=1;G.LINEAR_NEAREST_MIPNEAREST=9;G.LINEAR_NEAREST_MIPLINEAR=10;G.LINEAR_LINEAR=2;G.LINEAR_NEAREST=12;G.EXPLICIT_MODE=0;G.SPHERICAL_MODE=1;G.PLANAR_MODE=2;G.CUBIC_MODE=3;G.PROJECTION_MODE=4;G.SKYBOX_MODE=5;G.INVCUBIC_MODE=6;G.EQUIRECTANGULAR_MODE=7;G.FIXED_EQUIRECTANGULAR_MODE=8;G.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;G.CLAMP_ADDRESSMODE=0;G.WRAP_ADDRESSMODE=1;G.MIRROR_ADDRESSMODE=2;G.UseSerializedUrlIfAny=!1;M([C()],G.prototype,"url",void 0);M([C()],G.prototype,"uOffset",void 0);M([C()],G.prototype,"vOffset",void 0);M([C()],G.prototype,"uScale",void 0);M([C()],G.prototype,"vScale",void 0);M([C()],G.prototype,"uAng",void 0);M([C()],G.prototype,"vAng",void 0);M([C()],G.prototype,"wAng",void 0);M([C()],G.prototype,"uRotationCenter",void 0);M([C()],G.prototype,"vRotationCenter",void 0);M([C()],G.prototype,"wRotationCenter",void 0);M([C()],G.prototype,"homogeneousRotationInUVTransform",void 0);M([C()],G.prototype,"isBlocking",null);Ye("BABYLON.Texture",G);me._TextureParser=G.Parse;const vf="modulepreload",Cf=function(o,e){return new URL(o,e).href},Xo={},he=function(e,t,i){let s=Promise.resolve();if(t&&t.length>0){const n=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),h=a?.nonce||a?.getAttribute("nonce");s=Promise.allSettled(t.map(l=>{if(l=Cf(l,i),l in Xo)return;Xo[l]=!0;const c=l.endsWith(".css"),u=c?'[rel="stylesheet"]':"";if(!!i)for(let _=n.length-1;_>=0;_--){const m=n[_];if(m.href===l&&(!c||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${u}`))return;const d=document.createElement("link");if(d.rel=c?"stylesheet":vf,c||(d.as="script"),d.crossOrigin="",d.href=l,h&&d.setAttribute("nonce",h),document.head.appendChild(d),c)return new Promise((_,m)=>{d.addEventListener("load",_),d.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${l}`)))})}))}function r(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return s.then(n=>{for(const a of n||[])a.status==="rejected"&&r(a.reason);return e().catch(r)})},kr=new Map;function pi(o,e){Df(o)&&W.Warn(`Extension with the name '${o}' already exists`),kr.set(o,e)}function Df(o){return kr.delete(o)}function bl(o,e){(e==="image/ktx"||e==="image/ktx2")&&(o=".ktx"),kr.has(o)||(o.endsWith(".ies")&&pi(".ies",async()=>await he(()=>import("./iesTextureLoader-B8AoKSG2.js").then(i=>i.i),[],import.meta.url).then(i=>new i._IESTextureLoader)),o.endsWith(".dds")&&pi(".dds",async()=>await he(()=>import("./ddsTextureLoader-s5HptTVZ.js"),__vite__mapDeps([0,1]),import.meta.url).then(i=>new i._DDSTextureLoader)),o.endsWith(".basis")&&pi(".basis",async()=>await he(()=>import("./basisTextureLoader-BdapVvhf.js").then(i=>i.d),[],import.meta.url).then(i=>new i._BasisTextureLoader)),o.endsWith(".env")&&pi(".env",async()=>await he(()=>Promise.resolve().then(()=>Ld),void 0,import.meta.url).then(i=>new i._ENVTextureLoader)),o.endsWith(".hdr")&&pi(".hdr",async()=>await he(()=>import("./hdrTextureLoader-Dqvpv0kr.js").then(i=>i.h),[],import.meta.url).then(i=>new i._HDRTextureLoader)),(o.endsWith(".ktx")||o.endsWith(".ktx2"))&&(pi(".ktx",async()=>await he(()=>import("./ktxTextureLoader-DTr7AKqG.js").then(i=>i.k),__vite__mapDeps([2,3]),import.meta.url).then(i=>new i._KTXTextureLoader)),pi(".ktx2",async()=>await he(()=>import("./ktxTextureLoader-DTr7AKqG.js").then(i=>i.k),__vite__mapDeps([2,3]),import.meta.url).then(i=>new i._KTXTextureLoader))),o.endsWith(".tga")&&pi(".tga",async()=>await he(()=>import("./tgaTextureLoader-D7Pjisvo.js").then(i=>i.t),[],import.meta.url).then(i=>new i._TGATextureLoader)),o.endsWith(".exr")&&pi(".exr",async()=>await he(()=>import("./exrTextureLoader-D39k4eK_.js").then(i=>i.s),[],import.meta.url).then(i=>new i._ExrTextureLoader)));const t=kr.get(o);return t?Promise.resolve(t(e)):null}function Of(o){const e=o.split("?")[0],t=e.lastIndexOf(".");return t>-1?e.substring(t).toLowerCase():""}J.prototype._partialLoadFile=function(o,e,t,i,s=null){const r=a=>{t[e]=a,t._internalCount++,t._internalCount===6&&i(t)},n=(a,h)=>{s&&a&&s(a.status+" "+a.statusText,h)};this._loadFile(o,r,void 0,void 0,!0,n)};J.prototype._cascadeLoadFiles=function(o,e,t,i=null){const s=[];s._internalCount=0;for(let r=0;r<6;r++)this._partialLoadFile(t[r],r,s,e,i)};J.prototype._cascadeLoadImgs=function(o,e,t,i,s=null,r){const n=[];n._internalCount=0;for(let a=0;a<6;a++)this._partialLoadImg(i[a],a,n,o,e,t,s,r)};J.prototype._partialLoadImg=function(o,e,t,i,s,r,n=null,a){const h=Zr();jr(o,u=>{t[e]=u,t._internalCount++,i&&i.removePendingData(h),t._internalCount===6&&r&&r(s,t)},(u,f)=>{i&&i.removePendingData(h),n&&n(u,f)},i?i.offlineProvider:null,a),i&&i.addPendingData(h)};J.prototype.createCubeTextureBase=function(o,e,t,i,s=null,r=null,n,a=null,h=!1,l=0,c=0,u=null,f=null,d=null,_=!1,m=null){const g=u||new xt(this,7);g.isCube=!0,g.url=o,g.generateMipMaps=!i,g._lodGenerationScale=l,g._lodGenerationOffset=c,g._useSRGBBuffer=!!_&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!i),g!==u&&(g.label=o.substring(0,60)),this._doNotHandleContextLost||(g._extension=a,g._files=t,g._buffer=m);const T=o;this._transformTextureUrl&&!u&&(o=this._transformTextureUrl(o));const R=a??Of(o),A=bl(R),y=(x,b)=>{g.dispose(),r?r(x,b):x&&W.Warn(x)},E=(x,b)=>{o===T?x&&y(x.status+" "+x.statusText,b):(W.Warn(`Failed to load ${o}, falling back to the ${T}`),this.createCubeTextureBase(T,e,t,!!i,s,y,n,a,h,l,c,g,f,d,_,m))};if(A)A.then(x=>{const b=P=>{f&&f(g,P),x.loadCubeData(P,g,h,s,(v,O)=>{y(v,O)})};m?b(m):t&&t.length===6?x.supportCascades?this._cascadeLoadFiles(e,P=>b(P.map(v=>new Uint8Array(v))),t,y):y("Textures type does not support cascades."):this._loadFile(o,P=>b(new Uint8Array(P)),void 0,e?e.offlineProvider||null:void 0,!0,E)});else{if(!t||t.length===0)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(e,g,(x,b)=>{d&&d(x,b)},t,y)}return this._internalTexturesCache.push(g),g};const Ko=.8;class St extends Ve{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(D.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let s="";for(const r of e)s+=r;return new St(s,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,s=!0){const r=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const n=new St(e,t,null,!1,null,null,null,void 0,!0,i,s);return t.useDelayedTextureLoading=r,n}constructor(e,t,i=null,s=!1,r=null,n=null,a=null,h=5,l=!1,c=null,u=!1,f=Ko,d=0,_,m){super(t),this.onLoadObservable=new z,this.boundingBoxPosition=p.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new D,this._buffer=null,this.name=e,this.url=e,this._noMipmap=s,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=D.Identity(),this.coordinatesMode=G.CUBIC_MODE;let g,T=null;i!==null&&!Array.isArray(i)?(g=i.extensions??null,this._noMipmap=i.noMipmap??!1,r=i.files??null,T=i.buffer??null,this._format=i.format??5,l=i.prefiltered??!1,c=i.forcedExtension??null,this._createPolynomials=i.createPolynomials??!1,this._lodScale=i.lodScale??Ko,this._lodOffset=i.lodOffset??0,this._loaderOptions=i.loaderOptions,this._useSRGBBuffer=i.useSRGBBuffer,n=i.onLoad??null,a=i.onError??null):(this._noMipmap=s,this._format=h,this._createPolynomials=u,g=i,this._loaderOptions=_,this._useSRGBBuffer=m,this._lodScale=f,this._lodOffset=d),!(!e&&!r)&&this.updateURL(e,c,n,l,a,g,this.getScene()?.useDelayedTextureLoading,r,T)}getClassName(){return"CubeTexture"}updateURL(e,t=null,i=null,s=!1,r=null,n=null,a=!1,h=null,l=null){(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,t&&(this._forcedExtension=t);const c=e.lastIndexOf("."),u=t||(c>-1?e.substring(c).toLowerCase():""),f=u.indexOf(".dds")===0,d=u.indexOf(".env")===0,_=u.indexOf(".basis")===0;if(d?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=s,s&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),h)this._files=h;else if(!_&&!d&&!f&&!n&&(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,n){for(let m=0;m<n.length;m++)this._files.push(e+n[m]);this._extensions=n}this._buffer=l,a?(this.delayLoadState=4,this._delayedOnLoad=i,this._delayedOnError=r):this._loadTexture(i,r)}delayLoad(e){this.delayLoadState===4&&(e&&(this._forcedExtension=e),this.delayLoadState=1,this._loadTexture(this._delayedOnLoad,this._delayedOnError))}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){if(e.updateFlag===this._textureMatrix.updateFlag||(e.isIdentity()!==this._textureMatrix.isIdentity()&&this.getScene()?.markAllMaterialsAsDirty(1,r=>r.getActiveTextures().indexOf(this)!==-1),this._textureMatrix=e,!this.getScene()?.useRightHandedSystem))return;const t=U.Vector3[0],i=U.Quaternion[0],s=U.Vector3[1];this._textureMatrix.decompose(t,i,s),i.z*=-1,i.w*=-1,D.ComposeToRef(t,i,s,this._textureMatrixRefraction)}getRefractionTextureMatrix(){return this.getScene()?.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){const i=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const r=()=>{this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),this.getScene()?.markAllMaterialsAsDirty(1)),e&&e()},n=(a,h)=>{this._loadingError=!0,this._errorObject={message:a,exception:h},t&&t(a,h),G.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?fe.SetImmediate(()=>r()):this._texture.onLoadedObservable.add(()=>r()):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,i,this._lodScale,this._lodOffset,e,n,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,i,this._files,this._noMipmap,e,n,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer,this._buffer),this._texture?.onLoadedObservable.add(()=>this.onLoadObservable.notifyObservers(this)))}static Parse(e,t,i){const s=me.Parse(()=>{let r=!1;return e.prefiltered&&(r=e.prefiltered),new St(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,r,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(s.boundingBoxPosition=p.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=p.FromArray(e.boundingBoxSize)),e.animations)for(let r=0;r<e.animations.length;r++){const n=e.animations[r],a=Pi("BABYLON.Animation");a&&s.animations.push(a.Parse(n))}return s}clone(){let e=0;const t=me.Clone(()=>{const i=new St(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=i.uniqueId,i},this);return t.uniqueId=e,t}}M([C()],St.prototype,"url",void 0);M([Ut()],St.prototype,"boundingBoxPosition",void 0);M([Ut()],St.prototype,"boundingBoxSize",null);M([C("rotationY")],St.prototype,"rotationY",null);M([C("files")],St.prototype,"_files",void 0);M([C("forcedExtension")],St.prototype,"_forcedExtension",void 0);M([C("extensions")],St.prototype,"_extensions",void 0);M([Gh("textureMatrix")],St.prototype,"_textureMatrix",void 0);M([Gh("textureMatrixRefraction")],St.prototype,"_textureMatrixRefraction",void 0);G._CubeTextureParser=St.Parse;Ye("BABYLON.CubeTexture",St);var Yo;(function(o){o[o.LOCAL=0]="LOCAL",o[o.WORLD=1]="WORLD",o[o.BONE=2]="BONE"})(Yo||(Yo={}));class Vi{}Vi.X=new p(1,0,0);Vi.Y=new p(0,1,0);Vi.Z=new p(0,0,1);var jo;(function(o){o[o.X=0]="X",o[o.Y=1]="Y",o[o.Z=2]="Z"})(jo||(jo={}));class Gt{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new si(0,0,0,0));return Gt.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){Gt.GetNearPlaneToRef(e,t[0]),Gt.GetFarPlaneToRef(e,t[1]),Gt.GetLeftPlaneToRef(e,t[2]),Gt.GetRightPlaneToRef(e,t[3]),Gt.GetTopPlaneToRef(e,t[4]),Gt.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}var Zo;(function(o){o[o.CW=0]="CW",o[o.CCW=1]="CCW"})(Zo||(Zo={}));class Zp{static Interpolate(e,t,i,s,r){if(e===0)return 0;const n=1-3*s+3*t,a=3*s-6*t,h=3*t;let l=e;for(let c=0;c<5;c++){const u=l*l,f=u*l,d=n*f+a*u+h*l,_=1/(3*n*u+2*a*l+h);l-=(d-e)*_,l=Math.min(1,Math.max(0,l))}return 3*Math.pow(1-l,2)*l*i+3*(1-l)*Math.pow(l,2)*r+Math.pow(l,3)}}class fi{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return this._radians*180/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),s=Math.atan2(i.y,i.x);return new fi(s)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(i===0)return new fi(Math.PI/2);i=Math.sqrt(i);let s=e.dot(t)/i;s=ke(s,-1,1);const r=Math.acos(s);return new fi(r)}static FromRadians(e){return new fi(e)}static FromDegrees(e){return new fi(e*Math.PI/180)}}class Ff{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const s=Math.pow(t.x,2)+Math.pow(t.y,2),r=(Math.pow(e.x,2)+Math.pow(e.y,2)-s)/2,n=(s-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new ie((r*(t.y-i.y)-n*(e.y-t.y))/a,((e.x-t.x)*n-(t.x-i.x)*r)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=fi.BetweenTwoPoints(this.centerPoint,this.startPoint);const h=this.startAngle.degrees();let l=fi.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),c=fi.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-h>180&&(l-=360),l-h<-180&&(l+=360),c-l>180&&(c-=360),c-l<-180&&(c+=360),this.orientation=l-h<0?0:1,this.angle=fi.FromDegrees(this.orientation===0?h-c:c-h)}}class ar{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new ie(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new ie(e,t),s=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(s).length(),this}addArcTo(e,t,i,s,r=36){if(this.closed)return this;const n=this._points[this._points.length-1],a=new ie(e,t),h=new ie(i,s),l=new Ff(n,a,h);let c=l.angle.radians()/r;l.orientation===0&&(c*=-1);let u=l.startAngle.radians()+c;for(let f=0;f<r;f++){const d=Math.cos(u)*l.radius+l.centerPoint.x,_=Math.sin(u)*l.radius+l.centerPoint.y;this.addLineTo(d,_),u+=c}return this}addQuadraticCurveTo(e,t,i,s,r=36){if(this.closed)return this;const n=(h,l,c,u)=>(1-h)*(1-h)*l+2*h*(1-h)*c+h*h*u,a=this._points[this._points.length-1];for(let h=0;h<=r;h++){const l=h/r,c=n(l,a.x,e,i),u=n(l,a.y,t,s);this.addLineTo(c,u)}return this}addBezierCurveTo(e,t,i,s,r,n,a=36){if(this.closed)return this;const h=(c,u,f,d,_)=>(1-c)*(1-c)*(1-c)*u+3*c*(1-c)*(1-c)*f+3*c*c*(1-c)*d+c*c*c*_,l=this._points[this._points.length-1];for(let c=0;c<=a;c++){const u=c/a,f=h(u,l.x,e,i,r),d=h(u,l.y,t,s,n);this.addLineTo(f,d)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let s=i-1,r=0;r<i;s=r++){let n=this._points[s],a=this._points[r],h=a.x-n.x,l=a.y-n.y;if(Math.abs(l)>Number.EPSILON){if(l<0&&(n=this._points[r],h=-h,a=this._points[s],l=-l),e.y<n.y||e.y>a.y)continue;if(e.y===n.y&&e.x===n.x)return!0;{const c=l*(e.x-n.x)-h*(e.y-n.y);if(c===0)return!0;if(c<0)continue;t=!t}}else{if(e.y!==n.y)continue;if(a.x<=e.x&&e.x<=n.x||n.x<=e.x&&e.x<=a.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,s=0;s<e;i=s++)t+=this._points[i].x*this._points[s].y-this._points[s].x*this._points[i].y;return t*.5}getPoints(){return this._points}getPointAtLengthPosition(e){if(e<0||e>1)return ie.Zero();const t=e*this.length();let i=0;for(let s=0;s<this._points.length;s++){const r=(s+1)%this._points.length,n=this._points[s],h=this._points[r].subtract(n),l=h.length()+i;if(t>=i&&t<=l){const c=h.normalize(),u=t-i;return new ie(n.x+c.x*u,n.y+c.y*u)}i=l}return ie.Zero()}static StartingAt(e,t){return new ar(e,t)}}class Ks{constructor(e,t=null,i,s=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:p.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:D.Identity()};for(let r=0;r<e.length;r++)this._curve[r]=e[r].clone();this._raw=i||!1,this._alignTangentsWithPath=s,this._compute(t,s)}getCurve(){return this._curve}getPoints(){return this._curve}length(){return this._distances[this._distances.length-1]}getTangents(){return this._tangents}getNormals(){return this._normals}getBinormals(){return this._binormals}getDistances(){return this._distances}getPointAt(e){return this._updatePointAtData(e).point}getTangentAt(e,t=!1){return this._updatePointAtData(e,t),t?p.TransformCoordinates(p.Forward(),this._pointAtData.interpolationMatrix):this._tangents[this._pointAtData.previousPointArrayIndex]}getNormalAt(e,t=!1){return this._updatePointAtData(e,t),t?p.TransformCoordinates(p.Right(),this._pointAtData.interpolationMatrix):this._normals[this._pointAtData.previousPointArrayIndex]}getBinormalAt(e,t=!1){return this._updatePointAtData(e,t),t?p.TransformCoordinates(p.UpReadOnly,this._pointAtData.interpolationMatrix):this._binormals[this._pointAtData.previousPointArrayIndex]}getDistanceAt(e){return this.length()*e}getPreviousPointIndexAt(e){return this._updatePointAtData(e),this._pointAtData.previousPointArrayIndex}getSubPositionAt(e){return this._updatePointAtData(e),this._pointAtData.subPosition}getClosestPositionTo(e){let t=Number.MAX_VALUE,i=0;for(let s=0;s<this._curve.length-1;s++){const r=this._curve[s+0],n=this._curve[s+1].subtract(r).normalize(),a=this._distances[s+1]-this._distances[s+0],h=Math.min(Math.max(p.Dot(n,e.subtract(r).normalize()),0)*p.Distance(r,e)/a,1),l=p.Distance(r.add(n.scale(h*a)),e);l<t&&(t=l,i=(this._distances[s+0]+a*h)/this.length())}return i}slice(e=0,t=1){if(e<0&&(e=1-e*-1%1),t<0&&(t=1-t*-1%1),e>t){const l=e;e=t,t=l}const i=this.getCurve(),s=this.getPointAt(e);let r=this.getPreviousPointIndexAt(e);const n=this.getPointAt(t),a=this.getPreviousPointIndexAt(t)+1,h=[];return e!==0&&(r++,h.push(s)),h.push(...i.slice(r,a)),(t!==1||e===1)&&h.push(n),new Ks(h,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let s=0;s<e.length;s++)this._curve[s].x=e[s].x,this._curve[s].y=e[s].y,this._curve[s].z=e[s].z;return this._compute(t,i),this}_compute(e,t=!1){const i=this._curve.length;if(i<2)return;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();const s=this._tangents[0],r=this._normalVector(s,e);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=p.Cross(s,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;let n,a,h,l,c;for(let u=1;u<i;u++)n=this._getLastNonNullVector(u),u<i-1&&(a=this._getFirstNonNullVector(u),this._tangents[u]=t?a:n.add(a),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+this._curve[u].subtract(this._curve[u-1]).length(),h=this._tangents[u],c=this._binormals[u-1],this._normals[u]=p.Cross(c,h),this._raw||(this._normals[u].length()===0?(l=this._normals[u-1],this._normals[u]=l.clone()):this._normals[u].normalize()),this._binormals[u]=p.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize();this._pointAtData.id=NaN}_getFirstNonNullVector(e){let t=1,i=this._curve[e+t].subtract(this._curve[e]);for(;i.length()===0&&e+t+1<this._curve.length;)t++,i=this._curve[e+t].subtract(this._curve[e]);return i}_getLastNonNullVector(e){let t=1,i=this._curve[e].subtract(this._curve[e-t]);for(;i.length()===0&&e>t+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,s=e.length();if(s===0&&(s=1),t==null){let r;Ue(Math.abs(e.y)/s,1,Ke)?Ue(Math.abs(e.x)/s,1,Ke)?Ue(Math.abs(e.z)/s,1,Ke)?r=p.Zero():r=new p(0,0,1):r=new p(1,0,0):r=new p(0,-1,0),i=p.Cross(e,r)}else i=p.Cross(e,t),p.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;const i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let s=i[0],r,n=0;const a=e*this.length();for(let h=1;h<i.length;h++){r=i[h];const l=p.Distance(s,r);if(n+=l,n===a)return this._setPointAtData(e,1,r,h,t);if(n>a){const u=(n-a)/l,f=s.subtract(r),d=r.add(f.scaleInPlace(u));return this._setPointAtData(e,1-u,d,h-1,t)}s=r}return this._pointAtData}_setPointAtData(e,t,i,s,r){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=s,this._pointAtData.interpolateReady=r,r&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=D.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),s=this._normals[e].clone(),r=this._binormals[e].clone(),n=this._tangents[t].clone(),a=this._normals[t].clone(),h=this._binormals[t].clone(),l=re.RotationQuaternionFromAxis(s,r,i),c=re.RotationQuaternionFromAxis(a,h,n);re.Slerp(l,c,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class vi{static CreateQuadraticBezier(e,t,i,s){s=s>2?s:3;const r=[],n=(a,h,l,c)=>(1-a)*(1-a)*h+2*a*(1-a)*l+a*a*c;for(let a=0;a<=s;a++)r.push(new p(n(a/s,e.x,t.x,i.x),n(a/s,e.y,t.y,i.y),n(a/s,e.z,t.z,i.z)));return new vi(r)}static CreateCubicBezier(e,t,i,s,r){r=r>3?r:4;const n=[],a=(h,l,c,u,f)=>(1-h)*(1-h)*(1-h)*l+3*h*(1-h)*(1-h)*c+3*h*h*(1-h)*u+h*h*h*f;for(let h=0;h<=r;h++)n.push(new p(a(h/r,e.x,t.x,i.x,s.x),a(h/r,e.y,t.y,i.y,s.y),a(h/r,e.z,t.z,i.z,s.z)));return new vi(n)}static CreateHermiteSpline(e,t,i,s,r){const n=[],a=1/r;for(let h=0;h<=r;h++)n.push(p.Hermite(e,t,i,s,h*a));return new vi(n)}static CreateCatmullRomSpline(e,t,i){const s=[],r=1/t;let n=0;if(i){const a=e.length;for(let h=0;h<a;h++){n=0;for(let l=0;l<t;l++)s.push(p.CatmullRom(e[h%a],e[(h+1)%a],e[(h+2)%a],e[(h+3)%a],n)),n+=r}s.push(s[0])}else{const a=[];a.push(e[0].clone()),Array.prototype.push.apply(a,e),a.push(e[e.length-1].clone());let h=0;for(;h<a.length-3;h++){n=0;for(let l=0;l<t;l++)s.push(p.CatmullRom(a[h],a[h+1],a[h+2],a[h+3],n)),n+=r}h--,s.push(p.CatmullRom(a[h],a[h+1],a[h+2],a[h+3],n))}return new vi(s)}static ArcThru3Points(e,t,i,s=32,r=!1,n=!1){const a=[],h=t.subtract(e),l=i.subtract(t),c=e.subtract(i),u=p.Cross(h,l),f=u.length();if(f<Math.pow(10,-8))return new vi(a);const d=h.lengthSquared(),_=l.lengthSquared(),m=c.lengthSquared(),g=u.lengthSquared(),T=h.length(),R=l.length(),A=c.length(),y=.5*T*R*A/f,E=p.Dot(h,c),x=p.Dot(h,l),b=p.Dot(l,c),P=-.5*_*E/g,v=-.5*m*x/g,O=-.5*d*b/g,k=e.scale(P).add(t.scale(v)).add(i.scale(O)),q=e.subtract(k).normalize(),L=p.Cross(u,q).normalize();if(n){const ee=2*Math.PI/s;for(let Q=0;Q<=2*Math.PI;Q+=ee)a.push(k.add(q.scale(y*Math.cos(Q)).add(L.scale(y*Math.sin(Q)))));a.push(e)}else{const ee=1/s;let Q=0,se;do se=k.add(q.scale(y*Math.cos(Q)).add(L.scale(y*Math.sin(Q)))),a.push(se),Q+=ee;while(!se.equalsWithEpsilon(i,y*ee*1.1));a.push(i),r&&a.push(e)}return new vi(a)}constructor(e){this._length=0,this._points=e,this._length=this._computeLength(e)}getPoints(){return this._points}length(){return this._length}continue(e){const t=this._points[this._points.length-1],i=this._points.slice(),s=e.getPoints();for(let n=1;n<s.length;n++)i.push(s[n].subtract(s[0]).add(t));return new vi(i)}_computeLength(e){let t=0;for(let i=1;i<e.length;i++)t+=e[i].subtract(e[i-1]).length();return t}}class Ys{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new Ys(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new Ys(this.x,this.y,this.width,this.height)}}const ci=[Math.sqrt(1/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(3/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(15/(4*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(5/(16*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(15/(16*Math.PI))],wf=[()=>1,o=>o.y,o=>o.z,o=>o.x,o=>o.x*o.y,o=>o.y*o.z,o=>3*o.z*o.z-1,o=>o.x*o.z,o=>o.x*o.x-o.y*o.y],mi=(o,e)=>ci[o]*wf[o](e),Ti=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4];class js{constructor(){this.preScaled=!1,this.l00=p.Zero(),this.l1_1=p.Zero(),this.l10=p.Zero(),this.l11=p.Zero(),this.l2_2=p.Zero(),this.l2_1=p.Zero(),this.l20=p.Zero(),this.l21=p.Zero(),this.l22=p.Zero()}addLight(e,t,i){U.Vector3[0].set(t.r,t.g,t.b);const s=U.Vector3[0],r=U.Vector3[1];s.scaleToRef(i,r),r.scaleToRef(mi(0,e),U.Vector3[2]),this.l00.addInPlace(U.Vector3[2]),r.scaleToRef(mi(1,e),U.Vector3[2]),this.l1_1.addInPlace(U.Vector3[2]),r.scaleToRef(mi(2,e),U.Vector3[2]),this.l10.addInPlace(U.Vector3[2]),r.scaleToRef(mi(3,e),U.Vector3[2]),this.l11.addInPlace(U.Vector3[2]),r.scaleToRef(mi(4,e),U.Vector3[2]),this.l2_2.addInPlace(U.Vector3[2]),r.scaleToRef(mi(5,e),U.Vector3[2]),this.l2_1.addInPlace(U.Vector3[2]),r.scaleToRef(mi(6,e),U.Vector3[2]),this.l20.addInPlace(U.Vector3[2]),r.scaleToRef(mi(7,e),U.Vector3[2]),this.l21.addInPlace(U.Vector3[2]),r.scaleToRef(mi(8,e),U.Vector3[2]),this.l22.addInPlace(U.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(Ti[0]),this.l1_1.scaleInPlace(Ti[1]),this.l10.scaleInPlace(Ti[2]),this.l11.scaleInPlace(Ti[3]),this.l2_2.scaleInPlace(Ti[4]),this.l2_1.scaleInPlace(Ti[5]),this.l20.scaleInPlace(Ti[6]),this.l21.scaleInPlace(Ti[7]),this.l22.scaleInPlace(Ti[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(ci[0]),this.l1_1.scaleInPlace(ci[1]),this.l10.scaleInPlace(ci[2]),this.l11.scaleInPlace(ci[3]),this.l2_2.scaleInPlace(ci[4]),this.l2_1.scaleInPlace(ci[5]),this.l20.scaleInPlace(ci[6]),this.l21.scaleInPlace(ci[7]),this.l22.scaleInPlace(ci[8])}updateFromArray(e){return p.FromArrayToRef(e[0],0,this.l00),p.FromArrayToRef(e[1],0,this.l1_1),p.FromArrayToRef(e[2],0,this.l10),p.FromArrayToRef(e[3],0,this.l11),p.FromArrayToRef(e[4],0,this.l2_2),p.FromArrayToRef(e[5],0,this.l2_1),p.FromArrayToRef(e[6],0,this.l20),p.FromArrayToRef(e[7],0,this.l21),p.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return p.FromFloatsToRef(e[0],e[1],e[2],this.l00),p.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),p.FromFloatsToRef(e[6],e[7],e[8],this.l10),p.FromFloatsToRef(e[9],e[10],e[11],this.l11),p.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),p.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),p.FromFloatsToRef(e[18],e[19],e[20],this.l20),p.FromFloatsToRef(e[21],e[22],e[23],this.l21),p.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new js().updateFromArray(e)}static FromPolynomial(e){const t=new js;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}}class Ts{constructor(){this.x=p.Zero(),this.y=p.Zero(),this.z=p.Zero(),this.xx=p.Zero(),this.yy=p.Zero(),this.zz=p.Zero(),this.xy=p.Zero(),this.yz=p.Zero(),this.zx=p.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=js.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){U.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=U.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),U.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),U.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(U.Vector3[0]).addInPlace(U.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(U.Vector3[0]).subtractInPlace(U.Vector3[1]),this.zz.copyFrom(e.l00),U.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(U.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return new Ts().updateFromHarmonics(e)}static FromArray(e){const t=new Ts;return p.FromArrayToRef(e[0],0,t.x),p.FromArrayToRef(e[1],0,t.y),p.FromArrayToRef(e[2],0,t.z),p.FromArrayToRef(e[3],0,t.xx),p.FromArrayToRef(e[4],0,t.yy),p.FromArrayToRef(e[5],0,t.zz),p.FromArrayToRef(e[6],0,t.yz),p.FromArrayToRef(e[7],0,t.zx),p.FromArrayToRef(e[8],0,t.xy),t}}class Et{constructor(e){this.length=0,this.data=new Array(e),this._id=Et._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;t<this.length;t++)e(this.data[t])}sort(e){this.data.sort(e)}reset(){this.length=0}dispose(){this.reset(),this.data&&(this.data.length=0)}concat(e){if(e.length!==0){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t<e.length;t++)this.data[this.length++]=(e.data||e)[t]}}indexOf(e){const t=this.data.indexOf(e);return t>=this.length?-1:t}contains(e){return this.indexOf(e)!==-1}}Et._GlobalId=0;class Zi extends Et{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return e.__smartArrayFlags&&e.__smartArrayFlags[this._id]===this._duplicateId?!1:(this.push(e),!0)}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(e.length!==0){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t<e.length;t++){const i=(e.data||e)[t];this.pushNoDuplicate(i)}}}}class qo{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach((t,i)=>this.add(t,i))}get(e){const t=this._data[e];if(t!==void 0)return t}getOrAddWithFactory(e,t){let i=this.get(e);return i!==void 0||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return i!==void 0?i:(this.add(e,t),t)}contains(e){return this._data[e]!==void 0}add(e,t){return this._data[e]!==void 0?!1:(this._data[e]=t,++this._count,!0)}set(e,t){return this._data[e]===void 0?!1:(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return t!==void 0?(delete this._data[e],--this._count,t):null}remove(e){return this.contains(e)?(delete this._data[e],--this._count,!0):!1}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data){const i=this._data[t];e(t,i)}}first(e){for(const t in this._data){const i=this._data[t],s=e(t,i);if(s)return s}return null}}function Rl(o){o.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class qe{constructor(){this._dirty=!0,this._tempColor=new Ce(0,0,0,0),this._globalCurve=new Ce(0,0,0,0),this._highlightsCurve=new Ce(0,0,0,0),this._midtonesCurve=new Ce(0,0,0,0),this._shadowsCurve=new Ce(0,0,0,0),this._positiveCurve=new Ce(0,0,0,0),this._negativeCurve=new Ce(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",s="vCameraColorCurveNeutral",r="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(s,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(r,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,s,r){e!=null&&(e=qe._Clamp(e,0,360),t=qe._Clamp(t,-100,100),i=qe._Clamp(i,-100,100),s=qe._Clamp(s,-100,100),t=qe._ApplyColorGradingSliderNonlinear(t),t*=.5,s=qe._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),qe._FromHSBToRef(e,t,50+.25*s,r),r.scaleToRef(2,r),r.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,s){let r=qe._Clamp(e,0,360);const n=qe._Clamp(t/100,0,1),a=qe._Clamp(i/100,0,1);if(n===0)s.r=a,s.g=a,s.b=a;else{r/=60;const h=Math.floor(r),l=r-h,c=a*(1-n),u=a*(1-n*l),f=a*(1-n*(1-l));switch(h){case 0:s.r=a,s.g=f,s.b=c;break;case 1:s.r=u,s.g=a,s.b=c;break;case 2:s.r=c,s.g=a,s.b=f;break;case 3:s.r=c,s.g=u,s.b=a;break;case 4:s.r=f,s.g=c,s.b=a;break;default:s.r=a,s.g=c,s.b=u;break}}s.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return me.Clone(()=>new qe,this)}serialize(){return me.Serialize(this)}static Parse(e){return me.Parse(()=>new qe,e,null,null)}}qe.PrepareUniforms=Rl;M([C()],qe.prototype,"_globalHue",void 0);M([C()],qe.prototype,"_globalDensity",void 0);M([C()],qe.prototype,"_globalSaturation",void 0);M([C()],qe.prototype,"_globalExposure",void 0);M([C()],qe.prototype,"_highlightsHue",void 0);M([C()],qe.prototype,"_highlightsDensity",void 0);M([C()],qe.prototype,"_highlightsSaturation",void 0);M([C()],qe.prototype,"_highlightsExposure",void 0);M([C()],qe.prototype,"_midtonesHue",void 0);M([C()],qe.prototype,"_midtonesDensity",void 0);M([C()],qe.prototype,"_midtonesSaturation",void 0);M([C()],qe.prototype,"_midtonesExposure",void 0);me._ColorCurvesParser=qe.Parse;function Lf(o,e){e.EXPOSURE&&o.push("exposureLinear"),e.CONTRAST&&o.push("contrast"),e.COLORGRADING&&o.push("colorTransformSettings"),(e.VIGNETTE||e.DITHER)&&o.push("vInverseScreenSize"),e.VIGNETTE&&(o.push("vignetteSettings1"),o.push("vignetteSettings2")),e.COLORCURVES&&Rl(o),e.DITHER&&o.push("ditherIntensity")}function Bf(o,e){e.COLORGRADING&&o.push("txColorTransform")}class Oe{constructor(){this.colorCurves=new qe,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=Oe.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new Ce(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=Oe.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.outputTextureWidth=0,this.outputTextureHeight=0,this.onUpdateParameters=new z}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=0,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===Oe._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,!this._toneMappingEnabled)e.TONEMAPPING=0;else switch(this._toneMappingType){case Oe.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case Oe.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1;break}e.CONTRAST=this.contrast!==1,e.EXPOSURE=this.exposure!==1,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||!!e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&qe.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/(this.outputTextureWidth||e.getEngine().getRenderWidth()),s=1/(this.outputTextureHeight||e.getEngine().getRenderHeight());if(e.setFloat2("vInverseScreenSize",i,s),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=t??s/i;let n=Math.tan(this.vignetteCameraFov*.5),a=n*r;const h=Math.sqrt(a*n);a=wn(a,h,this.vignetteStretch),n=wn(n,h,this.vignetteStretch),e.setFloat4("vignetteSettings1",a,n,-a*this.vignetteCenterX,-n*this.vignetteCenterY);const l=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,l)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const i=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(i-1)/i,.5/i,i,this.colorGradingTexture.level)}}clone(){return me.Clone(()=>new Oe,this)}serialize(){return me.Serialize(this)}static Parse(e){const t=me.Parse(()=>new Oe,e,null,null);return e.vignetteCentreX!==void 0&&(t.vignetteCenterX=e.vignetteCentreX),e.vignetteCentreY!==void 0&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}Oe.TONEMAPPING_STANDARD=0;Oe.TONEMAPPING_ACES=1;Oe.TONEMAPPING_KHR_PBR_NEUTRAL=2;Oe.PrepareUniforms=Lf;Oe.PrepareSamplers=Bf;Oe._VIGNETTEMODE_MULTIPLY=0;Oe._VIGNETTEMODE_OPAQUE=1;M([du()],Oe.prototype,"colorCurves",void 0);M([C()],Oe.prototype,"_colorCurvesEnabled",void 0);M([qt("colorGradingTexture")],Oe.prototype,"_colorGradingTexture",void 0);M([C()],Oe.prototype,"_colorGradingEnabled",void 0);M([C()],Oe.prototype,"_colorGradingWithGreenDepth",void 0);M([C()],Oe.prototype,"_colorGradingBGR",void 0);M([C()],Oe.prototype,"_exposure",void 0);M([C()],Oe.prototype,"_toneMappingEnabled",void 0);M([C()],Oe.prototype,"_toneMappingType",void 0);M([C()],Oe.prototype,"_contrast",void 0);M([C()],Oe.prototype,"vignetteStretch",void 0);M([C()],Oe.prototype,"vignetteCenterX",void 0);M([C()],Oe.prototype,"vignetteCenterY",void 0);M([C()],Oe.prototype,"vignetteWeight",void 0);M([La()],Oe.prototype,"vignetteColor",void 0);M([C()],Oe.prototype,"vignetteCameraFov",void 0);M([C()],Oe.prototype,"_vignetteBlendMode",void 0);M([C()],Oe.prototype,"_vignetteEnabled",void 0);M([C()],Oe.prototype,"_ditheringEnabled",void 0);M([C()],Oe.prototype,"_ditheringIntensity",void 0);M([C()],Oe.prototype,"_skipFinalColorClamp",void 0);M([C()],Oe.prototype,"_applyByPostProcess",void 0);M([C()],Oe.prototype,"_isEnabled",void 0);M([C()],Oe.prototype,"outputTextureWidth",void 0);M([C()],Oe.prototype,"outputTextureHeight",void 0);me._ImageProcessingConfigurationParser=Oe.Parse;Ye("BABYLON.ImageProcessingConfiguration",Oe);class oe{constructor(e,t,i=!1,s,r=!1,n){this._uniformNames=[],this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,this._dynamic=i,this._name=s??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._trackUBOsInFrame=!1,(n===void 0&&this._engine._features.trackUbosInFrame||n===!0)&&(this._buffers=[],this._bufferIndex=-1,this._bufferUpdatedLastFrame=!1,this._createBufferOnWrite=!1,this._currentFrameId=0,this._trackUBOsInFrame=!0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}getUniformNames(){return this._uniformNames}_fillAlignment(e){let t;if(e<=2?t=e:t=4,this._uniformLocationPointer%t!==0){const i=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const s=this._uniformLocationPointer-i;for(let r=0;r<s;r++)this._data.push(0)}}addUniform(e,t,i=0){if(i>0&&typeof t=="number"&&(this._uniformArraySizes[e]={strideSize:t,arraySize:i}),this._uniformLocations[e]!==void 0||(this._uniformNames.push(e),this._noUBO))return;let s;if(i>0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;if(this._fillAlignment(4),t==16)t=t*i;else{const n=(4-t)*i;t=t*i+n}s=[];for(let r=0;r<t;r++)s.push(0)}else{if(t instanceof Array)s=t,t=s.length;else{s=[];for(let r=0;r<t;r++)s.push(0)}this._fillAlignment(t)}this._uniformSizes[e]=t,this._uniformLocations[e]=this._uniformLocationPointer,this._uniformLocationPointer+=t;for(let r=0;r<t;r++)this._data.push(s[r]);this._needSync=!0}addMatrix(e,t){this.addUniform(e,Array.prototype.slice.call(t.asArray()))}addFloat2(e,t,i){const s=[t,i];this.addUniform(e,s)}addFloat3(e,t,i,s){const r=[t,i,s];this.addUniform(e,r)}addColor3(e,t){const i=[t.r,t.g,t.b];this.addUniform(e,i)}addColor4(e,t,i){const s=[t.r,t.g,t.b,i];this.addUniform(e,s)}addVector3(e,t){const i=[t.x,t.y,t.z];this.addUniform(e,i)}addMatrix3x3(e){this.addUniform(e,12)}addMatrix2x2(e){this.addUniform(e,8)}create(){this._noUBO||this._buffer||(this._fillAlignment(4),this._bufferData=new Float32Array(this._data),this._rebuild(),this._needSync=!0)}_getNamesDebug(){const e=[];let t=0;for(const i in this._uniformLocations)if(e.push(i),++t===10)break;return e.join(",")}_rebuild(){this._noUBO||!this._bufferData||(this._dynamic?this._buffer=this._engine.createDynamicUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNamesDebug()):this._buffer=this._engine.createUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNamesDebug()),this._trackUBOsInFrame&&(this._buffers.push([this._buffer,this._engine._features.checkUbosContentBeforeUpload?this._bufferData.slice():void 0]),this._bufferIndex=this._buffers.length-1,this._createBufferOnWrite=!1))}_rebuildAfterContextLost(){this._trackUBOsInFrame&&(this._buffers=[],this._currentFrameId=0),this._rebuild()}get _numBuffers(){return this._buffers.length}get _indexBuffer(){return this._bufferIndex}get name(){return this._name}set name(e){this._name=e}get currentEffect(){return this._currentEffect}_buffersEqual(e,t){for(let i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0}_copyBuffer(e,t){for(let i=0;i<e.length;++i)t[i]=e[i]}update(){if(!this._noUBO){if(this.bindUniformBuffer(),!this._buffer){this.create();return}if(!this._dynamic&&!this._needSync){this._createBufferOnWrite=this._trackUBOsInFrame;return}if(this._buffers&&this._buffers.length>1&&this._buffers[this._bufferIndex][1])if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1])){this._needSync=!1,this._createBufferOnWrite=this._trackUBOsInFrame;return}else this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1]);this._bufferUpdatedLastFrame=!0,this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._needSync=!1,this._createBufferOnWrite=this._trackUBOsInFrame}}_createNewBuffer(){this._bufferIndex+1<this._buffers.length?(this._bufferIndex++,this._buffer=this._buffers[this._bufferIndex][0],this._createBufferOnWrite=!1,this._needSync=!0):this._rebuild()}_checkNewFrame(){this._trackUBOsInFrame&&this._currentFrameId!==this._engine.frameId&&(this._currentFrameId=this._engine.frameId,this._createBufferOnWrite=!1,this._buffers&&this._buffers.length>0?(this._buffers.length===1?this._needSync=!this._bufferUpdatedLastFrame:this._needSync=this._bufferIndex!==0,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let s=this._uniformLocations[e];if(s===void 0){if(this._buffer){W.Error("Cannot add an uniform after UBO has been created. uniformName="+e);return}this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let r=0;r<i;r++)this._bufferData[s+r]=t[r];else{let r=!1;for(let n=0;n<i;n++)(i===16&&!this._engine._features.uniformBufferHardCheckMatrix||this._bufferData[s+n]!==Math.fround(t[n]))&&(r=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[s+n]=t[n]);this._needSync=this._needSync||r}}updateUniformArray(e,t,i){this._checkNewFrame();const s=this._uniformLocations[e];if(s===void 0){W.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform and make sure that uniform buffers are supported by the current engine.");return}this._buffer||this.create();const r=this._uniformArraySizes[e];if(this._dynamic)for(let n=0;n<i;n++)this._bufferData[s+n]=t[n];else{let n=!1,a=0,h=0;for(let l=0;l<i;l++)if(this._bufferData[s+h*4+a]!==fe.FloatRound(t[l])&&(n=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[s+h*4+a]=t[l]),a++,a===r.strideSize){for(;a<4;a++)this._bufferData[s+h*4+a]=0;a=0,h++}this._needSync=this._needSync||n}}_cacheMatrix(e,t){this._checkNewFrame();const i=this._valueCache[e],s=t.updateFlag;return i!==void 0&&i===s?!1:(this._valueCache[e]=s,!0)}_updateMatrix3x3ForUniform(e,t){for(let i=0;i<3;i++)oe._TempBuffer[i*4]=t[i*3],oe._TempBuffer[i*4+1]=t[i*3+1],oe._TempBuffer[i*4+2]=t[i*3+2],oe._TempBuffer[i*4+3]=0;this.updateUniform(e,oe._TempBuffer,12)}_updateMatrix3x3ForEffect(e,t){this._currentEffect.setMatrix3x3(e,t)}_updateMatrix2x2ForEffect(e,t){this._currentEffect.setMatrix2x2(e,t)}_updateMatrix2x2ForUniform(e,t){for(let i=0;i<2;i++)oe._TempBuffer[i*4]=t[i*2],oe._TempBuffer[i*4+1]=t[i*2+1],oe._TempBuffer[i*4+2]=0,oe._TempBuffer[i*4+3]=0;this.updateUniform(e,oe._TempBuffer,8)}_updateFloatForEffect(e,t,i=""){this._currentEffect.setFloat(e+i,t)}_updateFloatForUniform(e,t){oe._TempBuffer[0]=t,this.updateUniform(e,oe._TempBuffer,1)}_updateFloat2ForEffect(e,t,i,s=""){this._currentEffect.setFloat2(e+s,t,i)}_updateFloat2ForUniform(e,t,i){oe._TempBuffer[0]=t,oe._TempBuffer[1]=i,this.updateUniform(e,oe._TempBuffer,2)}_updateFloat3ForEffect(e,t,i,s,r=""){this._currentEffect.setFloat3(e+r,t,i,s)}_updateFloat3ForUniform(e,t,i,s){oe._TempBuffer[0]=t,oe._TempBuffer[1]=i,oe._TempBuffer[2]=s,this.updateUniform(e,oe._TempBuffer,3)}_updateFloat4ForEffect(e,t,i,s,r,n=""){this._currentEffect.setFloat4(e+n,t,i,s,r)}_updateFloat4ForUniform(e,t,i,s,r){oe._TempBuffer[0]=t,oe._TempBuffer[1]=i,oe._TempBuffer[2]=s,oe._TempBuffer[3]=r,this.updateUniform(e,oe._TempBuffer,4)}_updateFloatArrayForEffect(e,t,i=""){switch(this._uniformArraySizes[e]?.strideSize){case 2:this._currentEffect.setFloatArray2(e+i,t);break;case 3:this._currentEffect.setFloatArray3(e+i,t);break;case 4:this._currentEffect.setFloatArray4(e+i,t);break;default:this._currentEffect.setFloatArray(e+i,t);break}}_updateFloatArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateArrayForEffect(e,t){this._currentEffect.setArray(e,t)}_updateArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateIntArrayForEffect(e,t){this._currentEffect.setIntArray(e,t)}_updateIntArrayForUniform(e,t){oe._TempBufferInt32View.set(t),this.updateUniformArray(e,oe._TempBuffer,t.length)}_updateUIntArrayForEffect(e,t){this._currentEffect.setUIntArray(e,t)}_updateUIntArrayForUniform(e,t){oe._TempBufferUInt32View.set(t),this.updateUniformArray(e,oe._TempBuffer,t.length)}_updateMatrixForEffect(e,t){this._currentEffect.setMatrix(e,t)}_updateMatrixForUniform(e,t){this._cacheMatrix(e,t)&&this.updateUniform(e,t.asArray(),16)}_updateMatricesForEffect(e,t){this._currentEffect.setMatrices(e,t)}_updateMatricesForUniform(e,t){this.updateUniform(e,t,t.length)}_updateVector3ForEffect(e,t){this._currentEffect.setVector3(e,t)}_updateVector3ForUniform(e,t){oe._TempBuffer[0]=t.x,oe._TempBuffer[1]=t.y,oe._TempBuffer[2]=t.z,this.updateUniform(e,oe._TempBuffer,3)}_updateVector4ForEffect(e,t){this._currentEffect.setVector4(e,t)}_updateVector4ForUniform(e,t){oe._TempBuffer[0]=t.x,oe._TempBuffer[1]=t.y,oe._TempBuffer[2]=t.z,oe._TempBuffer[3]=t.w,this.updateUniform(e,oe._TempBuffer,4)}_updateColor3ForEffect(e,t,i=""){this._currentEffect.setColor3(e+i,t)}_updateColor3ForUniform(e,t){oe._TempBuffer[0]=t.r,oe._TempBuffer[1]=t.g,oe._TempBuffer[2]=t.b,this.updateUniform(e,oe._TempBuffer,3)}_updateColor4ForEffect(e,t,i,s=""){this._currentEffect.setColor4(e+s,t,i)}_updateDirectColor4ForEffect(e,t,i=""){this._currentEffect.setDirectColor4(e+i,t)}_updateColor4ForUniform(e,t,i){oe._TempBuffer[0]=t.r,oe._TempBuffer[1]=t.g,oe._TempBuffer[2]=t.b,oe._TempBuffer[3]=i,this.updateUniform(e,oe._TempBuffer,4)}_updateDirectColor4ForUniform(e,t){oe._TempBuffer[0]=t.r,oe._TempBuffer[1]=t.g,oe._TempBuffer[2]=t.b,oe._TempBuffer[3]=t.a,this.updateUniform(e,oe._TempBuffer,4)}_updateIntForEffect(e,t,i=""){this._currentEffect.setInt(e+i,t)}_updateIntForUniform(e,t){oe._TempBufferInt32View[0]=t,this.updateUniform(e,oe._TempBuffer,1)}_updateInt2ForEffect(e,t,i,s=""){this._currentEffect.setInt2(e+s,t,i)}_updateInt2ForUniform(e,t,i){oe._TempBufferInt32View[0]=t,oe._TempBufferInt32View[1]=i,this.updateUniform(e,oe._TempBuffer,2)}_updateInt3ForEffect(e,t,i,s,r=""){this._currentEffect.setInt3(e+r,t,i,s)}_updateInt3ForUniform(e,t,i,s){oe._TempBufferInt32View[0]=t,oe._TempBufferInt32View[1]=i,oe._TempBufferInt32View[2]=s,this.updateUniform(e,oe._TempBuffer,3)}_updateInt4ForEffect(e,t,i,s,r,n=""){this._currentEffect.setInt4(e+n,t,i,s,r)}_updateInt4ForUniform(e,t,i,s,r){oe._TempBufferInt32View[0]=t,oe._TempBufferInt32View[1]=i,oe._TempBufferInt32View[2]=s,oe._TempBufferInt32View[3]=r,this.updateUniform(e,oe._TempBuffer,4)}_updateUIntForEffect(e,t,i=""){this._currentEffect.setUInt(e+i,t)}_updateUIntForUniform(e,t){oe._TempBufferUInt32View[0]=t,this.updateUniform(e,oe._TempBuffer,1)}_updateUInt2ForEffect(e,t,i,s=""){this._currentEffect.setUInt2(e+s,t,i)}_updateUInt2ForUniform(e,t,i){oe._TempBufferUInt32View[0]=t,oe._TempBufferUInt32View[1]=i,this.updateUniform(e,oe._TempBuffer,2)}_updateUInt3ForEffect(e,t,i,s,r=""){this._currentEffect.setUInt3(e+r,t,i,s)}_updateUInt3ForUniform(e,t,i,s){oe._TempBufferUInt32View[0]=t,oe._TempBufferUInt32View[1]=i,oe._TempBufferUInt32View[2]=s,this.updateUniform(e,oe._TempBuffer,3)}_updateUInt4ForEffect(e,t,i,s,r,n=""){this._currentEffect.setUInt4(e+n,t,i,s,r)}_updateUInt4ForUniform(e,t,i,s,r){oe._TempBufferUInt32View[0]=t,oe._TempBufferUInt32View[1]=i,oe._TempBufferUInt32View[2]=s,oe._TempBufferUInt32View[3]=r,this.updateUniform(e,oe._TempBuffer,4)}setTexture(e,t){this._currentEffect.setTexture(e,t)}setTextureArray(e,t){this._currentEffect.setTextureArray(e,t)}bindTexture(e,t){this._currentEffect._bindTexture(e,t)}updateUniformDirectly(e,t){this.updateUniform(e,t,t.length),this.update()}bindToEffect(e,t){this._currentEffect=e,this._currentEffectName=t}bindUniformBuffer(){!this._noUBO&&this._buffer&&this._currentEffect&&this._currentEffect.bindUniformBuffer(this._buffer,this._currentEffectName)}unbindEffect(){this._currentEffect=void 0,this._currentEffectName=void 0}setDataBuffer(e){if(!this._buffers)return this._buffer===e;for(let t=0;t<this._buffers.length;++t)if(this._buffers[t][0]===e)return this._bufferIndex=t,this._buffer=e,this._createBufferOnWrite=!1,this._currentEffect=void 0,this._buffers.length>1&&this._buffers[t][1]&&this._bufferData.set(this._buffers[t][1]),this._valueCache={},this._currentFrameId=this._engine.frameId,!0;return!1}has(e){return this._uniformLocations[e]!==void 0}dispose(){if(this._noUBO)return;const e=this._engine._uniformBuffers,t=e.indexOf(this);if(t!==-1&&(e[t]=e[e.length-1],e.pop()),this._trackUBOsInFrame&&this._buffers)for(let i=0;i<this._buffers.length;++i){const s=this._buffers[i][0];this._engine._releaseBuffer(s)}else this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)}}oe._MAX_UNIFORM_SIZE=256;oe._TempBuffer=new Float32Array(oe._MAX_UNIFORM_SIZE);oe._TempBufferInt32View=new Int32Array(oe._TempBuffer.buffer);oe._TempBufferUInt32View=new Uint32Array(oe._TempBuffer.buffer);class or{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=or._Counter++}}or._Counter=0;class Vr{get isDisposed(){return this._isDisposed}constructor(e,t,i,s=0,r=!1,n=!1,a=!1,h,l){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=n,this._divisor=h||1,this._label=l,t instanceof or?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=a?s:s*Float32Array.BYTES_PER_ELEMENT,r||this.create()}createVertexBuffer(e,t,i,s,r,n=!1,a){const h=n?t:t*Float32Array.BYTES_PER_ELEMENT,l=s?n?s:s*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new S(this._engine,this,e,this._updatable,!0,l,r===void 0?this._instanced:r,h,i,void 0,void 0,!0,this._divisor||a)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data,e&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e,this._label),this._data=e):this._buffer=this._engine.createVertexBuffer(e,void 0,this._label)))}_rebuild(){if(this._data)this._buffer=null,this.create(this._data);else{if(!this._buffer)return;if(this._buffer.capacity>0){this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label);return}W.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,s=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,s?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),t===0&&i===void 0?this._data=e:this._data=null)}_increaseReferences(){if(this._buffer){if(!this._isAlreadyOwned){this._isAlreadyOwned=!0;return}this._buffer.references++}}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class S{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=e!=0;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,s,r,n,a,h,l,c,u=!1,f=!1,d=1,_=!1){this._isDisposed=!1;let m;if(this.engine=e,typeof s=="object"&&s!==null?(m=s.updatable??!1,r=s.postponeInternalCreation,n=s.stride,a=s.instanced,h=s.offset,l=s.size,c=s.type,u=s.normalized??!1,f=s.useBytes??!1,d=s.divisor??1,_=s.takeBufferOwnership??!1,this._label=s.label):m=!!s,t instanceof Vr?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new Vr(e,t,m,n,r,a,f,d,this._label),this._ownsBuffer=!0),this.uniqueId=S._Counter++,this._kind=i,c===void 0){const T=this.getData();this.type=T?S.GetDataType(T):S.FLOAT}else this.type=c;const g=xi(this.type);f?(this._size=l||(n?n/g:S.DeduceStride(i)),this.byteStride=n||this._buffer.byteStride||this._size*g,this.byteOffset=h||0):(this._size=l||n||S.DeduceStride(i),this.byteStride=n?n*g:this._buffer.byteStride||this._size*g,this.byteOffset=(h||0)*g),this.normalized=u,this._instanced=a!==void 0?a:!1,this._instanceDivisor=a?d:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120<<0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){this._buffer?._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?Wo(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/xi(this.type)}getOffset(){return this.byteOffset/xi(this.type)}getSize(e=!1){return e?this._size*xi(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){ps(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,(i,s)=>{for(let r=0;r<this._size;r++)t(i[r],s+r)})}_alignBuffer(){}static DeduceStride(e){switch(e){case S.UVKind:case S.UV2Kind:case S.UV3Kind:case S.UV4Kind:case S.UV5Kind:case S.UV6Kind:return 2;case S.NormalKind:case S.PositionKind:return 3;case S.ColorKind:case S.ColorInstanceKind:case S.MatricesIndicesKind:case S.MatricesIndicesExtraKind:case S.MatricesWeightsKind:case S.MatricesWeightsExtraKind:case S.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?S.BYTE:e instanceof Uint8Array?S.UNSIGNED_BYTE:e instanceof Int16Array?S.SHORT:e instanceof Uint16Array?S.UNSIGNED_SHORT:e instanceof Int32Array?S.INT:e instanceof Uint32Array?S.UNSIGNED_INT:S.FLOAT}static GetTypeByteLength(e){return xi(e)}static ForEach(e,t,i,s,r,n,a,h){ps(e,t,i,s,r,n,a,(l,c)=>{for(let u=0;u<s;u++)h(l[u],c+u)})}static GetFloatData(e,t,i,s,r,n,a,h){return Wo(e,t,i,s,r,n,a,h)}}S._Counter=0;S.BYTE=5120;S.UNSIGNED_BYTE=5121;S.SHORT=5122;S.UNSIGNED_SHORT=5123;S.INT=5124;S.UNSIGNED_INT=5125;S.FLOAT=5126;S.PositionKind="position";S.NormalKind="normal";S.TangentKind="tangent";S.UVKind="uv";S.UV2Kind="uv2";S.UV3Kind="uv3";S.UV4Kind="uv4";S.UV5Kind="uv5";S.UV6Kind="uv6";S.ColorKind="color";S.ColorInstanceKind="instanceColor";S.MatricesIndicesKind="matricesIndices";S.MatricesWeightsKind="matricesWeights";S.MatricesIndicesExtraKind="matricesIndicesExtra";S.MatricesWeightsExtraKind="matricesWeightsExtra";class Zs{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(S.NormalKind))return null;let i=this.pickedMesh.getIndices();i?.length===0&&(i=null);let s;const r=U.Vector3[0],n=U.Vector3[1],a=U.Vector3[2];if(t){const l=this.pickedMesh.getVerticesData(S.NormalKind);let c=i?p.FromArrayToRef(l,i[this.faceId*3]*3,r):r.copyFromFloats(l[this.faceId*3*3],l[this.faceId*3*3+1],l[this.faceId*3*3+2]),u=i?p.FromArrayToRef(l,i[this.faceId*3+1]*3,n):n.copyFromFloats(l[(this.faceId*3+1)*3],l[(this.faceId*3+1)*3+1],l[(this.faceId*3+1)*3+2]),f=i?p.FromArrayToRef(l,i[this.faceId*3+2]*3,a):a.copyFromFloats(l[(this.faceId*3+2)*3],l[(this.faceId*3+2)*3+1],l[(this.faceId*3+2)*3+2]);c=c.scale(this.bu),u=u.scale(this.bv),f=f.scale(1-this.bu-this.bv),s=new p(c.x+u.x+f.x,c.y+u.y+f.y,c.z+u.z+f.z)}else{const l=this.pickedMesh.getVerticesData(S.PositionKind),c=i?p.FromArrayToRef(l,i[this.faceId*3]*3,r):r.copyFromFloats(l[this.faceId*3*3],l[this.faceId*3*3+1],l[this.faceId*3*3+2]),u=i?p.FromArrayToRef(l,i[this.faceId*3+1]*3,n):n.copyFromFloats(l[(this.faceId*3+1)*3],l[(this.faceId*3+1)*3+1],l[(this.faceId*3+1)*3+2]),f=i?p.FromArrayToRef(l,i[this.faceId*3+2]*3,a):a.copyFromFloats(l[(this.faceId*3+2)*3],l[(this.faceId*3+2)*3+1],l[(this.faceId*3+2)*3+2]),d=c.subtract(u),_=f.subtract(u);s=p.Cross(d,_)}const h=(l,c)=>{if(this.thinInstanceIndex!==-1){const f=l.thinInstanceGetWorldMatrices()[this.thinInstanceIndex];f&&p.TransformNormalToRef(c,f,c)}let u=l.getWorldMatrix();l.nonUniformScaling&&(U.Matrix[0].copyFrom(u),u=U.Matrix[0],u.setTranslationFromFloats(0,0,0),u.invert(),u.transposeToRef(U.Matrix[1]),u=U.Matrix[1]),p.TransformNormalToRef(c,u,c)};if(e&&h(this.pickedMesh,s),this.ray){const l=U.Vector3[0].copyFrom(s);e||h(this.pickedMesh,l),p.Dot(l,this.ray.direction)>0&&s.negateInPlace()}return s.normalize(),s}getTextureCoordinates(e=S.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const i=this.pickedMesh.getVerticesData(e);if(!i)return null;let s=ie.FromArray(i,t[this.faceId*3]*2),r=ie.FromArray(i,t[this.faceId*3+1]*2),n=ie.FromArray(i,t[this.faceId*3+2]*2);return s=s.scale(this.bu),r=r.scale(this.bv),n=n.scale(1-this.bu-this.bv),new ie(s.x+r.x+n.x,s.y+r.y+n.y)}}class gt{constructor(e,t,i,s,r,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=s,this.sourceEvent=r,this.additionalData=n}static CreateNew(e,t,i){const s=e.getScene();return new gt(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new gt(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new gt(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new gt(e,t.x,t.y,null,i,s)}}class zr{constructor(e){this._vertexBuffers={},this.onBeforeRenderObservable=new z,this._scene=e}_prepareBuffers(){if(this._vertexBuffers[S.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[S.PositionKind]=new S(this._scene.getEngine(),e,S.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}_rebuild(){const e=this._vertexBuffers[S.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!i||(t=t||i._postProcesses.filter(s=>s!=null),!t||t.length===0||!this._scene.postProcessesEnabled)?!1:(t[0].activate(i,e,t!=null),!0)}directRender(e,t=null,i=!1,s=0,r=0,n=!1,a=e.length){const h=this._scene.getEngine();for(let l=0;l<a;l++){l<e.length-1?e[l+1].activate(this._scene.activeCamera||this._scene,t?.texture):(t?h.bindFramebuffer(t,s,void 0,void 0,i,r):n||h.restoreDefaultFramebuffer(),h._debugInsertMarker?.(`post process ${e[l].name} output`));const c=e[l],u=c.apply();u&&(c.onBeforeRenderObservable.notifyObservers(u),this._prepareBuffers(),h.bindBuffers(this._vertexBuffers,this._indexBuffer,u),h.drawElementsType(0,0,6),c.onAfterRenderObservable.notifyObservers(u))}h.setDepthBuffer(!0),h.setDepthWrite(!0)}_finalizeFrame(e,t,i,s,r=!1){const n=this._scene.activeCamera;if(!n||(this.onBeforeRenderObservable.notifyObservers(this),s=s||n._postProcesses.filter(h=>h!=null),s.length===0||!this._scene.postProcessesEnabled))return;const a=this._scene.getEngine();for(let h=0,l=s.length;h<l;h++){const c=s[h];if(h<l-1?c._outputTexture=s[h+1].activate(n,t?.texture):(t?(a.bindFramebuffer(t,i,void 0,void 0,r),c._outputTexture=t):(a.restoreDefaultFramebuffer(),c._outputTexture=null),a._debugInsertMarker?.(`post process ${s[h].name} output`)),e)break;const u=c.apply();u&&(c.onBeforeRenderObservable.notifyObservers(u),this._prepareBuffers(),a.bindBuffers(this._vertexBuffers,this._indexBuffer,u),a.drawElementsType(0,0,6),c.onAfterRenderObservable.notifyObservers(u))}a.setDepthBuffer(!0),a.setDepthWrite(!0),a.setAlphaMode(0)}dispose(){const e=this._vertexBuffers[S.PositionKind];e&&(e.dispose(),this._vertexBuffers[S.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)}}const Wt=new D,Ht=new D,Xt=new D,zi={getScene:()=>{},eyeAtCamera:!0};function qs(o,e,t){const i=t.asArray(),s=e.asArray();for(let r=0;r<16;r++)i[r]=s[r];return i[12]-=o.x,i[13]-=o.y,i[14]-=o.z,t.markAsUpdated(),t}function Sl(o,e,t){return Ur(e,Ht),qs(o,Ht,Xt),Ur(Xt,t),t}function Wr(o,e,t){if(!zi.eyeAtCamera)return Sl(o,e,t);const i=t.asArray(),s=e.asArray();for(let r=0;r<16;r++)i[r]=s[r];return i[12]=0,i[13]=0,i[14]=0,t.markAsUpdated(),t}function Ln(o,e,t,i){return ms(Wr(o,e,i),t,i),i}function qp(o,e,t){return t.normal.copyFrom(e.normal),t.d=e.d+p.Dot(e.normal,o),t}function Nf(o,e,t,i,s){for(let r=0;r<i;++r)yl(o,e[r],t[r],Ht),Ht.copyToArray(s,r*16);return s}function Qo(o,e,t,i){return Ur(t,Ht),ms(e,Ht,Xt),qs(o,Xt,Ht),Wr(o,t,Xt),ms(Ht,Xt,i),i}function yl(o,e,t,i){return Sl(o,e,Xt),ms(Xt,t,i),i}function $o(o,e,t,i,s,r){return Ur(t,Ht),ms(e,Ht,Xt),qs(o,Xt,Ht),Ln(o,i,s,Xt),ms(Ht,Xt,r),r}function Jo(o,e){const t=zi.getScene();if(!t||Wt===e)return e;Wt.updateFlag=e.updateFlag;const i=t.floatingOriginOffset;switch(o){case"world":return qs(i,e,Wt);case"view":return Wr(i,e,Wt);case"worldView":return Qo(i,e,t.getViewMatrix(),Wt);case"viewProjection":return Ln(i,t.getViewMatrix(),t.getProjectionMatrix(),Wt);case"worldViewProjection":return $o(i,e,t.getTransformMatrix(),t.getViewMatrix(),t.getProjectionMatrix(),Wt);default:if(o.startsWith("u_")){const s=o.toLowerCase();if(s.startsWith("u_worldviewprojection"))return $o(i,e,t.getTransformMatrix(),t.getViewMatrix(),t.getProjectionMatrix(),Wt);if(s.startsWith("u_viewprojection"))return Ln(i,t.getViewMatrix(),t.getProjectionMatrix(),Wt);if(s.startsWith("u_worldview"))return Qo(i,e,t.getViewMatrix(),Wt);if(s.startsWith("u_world"))return qs(i,e,Wt);if(s.startsWith("u_view"))return Wr(i,e,Wt)}return e}}const Qs=oe,Bn=it,Al=Qs.prototype._updateMatrixForUniform,Ml=it.prototype.setMatrix;function Uf(){it.prototype.setMatrix=Ml,Bn._setMatrixOverride=void 0,Qs.prototype._updateMatrixForUniform=Al,Qs.prototype._updateMatrixForUniformOverride=void 0}function kf(){Bn.prototype._setMatrixOverride=Ml,Bn.prototype.setMatrix=function(o,e){return this._setMatrixOverride(o,Jo(o,e)),this},Qs.prototype._updateMatrixForUniformOverride=Al,Qs.prototype._updateMatrixForUniform=function(o,e){this._updateMatrixForUniformOverride(o,Jo(o,e))}}class ti{set opaqueSortCompareFn(e){e?this._opaqueSortCompareFn=e:this._opaqueSortCompareFn=ti.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){e?this._alphaTestSortCompareFn=e:this._alphaTestSortCompareFn=ti.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){e?this._transparentSortCompareFn=e:this._transparentSortCompareFn=ti.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,i=null,s=null,r=null){this.index=e,this._opaqueSubMeshes=new Et(256),this._transparentSubMeshes=new Et(256),this._alphaTestSubMeshes=new Et(256),this._depthOnlySubMeshes=new Et(256),this._particleSystems=new Et(256),this._spriteManagers=new Et(256),this._empty=!0,this._edgesRenderers=new Zi(16),this.disableDepthPrePass=!1,this._scene=t,this.opaqueSortCompareFn=i,this.alphaTestSortCompareFn=s,this.transparentSortCompareFn=r}render(e,t,i,s,r=!0,n=!0,a=!0,h=!0,l){if(e){e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);return}const c=this._scene.getEngine();r&&this._depthOnlySubMeshes.length!==0&&(c.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),c.setColorWrite(!0)),n&&this._opaqueSubMeshes.length!==0&&this._renderOpaque(this._opaqueSubMeshes),a&&this._alphaTestSubMeshes.length!==0&&this._renderAlphaTest(this._alphaTestSubMeshes);const u=c.getStencilBuffer();if(c.setStencilBuffer(!1),t&&this._renderSprites(),i&&this._renderParticles(s),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),h&&(l||this._transparentSubMeshes.length!==0||this._scene.useOrderIndependentTransparency)){if(c.setStencilBuffer(u),l)l(this._transparentSubMeshes,this);else if(this._scene.useOrderIndependentTransparency){const f=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);f.length&&this._renderTransparent(f)}else this._renderTransparent(this._transparentSubMeshes);c.setAlphaMode(0)}if(c.setStencilBuffer(!1),n&&this._edgesRenderers.length){for(let f=0;f<this._edgesRenderers.length;f++)this._edgesRenderers.data[f].render();c.setAlphaMode(0)}c.setStencilBuffer(u)}_renderOpaqueSorted(e){ti._RenderSorted(e,this._opaqueSortCompareFn,this._scene.activeCamera,!1,this.disableDepthPrePass)}_renderAlphaTestSorted(e){ti._RenderSorted(e,this._alphaTestSortCompareFn,this._scene.activeCamera,!1,this.disableDepthPrePass)}_renderTransparentSorted(e){ti._RenderSorted(e,this._transparentSortCompareFn,this._scene.activeCamera,!0,this.disableDepthPrePass)}static _RenderSorted(e,t,i,s,r){let n=0,a;const h=i?i.globalPosition:ti._ZeroVector;if(s)for(;n<e.length;n++)a=e.data[n],a._alphaIndex=a.getMesh().alphaIndex,a._distanceToCamera=p.Distance(a.getBoundingInfo().boundingSphere.centerWorld,h);const l=e.length===e.data.length?e.data:e.data.slice(0,e.length);t&&l.sort(t);const c=l[0].getMesh().getScene();for(n=0;n<l.length;n++)if(a=l[n],!(c._activeMeshesFrozenButKeepClipping&&!a.isInFrustum(c._frustumPlanes))){if(s){const u=a.getMaterial();if(u&&u.needDepthPrePass&&!r){const f=u.getScene().getEngine();f.setColorWrite(!1),f.setAlphaMode(0),a.render(!1),f.setColorWrite(!0)}}a.render(s)}}static defaultTransparentSortCompare(e,t){return e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:ti.backToFrontSortCompare(e,t)}static backToFrontSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?-1:e._distanceToCamera>t._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),s=t.getMesh();return i.material&&s.material?i.material.uniqueId-s.material.uniqueId:i.uniqueId-s.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){t===void 0&&(t=e.getMesh()),i===void 0&&(i=e.getMaterial()),i!=null&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTestingForMesh(t)?(i.needDepthPrePass&&!this.disableDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&!this.disableDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t.isEnabled()&&t.isVisible&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(this._particleSystems.length===0)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i<this._particleSystems.length;i++){const s=this._particleSystems.data[i];if((t&&t.layerMask&s.layerMask)===0)continue;const r=s.emitter;(!r.position||!e||e.indexOf(r)!==-1)&&this._scene._activeParticles.addCount(s.render(),!1)}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}_renderSprites(){if(!this._scene.spritesEnabled||this._spriteManagers.length===0)return;const e=this._scene.activeCamera;this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);for(let t=0;t<this._spriteManagers.length;t++){const i=this._spriteManagers.data[t];(e&&e.layerMask&i.layerMask)!==0&&i.render()}this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)}}ti._ZeroVector=p.Zero();class Vf{}class pt{get disableDepthPrePass(){return this._disableDepthPrePass}set disableDepthPrePass(e){this._disableDepthPrePass=e;for(const t of this._renderingGroups)t.disableDepthPrePass=e}get maintainStateBetweenFrames(){return this._maintainStateBetweenFrames}set maintainStateBetweenFrames(e){e!==this._maintainStateBetweenFrames&&(this._maintainStateBetweenFrames=e,this._maintainStateBetweenFrames||this.restoreDispachedFlags())}restoreDispachedFlags(){for(const e of this._scene.meshes)if(e.subMeshes)for(const t of e.subMeshes)t._wasDispatched=!1;if(this._scene.spriteManagers)for(const e of this._scene.spriteManagers)e._wasDispatched=!1;for(const e of this._scene.particleSystems)e._wasDispatched=!1}constructor(e){this._useSceneAutoClearSetup=!1,this._disableDepthPrePass=!1,this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new Vf,this._maintainStateBetweenFrames=!1,this._scene=e;for(let t=pt.MIN_RENDERINGGROUPS;t<pt.MAX_RENDERINGGROUPS;t++)this._autoClearDepthStencil[t]={autoClear:!0,depth:!0,stencil:!0}}get renderingGroups(){return this._renderingGroups}getRenderingGroup(e){const t=e||0;return this._prepareRenderingGroup(t),this._renderingGroups[t]}_clearDepthStencilBuffer(e=!0,t=!0){this._depthStencilBufferAlreadyCleaned||(this._scene.getEngine().clear(null,!1,e,t),this._depthStencilBufferAlreadyCleaned=!0)}render(e,t,i,s,r=!0,n=!0,a=!0,h=!0,l){const c=this._renderingGroupInfo;if(c.scene=this._scene,c.camera=this._scene.activeCamera,c.renderingManager=this,this._scene.spriteManagers&&s)for(let u=0;u<this._scene.spriteManagers.length;u++){const f=this._scene.spriteManagers[u];this.dispatchSprites(f)}for(let u=pt.MIN_RENDERINGGROUPS;u<pt.MAX_RENDERINGGROUPS;u++){this._depthStencilBufferAlreadyCleaned=u===pt.MIN_RENDERINGGROUPS;const f=this._renderingGroups[u];if(!f||f._empty)continue;const d=1<<u;if(c.renderingGroupId=u,this._scene.onBeforeRenderingGroupObservable.notifyObservers(c,d),pt.AUTOCLEAR){const _=this._useSceneAutoClearSetup?this._scene.getAutoClearDepthStencilSetup(u):this._autoClearDepthStencil[u];_&&_.autoClear&&this._clearDepthStencilBuffer(_.depth,_.stencil)}for(const _ of this._scene._beforeRenderingGroupDrawStage)_.action(u);f.render(e,s,i,t,r,n,a,h,l);for(const _ of this._scene._afterRenderingGroupDrawStage)_.action(u);this._scene.onAfterRenderingGroupObservable.notifyObservers(c,d)}}reset(){if(!this.maintainStateBetweenFrames)for(let e=pt.MIN_RENDERINGGROUPS;e<pt.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.prepare()}}resetSprites(){if(!this.maintainStateBetweenFrames)for(let e=pt.MIN_RENDERINGGROUPS;e<pt.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.prepareSprites()}}dispose(){this.freeRenderingGroups(),this._renderingGroups.length=0,this._renderingGroupInfo=null}freeRenderingGroups(){for(let e=pt.MIN_RENDERINGGROUPS;e<pt.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.dispose()}}_prepareRenderingGroup(e){this._renderingGroups[e]===void 0&&(this._renderingGroups[e]=new ti(e,this._scene,this._customOpaqueSortCompareFn[e],this._customAlphaTestSortCompareFn[e],this._customTransparentSortCompareFn[e]),this._renderingGroups[e].disableDepthPrePass=this._disableDepthPrePass)}dispatchSprites(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchSprites(e))}dispatchParticles(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchParticles(e))}dispatch(e,t,i){t===void 0&&(t=e.getMesh()),!(this.maintainStateBetweenFrames&&e._wasDispatched)&&(e._wasDispatched=!0,this.getRenderingGroup(t.renderingGroupId).dispatch(e,t,i))}setRenderingOrder(e,t=null,i=null,s=null){if(this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=i,this._customTransparentSortCompareFn[e]=s,this._renderingGroups[e]){const r=this._renderingGroups[e];r.opaqueSortCompareFn=this._customOpaqueSortCompareFn[e],r.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[e],r.transparentSortCompareFn=this._customTransparentSortCompareFn[e]}}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._autoClearDepthStencil[e]={autoClear:t,depth:i,stencil:s}}getAutoClearDepthStencilSetup(e){return this._autoClearDepthStencil[e]}}pt.MAX_RENDERINGGROUPS=4;pt.MIN_RENDERINGGROUPS=0;pt.AUTOCLEAR=!0;class ce{}ce.NAME_EFFECTLAYER="EffectLayer";ce.NAME_LAYER="Layer";ce.NAME_LENSFLARESYSTEM="LensFlareSystem";ce.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer";ce.NAME_PARTICLESYSTEM="ParticleSystem";ce.NAME_GAMEPAD="Gamepad";ce.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue";ce.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer";ce.NAME_PREPASSRENDERER="PrePassRenderer";ce.NAME_DEPTHRENDERER="DepthRenderer";ce.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer";ce.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager";ce.NAME_SPRITE="Sprite";ce.NAME_SUBSURFACE="SubSurface";ce.NAME_OUTLINERENDERER="Outline";ce.NAME_PROCEDURALTEXTURE="ProceduralTexture";ce.NAME_SHADOWGENERATOR="ShadowGenerator";ce.NAME_OCTREE="Octree";ce.NAME_PHYSICSENGINE="PhysicsEngine";ce.NAME_AUDIO="Audio";ce.NAME_FLUIDRENDERER="FluidRenderer";ce.NAME_IBLCDFGENERATOR="iblCDFGenerator";ce.NAME_CLUSTEREDLIGHTING="ClusteredLighting";ce.STEP_ISREADYFORMESH_EFFECTLAYER=0;ce.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0;ce.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0;ce.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0;ce.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1;ce.STEP_BEFORECAMERADRAW_PREPASS=0;ce.STEP_BEFORECAMERADRAW_EFFECTLAYER=1;ce.STEP_BEFORECAMERADRAW_LAYER=2;ce.STEP_BEFORERENDERTARGETDRAW_PREPASS=0;ce.STEP_BEFORERENDERTARGETDRAW_LAYER=1;ce.STEP_BEFORERENDERINGMESH_PREPASS=0;ce.STEP_BEFORERENDERINGMESH_OUTLINE=1;ce.STEP_AFTERRENDERINGMESH_PREPASS=0;ce.STEP_AFTERRENDERINGMESH_OUTLINE=1;ce.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0;ce.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1;ce.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0;ce.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0;ce.STEP_BEFORECLEAR_PREPASS=1;ce.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0;ce.STEP_AFTERRENDERTARGETDRAW_PREPASS=0;ce.STEP_AFTERRENDERTARGETDRAW_LAYER=1;ce.STEP_AFTERCAMERADRAW_PREPASS=0;ce.STEP_AFTERCAMERADRAW_EFFECTLAYER=1;ce.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2;ce.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3;ce.STEP_AFTERCAMERADRAW_LAYER=4;ce.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5;ce.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0;ce.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0;ce.STEP_AFTERRENDER_AUDIO=0;ce.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0;ce.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1;ce.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2;ce.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3;ce.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0;ce.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1;ce.STEP_GATHERACTIVECAMERARENDERTARGETS_CLUSTEREDLIGHTING=2;ce.STEP_POINTERMOVE_SPRITE=0;ce.STEP_POINTERDOWN_SPRITE=0;ce.STEP_POINTERUP_SPRITE=0;class st extends Array{constructor(e){super(...e)}static Create(){return Object.create(st.prototype)}registerStep(e,t,i){let s=0,r;for(;s<this.length&&(r=this[s].index,!(e<r));s++);this.splice(s,0,{index:e,component:t,action:i.bind(t)})}clear(){this.length=0}}class ve{}ve.POINTERDOWN=1;ve.POINTERUP=2;ve.POINTERMOVE=4;ve.POINTERWHEEL=8;ve.POINTERPICK=16;ve.POINTERTAP=32;ve.POINTERDOUBLETAP=64;class Pl{constructor(e,t){this.type=e,this.event=t}}class zf extends Pl{constructor(e,t,i,s){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new ie(i,s)}}class Ei extends Pl{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,i,s=null){super(e,t),this._pickInfo=i,this._inputManager=s}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}class Bt{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1,this.disposeWhenUnowned=!0}static get HasTriggers(){for(const e in Bt.Triggers)if(Object.prototype.hasOwnProperty.call(Bt.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in Bt.Triggers)if(Object.prototype.hasOwnProperty.call(Bt.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in Bt.Triggers)if(Object.prototype.hasOwnProperty.call(Bt.Triggers,t)&&parseInt(t)===e)return!0;return!1}}Bt.Triggers={};class $s{}$s.KEYDOWN=1;$s.KEYUP=2;class Nn{constructor(e,t){this.type=e,this.event=t}}class eh extends Nn{get skipOnPointerObservable(){return this.skipOnKeyboardObservable}set skipOnPointerObservable(e){this.skipOnKeyboardObservable=e}constructor(e,t){super(e,t),this.type=e,this.event=t,this.skipOnKeyboardObservable=!1}}var ue;(function(o){o[o.Generic=0]="Generic",o[o.Keyboard=1]="Keyboard",o[o.Mouse=2]="Mouse",o[o.Touch=3]="Touch",o[o.DualShock=4]="DualShock",o[o.Xbox=5]="Xbox",o[o.Switch=6]="Switch",o[o.DualSense=7]="DualSense"})(ue||(ue={}));var Te;(function(o){o[o.Horizontal=0]="Horizontal",o[o.Vertical=1]="Vertical",o[o.LeftClick=2]="LeftClick",o[o.MiddleClick=3]="MiddleClick",o[o.RightClick=4]="RightClick",o[o.BrowserBack=5]="BrowserBack",o[o.BrowserForward=6]="BrowserForward",o[o.MouseWheelX=7]="MouseWheelX",o[o.MouseWheelY=8]="MouseWheelY",o[o.MouseWheelZ=9]="MouseWheelZ",o[o.Move=12]="Move"})(Te||(Te={}));var th;(function(o){o[o.Horizontal=0]="Horizontal",o[o.Vertical=1]="Vertical",o[o.LeftClick=2]="LeftClick",o[o.MiddleClick=3]="MiddleClick",o[o.RightClick=4]="RightClick",o[o.BrowserBack=5]="BrowserBack",o[o.BrowserForward=6]="BrowserForward",o[o.MouseWheelX=7]="MouseWheelX",o[o.MouseWheelY=8]="MouseWheelY",o[o.MouseWheelZ=9]="MouseWheelZ",o[o.DeltaHorizontal=10]="DeltaHorizontal",o[o.DeltaVertical=11]="DeltaVertical"})(th||(th={}));var ih;(function(o){o[o.Cross=0]="Cross",o[o.Circle=1]="Circle",o[o.Square=2]="Square",o[o.Triangle=3]="Triangle",o[o.L1=4]="L1",o[o.R1=5]="R1",o[o.L2=6]="L2",o[o.R2=7]="R2",o[o.Share=8]="Share",o[o.Options=9]="Options",o[o.L3=10]="L3",o[o.R3=11]="R3",o[o.DPadUp=12]="DPadUp",o[o.DPadDown=13]="DPadDown",o[o.DPadLeft=14]="DPadLeft",o[o.DPadRight=15]="DPadRight",o[o.Home=16]="Home",o[o.TouchPad=17]="TouchPad",o[o.LStickXAxis=18]="LStickXAxis",o[o.LStickYAxis=19]="LStickYAxis",o[o.RStickXAxis=20]="RStickXAxis",o[o.RStickYAxis=21]="RStickYAxis"})(ih||(ih={}));var sh;(function(o){o[o.Cross=0]="Cross",o[o.Circle=1]="Circle",o[o.Square=2]="Square",o[o.Triangle=3]="Triangle",o[o.L1=4]="L1",o[o.R1=5]="R1",o[o.L2=6]="L2",o[o.R2=7]="R2",o[o.Create=8]="Create",o[o.Options=9]="Options",o[o.L3=10]="L3",o[o.R3=11]="R3",o[o.DPadUp=12]="DPadUp",o[o.DPadDown=13]="DPadDown",o[o.DPadLeft=14]="DPadLeft",o[o.DPadRight=15]="DPadRight",o[o.Home=16]="Home",o[o.TouchPad=17]="TouchPad",o[o.LStickXAxis=18]="LStickXAxis",o[o.LStickYAxis=19]="LStickYAxis",o[o.RStickXAxis=20]="RStickXAxis",o[o.RStickYAxis=21]="RStickYAxis"})(sh||(sh={}));var rh;(function(o){o[o.A=0]="A",o[o.B=1]="B",o[o.X=2]="X",o[o.Y=3]="Y",o[o.LB=4]="LB",o[o.RB=5]="RB",o[o.LT=6]="LT",o[o.RT=7]="RT",o[o.Back=8]="Back",o[o.Start=9]="Start",o[o.LS=10]="LS",o[o.RS=11]="RS",o[o.DPadUp=12]="DPadUp",o[o.DPadDown=13]="DPadDown",o[o.DPadLeft=14]="DPadLeft",o[o.DPadRight=15]="DPadRight",o[o.Home=16]="Home",o[o.LStickXAxis=17]="LStickXAxis",o[o.LStickYAxis=18]="LStickYAxis",o[o.RStickXAxis=19]="RStickXAxis",o[o.RStickYAxis=20]="RStickYAxis"})(rh||(rh={}));var nh;(function(o){o[o.B=0]="B",o[o.A=1]="A",o[o.Y=2]="Y",o[o.X=3]="X",o[o.L=4]="L",o[o.R=5]="R",o[o.ZL=6]="ZL",o[o.ZR=7]="ZR",o[o.Minus=8]="Minus",o[o.Plus=9]="Plus",o[o.LS=10]="LS",o[o.RS=11]="RS",o[o.DPadUp=12]="DPadUp",o[o.DPadDown=13]="DPadDown",o[o.DPadLeft=14]="DPadLeft",o[o.DPadRight=15]="DPadRight",o[o.Home=16]="Home",o[o.Capture=17]="Capture",o[o.LStickXAxis=18]="LStickXAxis",o[o.LStickYAxis=19]="LStickYAxis",o[o.RStickXAxis=20]="RStickXAxis",o[o.RStickYAxis=21]="RStickYAxis"})(nh||(nh={}));var ah;(function(o){o[o.PointerMove=0]="PointerMove",o[o.PointerDown=1]="PointerDown",o[o.PointerUp=2]="PointerUp"})(ah||(ah={}));class hr{}hr.DOM_DELTA_PIXEL=0;hr.DOM_DELTA_LINE=1;hr.DOM_DELTA_PAGE=2;class qi{static CreateDeviceEvent(e,t,i,s,r,n,a){switch(e){case ue.Keyboard:return this._CreateKeyboardEvent(i,s,r,n);case ue.Mouse:if(i===Te.MouseWheelX||i===Te.MouseWheelY||i===Te.MouseWheelZ)return this._CreateWheelEvent(e,t,i,s,r,n);case ue.Touch:return this._CreatePointerEvent(e,t,i,s,r,n,a);default:throw`Unable to generate event for device ${ue[e]}`}}static _CreatePointerEvent(e,t,i,s,r,n,a){const h=this._CreateMouseEvent(e,t,i,s,r,n);e===ue.Mouse?(h.deviceType=ue.Mouse,h.pointerId=1,h.pointerType="mouse"):(h.deviceType=ue.Touch,h.pointerId=a??t,h.pointerType="touch");let l=0;return l+=r.pollInput(e,t,Te.LeftClick),l+=r.pollInput(e,t,Te.RightClick)*2,l+=r.pollInput(e,t,Te.MiddleClick)*4,h.buttons=l,i===Te.Move?h.type="pointermove":i>=Te.LeftClick&&i<=Te.RightClick&&(h.type=s===1?"pointerdown":"pointerup",h.button=i-2),h}static _CreateWheelEvent(e,t,i,s,r,n){const a=this._CreateMouseEvent(e,t,i,s,r,n);switch(a.pointerId=1,a.type="wheel",a.deltaMode=hr.DOM_DELTA_PIXEL,a.deltaX=0,a.deltaY=0,a.deltaZ=0,i){case Te.MouseWheelX:a.deltaX=s;break;case Te.MouseWheelY:a.deltaY=s;break;case Te.MouseWheelZ:a.deltaZ=s;break}return a}static _CreateMouseEvent(e,t,i,s,r,n){const a=this._CreateEvent(n),h=r.pollInput(e,t,Te.Horizontal),l=r.pollInput(e,t,Te.Vertical);return n?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-n.getBoundingClientRect().x,a.offsetY=a.movementY-n.getBoundingClientRect().y):(a.movementX=r.pollInput(e,t,10),a.movementY=r.pollInput(e,t,11),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,r),a.clientX=h,a.clientY=l,a.x=h,a.y=l,a.deviceType=e,a.deviceSlot=t,a.inputIndex=i,a}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=ue.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=t===1?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(ue.Keyboard),s=i&&t.pollInput(ue.Keyboard,0,18)===1,r=i&&t.pollInput(ue.Keyboard,0,17)===1,n=i&&(t.pollInput(ue.Keyboard,0,91)===1||t.pollInput(ue.Keyboard,0,92)===1||t.pollInput(ue.Keyboard,0,93)===1),a=i&&t.pollInput(ue.Keyboard,0,16)===1;e.altKey=s,e.ctrlKey=r,e.metaKey=n,e.shiftKey=a}static _CreateEvent(e){const t={};return t.preventDefault=()=>{},t.target=e,t}}class Wf{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(s,r,n,a)=>{const h=qi.CreateDeviceEvent(s,r,n,a,this);i(s,r,h)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===ue.Mouse||e===ue.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const oh=255,hh=Object.keys(Te).length/2;class Gf{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=fe.IsSafari(),this._usingMacOs=Ji()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=r=>{},this._keyboardUpEvent=r=>{},this._keyboardBlurEvent=r=>{},this._pointerMoveEvent=r=>{},this._pointerDownEvent=r=>{},this._pointerUpEvent=r=>{},this._pointerCancelEvent=r=>{},this._pointerCancelTouch=r=>{},this._pointerLeaveEvent=r=>{},this._pointerWheelEvent=r=>{},this._pointerBlurEvent=r=>{},this._pointerMacOsChromeOutEvent=r=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=Ji()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._isUsingChromium=Ji()&&navigator.userAgent&&navigator.userAgent.indexOf("Chrome")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=r=>{},this._gamepadDisconnectedEvent=r=>{},this._eventPrefix=fe.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=s,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOs&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){const s=this._inputs[e][t];if(!s)throw`Unable to find device ${ue[e]}`;e>=ue.DualShock&&e<=ue.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(r===void 0)throw`Unable to find input ${i} for device ${ue[e]} in slot ${t}`;return i===Te.Move&&fe.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}isDeviceAvailable(e){return this._inputs[e]!==void 0}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this?._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(const t of this._inputs)if(t)for(const i in t){const s=+i,r=t[s];if(r)for(let n=0;n<r.length;n++)r[n]=0}}this._elementToAttachTo=e,this._elementToAttachTo.tabIndex=this._elementToAttachTo.tabIndex!==-1?this._elementToAttachTo.tabIndex:this._engine.canvasTabIndex,this._handleKeyActions(),this._handlePointerActions(),this._handleGamepadActions(),this._eventsAttached=!0,this._checkForConnectedDevices()}}_disableEvents(){this._elementToAttachTo&&(this._elementToAttachTo.removeEventListener("blur",this._keyboardBlurEvent),this._elementToAttachTo.removeEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.removeEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.removeEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"leave",this._pointerLeaveEvent),this._elementToAttachTo.removeEventListener(this._wheelEventName,this._pointerWheelEvent),this._usingMacOs&&this._isUsingChromium&&this._elementToAttachTo.removeEventListener("lostpointercapture",this._pointerMacOsChromeOutEvent),window.removeEventListener("gamepadconnected",this._gamepadConnectedEvent),window.removeEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)),this._pointerInputClearObserver&&this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver),this._eventsAttached=!1}_checkForConnectedDevices(){if(navigator.getGamepads){const e=navigator.getGamepads();for(const t of e)t&&this._addGamePad(t)}typeof matchMedia=="function"&&matchMedia("(pointer:fine)").matches&&this._addPointerDevice(ue.Mouse,0,0,0)}_addGamePad(e){const t=this._getGamepadDeviceType(e.id),i=e.index;this._gamepads=this._gamepads||new Array(e.index+1),this._registerDevice(t,i,e.buttons.length+e.axes.length),this._gamepads[i]=t}_addPointerDevice(e,t,i,s){this._pointerActive||(this._pointerActive=!0),this._registerDevice(e,t,hh);const r=this._inputs[e][t];r[0]=i,r[1]=s}_registerDevice(e,t,i){if(t===void 0)throw`Unable to register device ${ue[e]} to undefined slot.`;if(this._inputs[e]||(this._inputs[e]={}),!this._inputs[e][t]){const s=new Array(i);s.fill(0),this._inputs[e][t]=s,this._onDeviceConnected(e,t)}}_unregisterDevice(e,t){this._inputs[e][t]&&(delete this._inputs[e][t],this._onDeviceDisconnected(e,t))}_handleKeyActions(){this._keyboardDownEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(ue.Keyboard,0,oh));const t=this._inputs[ue.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOs&&e.metaKey&&e.key!=="Meta"&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(ue.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(ue.Keyboard,0,oh));const t=this._inputs[ue.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOs&&e.key==="Meta"&&this._metaKeys.length>0){for(const s of this._metaKeys){const r=qi.CreateDeviceEvent(ue.Keyboard,0,s,0,this,this._elementToAttachTo);t[s]=0,this._onInputChanged(ue.Keyboard,0,r)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(ue.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[ue.Keyboard][0];for(let t=0;t<e.length;t++)if(e[t]!==0){e[t]=0;const i=qi.CreateDeviceEvent(ue.Keyboard,0,t,0,this,this._elementToAttachTo);this._onInputChanged(ue.Keyboard,0,i)}this._usingMacOs&&this._metaKeys.splice(0,this._metaKeys.length)}},this._elementToAttachTo.addEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.addEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.addEventListener("blur",this._keyboardBlurEvent)}_handlePointerActions(){this._maxTouchPoints=Ji()&&navigator.maxTouchPoints||2,this._activeTouchIds||(this._activeTouchIds=new Array(this._maxTouchPoints));for(let i=0;i<this._maxTouchPoints;i++)this._activeTouchIds[i]=-1;this._pointerMoveEvent=i=>{const s=this._getPointerType(i);let r=s===ue.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(s===ue.Touch&&r===-1){const a=this._activeTouchIds.indexOf(-1);if(a>=0)r=a,this._activeTouchIds[a]=i.pointerId,this._onDeviceConnected(s,r);else{fe.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[s]||(this._inputs[s]={}),this._inputs[s][r]||this._addPointerDevice(s,r,i.clientX,i.clientY);const n=this._inputs[s][r];if(n){const a=i;a.inputIndex=Te.Move,n[Te.Horizontal]=i.clientX,n[Te.Vertical]=i.clientY,s===ue.Touch&&n[Te.LeftClick]===0&&(n[Te.LeftClick]=1),i.pointerId===void 0&&(i.pointerId=this._mouseId),this._onInputChanged(s,r,a),!this._usingSafari&&i.button!==-1&&(a.inputIndex=i.button+2,n[i.button+2]=n[i.button+2]?0:1,this._onInputChanged(s,r,a))}},this._pointerDownEvent=i=>{const s=this._getPointerType(i);let r=s===ue.Mouse?0:i.pointerId;if(s===ue.Touch){let a=this._activeTouchIds.indexOf(i.pointerId);if(a===-1&&(a=this._activeTouchIds.indexOf(-1)),a>=0)r=a,this._activeTouchIds[a]=i.pointerId;else{fe.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[s]||(this._inputs[s]={}),this._inputs[s][r]?s===ue.Touch&&this._onDeviceConnected(s,r):this._addPointerDevice(s,r,i.clientX,i.clientY);const n=this._inputs[s][r];if(n){const a=n[Te.Horizontal],h=n[Te.Vertical];if(s===ue.Mouse){if(i.pointerId===void 0&&(i.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch{}}else if(i.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(i.pointerId)}catch{}n[Te.Horizontal]=i.clientX,n[Te.Vertical]=i.clientY,n[i.button+2]=1;const l=i;l.inputIndex=i.button+2,this._onInputChanged(s,r,l),(a!==i.clientX||h!==i.clientY)&&(l.inputIndex=Te.Move,this._onInputChanged(s,r,l))}},this._pointerUpEvent=i=>{const s=this._getPointerType(i),r=s===ue.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(s===ue.Touch){if(r===-1)return;this._activeTouchIds[r]=-1}const n=this._inputs[s]?.[r];let a=i.button,h=n&&n[a+2]!==0;if(!h&&this._isUsingFirefox&&this._usingMacOs&&n&&(a=a===2?0:2,h=n[a+2]!==0),h){const l=n[Te.Horizontal],c=n[Te.Vertical];n[Te.Horizontal]=i.clientX,n[Te.Vertical]=i.clientY,n[a+2]=0;const u=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),(l!==i.clientX||c!==i.clientY)&&(u.inputIndex=Te.Move,this._onInputChanged(s,r,u)),u.inputIndex=a+2,s===ue.Mouse&&this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)?this._elementToAttachTo.releasePointerCapture(this._mouseId):i.pointerId&&this._elementToAttachTo.hasPointerCapture?.(i.pointerId)&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._onInputChanged(s,r,u),s===ue.Touch&&this._onDeviceDisconnected(s,r)}},this._pointerCancelTouch=i=>{const s=this._activeTouchIds.indexOf(i);if(s===-1)return;this._elementToAttachTo.hasPointerCapture?.(i)&&this._elementToAttachTo.releasePointerCapture(i),this._inputs[ue.Touch][s][Te.LeftClick]=0;const r=qi.CreateDeviceEvent(ue.Touch,s,Te.LeftClick,0,this,this._elementToAttachTo,i);this._onInputChanged(ue.Touch,s,r),this._activeTouchIds[s]=-1,this._onDeviceDisconnected(ue.Touch,s)},this._pointerCancelEvent=i=>{if(i.pointerType==="mouse"){const s=this._inputs[ue.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let r=Te.LeftClick;r<=Te.BrowserForward;r++)if(s[r]===1){s[r]=0;const n=qi.CreateDeviceEvent(ue.Mouse,0,r,0,this,this._elementToAttachTo);this._onInputChanged(ue.Mouse,0,n)}}else this._pointerCancelTouch(i.pointerId)},this._pointerLeaveEvent=i=>{i.pointerType==="pen"&&this._pointerCancelTouch(i.pointerId)},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":document.onmousewheel!==void 0?"mousewheel":"DOMMouseScroll";let e=!1;const t=function(){};try{const i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch{}this._pointerBlurEvent=()=>{if(this.isDeviceAvailable(ue.Mouse)){const i=this._inputs[ue.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let s=Te.LeftClick;s<=Te.BrowserForward;s++)if(i[s]===1){i[s]=0;const r=qi.CreateDeviceEvent(ue.Mouse,0,s,0,this,this._elementToAttachTo);this._onInputChanged(ue.Mouse,0,r)}}if(this.isDeviceAvailable(ue.Touch)){const i=this._inputs[ue.Touch];for(let s=0;s<this._activeTouchIds.length;s++){const r=this._activeTouchIds[s];if(this._elementToAttachTo.hasPointerCapture?.(r)&&this._elementToAttachTo.releasePointerCapture(r),r!==-1&&i[s]?.[Te.LeftClick]===1){i[s][Te.LeftClick]=0;const n=qi.CreateDeviceEvent(ue.Touch,s,Te.LeftClick,0,this,this._elementToAttachTo,r);this._onInputChanged(ue.Touch,s,n),this._activeTouchIds[s]=-1,this._onDeviceDisconnected(ue.Touch,s)}}}},this._pointerWheelEvent=i=>{const s=ue.Mouse,r=0;this._inputs[s]||(this._inputs[s]=[]),this._inputs[s][r]||(this._pointerActive=!0,this._registerDevice(s,r,hh));const n=this._inputs[s][r];if(n){n[Te.MouseWheelX]=i.deltaX||0,n[Te.MouseWheelY]=i.deltaY||i.wheelDelta||0,n[Te.MouseWheelZ]=i.deltaZ||0;const a=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),n[Te.MouseWheelX]!==0&&(a.inputIndex=Te.MouseWheelX,this._onInputChanged(s,r,a)),n[Te.MouseWheelY]!==0&&(a.inputIndex=Te.MouseWheelY,this._onInputChanged(s,r,a)),n[Te.MouseWheelZ]!==0&&(a.inputIndex=Te.MouseWheelZ,this._onInputChanged(s,r,a))}},this._usingMacOs&&this._isUsingChromium&&(this._pointerMacOsChromeOutEvent=i=>{i.buttons>1&&this._pointerCancelEvent(i)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOsChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"leave",this._pointerLeaveEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,e?{passive:!1}:!1),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add(()=>{if(this.isDeviceAvailable(ue.Mouse)){const i=this._inputs[ue.Mouse][0];i[Te.MouseWheelX]=0,i[Te.MouseWheelY]=0,i[Te.MouseWheelZ]=0}})}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const s=navigator.getGamepads()[t];if(s&&e===this._gamepads[t]){const r=this._inputs[e][t];i>=s.buttons.length?r[i]=s.axes[i-s.buttons.length].valueOf():r[i]=s.buttons[i].value}}_getGamepadDeviceType(e){return e.indexOf("054c")!==-1?e.indexOf("0ce6")!==-1?ue.DualSense:ue.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?ue.Xbox:e.indexOf("057e")!==-1?ue.Switch:ue.Generic}_getPointerType(e){let t=ue.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=ue.Touch),t}}class lh{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new z,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class Hf{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=n=>{for(let a=0;a<this._devices.length;a++){const h=this._devices[a];for(const l in h){const c=+l;n._addDevice(new lh(this._deviceInputSystem,a,c))}}this._registeredManagers.push(n)},this.unregisterManager=n=>{const a=this._registeredManagers.indexOf(n);a>-1&&this._registeredManagers.splice(a,1)};const t=Object.keys(ue).length/2;this._devices=new Array(t);const i=(n,a)=>{this._devices[n]||(this._devices[n]=new Array),this._devices[n][a]||(this._devices[n][a]=a);for(const h of this._registeredManagers){const l=new lh(this._deviceInputSystem,n,a);h._addDevice(l)}},s=(n,a)=>{this._devices[n]?.[a]&&delete this._devices[n][a];for(const h of this._registeredManagers)h._removeDevice(n,a)},r=(n,a,h)=>{if(h)for(const l of this._registeredManagers)l._onInputChanged(n,a,h)};typeof _native<"u"?this._deviceInputSystem=new Wf(i,s,r):this._deviceInputSystem=new Gf(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class Xf{getDeviceSource(e,t){if(t===void 0){if(this._firstDevice[e]===void 0)return null;t=this._firstDevice[e]}return!this._devices[e]||this._devices[e][t]===void 0?null:this._devices[e][t]}getDeviceSources(e){return this._devices[e]?this._devices[e].filter(t=>!!t):[]}constructor(e){const t=Object.keys(ue).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new Hf(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new z(i=>{for(const s of this._devices)if(s)for(const r of s)r&&this.onDeviceConnectedObservable.notifyObserver(i,r)}),this.onDeviceDisconnectedObservable=new z,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=[]),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){const i=this._devices[e]?.[t];this.onDeviceDisconnectedObservable.notifyObservers(i),this._devices[e]?.[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){this._devices[e]?.[t]?.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case ue.Keyboard:case ue.Mouse:this._firstDevice[e]=0;break;case ue.Touch:case ue.DualSense:case ue.DualShock:case ue.Xbox:case ue.Switch:case ue.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t){for(let i=0;i<t.length;i++)if(t[i]){this._firstDevice[e]=i;break}}break}}}}class Il{}Il._IsPickingAvailable=!1;class ch{constructor(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}get singleClick(){return this._singleClick}get doubleClick(){return this._doubleClick}get hasSwiped(){return this._hasSwiped}get ignore(){return this._ignore}set singleClick(e){this._singleClick=e}set doubleClick(e){this._doubleClick=e}set hasSwiped(e){this._hasSwiped=e}set ignore(e){this._ignore=e}}class rt{constructor(e){this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._activePointerIds=new Array,this._activePointerIdsCount=0,this._doubleClickOccured=!1,this._isSwiping=!1,this._swipeButtonPressed=-1,this._skipPointerTap=!1,this._isMultiTouchGesture=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new ie(0,0),this._previousStartingPointerPosition=new ie(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._meshUnderPointerId={},this._movePointerInfo=null,this._cameraObserverCount=0,this._delayedClicks=[null,null,null,null,null],this._deviceSourceManager=null,this._scene=e||ye.LastCreatedScene,this._scene}get meshUnderPointer(){return this._movePointerInfo&&(this._movePointerInfo._generatePickInfo(),this._movePointerInfo=null),this._pointerOverMesh}getMeshUnderPointerByPointerId(e){return this._meshUnderPointerId[e]||null}get unTranslatedPointer(){return new ie(this._unTranslatedPointerX,this._unTranslatedPointerY)}get pointerX(){return this._pointerX}set pointerX(e){this._pointerX=e}get pointerY(){return this._pointerY}set pointerY(e){this._pointerY=e}_updatePointerPosition(e){const t=this._scene.getEngine().getInputElementClientRect();t&&(this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY)}_processPointerMove(e,t){const i=this._scene,s=i.getEngine(),r=s.getInputElement();r&&(r.tabIndex=s.canvasTabIndex,i.doNotHandleCursors||(r.style.cursor=i.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,i);for(const h of i._pointerMoveStage){e=e||this._pickMove(t);const l=!!e?.pickedMesh;e=h.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,l,r)}const n=t.inputIndex>=Te.MouseWheelX&&t.inputIndex<=Te.MouseWheelZ?ve.POINTERWHEEL:ve.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n));let a;e?(a=new Ei(n,t,e),this._setRayOnPointerInfo(e,t)):(a=new Ei(n,t,null,this),this._movePointerInfo=a),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(a,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&Il._IsPickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,D.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const s=this._scene,r=new zf(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,t.pointerType==="xr-near"&&e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const r=i.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&r&&this._pointerOverMesh){const n=this._pointerOverMesh._getActionManagerForTrigger();n&&n.hasPointerTriggers&&(r.style.cursor=n.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=Te.Move,!this._checkPrePointerObservable(e,i,ve.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,ve.POINTERDOWN)&&this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const n=e.pickedMesh._getActionManagerForTrigger();if(n){if(n.hasPickTriggers)switch(n.processTrigger(5,new gt(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e)),t.button){case 0:n.processTrigger(2,new gt(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e));break;case 1:n.processTrigger(4,new gt(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e));break;case 2:n.processTrigger(3,new gt(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e));break}n.hasSpecificTrigger(8)&&window.setTimeout(()=>{const a=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,h=>h.isPickable&&h.isVisible&&h.isReady()&&h.actionManager&&h.actionManager.hasSpecificTrigger(8)&&h===this._pickedDownMesh,!1,i.cameraToUseForPointers);a?.pickedMesh&&n&&this._activePointerIdsCount!==0&&Date.now()-this._startingPointerTime>rt.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,n.processTrigger(8,gt.CreateNew(a.pickedMesh,t)))},rt.LongPressDelay)}}else for(const n of i._pointerDownStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=ve.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new Ei(r,t,e),this._setRayOnPointerInfo(e,t)):s=new Ei(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=Te.Move;const r=new ch;i?r.doubleClick=!0:r.singleClick=!0,!this._checkPrePointerObservable(e,s,ve.POINTERUP)&&this._processPointerUp(e,s,r)}_processPointerUp(e,t,i){const s=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){const n=ve.POINTERPICK,a=new Ei(n,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(a,n)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,gt.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,gt.CreateNew(e.pickedMesh,t,e));const n=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&n&&n.processTrigger(6,gt.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const r=this._pickedDownMesh._getActionManagerForTrigger(16);r&&r.processTrigger(16,gt.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new Ei(ve.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,ve.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,ve.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let n=0;if(i.singleClick?n=ve.POINTERTAP:i.doubleClick&&(n=ve.POINTERDOUBLETAP),n){const a=new Ei(n,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(n)&&s.onPointerObservable.notifyObservers(a,n)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const r=this._scene,n=r.getEngine();s||(s=n.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new Xf(n),this._initActionManager=a=>{if(!this._meshPickProceed){const h=r.skipPointerUpPicking||r._registeredActions===0&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers,r.pointerUpTrianglePredicate);this._currentPickResult=h,h&&(a=h.hit&&h.pickedMesh?h.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return a},this._delayedSimpleClick=(a,h,l)=>{if((Date.now()-this._previousStartingPointerTime>rt.DoubleClickDelay&&!this._doubleClickOccured||a!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,h.singleClick=!0,h.ignore=!1,this._delayedClicks[a])){const c=this._delayedClicks[a].evt,u=ve.POINTERTAP,f=new Ei(u,c,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(u)&&r.onPointerObservable.notifyObservers(f,u),this._delayedClicks[a]=null}},this._initClickEvent=(a,h,l,c)=>{const u=new ch;this._currentPickResult=null;let f=null,d=a.hasSpecificMask(ve.POINTERPICK)||h.hasSpecificMask(ve.POINTERPICK)||a.hasSpecificMask(ve.POINTERTAP)||h.hasSpecificMask(ve.POINTERTAP)||a.hasSpecificMask(ve.POINTERDOUBLETAP)||h.hasSpecificMask(ve.POINTERDOUBLETAP);!d&&Bt&&(f=this._initActionManager(f,u),f&&(d=f.hasPickTriggers));let _=!1;if(d=d&&!this._isMultiTouchGesture,d){const m=l.button;if(u.hasSwiped=this._isPointerSwiping(),!u.hasSwiped){let g=!rt.ExclusiveDoubleClickMode;if(g||(g=!a.hasSpecificMask(ve.POINTERDOUBLETAP)&&!h.hasSpecificMask(ve.POINTERDOUBLETAP),g&&!Bt.HasSpecificTrigger(6)&&(f=this._initActionManager(f,u),f&&(g=!f.hasSpecificTrigger(6)))),g)(Date.now()-this._previousStartingPointerTime>rt.DoubleClickDelay||m!==this._previousButtonPressed)&&(u.singleClick=!0,c(u,this._currentPickResult),_=!0);else{const R={evt:l,clickInfo:u,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,m,u,c),rt.DoubleClickDelay)};this._delayedClicks[m]=R}let T=a.hasSpecificMask(ve.POINTERDOUBLETAP)||h.hasSpecificMask(ve.POINTERDOUBLETAP);!T&&Bt.HasSpecificTrigger(6)&&(f=this._initActionManager(f,u),f&&(T=f.hasSpecificTrigger(6))),T&&(m===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime<rt.DoubleClickDelay&&!this._doubleClickOccured?(!u.hasSwiped&&!this._isPointerSwiping()?(this._previousStartingPointerTime=0,this._doubleClickOccured=!0,u.doubleClick=!0,u.ignore=!1,rt.ExclusiveDoubleClickMode&&this._delayedClicks[m]&&(clearTimeout(this._delayedClicks[m]?.timeoutId),this._delayedClicks[m]=null),c(u,this._currentPickResult)):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=m,rt.ExclusiveDoubleClickMode?(this._delayedClicks[m]&&(clearTimeout(this._delayedClicks[m]?.timeoutId),this._delayedClicks[m]=null),c(u,this._previousPickResult)):c(u,this._currentPickResult)),_=!0):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=m))}}_||c(u,this._currentPickResult)},this._onPointerMove=a=>{if(this._updatePointerPosition(a),!this._isSwiping&&this._swipeButtonPressed!==-1&&(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>rt.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>rt.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,a,a.inputIndex>=Te.MouseWheelX&&a.inputIndex<=Te.MouseWheelZ?ve.POINTERWHEEL:ve.POINTERMOVE)||!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking){this._processPointerMove(new Zs,a);return}r.pointerMovePredicate||(r.pointerMovePredicate=l=>l.isPickable&&l.isVisible&&l.isReady()&&l.isEnabled()&&(l.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||l._getActionManagerForTrigger()!==null)&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&l.layerMask)!==0));const h=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(a):null;this._processPointerMove(h,a)},this._onPointerDown=a=>{const h=this._activePointerIds.indexOf(-1);if(h===-1?this._activePointerIds.push(a.pointerId):this._activePointerIds[h]=a.pointerId,this._activePointerIdsCount++,this._pickedDownMesh=null,this._meshPickProceed=!1,rt.ExclusiveDoubleClickMode){for(let c=0;c<this._delayedClicks.length;c++)if(this._delayedClicks[c])if(a.button===c)clearTimeout(this._delayedClicks[c]?.timeoutId);else{const u=this._delayedClicks[c].clickInfo;this._doubleClickOccured=!1,u.singleClick=!0,u.ignore=!1;const f=this._delayedClicks[c].evt,d=ve.POINTERTAP,_=new Ei(d,f,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(d)&&r.onPointerObservable.notifyObservers(_,d),this._delayedClicks[c]=null}}if(this._updatePointerPosition(a),this._swipeButtonPressed===-1&&(this._swipeButtonPressed=a.button),r.preventDefaultOnPointerDown&&s&&(a.preventDefault(),s.focus()),this._startingPointerPosition.x=this._pointerX,this._startingPointerPosition.y=this._pointerY,this._startingPointerTime=Date.now(),this._checkPrePointerObservable(null,a,ve.POINTERDOWN)||!r.cameraToUseForPointers&&!r.activeCamera)return;this._pointerCaptures[a.pointerId]=!0,r.pointerDownPredicate||(r.pointerDownPredicate=c=>c.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&c.layerMask)!==0)),this._pickedDownMesh=null;let l;r.skipPointerDownPicking||r._registeredActions===0&&!this._checkForPicking()&&!r.onPointerDown?l=new Zs:l=r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers,r.pointerDownTrianglePredicate),this._processPointerDown(l,a)},this._onPointerUp=a=>{const h=this._activePointerIds.indexOf(a.pointerId);h!==-1&&(this._activePointerIds[h]=-1,this._activePointerIdsCount--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(a),r.preventDefaultOnPointerUp&&s&&(a.preventDefault(),s.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,a,(l,c)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!l.ignore)){if(this._checkPrePointerObservable(null,a,ve.POINTERUP)){this._swipeButtonPressed===a.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),a.buttons===0&&(this._pointerCaptures[a.pointerId]=!1);return}l.hasSwiped||(l.singleClick&&r.onPrePointerObservable.hasSpecificMask(ve.POINTERTAP)&&this._checkPrePointerObservable(null,a,ve.POINTERTAP)&&(this._skipPointerTap=!0),l.doubleClick&&r.onPrePointerObservable.hasSpecificMask(ve.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,a,ve.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[a.pointerId]){this._swipeButtonPressed===a.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}a.buttons===0&&(this._pointerCaptures[a.pointerId]=!1),!(!r.cameraToUseForPointers&&!r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=u=>u.isPickable&&u.isVisible&&u.isReady()&&u.isEnabled()&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&u.layerMask)!==0)),!this._meshPickProceed&&(Bt&&Bt.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,l),c||(c=this._currentPickResult),this._processPointerUp(c,a,l),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===a.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=a=>{const h=$s.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const l=new eh(h,a);if(r.onPreKeyboardObservable.notifyObservers(l,h),l.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const l=new Nn(h,a);r.onKeyboardObservable.notifyObservers(l,h)}r.actionManager&&r.actionManager.processTrigger(14,gt.CreateNewFromScene(r,a))},this._onKeyUp=a=>{const h=$s.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const l=new eh(h,a);if(r.onPreKeyboardObservable.notifyObservers(l,h),l.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const l=new Nn(h,a);r.onKeyboardObservable.notifyObservers(l,h)}r.actionManager&&r.actionManager.processTrigger(15,gt.CreateNewFromScene(r,a))},this._deviceSourceManager.onDeviceConnectedObservable.add(a=>{a.deviceType===ue.Mouse?a.onInputChangedObservable.add(h=>{this._originMouseEvent=h,h.inputIndex===Te.LeftClick||h.inputIndex===Te.MiddleClick||h.inputIndex===Te.RightClick||h.inputIndex===Te.BrowserBack||h.inputIndex===Te.BrowserForward?t&&a.getInput(h.inputIndex)===1?this._onPointerDown(h):e&&a.getInput(h.inputIndex)===0&&this._onPointerUp(h):i&&(h.inputIndex===Te.Move?this._onPointerMove(h):(h.inputIndex===Te.MouseWheelX||h.inputIndex===Te.MouseWheelY||h.inputIndex===Te.MouseWheelZ)&&this._onPointerMove(h))}):a.deviceType===ue.Touch?a.onInputChangedObservable.add(h=>{h.inputIndex===Te.LeftClick&&(t&&a.getInput(h.inputIndex)===1?(this._onPointerDown(h),this._activePointerIdsCount>1&&(this._isMultiTouchGesture=!0)):e&&a.getInput(h.inputIndex)===0&&(this._onPointerUp(h),this._activePointerIdsCount===0&&(this._isMultiTouchGesture=!1))),i&&h.inputIndex===Te.Move&&this._onPointerMove(h)}):a.deviceType===ue.Keyboard&&a.onInputChangedObservable.add(h=>{h.type==="keydown"?this._onKeyDown(h):h.type==="keyup"&&this._onKeyUp(h)})}),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,s){if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const r=this._meshUnderPointerId[t];let n;r&&(n=r._getActionManagerForTrigger(10),n&&n.processTrigger(10,new gt(r,this._pointerX,this._pointerY,e,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,new gt(e,this._pointerX,this._pointerY,e,s,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null),this._scene.onMeshUnderPointerUpdatedObservable.hasObservers()&&this._scene.onMeshUnderPointerUpdatedObservable.notifyObservers({mesh:e,pointerId:t})}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(const t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}rt.DragMovementThreshold=10;rt.LongPressDelay=500;rt.DoubleClickDelay=300;rt.ExclusiveDoubleClickMode=!1;class di{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){di.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){di.Enabled&&(this._startMonitoringTime=Si.Now)}endMonitoring(e=!0){if(!di.Enabled)return;e&&this.fetchNewFrame();const t=Si.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;const e=Si.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}di.Enabled=!0;class $r{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}$r._UniqueIdCounter=1;class Be{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}Be.FALLOFF_DEFAULT=0;Be.FALLOFF_PHYSICAL=1;Be.FALLOFF_GLTF=2;Be.FALLOFF_STANDARD=3;Be.LIGHTMAP_DEFAULT=0;Be.LIGHTMAP_SPECULAR=1;Be.LIGHTMAP_SHADOWSONLY=2;Be.INTENSITYMODE_AUTOMATIC=0;Be.INTENSITYMODE_LUMINOUSPOWER=1;Be.INTENSITYMODE_LUMINOUSINTENSITY=2;Be.INTENSITYMODE_ILLUMINANCE=3;Be.INTENSITYMODE_LUMINANCE=4;Be.LIGHTTYPEID_POINTLIGHT=0;Be.LIGHTTYPEID_DIRECTIONALLIGHT=1;Be.LIGHTTYPEID_SPOTLIGHT=2;Be.LIGHTTYPEID_HEMISPHERICLIGHT=3;Be.LIGHTTYPEID_RECT_AREALIGHT=4;Be.LIGHTTYPEID_CLUSTERED_CONTAINER=5;class Kf{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}const Yf=new Me,jf=new Me;var Un;(function(o){o[o.BackwardCompatible=0]="BackwardCompatible",o[o.Intermediate=1]="Intermediate",o[o.Aggressive=2]="Aggressive"})(Un||(Un={}));class je{static DefaultMaterialFactory(e){throw pe("StandardMaterial")}static CollisionCoordinatorFactory(){throw pe("DefaultCollisionCoordinator")}get clearColor(){return this._clearColor}set clearColor(e){e!==this._clearColor&&(this._clearColor=e,this.onClearColorChangedObservable.notifyObservers(this._clearColor))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case 0:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case 1:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case 2:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1;break}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.onEnvironmentTextureChangedObservable.notifyObservers(e),this.markAllMaterialsAsDirty(1))}getNodes(){let e=[];e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes);for(const t of this.skeletons)e=e.concat(t.bones);return e}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return rt.DragMovementThreshold}static set DragMovementThreshold(e){rt.DragMovementThreshold=e}static get LongPressDelay(){return rt.LongPressDelay}static set LongPressDelay(e){rt.LongPressDelay=e}static get DoubleClickDelay(){return rt.DoubleClickDelay}static set DoubleClickDelay(e){rt.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return rt.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){rt.ExclusiveDoubleClickMode=e}get _eyePosition(){return this._forcedViewPosition??this.activeCamera?.globalPosition??p.ZeroReadOnly}bindEyePosition(e,t="vEyePosition",i=!1){const s=this._eyePosition,r=this.useRightHandedSystem===(this._mirroredCameraPosition!=null),n=this.floatingOriginOffset,a=Yf.set(s.x,s.y,s.z,r?-1:1),h=a.subtractFromFloatsToRef(n.x,n.y,n.z,0,jf);return e&&(i?e.setFloat3(t,h.x,h.y,h.z):e.setVector4(t,h)),a}finalizeSceneUbo(){const e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null),i=this.floatingOriginOffset;return e.updateFloat4("vEyePosition",t.x-i.x,t.y-i.y,t.z-i.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=fl(e,()=>{this.onActiveCamerasChanged.notifyObservers(this)})),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get _hasDefaultMaterial(){return je.DefaultMaterialFactory!==je._OriginalDefaultMaterialFactory}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=je.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}get frameGraph(){return this._frameGraph}set frameGraph(e){if(this._frameGraph){this._frameGraph=e,e||(this.customRenderFunction=this._currentCustomRenderFunction);return}this._frameGraph=e,e&&(this._currentCustomRenderFunction=this.customRenderFunction,this.customRenderFunction=this._renderWithFrameGraph,this.activeCamera=null)}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=je.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}get uniqueId(){return this._uniqueId}constructor(e,t){this._inputManager=new rt(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this._clearColor=new Ce(.2,.2,.3,1),this.onClearColorChangedObservable=new z,this.ambientColor=new Re(0,0,0),this.environmentIntensity=1,this.iblIntensity=1,this._performancePriority=0,this.onScenePerformancePriorityChangedObservable=new z,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.objectRenderers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[],this.effectLayers=[],this.sounds=null,this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new z,this._onDisposeObserver=null,this.onBeforeRenderObservable=new z,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new z,this.onAfterRenderCameraObservable=new z,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new z,this.onAfterAnimationsObservable=new z,this.onBeforeDrawPhaseObservable=new z,this.onAfterDrawPhaseObservable=new z,this.onReadyObservable=new z,this.onBeforeCameraRenderObservable=new z,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new z,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new z,this.onAfterActiveMeshesEvaluationObservable=new z,this.onBeforeParticlesRenderingObservable=new z,this.onAfterParticlesRenderingObservable=new z,this.onDataLoadedObservable=new z,this.onNewCameraAddedObservable=new z,this.onCameraRemovedObservable=new z,this.onNewLightAddedObservable=new z,this.onLightRemovedObservable=new z,this.onNewGeometryAddedObservable=new z,this.onGeometryRemovedObservable=new z,this.onNewTransformNodeAddedObservable=new z,this.onTransformNodeRemovedObservable=new z,this.onNewMeshAddedObservable=new z,this.onMeshRemovedObservable=new z,this.onNewSkeletonAddedObservable=new z,this.onSkeletonRemovedObservable=new z,this.onNewParticleSystemAddedObservable=new z,this.onParticleSystemRemovedObservable=new z,this.onNewAnimationGroupAddedObservable=new z,this.onAnimationGroupRemovedObservable=new z,this.onNewMaterialAddedObservable=new z,this.onNewMultiMaterialAddedObservable=new z,this.onMaterialRemovedObservable=new z,this.onMultiMaterialRemovedObservable=new z,this.onNewTextureAddedObservable=new z,this.onTextureRemovedObservable=new z,this.onNewFrameGraphAddedObservable=new z,this.onFrameGraphRemovedObservable=new z,this.onNewObjectRendererAddedObservable=new z,this.onObjectRendererRemovedObservable=new z,this.onNewPostProcessAddedObservable=new z,this.onPostProcessRemovedObservable=new z,this.onNewEffectLayerAddedObservable=new z,this.onEffectLayerRemovedObservable=new z,this.onBeforeRenderTargetsRenderObservable=new z,this.onAfterRenderTargetsRenderObservable=new z,this.onBeforeStepObservable=new z,this.onAfterStepObservable=new z,this.onActiveCameraChanged=new z,this.onActiveCamerasChanged=new z,this.onBeforeRenderingGroupObservable=new z,this.onAfterRenderingGroupObservable=new z,this.onMeshImportedObservable=new z,this.onAnimationFileImportedObservable=new z,this.onEnvironmentTextureChangedObservable=new z,this.onMeshUnderPointerUpdatedObservable=new z,this._registeredForLateAnimationBindings=new Zi(256),this._pointerPickingConfiguration=new Kf,this.onPrePointerObservable=new z,this.onPointerObservable=new z,this.onPreKeyboardObservable=new z,this.onKeyboardObservable=new z,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=je.FOGMODE_NONE,this.fogColor=new Re(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this._frameGraph=null,this.frameGraphs=[],this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new p(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new Zi(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new di,this._activeIndices=new di,this._activeParticles=new di,this._activeBones=new di,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=new Array(256),this._activeRequests=new Array,this._pendingData=[],this._isDisposed=!1,this._isReadyChecks=[],this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new Et(256),this._processedMaterials=new Et(256),this._renderTargets=new Zi(256),this._materialsRenderTargets=new Zi(256),this._activeParticleSystems=new Et(256),this._activeSkeletons=new Zi(32),this._softwareSkinnedMeshes=new Zi(32),this._activeAnimatables=new Array,this._transformMatrix=D.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=st.Create(),this._beforeClearStage=st.Create(),this._beforeRenderTargetClearStage=st.Create(),this._gatherRenderTargetsStage=st.Create(),this._gatherActiveCameraRenderTargetsStage=st.Create(),this._isReadyForMeshStage=st.Create(),this._beforeEvaluateActiveMeshStage=st.Create(),this._evaluateSubMeshStage=st.Create(),this._preActiveMeshStage=st.Create(),this._cameraDrawRenderTargetStage=st.Create(),this._beforeCameraDrawStage=st.Create(),this._beforeRenderTargetDrawStage=st.Create(),this._beforeRenderingGroupDrawStage=st.Create(),this._beforeRenderingMeshStage=st.Create(),this._afterRenderingMeshStage=st.Create(),this._afterRenderingGroupDrawStage=st.Create(),this._afterCameraDrawStage=st.Create(),this._afterCameraPostProcessStage=st.Create(),this._afterRenderTargetDrawStage=st.Create(),this._afterRenderTargetPostProcessStage=st.Create(),this._afterRenderStage=st.Create(),this._pointerMoveStage=st.Create(),this._pointerDownStage=st.Create(),this._pointerUpStage=st.Create(),this._geometriesByUniqueId=null,this._uniqueId=0,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this.onReadyTimeoutObservable=new z,this.onReadyTimeoutDuration=2*60*1e3,this._timeoutChecksStartTime=0,this._floatingOriginScene=void 0,this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._freezeActiveMeshesCancel=null,this._useCurrentFrameBuffer=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._getFloatingOriginScene=()=>this._floatingOriginScene,this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[],this._uniqueId=this.getUniqueId();const i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};e=this._engine=e||ye.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(ye._LastCreatedScene=this,e.scenes.push(this)),(e.getCreationOptions().useLargeWorldRendering||t?.useFloatingOrigin)&&(kf(),this._floatingOriginScene=this,zi.getScene=this._getFloatingOriginScene),this._uid=null,this._renderingManager=new pt(this),zr&&(this.postProcessManager=new zr(this)),mt()&&this.attachControl(),this._createUbo(),Oe&&(this._imageProcessingConfiguration=new Oe),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,(!t||!t.virtual)&&e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return this._animationRatio!==void 0?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){if(this._isDisposed)return!1;let t;const i=this.getEngine(),s=i.currentRenderPassId;i.currentRenderPassId=this.activeCamera?.renderPassId??s;let r=!0;for(this._pendingData.length>0&&(r=!1),this.prePassRenderer?.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&r&&(r=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t<this.meshes.length;t++){const n=this.meshes[t];if(!n.subMeshes||n.subMeshes.length===0)continue;if(!n.isReady(!0)){r=!1;continue}const a=n.hasThinInstances||n.getClassName()==="InstancedMesh"||n.getClassName()==="InstancedLinesMesh"||i.getCaps().instancedArrays&&n.instances.length>0;for(const l of this._isReadyForMeshStage)l.action(n,a)||(r=!1);if(!e)continue;const h=n.material||this.defaultMaterial;if(h)if(h._storeEffectOnSubMeshes)for(const l of n.subMeshes){const c=l.getMaterial();c&&c.hasRenderTargetTextures&&c.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(c)===-1&&(this._processedMaterials.push(c),this._materialsRenderTargets.concatWithNoDuplicate(c.getRenderTargetTextures()))}else h.hasRenderTargetTextures&&h.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(h)===-1&&(this._processedMaterials.push(h),this._materialsRenderTargets.concatWithNoDuplicate(h.getRenderTargetTextures()))}if(e)for(t=0;t<this._materialsRenderTargets.length;++t)this._materialsRenderTargets.data[t].isReadyForRendering()||(r=!1);for(t=0;t<this.geometries.length;t++)this.geometries[t].delayLoadState===2&&(r=!1);if(this.activeCameras&&this.activeCameras.length>0)for(const n of this.activeCameras)n.isReady(!0)||(r=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(r=!1));for(const n of this.particleSystems)n.isReady()||(r=!1);if(this.layers)for(const n of this.layers)n.isReady()||(r=!1);if(this.effectLayers)for(const n of this.effectLayers)n.isLayerReady()||(r=!1);for(const n of this._isReadyChecks)n.isReady()||(r=!1);return i.areAllEffectsReady()||(r=!1),i.currentRenderPassId=s,r}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout(()=>{this.unregisterBeforeRender(t)})};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){t!==void 0?setTimeout(()=>{this._executeOnceBeforeRender(e)},t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){const t=this.isLoading,i=this._pendingData.indexOf(e);i!==-1&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}addIsReadyCheck(e){this._isReadyChecks.indexOf(e)===-1&&this._isReadyChecks.push(e)}removeIsReadyCheck(e){const t=this._isReadyChecks.indexOf(e);t!==-1&&this._isReadyChecks.splice(t,1)}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),this._executeWhenReadyTimeoutId===null&&this._checkIsReady(t)}async whenReadyAsync(e=!1){return await new Promise(t=>{this.executeWhenReady(()=>{t()},e)})}_clearReadynessChecksData(){this._timeoutChecksStartTime=0,this.onReadyTimeoutObservable.clear(),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null}_checkIsReady(e=!1){if(this._registerTransientComponents(),this._timeoutChecksStartTime===0)this._timeoutChecksStartTime=Si.Now;else if(this.onReadyTimeoutDuration>0&&Si.Now-this._timeoutChecksStartTime>this.onReadyTimeoutDuration){this.onReadyTimeoutObservable.notifyObservers(this),this._clearReadynessChecksData();return}if(this.isReady(e)){this.onReadyObservable.notifyObservers(this),this._clearReadynessChecksData();return}if(this._isDisposed){this._clearReadynessChecksData();return}this._executeWhenReadyTimeoutId=setTimeout(()=>{this.incrementRenderId(),this._checkIsReady(e)},100)}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=Si.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,s){this._multiviewSceneUboIsActive=!!(i&&s&&this._multiviewSceneUbo),!(this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag)&&(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?Gt.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Gt.GetPlanes(this._transformMatrix),this._multiviewSceneUboIsActive&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,s):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUboIsActive&&this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e,t){const i=typeof t=="boolean"?t:t?.trackUBOsInFrame,s=new oe(this._engine,void 0,!1,e??"scene",void 0,i);return s.addUniform("viewProjection",16),s.addUniform("view",16),s.addUniform("projection",16),s.addUniform("vEyePosition",4),s}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}get floatingOriginMode(){return this._floatingOriginScene!==void 0}get floatingOriginOffset(){return this.floatingOriginMode?this._eyePosition:p.ZeroReadOnly}getUniqueId(){return $r.UniqueId}addMesh(e,t=!1){if(!this._blockEntityCollection&&(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),fe.SetImmediate(()=>{this.onNewMeshAddedObservable.notifyObservers(e)}),t)){const i=e.getChildMeshes();for(const s of i)this.addMesh(s)}}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);if(i!==-1&&(this.meshes.splice(i,1),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t){const s=e.getChildMeshes();for(const r of s)this.removeMesh(r)}return i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&e._indexInSceneTransformNodesArray!==-1||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(t!==-1){if(t!==this.transformNodes.length-1){const i=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=i,i._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){const t=this.skeletons.indexOf(e);return t!==-1&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return t!==-1&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(t!==-1){for(const i of this.meshes)i._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes(),this.onLightRemovedObservable.notifyObservers(e)}return t}removeCamera(e){const t=this.cameras.indexOf(e);if(t!==-1&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const i=this.activeCameras.indexOf(e);i!==-1&&this.activeCameras.splice(i,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){const t=this.particleSystems.indexOf(e);return t!==-1&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),this.onParticleSystemRemovedObservable.notifyObservers(e),t}removeAnimation(e){const t=this.animations.indexOf(e);return t!==-1&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return t!==-1&&this.animationGroups.splice(t,1),this.onAnimationGroupRemovedObservable.notifyObservers(e),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return t!==-1&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(t!==-1&&t<this.materials.length){if(t!==this.materials.length-1){const i=this.materials[this.materials.length-1];this.materials[t]=i,i._indexInSceneMaterialArray=t}e._indexInSceneMaterialArray=-1,this.materials.pop()}return this.onMaterialRemovedObservable.notifyObservers(e),t}removeActionManager(e){const t=this.actionManagers.indexOf(e);return t!==-1&&this.actionManagers.splice(t,1),t}removeTexture(e){const t=this.textures.indexOf(e);return t!==-1&&this.textures.splice(t,1),this.onTextureRemovedObservable.notifyObservers(e),t}removeFrameGraph(e){const t=this.frameGraphs.indexOf(e);return t!==-1&&this.frameGraphs.splice(t,1),this.onFrameGraphRemovedObservable.notifyObservers(e),t}removeObjectRenderer(e){const t=this.objectRenderers.indexOf(e);return t!==-1&&this.objectRenderers.splice(t,1),this.onObjectRendererRemovedObservable.notifyObservers(e),t}removePostProcess(e){const t=this.postProcesses.indexOf(e);return t!==-1&&this.postProcesses.splice(t,1),this.onPostProcessRemovedObservable.notifyObservers(e),t}removeEffectLayer(e){const t=this.effectLayers.indexOf(e);return t!==-1&&this.effectLayers.splice(t,1),this.onEffectLayerRemovedObservable.notifyObservers(e),t}addLight(e){if(!this._blockEntityCollection){this.lights.push(e),this.sortLightsByPriority(),e.parent||e._addToSceneRootNodes();for(const t of this.meshes)t.lightSources.indexOf(e)===-1&&(t.lightSources.push(e),t._resyncLightSources());fe.SetImmediate(()=>{this.onNewLightAddedObservable.notifyObservers(e)})}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort(Be.CompareLightsPriority)}addCamera(e){this._blockEntityCollection||(this.cameras.push(e),fe.SetImmediate(()=>{this.onNewCameraAddedObservable.notifyObservers(e)}),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),fe.SetImmediate(()=>{this.onNewSkeletonAddedObservable.notifyObservers(e)}))}addParticleSystem(e){this._blockEntityCollection||(this.particleSystems.push(e),fe.SetImmediate(()=>{this.onNewParticleSystemAddedObservable.notifyObservers(e)}))}addAnimation(e){this._blockEntityCollection||this.animations.push(e)}addAnimationGroup(e){this._blockEntityCollection||(this.animationGroups.push(e),fe.SetImmediate(()=>{this.onNewAnimationGroupAddedObservable.notifyObservers(e)}))}addMultiMaterial(e){this._blockEntityCollection||(this.multiMaterials.push(e),fe.SetImmediate(()=>{this.onNewMultiMaterialAddedObservable.notifyObservers(e)}))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&e._indexInSceneMaterialArray!==-1||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),fe.SetImmediate(()=>{this.onNewMaterialAddedObservable.notifyObservers(e)}))}addMorphTargetManager(e){this._blockEntityCollection||this.morphTargetManagers.push(e)}addGeometry(e){this._blockEntityCollection||(this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))}addActionManager(e){this.actionManagers.push(e)}addTexture(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))}addFrameGraph(e){this.frameGraphs.push(e),fe.SetImmediate(()=>{this.onNewFrameGraphAddedObservable.notifyObservers(e)})}addObjectRenderer(e){this.objectRenderers.push(e),fe.SetImmediate(()=>{this.onNewObjectRendererAddedObservable.notifyObservers(e)})}addPostProcess(e){this._blockEntityCollection||(this.postProcesses.push(e),fe.SetImmediate(()=>{this.onNewPostProcessAddedObservable.notifyObservers(e)}))}addEffectLayer(e){this._blockEntityCollection||(this.effectLayers.push(e),fe.SetImmediate(()=>{this.onNewEffectLayerAddedObservable.notifyObservers(e)}))}switchActiveCamera(e,t=!0){this._engine.getInputElement()&&(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,t&&e.attachControl())}setActiveCameraById(e){const t=this.getCameraById(e);return t?(this.activeCamera=t,t):null}setActiveCameraByName(e){const t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null}getAnimationGroupByName(e){for(let t=0;t<this.animationGroups.length;t++)if(this.animationGroups[t].name===e)return this.animationGroups[t];return null}_getMaterial(e,t){for(let i=0;i<this.materials.length;i++){const s=this.materials[i];if(t(s))return s}if(e)for(let i=0;i<this.multiMaterials.length;i++){const s=this.multiMaterials[i];if(t(s))return s}return null}getMaterialByUniqueID(e,t=!1){return this.getMaterialByUniqueId(e,t)}getMaterialByUniqueId(e,t=!1){return this._getMaterial(t,i=>i.uniqueId===e)}getMaterialById(e,t=!1){return this._getMaterial(t,i=>i.id===e)}getMaterialByName(e,t=!1){return this._getMaterial(t,i=>i.name===e)}getLastMaterialById(e,t=!1){for(let i=this.materials.length-1;i>=0;i--)if(this.materials[i].id===e)return this.materials[i];if(t){for(let i=this.multiMaterials.length-1;i>=0;i--)if(this.multiMaterials[i].id===e)return this.multiMaterials[i]}return null}getTextureByUniqueId(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].uniqueId===e)return this.textures[t];return null}getTextureByName(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].name===e)return this.textures[t];return null}getCameraById(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].id===e)return this.cameras[t];return null}getCameraByUniqueId(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].uniqueId===e)return this.cameras[t];return null}getCameraByName(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].name===e)return this.cameras[t];return null}getBoneById(e){for(let t=0;t<this.skeletons.length;t++){const i=this.skeletons[t];for(let s=0;s<i.bones.length;s++)if(i.bones[s].id===e)return i.bones[s]}return null}getBoneByName(e){for(let t=0;t<this.skeletons.length;t++){const i=this.skeletons[t];for(let s=0;s<i.bones.length;s++)if(i.bones[s].name===e)return i.bones[s]}return null}getLightByName(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].name===e)return this.lights[t];return null}getLightById(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].id===e)return this.lights[t];return null}getLightByUniqueId(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].uniqueId===e)return this.lights[t];return null}getParticleSystemById(e){for(let t=0;t<this.particleSystems.length;t++)if(this.particleSystems[t].id===e)return this.particleSystems[t];return null}getGeometryById(e){for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].id===e)return this.geometries[t];return null}_getGeometryByUniqueId(e){if(this._geometriesByUniqueId){const t=this._geometriesByUniqueId[e];if(t!==void 0)return this.geometries[t]}else for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].uniqueId===e)return this.geometries[t];return null}getFrameGraphByName(e){for(let t=0;t<this.frameGraphs.length;t++)if(this.frameGraphs[t].name===e)return this.frameGraphs[t];return null}pushGeometry(e,t){return!t&&this._getGeometryByUniqueId(e.uniqueId)?!1:(this.addGeometry(e),fe.SetImmediate(()=>{this.onNewGeometryAddedObservable.notifyObservers(e)}),!0)}removeGeometry(e){let t;if(this._geometriesByUniqueId){if(t=this._geometriesByUniqueId[e.uniqueId],t===void 0)return!1}else if(t=this.geometries.indexOf(e),t<0)return!1;if(t!==this.geometries.length-1){const i=this.geometries[this.geometries.length-1];i&&(this.geometries[t]=i,this._geometriesByUniqueId&&(this._geometriesByUniqueId[i.uniqueId]=t))}return this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=void 0),this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0}getGeometries(){return this.geometries}getMeshById(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].id===e)return this.meshes[t];return null}getMeshesById(e){return this.meshes.filter(function(t){return t.id===e})}getTransformNodeById(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getTransformNodeByUniqueId(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].uniqueId===e)return this.transformNodes[t];return null}getTransformNodesById(e){return this.transformNodes.filter(function(t){return t.id===e})}getMeshByUniqueId(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].uniqueId===e)return this.meshes[t];return null}getLastMeshById(e){for(let t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];for(t=this.skeletons.length-1;t>=0;t--){const i=this.skeletons[t];for(let s=i.bones.length-1;s>=0;s--)if(i.bones[s].id===e)return i.bones[s]}return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const s=this.getLightById(e);if(s)return s;const r=this.getCameraById(e);if(r)return r;const n=this.getBoneById(e);return n||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const s=this.getLightByName(e);if(s)return s;const r=this.getCameraByName(e);if(r)return r;const n=this.getBoneByName(e);return n||null}getMeshByName(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].name===e)return this.meshes[t];return null}getTransformNodeByName(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].name===e)return this.transformNodes[t];return null}getLastSkeletonById(e){for(let t=this.skeletons.length-1;t>=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].uniqueId===e)return this.skeletons[t];return null}getSkeletonById(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByName(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].name===e)return this.skeletons[t];return null}getMorphTargetManagerById(e){for(let t=0;t<this.morphTargetManagers.length;t++)if(this.morphTargetManagers[t].uniqueId===e)return this.morphTargetManagers[t];return null}getMorphTargetById(e){for(let t=0;t<this.morphTargetManagers.length;++t){const i=this.morphTargetManagers[t];for(let s=0;s<i.numTargets;++s){const r=i.getTarget(s);if(r.id===e)return r}}return null}getMorphTargetByName(e){for(let t=0;t<this.morphTargetManagers.length;++t){const i=this.morphTargetManagers[t];for(let s=0;s<i.numTargets;++s){const r=i.getTarget(s);if(r.name===e)return r}}return null}getPostProcessByName(e){for(let t=0;t<this.postProcesses.length;++t){const i=this.postProcesses[t];if(i.name===e)return i}return null}isActiveMesh(e){return this._activeMeshes.indexOf(e)!==-1}get uid(){return this._uid||(this._uid=fe.RandomId()),this._uid}addExternalData(e,t){return this._externalData||(this._externalData=new qo),this._externalData.add(e,t)}getExternalData(e){return this._externalData?this._externalData.get(e):null}getOrAddExternalDataWithFactory(e,t){return this._externalData||(this._externalData=new qo),this._externalData.getOrAddWithFactory(e,t)}removeExternalData(e){return this._externalData.remove(e)}_evaluateSubMesh(e,t,i,s){if(s||e.isInFrustum(this._frustumPlanes)){for(const n of this._evaluateSubMeshStage)n.action(t,e);const r=e.getMaterial();r!=null&&(r.hasRenderTargetTextures&&r.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(r)===-1&&(this._processedMaterials.push(r),this._materialsRenderTargets.concatWithNoDuplicate(r.getRenderTargetTextures())),this._renderingManager.dispatch(e,t,r))}}freeProcessedMaterials(){this._processedMaterials.dispose()}get blockfreeActiveMeshesAndRenderingGroups(){return this._preventFreeActiveMeshesAndRenderingGroups}set blockfreeActiveMeshesAndRenderingGroups(e){this._preventFreeActiveMeshesAndRenderingGroups!==e&&(e&&(this.freeActiveMeshes(),this.freeRenderingGroups()),this._preventFreeActiveMeshesAndRenderingGroups=e)}freeActiveMeshes(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._activeMeshes.dispose(),this.activeCamera&&this.activeCamera._activeMeshes&&this.activeCamera._activeMeshes.dispose(),this.activeCameras))for(let e=0;e<this.activeCameras.length;e++){const t=this.activeCameras[e];t&&t._activeMeshes&&t._activeMeshes.dispose()}}freeRenderingGroups(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._renderingManager&&this._renderingManager.freeRenderingGroups(),this.textures))for(let e=0;e<this.textures.length;e++){const t=this.textures[e];t&&t.renderList&&t.freeRenderingGroups()}}_isInIntermediateRendering(){return this._intermediateRendering}freezeActiveMeshes(e=!1,t,i,s=!0,r=!1){if(this.frameGraph){this._renderWithFrameGraph(!0,!1,!0);const n=this.frameGraph.getTasksByClassName(["FrameGraphObjectRendererTask","FrameGraphGeometryRendererTask"]);for(const a of n)a.objectRenderer._freezeActiveMeshes(s);return this._freezeActiveMeshesCancel=Yr(()=>{let a=!0,h=!0;for(const l of n)a&&(a=l.objectRenderer._isFrozen),h&&(h=l.objectRenderer._freezeActiveMeshesCancel!==null);if(a)return!0;if(!h)throw new Error("Freezing active meshes was cancelled");return!1},()=>{this._freezeActiveMeshesCancel=null,this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,t?.()},(a,h)=>{if(this._freezeActiveMeshesCancel=null,this.unfreezeActiveMeshes(),h){const l="Scene: Timeout while waiting for meshes to be frozen.";i?i(l):(W.Error(l),a&&W.Error(a))}else{const l="Scene: An unexpected error occurred while trying to freeze active meshes.";i?i(l):(W.Error(l),a&&(W.Error(a),a.stack&&W.Error(a.stack)))}}),this}return this.executeWhenReady(()=>{if(!this.activeCamera){i&&i("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,s)for(let n=0;n<this._activeMeshes.length;n++)this._activeMeshes.data[n]._freeze();t&&t()}),this}unfreezeActiveMeshes(){for(let e=0;e<this.meshes.length;e++){const t=this.meshes[e];t._internalAbstractMeshDataInfo&&(t._internalAbstractMeshDataInfo._isActive=!1)}if(this._freezeActiveMeshesCancel?.(),this._freezeActiveMeshesCancel=null,this.frameGraph){const e=this.frameGraph.getTasksByClassName(["FrameGraphObjectRendererTask","FrameGraphGeometryRendererTask"]);for(const t of e)t.objectRenderer._unfreezeActiveMeshes()}else for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._unFreeze();return this._activeMeshesFrozen=!1,this}_executeActiveContainerCleanup(e){!(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1)&&this._activeMeshesFrozen&&this._activeMeshes.length||this.onBeforeRenderObservable.addOnce(()=>e.dispose())}_evaluateActiveMeshes(){if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1){this._activeMeshes.length>0&&(this.activeCamera?._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const i=this._activeMeshes.length;for(let s=0;s<i;s++)this._activeMeshes.data[s].computeWorldMatrix()}if(this._activeParticleSystems){const i=this._activeParticleSystems.length;for(let s=0;s<i;s++)this._activeParticleSystems.data[s].animate()}this._renderingManager.resetSprites();return}if(!this.activeCamera)return;this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this),this.activeCamera._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset(),this._materialsRenderTargets.reset();for(const i of this._beforeEvaluateActiveMeshStage)i.action();const e=this.getActiveMeshCandidates(),t=e.length;for(let i=0;i<t;i++){const s=e.data[i];let r=s._internalAbstractMeshDataInfo._currentLOD.get(this.activeCamera);if(r?r[1]=-1:(r=[s,-1],s._internalAbstractMeshDataInfo._currentLOD.set(this.activeCamera,r)),s.isBlocked||(this._totalVertices.addCount(s.getTotalVertices(),!1),!s.isReady()||!s.isEnabled()||s.scaling.hasAZeroComponent))continue;s.computeWorldMatrix(),s.actionManager&&s.actionManager.hasSpecificTriggers2(12,13)&&this._meshesForIntersections.pushNoDuplicate(s);let n=this.customLODSelector?this.customLODSelector(s,this.activeCamera):s.getLOD(this.activeCamera);if(r[0]=n,r[1]=this._frameId,n!=null&&(n!==s&&n.billboardMode!==0&&n.computeWorldMatrix(),s._preActivate(),s.isVisible&&s.visibility>0&&s.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||s.alwaysSelectAsActiveMesh||s.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(s),this.activeCamera._activeMeshes.push(s),n!==s&&n._activate(this._renderId,!1);for(const a of this._preActiveMeshStage)a.action(s);s._activate(this._renderId,!1)&&(s.isAnInstance?s._internalAbstractMeshDataInfo._actAsRegularMesh&&(n=s):n._internalAbstractMeshDataInfo._onlyForInstances=!1,n._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(s,n)),s._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let i=0;i<this.particleSystems.length;i++){const s=this.particleSystems[i];if(!s.isStarted()||!s.emitter)continue;const r=s.emitter;(!r.position||r.isEnabled())&&(this._activeParticleSystems.push(s),s.animate(),this._renderingManager.dispatchParticles(s))}this.onAfterParticlesRenderingObservable.notifyObservers(this)}}_prepareSkeleton(e){!this._skeletonsEnabled||!e.skeleton||(this._activeSkeletons.pushNoDuplicate(e.skeleton)&&(e.skeleton.prepare(),this._activeBones.addCount(e.skeleton.bones.length,!1)),e.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(e)&&this.frameGraph&&e.applySkeleton(e.skeleton))}_activeMesh(e,t){this._prepareSkeleton(t);let i=e.hasInstances||e.isAnInstance||this.dispatchAllSubMeshesOfActiveMeshes||this._skipFrustumClipping||t.alwaysSelectAsActiveMesh;if(t&&t.subMeshes&&t.subMeshes.length>0){const s=this.getActiveSubMeshCandidates(t),r=s.length;i=i||r===1;for(let n=0;n<r;n++){const a=s.data[n];this._evaluateSubMesh(a,t,e,i)}}}updateTransformMatrix(e){const t=this.activeCamera;if(t)if(t._renderingMultiview){const i=t._rigCameras[0],s=t._rigCameras[1];this.setTransformMatrix(i.getViewMatrix(),i.getProjectionMatrix(e),s.getViewMatrix(),s.getProjectionMatrix(e))}else this.setTransformMatrix(t.getViewMatrix(),t.getProjectionMatrix(e))}_bindFrameBuffer(e,t=!0){this._useCurrentFrameBuffer||(e&&e._multiviewTexture?e._multiviewTexture._bindFrameBuffer():e&&e.outputRenderTarget?e.outputRenderTarget._bindFrameBuffer():this._engine._currentFrameBufferIsDefaultFrameBuffer()||this._engine.restoreDefaultFramebuffer()),t&&this._clearFrameBuffer(e)}_clearFrameBuffer(e){if(!(e&&e._multiviewTexture))if(e&&e.outputRenderTarget&&!e._renderingMultiview){const t=e.outputRenderTarget;t.onClearObservable.hasObservers()?t.onClearObservable.notifyObservers(this._engine):!t.skipInitialClear&&!e.isRightCamera&&(this.autoClear&&this._engine.clear(t.clearColor||this._clearColor,!t._cleared,!0,!0),t._cleared=!0)}else this._defaultFrameBufferCleared?this._engine.clear(null,!1,!0,!0):(this._defaultFrameBufferCleared=!0,this._clear())}_renderForCamera(e,t,i=!0){if(e&&e._skipRendering)return;const s=this._engine;if(this._activeCamera=e,!this.activeCamera)throw new Error("Active camera not set");if(s.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,!this.prePass&&i){let a=!0;e._renderingMultiview&&e.outputRenderTarget&&(a=e.outputRenderTarget.skipInitialClear,this.autoClear&&(this._defaultFrameBufferCleared=!1,e.outputRenderTarget.skipInitialClear=!1)),this._bindFrameBuffer(this._activeCamera),e._renderingMultiview&&e.outputRenderTarget&&(e.outputRenderTarget.skipInitialClear=a)}this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._engine.currentRenderPassId=e.outputRenderTarget?.renderPassId??e.renderPassId??0,this._evaluateActiveMeshes();for(let a=0;a<this._softwareSkinnedMeshes.length;a++){const h=this._softwareSkinnedMeshes.data[a];h.applySkeleton(h.skeleton)}this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets),e.customRenderTargets&&e.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const a of this._gatherActiveCameraRenderTargetsStage)a.action(this._renderTargets);let r=!1;if(this.renderTargetsEnabled){this._intermediateRendering=!0;let a;if(this._renderTargets.length>0){fe.StartPerformanceCounter("Render targets",this._renderTargets.length>0);const h=this.getBoundingBoxRenderer?.();for(let l=0;l<this._renderTargets.length;l++){const c=this._renderTargets.data[l];if(c._shouldRender()){this._renderId++;const u=c.activeCamera&&c.activeCamera!==this.activeCamera;h&&!a&&(a=h.renderList.length>0?h.renderList.data.slice():[],a.length=h.renderList.length),c.render(u,this.dumpNextRenderTargets),r=!0}}h&&a&&(h.renderList.data=a,h.renderList.length=a.length),fe.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}if(this._cameraDrawRenderTargetStage.length>0){const h=this.getBoundingBoxRenderer?.();h&&!a&&(a=h.renderList.length>0?h.renderList.data.slice():[],a.length=h.renderList.length);for(const l of this._cameraDrawRenderTargetStage)r=l.action(this.activeCamera)||r;h&&a&&(h.renderList.data=a,h.renderList.length=a.length)}this._intermediateRendering=!1}r&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.postProcessManager&&!e._multiviewTexture&&!this.prePass&&this.postProcessManager._prepareFrame();for(const a of this._beforeCameraDrawStage)a.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this);const n=s.snapshotRendering&&s.snapshotRenderingMode===1;n&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!n),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const a of this._afterCameraDrawStage)a.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const a=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,a)}for(const a of this._afterCameraPostProcessStage)a.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(e.cameraRigMode===0||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let i=0;i<e._rigCameras.length;i++)this._renderForCamera(e._rigCameras[i],e)}this._activeCamera=e,this.updateTransformMatrix(),this.onAfterRenderCameraObservable.notifyObservers(e)}_checkIntersections(){for(let e=0;e<this._meshesForIntersections.length;e++){const t=this._meshesForIntersections.data[e];if(t.actionManager)for(let i=0;t.actionManager&&i<t.actionManager.actions.length;i++){const s=t.actionManager.actions[i];if(s.trigger===12||s.trigger===13){const r=s.getTriggerParameter(),n=r.mesh?r.mesh:r,a=n.intersectsMesh(t,r.usePreciseIntersection),h=t._intersectionsInProgress.indexOf(n);a&&h===-1?s.trigger===12?(s._executeCurrent(gt.CreateNew(t,void 0,n)),t._intersectionsInProgress.push(n)):s.trigger===13&&t._intersectionsInProgress.push(n):!a&&h>-1&&(s.trigger===13&&s._executeCurrent(gt.CreateNew(t,void 0,n)),(!t.actionManager.hasSpecificTrigger(13,l=>{const c=l.mesh?l.mesh:l;return n===c})||s.trigger===13)&&t._intersectionsInProgress.splice(h,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(je.MinDeltaTime,Math.min(this._engine.getDeltaTime(),je.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&s<n;)this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=t*i,this._animate(t),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(t),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,s++,e-=t;this._timeAccumulator=e<0?0:e}else{const e=this.useConstantAnimationDeltaTime?16:Math.max(je.MinDeltaTime,Math.min(this._engine.getDeltaTime(),je.MaxDeltaTime));this._animationRatio=e*(60/1e3),this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(e)}}_clear(){(this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this._clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil)}_checkCameraRenderTarget(e){if(e?.outputRenderTarget&&!e?.isRigCamera&&(e.outputRenderTarget._cleared=!1),e?.rigCameras?.length)for(let t=0;t<e.rigCameras.length;++t){const i=e.rigCameras[t].outputRenderTarget;i&&(i._cleared=!1)}}resetDrawCache(e){if(this.meshes)for(const t of this.meshes)t.resetDrawCache(e)}_renderWithFrameGraph(e=!0,t=!1,i=!1){if(this.activeCamera=null,this.activeCameras=null,e){for(const r of this.cameras)if(r.update(),r.cameraRigMode!==0)for(let n=0;n<r._rigCameras.length;n++)r._rigCameras[n].update()}this.onBeforeRenderObservable.notifyObservers(this),this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),this._renderTargets.reset();const s=this._frameGraph?.findMainCamera()??null;if(this.renderTargetsEnabled){this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture),this._renderTargets.concatWithNoDuplicate(this.customRenderTargets),fe.StartPerformanceCounter("Custom render targets",this._renderTargets.length>0);for(let r=0;r<this._renderTargets.length;r++){const n=this._renderTargets.data[r],a=n.activeCamera||s;this._renderRenderTarget(n,a,!0,this.dumpNextRenderTargets)}fe.EndPerformanceCounter("Custom render targets",this._renderTargets.length>0),this._renderId++}this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const r of this._beforeClearStage)r.action();if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1)this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset();else{const r=this.getActiveMeshCandidates(),n=r.length;if(this._activeMeshesFrozen){if(!this._skipEvaluateActiveMeshesCompletely)for(let a=0;a<n;a++){const h=r.data[a];h._internalAbstractMeshDataInfo._wasActiveLastFrame&&h.computeWorldMatrix()}if(this.particlesEnabled){const a=this._activeParticleSystems.length;for(let h=0;h<a;h++)this._activeParticleSystems.data[h].animate()}}else{this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset();for(let a=0;a<n;a++){const h=r.data[a];h._internalAbstractMeshDataInfo._wasActiveLastFrame=!1,!h.isBlocked&&(this._totalVertices.addCount(h.getTotalVertices(),!1),!(!h.isReady()||!h.isEnabled()||h.scaling.hasAZeroComponent)&&(h.computeWorldMatrix(i),h.actionManager&&h.actionManager.hasSpecificTriggers2(12,13)&&this._meshesForIntersections.pushNoDuplicate(h)))}if(this.particlesEnabled)for(let a=0;a<this.particleSystems.length;a++){const h=this.particleSystems[a];if(!h.isStarted()||!h.emitter)continue;const l=h.emitter;(!l.position||l.isEnabled())&&(this._activeParticleSystems.push(h),h.animate())}}}this.frameGraph?.execute()}_renderRenderTarget(e,t,i=!1,s=!1){if(this._intermediateRendering=!0,e._shouldRender()){if(this._renderId++,this.activeCamera=t,!this.activeCamera)throw new Error("Active camera not set");this._engine.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),e.render(i,s)}this._intermediateRendering=!1}render(e=!0,t=!1){if(!this.isDisposed){if(this.onReadyObservable.hasObservers()&&this._executeWhenReadyTimeoutId===null&&this._checkIsReady(),zi.getScene=this._getFloatingOriginScene,this._frameId++,this._defaultFrameBufferCleared=!1,this._checkCameraRenderTarget(this.activeCamera),this.activeCameras?.length)for(const i of this.activeCameras)this._checkCameraRenderTarget(i);this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(11),t||this.animate();for(const i of this._beforeCameraUpdateStage)i.action();if(e){if(this.activeCameras&&this.activeCameras.length>0)for(let i=0;i<this.activeCameras.length;i++){const s=this.activeCameras[i];if(s.update(),s.cameraRigMode!==0)for(let r=0;r<s._rigCameras.length;r++)s._rigCameras[r].update()}else if(this.activeCamera&&(this.activeCamera.update(),this.activeCamera.cameraRigMode!==0))for(let i=0;i<this.activeCamera._rigCameras.length;i++)this.activeCamera._rigCameras[i].update()}if(this.customRenderFunction)this._renderId++,this._engine.currentRenderPassId=0,this.customRenderFunction(e,t);else{this.onBeforeRenderObservable.notifyObservers(this),this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);const i=this.activeCameras?.length?this.activeCameras[0]:this.activeCamera;if(this.renderTargetsEnabled){fe.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0);for(let s=0;s<this.customRenderTargets.length;s++){const r=this.customRenderTargets[s],n=r.activeCamera||this.activeCamera;this._renderRenderTarget(r,n,i!==n,this.dumpNextRenderTargets)}fe.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._renderId++}this._engine.currentRenderPassId=i?.renderPassId??0,this.activeCamera=i,this._activeCamera&&this._activeCamera.cameraRigMode!==22&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const s of this._beforeClearStage)s.action();this._clearFrameBuffer(this.activeCamera);for(const s of this._gatherRenderTargetsStage)s.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let s=0;s<this.activeCameras.length;s++)this._processSubCameras(this.activeCameras[s],s>0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}}this._checkIntersections();for(const i of this._afterRenderStage)i.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let i=0;i<this._toBeDisposed.length;i++){const s=this._toBeDisposed[i];s&&s.dispose()}this._toBeDisposed.length=0}this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0),this._engine.restoreDefaultFramebuffer()}}freezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].freeze()}unfreezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].unfreeze()}dispose(){if(this.isDisposed)return;if(this.beforeRender=null,this.afterRender=null,this.metadata=null,this.skeletons.length=0,this.morphTargetManagers.length=0,this._transientComponents.length=0,this._isReadyForMeshStage.clear(),this._beforeEvaluateActiveMeshStage.clear(),this._evaluateSubMeshStage.clear(),this._preActiveMeshStage.clear(),this._cameraDrawRenderTargetStage.clear(),this._beforeCameraDrawStage.clear(),this._beforeRenderTargetDrawStage.clear(),this._beforeRenderingGroupDrawStage.clear(),this._beforeRenderingMeshStage.clear(),this._afterRenderingMeshStage.clear(),this._afterRenderingGroupDrawStage.clear(),this._afterCameraDrawStage.clear(),this._afterRenderTargetDrawStage.clear(),this._afterRenderStage.clear(),this._beforeCameraUpdateStage.clear(),this._beforeClearStage.clear(),this._gatherRenderTargetsStage.clear(),this._gatherActiveCameraRenderTargetsStage.clear(),this._pointerMoveStage.clear(),this._pointerDownStage.clear(),this._pointerUpStage.clear(),this._isReadyChecks.length=0,this.importedMeshesFiles=[],this._activeAnimatables&&this.stopAllAnimations){for(const r of this._activeAnimatables)r.onAnimationEndObservable.clear(),r.onAnimationEnd=null;this.stopAllAnimations()}this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;const e=this._activeRequests.slice();for(const r of e)r.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(r){W.Error("An error occurred while calling onDisposeObservable!",r)}if(this.detachControl(),this._engine.getInputElement())for(let r=0;r<this.cameras.length;r++)this.cameras[r].detachControl();this._disposeList(this.animationGroups),this._disposeList(this.lights),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.meshes,r=>r.dispose(!0)),this._disposeList(this.transformNodes,r=>r.dispose(!0));const i=this.cameras;this._disposeList(i),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._disposeList(this.frameGraphs),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let s=this._engine.scenes.indexOf(this);if(s>-1&&this._engine.scenes.splice(s,1),this._floatingOriginScene=void 0,this._engine.scenes.length===0&&Uf(),ye._LastCreatedScene===this){ye._LastCreatedScene=null;let r=ye.Instances.length-1;for(;r>=0;){const n=ye.Instances[r];if(n.scenes.length>0){ye._LastCreatedScene=n.scenes[this._engine.scenes.length-1];break}r--}}s=this._engine._virtualScenes.indexOf(this),s>-1&&this._engine._virtualScenes.splice(s,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onNewFrameGraphAddedObservable.clear(),this.onFrameGraphRemovedObservable.clear(),this.onNewObjectRendererAddedObservable.clear(),this.onObjectRendererRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this.onClearColorChangedObservable.clear(),this.onEnvironmentTextureChangedObservable.clear(),this.onMeshUnderPointerUpdatedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const i=e.slice(0);t=t??(s=>s.dispose());for(const s of i)t(s);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e<this.meshes.length;e++){const i=this.meshes[e].geometry;i&&i.clearCachedData()}}cleanCachedTextureBuffer(){for(const e of this.textures)e._buffer&&(e._buffer=null)}getWorldExtends(e){const t=new p(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new p(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);e=e||(()=>!0);const s=this.meshes.filter(e);for(const r of s){if(r.computeWorldMatrix(!0),!r.subMeshes||r.subMeshes.length===0||r.infiniteDistance)continue;const n=r.getBoundingInfo(),a=n.boundingBox.minimumWorld,h=n.boundingBox.maximumWorld;p.CheckExtends(a,t,i),p.CheckExtends(h,t,i)}return t.x===Number.MAX_VALUE?{min:p.Zero(),max:p.Zero()}:{min:t,max:i}}createPickingRay(e,t,i,s,r=!1){throw pe("Ray")}createPickingRayToRef(e,t,i,s,r,n=!1,a=!1){throw pe("Ray")}createPickingRayInCameraSpace(e,t,i){throw pe("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw pe("Ray")}pick(e,t,i,s,r,n){const a=pe("Ray",!0);return a&&W.Warn(a),new Zs}pickWithBoundingInfo(e,t,i,s,r){const n=pe("Ray",!0);return n&&W.Warn(n),new Zs}pickWithRay(e,t,i,s){throw pe("Ray")}multiPick(e,t,i,s,r){throw pe("Ray")}multiPickWithRay(e,t,i){throw pe("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(t===void 0)return e;const s=[];for(const r in e){const n=e[r];Le&&Le.MatchesQuery(n,t)&&(!i||i(n))&&s.push(n)}return s}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,s)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(127))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,s,r,n,a){const h=ki(e,t,i,s?this.offlineProvider:void 0,r,n,a);return this._activeRequests.push(h),h.onCompleteObservable.add(l=>{this._activeRequests.splice(this._activeRequests.indexOf(l),1)}),h}async _loadFileAsync(e,t,i,s,r){return await new Promise((n,a)=>{this._loadFile(e,h=>{n(h)},t,i,s,(h,l)=>{a(l)},r)})}_requestFile(e,t,i,s,r,n,a){const h=Ga(e,t,i,s?this.offlineProvider:void 0,r,n,a);return this._activeRequests.push(h),h.onCompleteObservable.add(l=>{this._activeRequests.splice(this._activeRequests.indexOf(l),1)}),h}async _requestFileAsync(e,t,i,s,r){return await new Promise((n,a)=>{this._requestFile(e,h=>{n(h)},t,i,s,h=>{a(h)},r)})}_readFile(e,t,i,s,r){const n=Hs(e,t,i,s,r);return this._activeRequests.push(n),n.onCompleteObservable.add(a=>{this._activeRequests.splice(this._activeRequests.indexOf(a),1)}),n}async _readFileAsync(e,t,i){return await new Promise((s,r)=>{this._readFile(e,n=>{s(n)},t,i,n=>{r(n)})})}getPerfCollector(){throw pe("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}je.FOGMODE_NONE=0;je.FOGMODE_EXP=1;je.FOGMODE_EXP2=2;je.FOGMODE_LINEAR=3;je.MinDeltaTime=1;je.MaxDeltaTime=1e3;je._OriginalDefaultMaterialFactory=je.DefaultMaterialFactory;Ye("BABYLON.Scene",je);const Qp=Object.freeze(Object.defineProperty({__proto__:null,Scene:je,get ScenePerformancePriority(){return Un}},Symbol.toStringTag,{value:"Module"}));class ys{static GetEffect(e){return e.getPipelineContext===void 0?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){this.effect=e,t!==void 0&&(this.defines=t),i&&this.drawContext?.reset()}dispose(e=!1){if(this.effect){const t=this.effect;e?t.dispose():Gs.SetImmediate(()=>{t.getEngine().onEndFrameObservable.addOnce(()=>{t.dispose()})}),this.effect=null}this.drawContext?.dispose()}}const kn="postprocessVertexShader",vl=`attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);
|
|
24
|
+
#define CUSTOM_VERTEX_DEFINITIONS
|
|
25
|
+
void main(void) {
|
|
26
|
+
#define CUSTOM_VERTEX_MAIN_BEGIN
|
|
27
|
+
vUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0);
|
|
28
|
+
#define CUSTOM_VERTEX_MAIN_END
|
|
29
|
+
}`;Z.ShadersStore[kn]||(Z.ShadersStore[kn]=vl);const Zf={name:kn,shader:vl},qf=Object.freeze(Object.defineProperty({__proto__:null,postprocessVertexShader:Zf},Symbol.toStringTag,{value:"Module"})),Vn="postprocessVertexShader",Cl=`attribute position: vec2<f32>;uniform scale: vec2<f32>;varying vUV: vec2<f32>;const madd=vec2(0.5,0.5);
|
|
30
|
+
#define CUSTOM_VERTEX_DEFINITIONS
|
|
31
|
+
@vertex
|
|
32
|
+
fn main(input : VertexInputs)->FragmentInputs {
|
|
33
|
+
#define CUSTOM_VERTEX_MAIN_BEGIN
|
|
34
|
+
vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0);
|
|
35
|
+
#define CUSTOM_VERTEX_MAIN_END
|
|
36
|
+
}
|
|
37
|
+
`;Z.ShadersStoreWGSL[Vn]||(Z.ShadersStoreWGSL[Vn]=Cl);const Qf={name:Vn,shader:Cl},$f=Object.freeze(Object.defineProperty({__proto__:null,postprocessVertexShaderWGSL:Qf},Symbol.toStringTag,{value:"Module"})),bn={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class Jf{constructor(e,t=bn){this._fullscreenViewport=new Ys(0,0,1,1);const i=t.positions??bn.positions,s=t.indices??bn.indices;this.engine=e,this._vertexBuffers={[S.PositionKind]:new S(e,i,S.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(s),this._indexBufferLength=s.length,this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(s);for(const r in this._vertexBuffers)this._vertexBuffers[r]._rebuild()})}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e,t=!1,i=!1){this.engine.setState(!0),this.engine.depthCullingState.depthTest=t,this.engine.stencilState.stencilTest=i,this.engine.enableEffect(e.drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,this._indexBufferLength)}_isRenderTargetTexture(e){return e.renderTarget!==void 0}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=t===null?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){const e=this._vertexBuffers[S.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[S.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class Qe{static RegisterShaderCodeProcessing(e,t){if(!t){delete Qe._CustomShaderCodeProcessing[e??""];return}Qe._CustomShaderCodeProcessing[e??""]=t}static _GetShaderCodeProcessing(e){return Qe._CustomShaderCodeProcessing[e]??Qe._CustomShaderCodeProcessing[""]}get name(){return this.options.name}set name(e){this.options.name=e}isReady(){return this._drawWrapper.effect?.isReady()??!1}get drawWrapper(){return this._drawWrapper}get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){this.alphaMode=0,this.onEffectCreatedObservable=new z(void 0,!0),this.onApplyObservable=new z,this._shadersLoaded=!1,this._webGPUReady=!1,this._importPromises=[],this.options={...e,name:e.name||"effectWrapper",engine:e.engine,uniforms:e.uniforms||e.uniformNames||[],uniformNames:void 0,samplers:e.samplers||e.samplerNames||[],samplerNames:void 0,attributeNames:e.attributeNames||["position"],uniformBuffers:e.uniformBuffers||[],defines:e.defines||"",useShaderStore:e.useShaderStore||!1,vertexUrl:e.vertexUrl||e.vertexShader||"postprocess",vertexShader:void 0,fragmentShader:e.fragmentShader||"pass",indexParameters:e.indexParameters,blockCompilation:e.blockCompilation||!1,shaderLanguage:e.shaderLanguage||0,onCompiled:e.onCompiled||void 0,extraInitializations:e.extraInitializations||void 0,extraInitializationsAsync:e.extraInitializationsAsync||void 0,useAsPostProcess:e.useAsPostProcess??!1,allowEmptySourceTexture:e.allowEmptySourceTexture??!1},this.options.uniformNames=this.options.uniforms,this.options.samplerNames=this.options.samplers,this.options.vertexShader=this.options.vertexUrl,this.options.useAsPostProcess&&(!this.options.allowEmptySourceTexture&&this.options.samplers.indexOf("textureSampler")===-1&&this.options.samplers.push("textureSampler"),this.options.uniforms.indexOf("scale")===-1&&this.options.uniforms.push("scale")),e.vertexUrl||e.vertexShader?this._shaderPath={vertexSource:this.options.vertexShader}:(this.options.useAsPostProcess||(this.options.uniforms.push("scale"),this.onApplyObservable.add(()=>{this.effect.setFloat2("scale",1,1)})),this._shaderPath={vertex:this.options.vertexShader}),this._shaderPath.fragmentSource=this.options.fragmentShader,this._shaderPath.spectorName=this.options.name,this.options.useShaderStore&&(this._shaderPath.fragment=this._shaderPath.fragmentSource,this._shaderPath.vertex||(this._shaderPath.vertex=this._shaderPath.vertexSource),delete this._shaderPath.fragmentSource,delete this._shaderPath.vertexSource),this.onApplyObservable.add(()=>{this.bind()}),this.options.useShaderStore||(this._onContextRestoredObserver=this.options.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})),this._drawWrapper=new ys(this.options.engine),this._webGPUReady=this.options.shaderLanguage===1;const t=Array.isArray(this.options.defines)?this.options.defines.join(`
|
|
38
|
+
`):this.options.defines;this._postConstructor(this.options.blockCompilation,t,this.options.extraInitializations)}_gatherImports(e=!1,t){}_postConstructor(e,t=null,i,s){this._importPromises.length=0,s&&this._importPromises.push(...s);const r=this.options.engine.isWebGPU&&!Qe.ForceGLSL;this._gatherImports(r,this._importPromises),i!==void 0&&i(r,this._importPromises),r&&this._webGPUReady&&(this.options.shaderLanguage=1),e||this.updateEffect(t)}updateEffect(e=null,t=null,i=null,s,r,n,a,h){const l=Qe._GetShaderCodeProcessing(this.name);if(l?.defineCustomBindings){const f=t?.slice()??[];f.push(...this.options.uniforms);const d=i?.slice()??[];d.push(...this.options.samplers),e=l.defineCustomBindings(this.name,e,f,d),t=f,i=d}this.options.defines=e||"";const c=this._shadersLoaded||this._importPromises.length===0?void 0:async()=>{await Promise.all(this._importPromises),this._shadersLoaded=!0};let u;this.options.extraInitializationsAsync?u=async()=>{c?.(),await this.options.extraInitializationsAsync()}:u=c,this.options.useShaderStore?this._drawWrapper.effect=this.options.engine.createEffect({vertex:a??this._shaderPath.vertex,fragment:h??this._shaderPath.fragment},{attributes:this.options.attributeNames,uniformsNames:t||this.options.uniforms,uniformBuffersNames:this.options.uniformBuffers,samplers:i||this.options.samplers,defines:e!==null?e:"",fallbacks:null,onCompiled:r??this.options.onCompiled,onError:n??null,indexParameters:s||this.options.indexParameters,processCodeAfterIncludes:l?.processCodeAfterIncludes?(f,d)=>l.processCodeAfterIncludes(this.name,f,d):null,processFinalCode:l?.processFinalCode?(f,d)=>l.processFinalCode(this.name,f,d):null,shaderLanguage:this.options.shaderLanguage,extraInitializationsAsync:u},this.options.engine):this._drawWrapper.effect=new it(this._shaderPath,this.options.attributeNames,t||this.options.uniforms,i||this.options.samplerNames,this.options.engine,e,void 0,r||this.options.onCompiled,void 0,void 0,void 0,this.options.shaderLanguage,u),this.onEffectCreatedObservable.notifyObservers(this._drawWrapper.effect)}bind(e=!1){this.options.useAsPostProcess&&!e&&(this.options.engine.setAlphaMode(this.alphaMode),this.drawWrapper.effect.setFloat2("scale",1,1)),Qe._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name,this._drawWrapper.effect)}dispose(e=!1){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.onEffectCreatedObservable.clear(),this._drawWrapper.dispose(!0)}}Qe.ForceGLSL=!1;Qe._CustomShaderCodeProcessing={};J.prototype.setTextureFromPostProcess=function(o,e,t){let i=null;e&&(e._forcedOutputTexture?i=e._forcedOutputTexture:e._textures.data[e._currentRenderTextureInd]&&(i=e._textures.data[e._currentRenderTextureInd])),this._bindTexture(o,i?.texture??null,t)};J.prototype.setTextureFromPostProcessOutput=function(o,e,t){this._bindTexture(o,e?._outputTexture?.texture??null,t)};it.prototype.setTextureFromPostProcess=function(o,e){this._engine.setTextureFromPostProcess(this._samplers[o],e,o)};it.prototype.setTextureFromPostProcessOutput=function(o,e){this._engine.setTextureFromPostProcessOutput(this._samplers[o],e,o)};class Ne{static get ForceGLSL(){return Qe.ForceGLSL}static set ForceGLSL(e){Qe.ForceGLSL=e}static RegisterShaderCodeProcessing(e,t){Qe.RegisterShaderCodeProcessing(e,t)}get name(){return this._effectWrapper.name}set name(e){this._effectWrapper.name=e}get alphaMode(){return this._effectWrapper.alphaMode}set alphaMode(e){this._effectWrapper.alphaMode=e}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach(t=>{t.setSamples(this._samples)})}get shaderLanguage(){return this._shaderLanguage}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,s,r,n,a=1,h,l,c=null,u=0,f="postprocess",d,_=!1,m=5,g,T){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this.doNotSerialize=!1,this._webGPUReady=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new Et(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new ie(1,1),this._texelSize=ie.Zero(),this.onActivateObservable=new z,this.onSizeChangedObservable=new z,this.onApplyObservable=new z,this.onBeforeRenderObservable=new z,this.onAfterRenderObservable=new z,this.onDisposeObservable=new z;let R=1,A=null,y;if(i&&!Array.isArray(i)){const E=i;i=E.uniforms??null,s=E.samplers??null,R=E.size??1,n=E.camera??null,a=E.samplingMode??1,h=E.engine,l=E.reusable,c=Array.isArray(E.defines)?E.defines.join(`
|
|
39
|
+
`):E.defines??null,u=E.textureType??0,f=E.vertexUrl??"postprocess",d=E.indexParameters,_=E.blockCompilation??!1,m=E.textureFormat??5,g=E.shaderLanguage??0,A=E.uniformBuffers??null,T=E.extraInitializations,y=E.effectWrapper}else r&&(typeof r=="number"?R=r:R={width:r.width,height:r.height});if(this._useExistingThinPostProcess=!!y,this._effectWrapper=y??new Qe({name:e,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:t,engine:h||n?.getScene().getEngine(),uniforms:i,samplers:s,uniformBuffers:A,defines:c,vertexUrl:f,indexParameters:d,blockCompilation:!0,shaderLanguage:g,extraInitializations:void 0}),this.name=e,this.onEffectCreatedObservable=this._effectWrapper.onEffectCreatedObservable,n!=null?(this._camera=n,this._scene=n.getScene(),n.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.addPostProcess(this),this.uniqueId=this._scene.getUniqueId()):h&&(this._engine=h,this._engine.postProcesses.push(this)),this._options=R,this.renderTargetSamplingMode=a||1,this._reusable=l||!1,this._textureType=u,this._textureFormat=m,this._shaderLanguage=g||0,this._samplers=s||[],this._samplers.indexOf("textureSampler")===-1&&this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=f,this._parameters=i||[],this._parameters.indexOf("scale")===-1&&this._parameters.push("scale"),this._uniformBuffers=A||[],this._indexParameters=d,!this._useExistingThinPostProcess){this._webGPUReady=this._shaderLanguage===1;const E=[];this._gatherImports(this._engine.isWebGPU&&!Ne.ForceGLSL,E),this._effectWrapper._webGPUReady=this._webGPUReady,this._effectWrapper._postConstructor(_,c,T,E)}}_gatherImports(e=!1,t){e&&this._webGPUReady?t.push(Promise.all([he(()=>Promise.resolve().then(()=>$f),void 0,import.meta.url)])):t.push(Promise.all([he(()=>Promise.resolve().then(()=>qf),void 0,import.meta.url)]))}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._effectWrapper.drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){this._textures.length==0&&(this._textures=new Et(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,r,n,a,h){this._effectWrapper.updateEffect(e,t,i,s,r,n,a,h),this._postProcessDefines=Array.isArray(this._effectWrapper.options.defines)?this._effectWrapper.options.defines.join(`
|
|
40
|
+
`):this._effectWrapper.options.defines}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let r=0;r<this._textureCache.length;r++)if(this._textureCache[r].texture.width===e.width&&this._textureCache[r].texture.height===e.height&&this._textureCache[r].postProcessChannel===i&&this._textureCache[r].texture._generateDepthBuffer===t.generateDepthBuffer&&this._textureCache[r].texture.samples===t.samples)return this._textureCache[r].texture;const s=this._engine.createRenderTargetTexture(e,t);return this._textureCache.push({texture:s,postProcessChannel:i,lastUsedRenderId:-1}),s}_flushTextureCache(){const e=this._renderId;for(let t=this._textureCache.length-1;t>=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let i=!1;for(let s=0;s<this._textures.length;s++)if(this._textures.data[s]===this._textureCache[t].texture){i=!0;break}i||(this._textureCache[t].texture.dispose(),this._textureCache.splice(t,1))}}resize(e,t,i=null,s=!1,r=!1){this._textures.length>0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i){for(let l=0;l<i._postProcesses.length;l++)if(i._postProcesses[l]!==null){n=i._postProcesses[l];break}}const a={width:this.width,height:this.height},h={generateMipMaps:s,generateDepthBuffer:r||n===this,generateStencilBuffer:(r||n===this)&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType,format:this._textureFormat,samples:this._samples,label:"PostProcessRTT-"+this.name};this._textures.push(this._createRenderTargetTexture(a,h,0)),this._reusable&&this._textures.push(this._createRenderTargetTexture(a,h,1)),this._texelSize.copyFromFloats(1/this.width,1/this.height),this.onSizeChangedObservable.notifyObservers(this)}_getTarget(){let e;if(this._shareOutputWithPostProcess)e=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)e=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{e=this.inputTexture;let t;for(let i=0;i<this._textureCache.length;i++)if(this._textureCache[i].texture===e){t=this._textureCache[i];break}t&&(t.lastUsedRenderId=this._renderId)}return e}activate(e,t=null,i){const s=e===null||e.cameraRigMode!==void 0?e||this._camera:null,r=s?.getScene()??e,n=r.getEngine(),a=n.getCaps().maxTextureSize,h=(t?t.width:this._engine.getRenderWidth(!0))*this._options|0,l=(t?t.height:this._engine.getRenderHeight(!0))*this._options|0;let c=this._options.width||h,u=this._options.height||l;const f=this.renderTargetSamplingMode!==7&&this.renderTargetSamplingMode!==1&&this.renderTargetSamplingMode!==2;let d=null;if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this.adaptScaleToCurrentViewport){const _=n.currentViewport;_&&(c*=_.width,u*=_.height)}(f||this.alwaysForcePOT)&&(this._options.width||(c=n.needPOTTextures?ni(c,a,this.scaleMode):c),this._options.height||(u=n.needPOTTextures?ni(u,a,this.scaleMode):u)),(this.width!==c||this.height!==u||!(d=this._getTarget()))&&this.resize(c,u,s,f,i),this._textures.forEach(_=>{_.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(_,this.samples)}),this._flushTextureCache(),this._renderId++}return d||(d=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(h/c,l/u),this._engine.bindFramebuffer(d,0,h,l,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(d,0,void 0,void 0,this.forceFullscreenViewport)),this._engine._debugInsertMarker?.(`post process ${this.name} input`),this.onActivateObservable.notifyObservers(s),this.autoClear&&(this.alphaMode===0||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:r.clearColor,r._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),d}get isSupported(){return this._effectWrapper.drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._effectWrapper.isReady()}apply(){if(!this._effectWrapper.isReady())return null;this._engine.enableEffect(this._effectWrapper.drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),this._engine.setAlphaMode(this.alphaMode);let e;return this._shareOutputWithPostProcess?e=this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?e=this._forcedOutputTexture:e=this.inputTexture,this.externalTextureSamplerBinding||this._effectWrapper.drawWrapper.effect._bindTexture("textureSampler",e?.texture),this._effectWrapper.drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._effectWrapper.drawWrapper.effect),this._effectWrapper.bind(!0),this._effectWrapper.drawWrapper.effect}_disposeTextures(){if(this._shareOutputWithPostProcess||this._forcedOutputTexture){this._disposeTextureCache();return}this._disposeTextureCache(),this._textures.dispose()}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return this._prePassEffectConfiguration?(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0):!1}dispose(e){e=e||this._camera,this._useExistingThinPostProcess||this._effectWrapper.dispose(),this._disposeTextures(),this._scene&&this._scene.removePostProcess(this);let t;if(this._parentContainer&&(t=this._parentContainer.postProcesses.indexOf(this),t>-1&&this._parentContainer.postProcesses.splice(t,1),this._parentContainer=null),t=this._engine.postProcesses.indexOf(this),t!==-1&&this._engine.postProcesses.splice(t,1),this.onDisposeObservable.notifyObservers(),!!e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),t===0&&e._postProcesses.length>0){const i=this._camera._getFirstPostProcess();i&&i.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear(),this.onEffectCreatedObservable.clear()}}serialize(){const e=me.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.uniformBuffers=this._uniformBuffers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const e=this.serialize();e._engine=this._engine,e.cameraId=null;const t=Ne.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const s=Pi(e.customType);if(!s||!s._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return s._Parse(e,r,t,i)}static _Parse(e,t,i,s){return me.Parse(()=>new Ne(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat),e,i,s)}}M([C()],Ne.prototype,"uniqueId",void 0);M([C()],Ne.prototype,"name",null);M([C()],Ne.prototype,"width",void 0);M([C()],Ne.prototype,"height",void 0);M([C()],Ne.prototype,"renderTargetSamplingMode",void 0);M([La()],Ne.prototype,"clearColor",void 0);M([C()],Ne.prototype,"autoClear",void 0);M([C()],Ne.prototype,"forceAutoClearInAlphaMode",void 0);M([C()],Ne.prototype,"alphaMode",null);M([C()],Ne.prototype,"alphaConstants",void 0);M([C()],Ne.prototype,"enablePixelPerfectMode",void 0);M([C()],Ne.prototype,"forceFullscreenViewport",void 0);M([C()],Ne.prototype,"scaleMode",void 0);M([C()],Ne.prototype,"alwaysForcePOT",void 0);M([C("samples")],Ne.prototype,"_samples",void 0);M([C()],Ne.prototype,"adaptScaleToCurrentViewport",void 0);Ye("BABYLON.PostProcess",Ne);class jt{get renderList(){return this._renderList}set renderList(e){this._renderList!==e&&(this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=fl(e,this._renderListHasChanged)),this._renderList=e)}get disableImageProcessing(){return this._disableImageProcessing}set disableImageProcessing(e){e!==this._disableImageProcessing&&(this._disableImageProcessing=e,this._scene.markAllMaterialsAsDirty(64))}get disableDepthPrePass(){return this._disableDepthPrePass}set disableDepthPrePass(e){this._disableDepthPrePass=e,this._renderingManager.disableDepthPrePass=e}get name(){return this._name}set name(e){if(this._name!==e){if(this._name=e,this._sceneUBOs)for(let t=0;t<this._sceneUBOs.length;++t)this._sceneUBOs[t].name=`Scene ubo #${t} for ${this.name}`;if(this._scene)for(let t=0;t<this._renderPassIds.length;++t){const i=this._renderPassIds[t];this._engine._renderPassNames[i]=`${this._name}#${t}`}}}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}getActiveMeshes(){return this._activeMeshes}setMaterialForRendering(e,t){let i;Array.isArray(e)?i=e:i=[e];for(let s=0;s<i.length;++s)for(let r=0;r<this.options.numPasses;++r){let n=i[s];i[s].isAnInstance&&(n=i[s].sourceMesh),n.setMaterialForRenderPass(this._renderPassIds[r],t!==void 0?Array.isArray(t)?t[r]:t:void 0)}}_freezeActiveMeshes(e){this._freezeActiveMeshesCancel=Yr(()=>this._checkReadiness(),()=>{if(this._freezeActiveMeshesCancel=null,e)for(let t=0;t<this._activeMeshes.length;t++)this._activeMeshes.data[t]._freeze();this._prepareRenderingManager(0,!0),this._isFrozen=!0},(t,i)=>{this._freezeActiveMeshesCancel=null,i?(W.Error("ObjectRenderer: Timeout while waiting for the renderer to be ready."),t&&W.Error(t)):(W.Error("ObjectRenderer: An unexpected error occurred while waiting for the renderer to be ready."),t&&(W.Error(t),t.stack&&W.Error(t.stack)))})}_unfreezeActiveMeshes(){this._freezeActiveMeshesCancel?.(),this._freezeActiveMeshesCancel=null;for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._unFreeze();this._isFrozen=!1}constructor(e,t,i){this._unObserveRenderList=null,this._renderListHasChanged=(s,r)=>{const n=this._renderList?this._renderList.length:0;if(r===0&&n>0||n===0)for(const a of this._scene.meshes)a._markSubMeshesAsLightDirty()},this.particleSystemList=null,this.getCustomRenderList=null,this.renderMeshes=!0,this.renderDepthOnlyMeshes=!0,this.renderOpaqueMeshes=!0,this.renderAlphaTestMeshes=!0,this.renderTransparentMeshes=!0,this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.enableBoundingBoxRendering=!1,this.enableOutlineRendering=!0,this._disableImageProcessing=!1,this.dontSetTransformationMatrix=!1,this._disableDepthPrePass=!1,this.onBeforeRenderObservable=new z,this.onAfterRenderObservable=new z,this.onBeforeRenderingManagerRenderObservable=new z,this.onAfterRenderingManagerRenderObservable=new z,this.onInitRenderingObservable=new z,this.onFinishRenderingObservable=new z,this.onFastPathRenderObservable=new z,this._currentRefreshId=-1,this._refreshRate=1,this._currentApplyByPostProcessSetting=!1,this._activeMeshes=new Et(256),this._activeBoundingBoxes=new Et(32),this._currentFrameId=-1,this._currentSceneUBOIndex=0,this._isFrozen=!1,this._freezeActiveMeshesCancel=null,this._currentSceneCamera=null,this.name=e,this._scene=t,this._engine=this._scene.getEngine(),this._useUBO=this._engine.supportsUniformBuffers,this.renderList=[],this._renderPassIds=[],this.options={numPasses:1,doNotChangeAspectRatio:!0,enableClusteredLights:!1,...i},this._createRenderPassId(),this.renderPassId=this._renderPassIds[0],this._renderingManager=new pt(t),this._renderingManager._useSceneAutoClearSetup=!0,this.options.enableClusteredLights&&this.onInitRenderingObservable.add(()=>{for(const s of this._scene.lights)s.getTypeID()===Be.LIGHTTYPEID_CLUSTERED_CONTAINER&&s.isSupported&&s._updateBatches(this.activeCamera).render()}),this._scene.addObjectRenderer(this)}_releaseRenderPassId(){for(let e=0;e<this.options.numPasses;++e)this._engine.releaseRenderPassId(this._renderPassIds[e]);this._renderPassIds.length=0}_createRenderPassId(){this._releaseRenderPassId();for(let e=0;e<this.options.numPasses;++e)this._renderPassIds[e]=this._engine.createRenderPassId(`${this.name}#${e}`)}_createSceneUBO(e,t){const i=this._scene.getEngine(),s=new oe(i,void 0,t,e,void 0,!1);return s.addUniform("viewProjection",16),t&&s.addUniform("viewProjectionR",16),s.addUniform("view",16),s.addUniform("projection",16),s.addUniform("vEyePosition",4),s}_getSceneUBO(){this._currentFrameId!==this._engine.frameId&&(this._currentSceneUBOIndex=0,this._currentFrameId=this._engine.frameId),this._sceneUBOs||(this._sceneUBOs=[],this._sceneUBOIsMultiview=[]);const e=this._engine._currentRenderTarget,t=!!(e&&e.texture?.isMultiview)||!!this._scene._multiviewSceneUboIsActive;if(this._currentSceneUBOIndex>=this._sceneUBOs.length){const s=this._sceneUBOs.length;this._sceneUBOs.push(this._createSceneUBO(`Scene ubo #${s} for ${this.name}`,t)),this._sceneUBOIsMultiview.push(t)}else this._sceneUBOIsMultiview[this._currentSceneUBOIndex]!==t&&(this._sceneUBOs[this._currentSceneUBOIndex].dispose(),this._sceneUBOs[this._currentSceneUBOIndex]=this._createSceneUBO(`Scene ubo #${this._currentSceneUBOIndex} for ${this.name}`,t),this._sceneUBOIsMultiview[this._currentSceneUBOIndex]=t);const i=this._sceneUBOs[this._currentSceneUBOIndex++];return i.unbindEffect(),i}resetRefreshCounter(){this._currentRefreshId=-1}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}shouldRender(){return this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}isReadyForRendering(e,t){this.prepareRenderList(),this.initRender(e,t);const i=this._checkReadiness();return this.finishRender(),i}prepareRenderList(){const e=this._scene;if(this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let t=0;t<this._waitingRenderList.length;t++){const i=this._waitingRenderList[t],s=e.getMeshById(i);s&&this.renderList.push(s)}}this._waitingRenderList=void 0}if(this.renderListPredicate){this.renderList?this.renderList.length=0:this.renderList=[];const t=this._scene.meshes;for(let i=0;i<t.length;i++){const s=t[i];this.renderListPredicate(s)&&this.renderList.push(s)}}this._currentApplyByPostProcessSetting=this._scene.imageProcessingConfiguration.applyByPostProcess,this._disableImageProcessing&&(this._scene.imageProcessingConfiguration._applyByPostProcess=this._disableImageProcessing)}initRender(e,t){const i=this.activeCamera??this._scene.activeCamera;this._currentSceneCamera=this._scene.activeCamera,this._useUBO&&(this._currentSceneUBO=this._scene.getSceneUniformBuffer(),this._currentSceneUBO.unbindEffect(),this._scene.setSceneUniformBuffer(this._getSceneUBO())),this.onInitRenderingObservable.notifyObservers(this),i&&(this.dontSetTransformationMatrix||this._scene.setTransformMatrix(i.getViewMatrix(),i.getProjectionMatrix(!0)),this._scene.activeCamera=i,this._engine.setViewport(i.rigParent?i.rigParent.viewport:i.viewport,e,t)),this._useUBO&&this._scene.finalizeSceneUbo(),this._defaultRenderListPrepared=!1}finishRender(){const e=this._scene;this._useUBO&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._disableImageProcessing&&(e.imageProcessingConfiguration._applyByPostProcess=this._currentApplyByPostProcessSetting),e.activeCamera=this._currentSceneCamera,this._currentSceneCamera&&(this.activeCamera&&this.activeCamera!==e.activeCamera&&e.setTransformMatrix(this._currentSceneCamera.getViewMatrix(),this._currentSceneCamera.getProjectionMatrix(!0)),this._engine.setViewport(this._currentSceneCamera.viewport)),e.resetCachedMaterial(),this.onFinishRenderingObservable.notifyObservers(this)}render(e=0,t=!1){const i=this._engine.currentRenderPassId;if(this._engine.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e),this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1)this.onFastPathRenderObservable.notifyObservers(e);else{const r=this._prepareRenderingManager(e),n=this._scene.getOutlineRenderer?.(),a=n?.enabled;n&&(n.enabled=this.enableOutlineRendering),this.onBeforeRenderingManagerRenderObservable.notifyObservers(e),this._renderingManager.render(this.customRenderFunction,r,this.renderParticles,this.renderSprites,this.renderDepthOnlyMeshes,this.renderOpaqueMeshes,this.renderAlphaTestMeshes,this.renderTransparentMeshes,this.customRenderTransparentSubMeshes),this.onAfterRenderingManagerRenderObservable.notifyObservers(e),n&&(n.enabled=a)}t||this.onAfterRenderObservable.notifyObservers(e),this._engine.currentRenderPassId=i}_checkReadiness(){const e=this._scene,t=this._engine.currentRenderPassId;let i=!0;e.getViewMatrix()||e.updateTransformMatrix();const s=this.options.numPasses;for(let n=0;n<s&&i;n++){const a=this.renderList?this.renderList:e.frameGraph?e.meshes:e.getActiveMeshes().data,h=this.renderList||e.frameGraph?a.length:e.getActiveMeshes().length;this._engine.currentRenderPassId=this._renderPassIds[n],this.onBeforeRenderObservable.notifyObservers(n);let l=null,c=h;this.getCustomRenderList&&(l=this.getCustomRenderList(n,a,h),l&&(c=l.length)),l||(l=a),this.options.doNotChangeAspectRatio||e.updateTransformMatrix(!0);for(let u=0;u<c&&i;++u){const f=l[u];if(!(!f.isEnabled()||f.isBlocked||!f.isVisible||!f.subMeshes)){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(f,this.refreshRate,!0)){i=!1;continue}}else if(!f.isReady(!0)){i=!1;continue}}}this.onAfterRenderObservable.notifyObservers(n),s>1&&(e.incrementRenderId(),e.resetCachedMaterial())}const r=this.particleSystemList||e.particleSystems;for(const n of r)n.isReady()||(i=!1);return this._engine.currentRenderPassId=t,i}_prepareRenderingManager(e=0,t=!1){const i=this._scene;let s=null,r,n;const a=this.renderList?this.renderList:i.frameGraph?i.meshes:i.getActiveMeshes().data,h=this.renderList||i.frameGraph?a.length:i.getActiveMeshes().length;if(this.getCustomRenderList&&(s=this.getCustomRenderList(e,a,h)),s)r=s.length,n=this.forceLayerMaskCheck;else{if(this._defaultRenderListPrepared&&!t&&!this._engine.isWebGPU)return a;this._defaultRenderListPrepared=!0,s=a,r=h,n=!this.renderList||this.forceLayerMaskCheck}const l=i.activeCamera,c=this.cameraForLOD??l,u=i.getBoundingBoxRenderer?.();if(i._activeMeshesFrozen&&this._isFrozen){if(this._renderingManager.resetSprites(),this.enableBoundingBoxRendering&&u){u.reset();for(let f=0;f<this._activeBoundingBoxes.length;f++){const d=this._activeBoundingBoxes.data[f];u.renderList.push(d)}}return s}if(this._renderingManager.reset(),this._activeMeshes.reset(),this._activeBoundingBoxes.reset(),u&&u.reset(),this.renderMeshes){const f=i.getRenderId(),d=i.getFrameId();for(let _=0;_<r;_++){const m=s[_];if(m&&!m.isBlocked){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(m,this.refreshRate,!1)){this.resetRefreshCounter();continue}}else if(!m.isReady(this.refreshRate===0)){this.resetRefreshCounter();continue}let g;if(c){const R=m._internalAbstractMeshDataInfo._currentLOD.get(c);!R||R[1]!==d?(g=i.customLODSelector?i.customLODSelector(m,c):m.getLOD(c),R?(R[0]=g,R[1]=d):m._internalAbstractMeshDataInfo._currentLOD.set(c,[g,d])):g=R[0]}else g=m;if(!g)continue;g!==m&&g.billboardMode!==0&&g.computeWorldMatrix(),g._preActivateForIntermediateRendering(f);let T;if(n&&l?T=(m.layerMask&l.layerMask)===0:T=!1,m.isEnabled()&&m.isVisible&&m.subMeshes&&!T){if(this._activeMeshes.push(m),g._internalAbstractMeshDataInfo._wasActiveLastFrame=!0,g!==m&&g._activate(f,!0),this.enableBoundingBoxRendering&&u&&u._preActiveMesh(m),m._activate(f,!0)&&m.subMeshes.length){m.isAnInstance?m._internalAbstractMeshDataInfo._actAsRegularMesh&&(g=m):g._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!1,g._internalAbstractMeshDataInfo._isActiveIntermediate=!0,i._prepareSkeleton(g);for(let R=0;R<g.subMeshes.length;R++){const A=g.subMeshes[R];this.enableBoundingBoxRendering&&u&&u._evaluateSubMesh(m,A),this._renderingManager.dispatch(A,g)}}m._postActivate()}}}}if(this.enableBoundingBoxRendering&&u&&t)for(let f=0;f<u.renderList.length;f++){const d=u.renderList.data[f];this._activeBoundingBoxes.push(d)}if(this._scene.particlesEnabled&&this.renderParticles){this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);const f=this.particleSystemList||i.particleSystems;for(let d=0;d<f.length;d++){const _=f[d],m=_.emitter;!_.isStarted()||!m||m.position&&!m.isEnabled()||this._renderingManager.dispatchParticles(_)}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}return s}get renderingManager(){return this._renderingManager}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,s),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=new jt(this.name,this._scene,this.options);return this.renderList&&(e.renderList=this.renderList.slice(0)),e}dispose(){const e=this.renderList?this.renderList:this._scene.getActiveMeshes().data,t=this.renderList?this.renderList.length:this._scene.getActiveMeshes().length;for(let i=0;i<t;i++){const s=e[i];s&&s.getMaterialForRenderPass(this.renderPassId)!==void 0&&s.setMaterialForRenderPass(this.renderPassId,void 0)}if(this.onInitRenderingObservable.clear(),this.onFinishRenderingObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderingManagerRenderObservable.clear(),this.onAfterRenderingManagerRenderObservable.clear(),this.onFastPathRenderObservable.clear(),this._releaseRenderPassId(),this.renderList=null,this._sceneUBOs)for(const i of this._sceneUBOs)i.dispose();this._sceneUBOs=void 0,this._scene.removeObjectRenderer(this)}_rebuild(){this.refreshRate===jt.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=jt.REFRESHRATE_RENDER_ONCE)}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}}jt.REFRESHRATE_RENDER_ONCE=0;jt.REFRESHRATE_RENDER_ONEVERYFRAME=1;jt.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2;it.prototype.setDepthStencilTexture=function(o,e){this._engine.setDepthStencilTexture(this._samplers[o],this._uniforms[o],e,o)};class yt extends G{get renderListPredicate(){return this._objectRenderer.renderListPredicate}set renderListPredicate(e){this._objectRenderer.renderListPredicate=e}get renderList(){return this._objectRenderer.renderList}set renderList(e){this._objectRenderer.renderList=e}get particleSystemList(){return this._objectRenderer.particleSystemList}set particleSystemList(e){this._objectRenderer.particleSystemList=e}get getCustomRenderList(){return this._objectRenderer.getCustomRenderList}set getCustomRenderList(e){this._objectRenderer.getCustomRenderList=e}get renderParticles(){return this._objectRenderer.renderParticles}set renderParticles(e){this._objectRenderer.renderParticles=e}get renderSprites(){return this._objectRenderer.renderSprites}set renderSprites(e){this._objectRenderer.renderSprites=e}get enableBoundingBoxRendering(){return this._objectRenderer.enableBoundingBoxRendering}set enableBoundingBoxRendering(e){this._objectRenderer.enableBoundingBoxRendering=e}get enableOutlineRendering(){return this._objectRenderer.enableOutlineRendering}set enableOutlineRendering(e){this._objectRenderer.enableOutlineRendering=e}get forceLayerMaskCheck(){return this._objectRenderer.forceLayerMaskCheck}set forceLayerMaskCheck(e){this._objectRenderer.forceLayerMaskCheck=e}get activeCamera(){return this._objectRenderer.activeCamera}set activeCamera(e){this._objectRenderer.activeCamera=e}get cameraForLOD(){return this._objectRenderer.cameraForLOD}set cameraForLOD(e){this._objectRenderer.cameraForLOD=e}get disableImageProcessing(){return this._objectRenderer.disableImageProcessing}set disableImageProcessing(e){this._objectRenderer.disableImageProcessing=e}get customIsReadyFunction(){return this._objectRenderer.customIsReadyFunction}set customIsReadyFunction(e){this._objectRenderer.customIsReadyFunction=e}get customRenderFunction(){return this._objectRenderer.customRenderFunction}set customRenderFunction(e){this._objectRenderer.customRenderFunction=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}get onBeforeRenderObservable(){return this._objectRenderer.onBeforeRenderObservable}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}get onAfterRenderObservable(){return this._objectRenderer.onAfterRenderObservable}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get _waitingRenderList(){return this._objectRenderer._waitingRenderList}set _waitingRenderList(e){this._objectRenderer._waitingRenderList=e}get renderPassId(){return this._objectRenderer.renderPassId}get renderPassIds(){return this._objectRenderer.renderPassIds}get currentRefreshId(){return this._objectRenderer.currentRefreshId}setMaterialForRendering(e,t){this._objectRenderer.setMaterialForRendering(e,t)}get isMulti(){return this._renderTarget?.isMulti??!1}get renderTargetOptions(){return this._renderTargetOptions}get renderTarget(){return this._renderTarget}_onRatioRescale(){this._sizeRatio&&this.resize(this._initialSizeParameter)}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}get depthStencilTexture(){return this._renderTarget?._depthStencilTexture??null}constructor(e,t,i,s=!1,r=!0,n=0,a=!1,h=G.TRILINEAR_SAMPLINGMODE,l=!0,c=!1,u=!1,f=5,d=!1,_,m,g=!1,T=!1){let R,A=!0,y,E=!1;if(typeof s=="object"){const b=s;s=!!b.generateMipMaps,r=b.doNotChangeAspectRatio??!0,n=b.type??0,a=!!b.isCube,h=b.samplingMode??G.TRILINEAR_SAMPLINGMODE,l=b.generateDepthBuffer??!0,c=!!b.generateStencilBuffer,u=!!b.isMulti,f=b.format??5,d=!!b.delayAllocation,_=b.samples,m=b.creationFlags,g=!!b.noColorAttachment,T=!!b.useSRGBBuffer,R=b.colorAttachment,A=b.gammaSpace??A,y=b.existingObjectRenderer,E=!!b.enableClusteredLights}if(super(null,i,!s,void 0,h,void 0,void 0,void 0,void 0,f),this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new z,this.onAfterUnbindObservable=new z,this.onClearObservable=new z,this.onResizeObservable=new z,this._cleared=!1,this.skipInitialClear=!1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this._dontDisposeObjectRenderer=!1,this.boundingBoxPosition=p.Zero(),this._disableEngineStages=!1,this._dumpToolsLoading=!1,i=this.getScene(),!i)return;const x=this.getScene().getEngine();this._gammaSpace=A,this._coordinatesMode=G.PROJECTION_MODE,this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._dontDisposeObjectRenderer=!!y,this._processSizeParameter(t),this._objectRenderer=y??new jt(e,i,{numPasses:a?6:this.getRenderLayers()||1,doNotChangeAspectRatio:r,enableClusteredLights:E}),this._onBeforeRenderingManagerRenderObserver=this._objectRenderer.onBeforeRenderingManagerRenderObservable.add(()=>{const b=this._scene;if(!this._disableEngineStages)for(const P of b._beforeRenderTargetClearStage)P.action(this,this._currentFaceIndex,this._currentLayer);if(this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(x):this.skipInitialClear||x.clear(this.clearColor??b.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||b.updateTransformMatrix(!0),!this._disableEngineStages)for(const P of b._beforeRenderTargetDrawStage)P.action(this,this._currentFaceIndex,this._currentLayer);x._debugPushGroup&&x._debugPushGroup(`Render to ${this.name} (face #${this._currentFaceIndex} layer #${this._currentLayer})`)}),this._onAfterRenderingManagerRenderObserver=this._objectRenderer.onAfterRenderingManagerRenderObservable.add(()=>{if(x._debugPopGroup&&x._debugPopGroup(),!this._disableEngineStages)for(const P of this._scene._afterRenderTargetDrawStage)P.action(this,this._currentFaceIndex,this._currentLayer);const b=this._texture?.generateMipMaps??!1;if(this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,this._currentFaceIndex,this._postProcesses,this.ignoreCameraViewport):this._currentUseCameraPostProcess&&this._scene.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,this._currentFaceIndex),!this._disableEngineStages)for(const P of this._scene._afterRenderTargetPostProcessStage)P.action(this,this._currentFaceIndex,this._currentLayer);this._texture&&(this._texture.generateMipMaps=b),this._doNotChangeAspectRatio||this._scene.updateTransformMatrix(!0),this._currentDumpForDebug&&(this._dumpTools?this._dumpTools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),x):W.Error("dumpTools module is still being loaded. To speed up the process import dump tools directly in your project"))}),this._onFastPathRenderObserver=this._objectRenderer.onFastPathRenderObservable.add(()=>{this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(x):this.skipInitialClear||x.clear(this.clearColor||this._scene.clearColor,!0,!0,!0)}),this._resizeObserver=x.onResizeObservable.add(()=>{}),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=r,!u&&(this._renderTargetOptions={generateMipMaps:s,type:n,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:c,samples:_,creationFlags:m,noColorAttachment:g,useSRGBBuffer:T,colorAttachment:R,label:this.name},this.samplingMode===G.NEAREST_SAMPLINGMODE&&(this.wrapU=G.CLAMP_ADDRESSMODE,this.wrapV=G.CLAMP_ADDRESSMODE),d||(a?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=G.INVCUBIC_MODE,this._textureMatrix=D.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,_!==void 0&&(this.samples=_)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){this._renderTarget?.createDepthStencilTexture(e,t,i,s,r,n)}_processSizeParameter(e){if(e.ratio){this._sizeRatio=e.ratio;const t=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(t.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(t.getRenderHeight(),this._sizeRatio)}}else this._size=e}get samples(){return this._renderTarget?.samples??this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}addPostProcess(e){if(!this._postProcessManager){const t=this.getScene();if(!t)return;this._postProcessManager=new zr(t),this._postProcesses=new Array}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1}clearPostProcesses(e=!1){if(this._postProcesses){if(e)for(const t of this._postProcesses)t.dispose();this._postProcesses=[]}}removePostProcess(e){if(!this._postProcesses)return;const t=this._postProcesses.indexOf(e);t!==-1&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}resetRefreshCounter(){this._objectRenderer.resetRefreshCounter()}get refreshRate(){return this._objectRenderer.refreshRate}set refreshRate(e){this._objectRenderer.refreshRate=e}_shouldRender(){return this._objectRenderer.shouldRender()}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;if(e)return e;const t=this._size.depth;return t||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){const t=this.isCube;this._renderTarget?.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e),t?this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,this._renderTargetOptions.samples!==void 0&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){this._dumpToolsLoading||(this._dumpToolsLoading=!0,he(()=>Promise.resolve().then(()=>Dd),void 0,import.meta.url).then(t=>this._dumpTools=t)),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight());const e=this._objectRenderer._checkReadiness();return this.onAfterUnbindObservable.notifyObservers(this),this._objectRenderer.finishRender(),e}_render(e=!1,t=!1){const i=this.getScene();if(!i)return;this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses);const s=i.getEngine();if(s._debugPushGroup&&s._debugPushGroup(`Render to ${this.name}`),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight()),(this.is2DArray||this.is3D)&&!this.isMulti)for(let r=0;r<this.getRenderLayers();r++)this._renderToTarget(0,e,t,r),i.incrementRenderId(),i.resetCachedMaterial();else if(this.isCube&&!this.isMulti)for(let r=0;r<6;r++)this._renderToTarget(r,e,t),i.incrementRenderId(),i.resetCachedMaterial();else this._renderToTarget(0,e,t);this.onAfterUnbindObservable.notifyObservers(this),this._objectRenderer.finishRender(),s._debugPopGroup&&s._debugPopGroup()}_bestReflectionRenderTargetDimension(e,t){const s=e*t,r=ll(s+128*128/(128+s));return Math.min(Xa(e),r)}_bindFrameBuffer(e=0,t=0){const i=this.getScene();if(!i)return;const s=i.getEngine();this._renderTarget&&s.bindFramebuffer(this._renderTarget,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,0,t)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindFramebuffer(this._renderTarget,this.isCube,()=>{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses)||this._bindFrameBuffer(t,i):(!s||!e.postProcessManager._prepareFrame(this._texture))&&this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0){const r=this.getScene();if(!r)return;const n=r.getEngine();this._currentFaceIndex=e,this._currentLayer=s,this._currentUseCameraPostProcess=t,this._currentDumpForDebug=i,this._prepareFrame(r,e,s,t),this._objectRenderer.render(e+s,!0),this._unbindFrameBuffer(n,e),this._texture&&this.isCube&&e===5&&n.generateMipMapsForCubemap(this._texture,!0)}setRenderingOrder(e,t=null,i=null,s=null){this._objectRenderer.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t){this._objectRenderer.setRenderingAutoClearDepthStencil(e,t)}clone(){const e=this.getSize(),t=new yt(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t<this.renderList.length;t++)e.renderList.push(this.renderList[t].id);return e}disposeFramebufferObjects(){this._renderTarget?.dispose(!0)}releaseInternalTexture(){this._renderTarget?.releaseTextures(),this._texture=null}dispose(){this.onResizeObservable.clear(),this.onClearObservable.clear(),this.onAfterUnbindObservable.clear(),this.onBeforeBindObservable.clear(),this._postProcessManager&&(this._postProcessManager.dispose(),this._postProcessManager=null),this._prePassRenderTarget&&this._prePassRenderTarget.dispose(),this._objectRenderer.onBeforeRenderingManagerRenderObservable.remove(this._onBeforeRenderingManagerRenderObserver),this._objectRenderer.onAfterRenderingManagerRenderObservable.remove(this._onAfterRenderingManagerRenderObserver),this._objectRenderer.onFastPathRenderObservable.remove(this._onFastPathRenderObserver),this._dontDisposeObjectRenderer||this._objectRenderer.dispose(),this.clearPostProcesses(!0),this._resizeObserver&&(this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null);const e=this.getScene();if(!e)return;let t=e.customRenderTargets.indexOf(this);t>=0&&e.customRenderTargets.splice(t,1);for(const i of e.cameras)t=i.customRenderTargets.indexOf(this),t>=0&&i.customRenderTargets.splice(t,1);this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this._objectRenderer._rebuild(),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._objectRenderer.freeRenderingGroups()}getViewCount(){return 1}}yt.REFRESHRATE_RENDER_ONCE=jt.REFRESHRATE_RENDER_ONCE;yt.REFRESHRATE_RENDER_ONEVERYFRAME=jt.REFRESHRATE_RENDER_ONEVERYFRAME;yt.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=jt.REFRESHRATE_RENDER_ONEVERYTWOFRAMES;G._CreateRenderTargetTexture=(o,e,t,i,s)=>new yt(o,e,t,i);function Dl(o){return o.getPipelineContext===void 0}class ed{constructor(){this.shaderLanguage=0}postProcessor(e,t,i,s,r){if(r.drawBuffersExtensionDisabled){const n=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(n,"")}return e}}const td=/(flat\s)?\s*varying\s*.*/;class id{constructor(){this.shaderLanguage=0}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return td.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,r=/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;if(e=e.replace(r,""),e=e.replace(/texture2D\s*\(/g,"texture("),i){const n=e.search(/layout *\(location *= *0\) *out/g)!==-1,a=t.indexOf("#define DUAL_SOURCE_BLENDING")!==-1,h=a?`layout(location = 0, index = 0) out vec4 glFragColor;
|
|
41
|
+
layout(location = 0, index = 1) out vec4 glFragColor2;
|
|
42
|
+
`:`layout(location = 0) out vec4 glFragColor;
|
|
43
|
+
`;a&&(e=`#extension GL_EXT_blend_func_extended : require
|
|
44
|
+
`+e),e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCube\s*\(/g,"texture("),e=e.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),e=e.replace(/gl_FragColor/g,"glFragColor"),e=e.replace(/gl_FragData/g,"glFragData"),e=e.replace(/void\s+?main\s*\(/g,(s||n?"":h)+"void main(")}else if(t.indexOf("#define VERTEXOUTPUT_INVARIANT")>=0&&(e=`invariant gl_Position;
|
|
45
|
+
`+e),t.indexOf("#define MULTIVIEW")!==-1)return`#extension GL_OVR_multiview2 : require
|
|
46
|
+
layout (num_views = 2) in;
|
|
47
|
+
`+e;return e}}class Js extends or{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class Ol{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&(e=t.createTexture(),!e))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){return this._MSAARenderBuffers?.[e]??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}function uh(o){return o===13||o===14||o===15||o===16||o===17||o===18||o===19}function $p(o){switch(o){case 13:case 17:case 18:case 14:case 16:return 1;case 15:return 5;case 19:return 0}return 0}function er(o){return o===13||o===17||o===18||o===19}class sd{}class Ie extends J{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return it.ShadersRepository}static set ShadersRepository(e){it.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}snapshotRenderingReset(){this.snapshotRendering=!1}constructor(e,t,i,s){if(i=i||{},super(t??i.antialias,i,s),this._name="WebGL",this.forcePOTTextures=!1,this.validateShaderPrograms=!1,this.disableUniformBuffers=!1,this._webGLVersion=1,this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},!e)return;let r;if(e.getContext){if(r=e,i.preserveDrawingBuffer===void 0&&(i.preserveDrawingBuffer=!1),i.xrCompatible===void 0&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();const h=navigator.userAgent;for(const l of Ie.ExceptionList){const c=l.key,u=l.targets;if(new RegExp(c).test(h)){if(l.capture&&l.captureConstraint){const d=l.capture,_=l.captureConstraint,g=new RegExp(d).exec(h);if(g&&g.length>0&&parseInt(g[g.length-1])>=_)continue}for(const d of u)switch(d){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1;break}}}}if(this._doNotHandleContextLost?this._onContextLost=()=>{xn(this._gl)}:(this._onContextLost=h=>{h.preventDefault(),this._contextWasLost=!0,xn(this._gl),W.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},r.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),r.addEventListener("webglcontextlost",this._onContextLost,!1),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=r.getContext("webgl2",i)||r.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch{}if(!this._gl){if(!r)throw new Error("The provided canvas is null or undefined.");try{this._gl=r.getContext("webgl",i)||r.getContext("experimental-webgl",i)}catch(h){throw new Error("WebGL not supported",{cause:h})}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,r=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";const h=this._gl.getContextAttributes();h&&(i.stencil=h.stencil)}this._sharedInit(r),this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),i.useHighPrecisionFloats!==void 0&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let h=0;h<this._caps.maxVertexAttribs;h++)this._currentBufferPointers[h]=new sd;this._shaderProcessor=this.webGLVersion>1?new id:new ed;const n=`Babylon.js v${Ie.Version}`;W.Log(n+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",n);const a=Ft(this._gl);a.validateShaderPrograms=this.validateShaderPrograms,a.parallelShaderCompile=this._caps.parallelShaderCompile}_clearEmptyResources(){this._dummyFramebuffer=null,super._clearEmptyResources()}_getShaderProcessingContext(e){return null}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_initGLContext(){this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),shaderFloatPrecision:0,parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||this._gl.getExtension("OES_standard_derivatives")!==null,maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||this._gl.getExtension("OES_element_index_uint")!==null,fragmentDepthSupported:this._webGLVersion>1||this._gl.getExtension("EXT_frag_depth")!==null,highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),blendFloat:this._gl.getExtension("EXT_float_blend")!==null,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:this._webGLVersion!==1,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1,textureNorm16:!!this._gl.getExtension("EXT_texture_norm16"),blendParametersPerTarget:!1,dualSourceBlending:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");e!=null&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),this._gl.HALF_FLOAT_OES!==36193&&(this._gl.HALF_FLOAT_OES=36193),this._gl.RGBA16F!==34842&&(this._gl.RGBA16F=34842),this._gl.RGBA32F!==34836&&(this._gl.RGBA32F=34836),this._gl.DEPTH24_STENCIL8!==35056&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(this._webGLVersion===1&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)??0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!!(this._caps.textureFloat&&this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!!(this._caps.textureFloat&&this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.textureNorm16&&(this._gl.R16_EXT=33322,this._gl.RG16_EXT=33324,this._gl.RGB16_EXT=32852,this._gl.RGBA16_EXT=32859,this._gl.R16_SNORM_EXT=36760,this._gl.RG16_SNORM_EXT=36761,this._gl.RGB16_SNORM_EXT=36762,this._gl.RGBA16_SNORM_EXT=36763);const t=this._gl.getExtension("OES_draw_buffers_indexed");if(this._caps.blendParametersPerTarget=!!t,this._alphaState=new tl(this._caps.blendParametersPerTarget),t&&(this._gl.blendEquationSeparateIndexed=t.blendEquationSeparateiOES.bind(t),this._gl.blendEquationIndexed=t.blendEquationiOES.bind(t),this._gl.blendFuncSeparateIndexed=t.blendFuncSeparateiOES.bind(t),this._gl.blendFuncIndexed=t.blendFunciOES.bind(t),this._gl.colorMaskIndexed=t.colorMaskiOES.bind(t),this._gl.disableIndexed=t.disableiOES.bind(t),this._gl.enableIndexed=t.enableiOES.bind(t)),this._caps.dualSourceBlending=!!this._gl.getExtension("WEBGL_blend_func_extended"),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&this._gl.HALF_FLOAT_OES!==5131&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=this._maxMSAASamplesOverride!==null?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES),this._caps.maxDrawBuffers=this._gl.getParameter(this._gl.MAX_DRAW_BUFFERS);else{const i=this._gl.getExtension("WEBGL_draw_buffers");if(i!==null){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=i.drawBuffersWEBGL.bind(i),this._caps.maxDrawBuffers=this._gl.getParameter(i.MAX_DRAW_BUFFERS_WEBGL),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let s=0;s<16;s++)this._gl["COLOR_ATTACHMENT"+s+"_WEBGL"]=i["COLOR_ATTACHMENT"+s+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const i=this._gl.getExtension("WEBGL_depth_texture");i!=null&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=i.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const i=this._gl.getExtension("OES_vertex_array_object");i!=null&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=i.createVertexArrayOES.bind(i),this._gl.bindVertexArray=i.bindVertexArrayOES.bind(i),this._gl.deleteVertexArray=i.deleteVertexArrayOES.bind(i))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const i=this._gl.getExtension("ANGLE_instanced_arrays");i!=null?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=i.drawArraysInstancedANGLE.bind(i),this._gl.drawElementsInstanced=i.drawElementsInstancedANGLE.bind(i),this._gl.vertexAttribDivisor=i.vertexAttribDivisorANGLE.bind(i)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const i=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),s=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);if(i&&s&&(this._caps.highPrecisionShaderSupported=i.precision!==0&&s.precision!==0,this._caps.shaderFloatPrecision=Math.min(i.precision,s.precision)),!this._shouldUseHighPrecisionShader){const r=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.MEDIUM_FLOAT),n=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.MEDIUM_FLOAT);r&&n&&(this._caps.shaderFloatPrecision=Math.min(r.precision,n.precision))}this._caps.shaderFloatPrecision<10&&(this._caps.shaderFloatPrecision=10)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const i=this._gl.getExtension("EXT_blend_minmax");i!=null&&(this._caps.blendMinMax=!0,this._gl.MAX=i.MAX_EXT,this._gl.MIN=i.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const i=this._gl.getExtension("EXT_sRGB");i!=null&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:i.SRGB_EXT,SRGB8:i.SRGB_ALPHA_EXT,SRGB8_ALPHA8:i.SRGB_ALPHA_EXT})}if(this._creationOptions){const i=this._creationOptions.forceSRGBBufferSupportState;i!==void 0&&(this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&i)}}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let i=0;i<this._maxSimultaneousTextures;i++)this._nextFreeTextureSlots.push(i);this._glRenderer==="Mali-G72"&&(this._caps.disableMorphTargetTexture=!0)}_initFeatures(){this._features={forceBitmapOverHTMLImageElement:typeof HTMLImageElement>"u",supportRenderAndCopyToLodForFloatTextures:this._webGLVersion!==1,supportDepthStencilTexture:this._webGLVersion!==1,supportShadowSamplers:this._webGLVersion!==1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:this._webGLVersion!==1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:this._webGLVersion!==1,basisNeedsPOT:this._webGLVersion===1,support3DTextures:this._webGLVersion!==1,needTypeSuffixInShaderConstants:this._webGLVersion!==1,supportMSAA:this._webGLVersion!==1,supportSSAO2:this._webGLVersion!==1,supportIBLShadows:this._webGLVersion!==1,supportExtendedTextureFormats:this._webGLVersion!==1,supportSwitchCaseInShader:this._webGLVersion!==1,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1}}get webGLVersion(){return this._webGLVersion}getClassName(){return"ThinEngine"}_prepareWorkingCanvas(){if(this._workingCanvas)return;this._workingCanvas=this.createCanvas(1,1);const e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}getInfo(){return this.getGlInfo()}getGlInfo(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}}extractDriverInfo(){const e=this.getGlInfo();return e&&e.renderer?e.renderer:""}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight}clear(e,t,i,s=!1,r=0){const n=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=n;let a=0;if(t&&e){let h=!0;if(this._currentRenderTarget){const l=this._currentRenderTarget.texture?.format;if(l===8||l===9||l===10||l===11){const c=this._currentRenderTarget.texture?.type;c===7||c===5?(Ie._TempClearColorUint32[0]=e.r*255,Ie._TempClearColorUint32[1]=e.g*255,Ie._TempClearColorUint32[2]=e.b*255,Ie._TempClearColorUint32[3]=e.a*255,this._gl.clearBufferuiv(this._gl.COLOR,0,Ie._TempClearColorUint32),h=!1):(Ie._TempClearColorInt32[0]=e.r*255,Ie._TempClearColorInt32[1]=e.g*255,Ie._TempClearColorInt32[2]=e.b*255,Ie._TempClearColorInt32[3]=e.a*255,this._gl.clearBufferiv(this._gl.COLOR,0,Ie._TempClearColorInt32),h=!1)}}h&&(this._gl.clearColor(e.r,e.g,e.b,e.a!==void 0?e.a:1),a|=this._gl.COLOR_BUFFER_BIT)}i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),a|=this._gl.DEPTH_BUFFER_BIT),s&&(this._gl.clearStencil(r),a|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(a)}_viewport(e,t,i,s){(e!==this._viewportCached.x||t!==this._viewportCached.y||i!==this._viewportCached.z||s!==this._viewportCached.w)&&(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=s,this._gl.viewport(e,t,i,s))}endFrame(){super.endFrame(),this._badOS&&this.flushFramebuffer()}get performanceMonitor(){throw new Error("Not Supported by ThinEngine")}bindFramebuffer(e,t=0,i,s,r,n=0,a=0){const h=e;this._currentRenderTarget&&this._resolveAndGenerateMipMapsFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(h._framebuffer);const l=this._gl;e.isMulti||(e.is2DArray||e.is3D?(l.framebufferTextureLayer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,e.texture._hardwareTexture?.underlyingResource,n,a),h._currentLOD=n):e.isCube?l.framebufferTexture2D(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.TEXTURE_CUBE_MAP_POSITIVE_X+t,e.texture._hardwareTexture?.underlyingResource,n):h._currentLOD!==n&&(l.framebufferTexture2D(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.TEXTURE_2D,e.texture._hardwareTexture?.underlyingResource,n),h._currentLOD=n));const c=e._depthStencilTexture;if(c){e.is3D&&(e.texture.width!==c.width||e.texture.height!==c.height||e.texture.depth!==c.depth)&&W.Warn("Depth/Stencil attachment for 3D target must have same dimensions as color attachment");const u=e._depthStencilTextureWithStencil?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT;e.is2DArray||e.is3D?l.framebufferTextureLayer(l.FRAMEBUFFER,u,c._hardwareTexture?.underlyingResource,n,a):e.isCube?l.framebufferTexture2D(l.FRAMEBUFFER,u,l.TEXTURE_CUBE_MAP_POSITIVE_X+t,c._hardwareTexture?.underlyingResource,n):l.framebufferTexture2D(l.FRAMEBUFFER,u,l.TEXTURE_2D,c._hardwareTexture?.underlyingResource,n)}h._MSAAFramebuffer&&this._bindUnboundFramebuffer(h._MSAAFramebuffer),this._cachedViewport&&!r?this.setViewport(this._cachedViewport,i,s):(i||(i=e.width,n&&(i=i/Math.pow(2,n))),s||(s=e.height,n&&(s=s/Math.pow(2,n))),this._viewport(0,0,i,s)),this.wipeCaches()}setStateCullFaceType(e,t){const i=this.cullBackFaces??e??!0?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==i||t)&&(this._depthCullingState.cullFace=i)}setState(e,t=0,i,s=!1,r,n,a=0){(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e),this.setStateCullFaceType(r,i),this.setZOffset(t),this.setZOffsetUnits(a);const h=s?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==h||i)&&(this._depthCullingState.frontFace=h),this._stencilStateComposer.stencilMaterial=n}_resolveAndGenerateMipMapsFramebuffer(e,t=!1){e.disableAutomaticMSAAResolve||(e.isMulti?this.resolveMultiFramebuffer(e):this.resolveFramebuffer(e)),t||(e.isMulti?this.generateMipMapsMultiFramebuffer(e):this.generateMipMapsFramebuffer(e))}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return this._currentFramebuffer===null}generateMipmaps(e){const t=this._getTextureTarget(e);this._bindTextureDirectly(t,e,!0),this._gl.generateMipmap(t),this._bindTextureDirectly(t,null)}unBindFramebuffer(e,t,i){const s=e;this._currentRenderTarget=null,this._resolveAndGenerateMipMapsFramebuffer(e,t),i&&(s._MSAAFramebuffer&&this._bindUnboundFramebuffer(s._framebuffer),i()),this._bindUnboundFramebuffer(null)}generateMipMapsFramebuffer(e){!e.isMulti&&e.texture?.generateMipMaps&&!e.isCube&&this.generateMipmaps(e.texture)}resolveFramebuffer(e){const t=e,i=this._gl;if(!t._MSAAFramebuffer||t.isMulti)return;let s=t.resolveMSAAColors?i.COLOR_BUFFER_BIT:0;s|=t._generateDepthBuffer&&t.resolveMSAADepth?i.DEPTH_BUFFER_BIT:0,s|=t._generateStencilBuffer&&t.resolveMSAAStencil?i.STENCIL_BUFFER_BIT:0,i.bindFramebuffer(i.READ_FRAMEBUFFER,t._MSAAFramebuffer),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),i.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,s,i.NEAREST)}flushFramebuffer(){this._gl.flush()}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_resetVertexBufferBinding(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null}createVertexBuffer(e,t,i){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create vertex buffer");const s=new Js(i);return this.bindArrayBuffer(s),typeof e!="number"?e instanceof Array?(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t),s.capacity=e.length*4):(this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),s.capacity=e.byteLength):(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Uint8Array(e),t),s.capacity=e),this._resetVertexBufferBinding(),s.references=1,s}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,i){const s=this._gl.createBuffer(),r=new Js(s);if(!s)throw new Error("Unable to create index buffer");this.bindIndexBuffer(r);const n=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,n,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),r.references=1,r.is32Bits=n.BYTES_PER_ELEMENT===4,r}_normalizeIndexData(e){if(e.BYTES_PER_ELEMENT===2)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let i=0;i<e.length;i++)if(e[i]>=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);this._gl.uniformBlockBinding(s,r,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,s,r,n,a){const h=this._currentBufferPointers[t];if(!h)return;let l=!1;h.active?(h.buffer!==e&&(h.buffer=e,l=!0),h.size!==i&&(h.size=i,l=!0),h.type!==s&&(h.type=s,l=!0),h.normalized!==r&&(h.normalized=r,l=!0),h.stride!==n&&(h.stride=n,l=!0),h.offset!==a&&(h.offset=a,l=!0)):(l=!0,h.active=!0,h.index=t,h.size=i,h.type=s,h.normalized=r,h.stride=n,h.offset=a,h.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),s===this._gl.UNSIGNED_INT||s===this._gl.INT?this._gl.vertexAttribIPointer(t,i,s,n,a):this._gl.vertexAttribPointer(t,i,s,r,n,a))}_bindIndexBufferWithCache(e){e!=null&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const s=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let r=0;r<s.length;r++){const n=t.getAttributeLocation(r);if(n>=0){const a=s[r];let h=null;if(i&&(h=i[a]),h||(h=e[a]),!h)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const l=h.getBuffer();l&&(this._vertexAttribPointer(l,n,h.getSize(),h.type,h.normalized,h.byteStride,h.byteOffset),h.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,h.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(l))))}}}recordVertexArrayObject(e,t,i,s){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,s),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=t!=null&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,s,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const n=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let a=0;for(let h=0;h<n;h++)if(h<i.length){const l=r.getAttributeLocation(h);l>=0&&(this._gl.enableVertexAttribArray(l),this._vertexAttribArraysEnabled[l]=!0,this._vertexAttribPointer(e,l,i[h],this._gl.FLOAT,!1,s,a)),a+=i[h]*4}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,s){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,s)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t<i;t++){const s=this._currentInstanceBuffers[t];e!=s&&s.references&&(e=s,this.bindArrayBuffer(s));const r=this._currentInstanceLocations[t];this._gl.vertexAttribDivisor(r,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0}releaseVertexArrayObject(e){this._gl.deleteVertexArray(e)}_releaseBuffer(e){return e.references--,e.references===0?(this._deleteBuffer(e),!0):!1}_deleteBuffer(e){this._gl.deleteBuffer(e.underlyingResource)}updateAndBindInstancesBuffer(e,t,i){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),i[0].index!==void 0)this.bindInstancesBuffer(e,i,!0);else for(let s=0;s<4;s++){const r=i[s];this._vertexAttribArraysEnabled[r]||(this._gl.enableVertexAttribArray(r),this._vertexAttribArraysEnabled[r]=!0),this._vertexAttribPointer(e,r,4,this._gl.FLOAT,!1,64,s*16),this._gl.vertexAttribDivisor(r,1),this._currentInstanceLocations.push(r),this._currentInstanceBuffers.push(e)}}bindInstancesBuffer(e,t,i=!0){this.bindArrayBuffer(e);let s=0;if(i)for(let r=0;r<t.length;r++){const n=t[r];s+=n.attributeSize*4}for(let r=0;r<t.length;r++){const n=t[r];n.index===void 0&&(n.index=this._currentEffect.getAttributeLocationByName(n.attributeName)),!(n.index<0)&&(this._vertexAttribArraysEnabled[n.index]||(this._gl.enableVertexAttribArray(n.index),this._vertexAttribArraysEnabled[n.index]=!0),this._vertexAttribPointer(e,n.index,n.attributeSize,n.attributeType||this._gl.FLOAT,n.normalized||!1,s,n.offset),this._gl.vertexAttribDivisor(n.index,n.divisor===void 0?1:n.divisor),this._currentInstanceLocations.push(n.index),this._currentInstanceBuffers.push(e))}}disableInstanceAttributeByName(e){if(!this._currentEffect)return;const t=this._currentEffect.getAttributeLocationByName(e);this.disableInstanceAttribute(t)}disableInstanceAttribute(e){let t=!1,i;for(;(i=this._currentInstanceLocations.indexOf(e))!==-1;)this._currentInstanceLocations.splice(i,1),this._currentInstanceBuffers.splice(i,1),t=!0;t&&(this._gl.vertexAttribDivisor(e,0),this.disableAttributeByIndex(e))}disableAttributeByIndex(e){this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1}draw(e,t,i,s){this.drawElementsType(e?0:1,t,i,s)}drawPointClouds(e,t,i){this.drawArraysType(2,e,t,i)}drawUnIndexed(e,t,i,s){this.drawArraysType(e?0:1,t,i,s)}drawElementsType(e,t,i,s){this.applyStates(),this._reportDrawCall();const r=this._drawMode(e),n=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,a=this._uintIndicesCurrentlySet?4:2;s?this._gl.drawElementsInstanced(r,i,n,t*a,s):this._gl.drawElements(r,i,n,t*a)}drawArraysType(e,t,i,s){this.applyStates(),this._reportDrawCall();const r=this._drawMode(e);s?this._gl.drawArraysInstanced(r,t,i,s):this._gl.drawArrays(r,t,i)}_drawMode(e){switch(e){case 0:return this._gl.TRIANGLES;case 2:return this._gl.POINTS;case 1:return this._gl.LINES;case 3:return this._gl.POINTS;case 4:return this._gl.LINES;case 5:return this._gl.LINE_LOOP;case 6:return this._gl.LINE_STRIP;case 7:return this._gl.TRIANGLE_STRIP;case 8:return this._gl.TRIANGLE_FAN;default:return this._gl.TRIANGLES}}_releaseEffect(e){this._compiledEffects[e._key]&&delete this._compiledEffects[e._key];const t=e.getPipelineContext();t&&this._deletePipelineContext(t)}_deletePipelineContext(e){const t=e;t&&t.program&&(t.program.__SPECTOR_rebuildProgram=null,el(t),this._gl&&(this._currentProgram===t.program&&this._setProgram(null),this._gl.deleteProgram(t.program)))}_getGlobalDefines(e){return jh(e,this.isNDCHalfZRange,this.useReverseDepthBuffer,this.useExactSrgbConversions)}createEffect(e,t,i,s,r,n,a,h,l,c=0,u){const f=typeof e=="string"?e:e.vertexToken||e.vertexSource||e.vertexElement||e.vertex,d=typeof e=="string"?e:e.fragmentToken||e.fragmentSource||e.fragmentElement||e.fragment,_=this._getGlobalDefines(),m=t.attributes!==void 0;let g=r??t.defines??"";_&&(g+=_);const T=f+"+"+d+"@"+g;if(this._compiledEffects[T]){const A=this._compiledEffects[T];return a&&A.isReady()&&a(A),A._refCount++,A}this._gl&&Ft(this._gl);const R=new it(e,t,m?this:i,s,this,r,n,a,h,l,T,t.shaderLanguage??c,t.extraInitializationsAsync??u);return this._compiledEffects[T]=R,R}_getShaderSource(e){return this._gl.getShaderSource(e)}createRawShaderProgram(e,t,i,s,r=null){const n=Ft(this._gl);return n._contextWasLost=this._contextWasLost,n.validateShaderPrograms=this.validateShaderPrograms,$h(e,t,i,s||this._gl,r)}createShaderProgram(e,t,i,s,r,n=null){const a=Ft(this._gl);return a._contextWasLost=this._contextWasLost,a.validateShaderPrograms=this.validateShaderPrograms,Jh(e,t,i,s,r||this._gl,n)}inlineShaderCode(e){return e}createPipelineContext(e){if(this._gl){const i=Ft(this._gl);i.parallelShaderCompile=this._caps.parallelShaderCompile}const t=Yu(this._gl);return t.engine=this,t}createMaterialContext(){}createDrawContext(){}_finalizePipelineContext(e){return Va(e,this._gl,this.validateShaderPrograms)}_preparePipelineContextAsync(e,t,i,s,r,n,a,h,l,c,u){const f=Ft(this._gl);return f._contextWasLost=this._contextWasLost,f.validateShaderPrograms=this.validateShaderPrograms,f._createShaderProgramInjection=this._createShaderProgram.bind(this),f.createRawShaderProgramInjection=this.createRawShaderProgram.bind(this),f.createShaderProgramInjection=this.createShaderProgram.bind(this),f.loadFileInjection=this._loadFile.bind(this),Zu(e,t,i,s,r,n,a,h,l,c,u)}_createShaderProgram(e,t,i,s,r=null){return ka(e,t,i,s,r)}_isRenderingStateCompiled(e){return this._isDisposed?!1:ju(e,this._gl,this.validateShaderPrograms)}_executeWhenRenderingStateIsCompiled(e,t){Qu(e,t)}getUniforms(e,t){const i=new Array,s=e;for(let r=0;r<t.length;r++)i.push(this._gl.getUniformLocation(s.program,t[r]));return i}getAttributes(e,t){const i=[],s=e;for(let r=0;r<t.length;r++)try{i.push(this._gl.getAttribLocation(s.program,t[r]))}catch{i.push(-1)}return i}enableEffect(e){e=e!==null&&Dl(e)?e.effect:e,!(!e||e===this._currentEffect)&&(this._stencilStateComposer.stencilMaterial=void 0,this.bindSamplers(e),this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setInt(e,t){return e?(this._gl.uniform1i(e,t),!0):!1}setInt2(e,t,i){return e?(this._gl.uniform2i(e,t,i),!0):!1}setInt3(e,t,i,s){return e?(this._gl.uniform3i(e,t,i,s),!0):!1}setInt4(e,t,i,s,r){return e?(this._gl.uniform4i(e,t,i,s,r),!0):!1}setIntArray(e,t){return e?(this._gl.uniform1iv(e,t),!0):!1}setIntArray2(e,t){return!e||t.length%2!==0?!1:(this._gl.uniform2iv(e,t),!0)}setIntArray3(e,t){return!e||t.length%3!==0?!1:(this._gl.uniform3iv(e,t),!0)}setIntArray4(e,t){return!e||t.length%4!==0?!1:(this._gl.uniform4iv(e,t),!0)}setUInt(e,t){return e?(this._gl.uniform1ui(e,t),!0):!1}setUInt2(e,t,i){return e?(this._gl.uniform2ui(e,t,i),!0):!1}setUInt3(e,t,i,s){return e?(this._gl.uniform3ui(e,t,i,s),!0):!1}setUInt4(e,t,i,s,r){return e?(this._gl.uniform4ui(e,t,i,s,r),!0):!1}setUIntArray(e,t){return e?(this._gl.uniform1uiv(e,t),!0):!1}setUIntArray2(e,t){return!e||t.length%2!==0?!1:(this._gl.uniform2uiv(e,t),!0)}setUIntArray3(e,t){return!e||t.length%3!==0?!1:(this._gl.uniform3uiv(e,t),!0)}setUIntArray4(e,t){return!e||t.length%4!==0?!1:(this._gl.uniform4uiv(e,t),!0)}setArray(e,t){return!e||t.length<1?!1:(this._gl.uniform1fv(e,t),!0)}setArray2(e,t){return!e||t.length%2!==0?!1:(this._gl.uniform2fv(e,t),!0)}setArray3(e,t){return!e||t.length%3!==0?!1:(this._gl.uniform3fv(e,t),!0)}setArray4(e,t){return!e||t.length%4!==0?!1:(this._gl.uniform4fv(e,t),!0)}setMatrices(e,t){return e?(this._gl.uniformMatrix4fv(e,!1,t),!0):!1}setMatrix3x3(e,t){return e?(this._gl.uniformMatrix3fv(e,!1,t),!0):!1}setMatrix2x2(e,t){return e?(this._gl.uniformMatrix2fv(e,!1,t),!0):!1}setFloat(e,t){return e?(this._gl.uniform1f(e,t),!0):!1}setFloat2(e,t,i){return e?(this._gl.uniform2f(e,t,i),!0):!1}setFloat3(e,t,i,s){return e?(this._gl.uniform3f(e,t,i,s),!0):!1}setFloat4(e,t,i,s,r){return e?(this._gl.uniform4f(e,t,i,s,r),!0):!1}applyStates(){if(this._depthCullingState.apply(this._gl),this._stencilStateComposer.apply(this._gl),this._alphaState.apply(this._gl,this._currentRenderTarget&&this._currentRenderTarget.textures?this._currentRenderTarget.textures.length:1),this._colorWriteChanged){this._colorWriteChanged=!1;const e=this._colorWrite;this._gl.colorMask(e,e,e,e)}}wipeCaches(e){this.preventCacheWipeBetweenFrames&&!e||(this._currentEffect=null,this._viewportCached.x=0,this._viewportCached.y=0,this._viewportCached.z=0,this._viewportCached.w=0,this._unbindVertexArrayObject(),e&&(this._currentProgram=null,this.resetTextureCache(),this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=this._gl.LEQUAL,this._alphaState.reset(),this._resetAlphaMode(),this._colorWrite=!0,this._colorWriteChanged=!0,this._unpackFlipYCached=null,this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this._mustWipeVertexAttributes=!0,this.unbindAllAttributes()),this._resetVertexBufferBinding(),this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null,this.bindIndexBuffer(null))}_getSamplingParameters(e,t){const i=this._gl;let s=i.NEAREST,r=i.NEAREST,n=!1;switch(e){case 11:s=i.LINEAR,t?r=i.LINEAR_MIPMAP_NEAREST:r=i.LINEAR;break;case 3:s=i.LINEAR,n=!0,t?r=i.LINEAR_MIPMAP_LINEAR:r=i.LINEAR;break;case 8:n=!0,s=i.NEAREST,t?r=i.NEAREST_MIPMAP_LINEAR:r=i.NEAREST;break;case 4:s=i.NEAREST,t?r=i.NEAREST_MIPMAP_NEAREST:r=i.NEAREST;break;case 5:s=i.NEAREST,t?r=i.LINEAR_MIPMAP_NEAREST:r=i.LINEAR;break;case 6:n=!0,s=i.NEAREST,t?r=i.LINEAR_MIPMAP_LINEAR:r=i.LINEAR;break;case 7:s=i.NEAREST,r=i.LINEAR;break;case 1:s=i.NEAREST,r=i.NEAREST;break;case 9:s=i.LINEAR,t?r=i.NEAREST_MIPMAP_NEAREST:r=i.NEAREST;break;case 10:n=!0,s=i.LINEAR,t?r=i.NEAREST_MIPMAP_LINEAR:r=i.NEAREST;break;case 2:s=i.LINEAR,r=i.LINEAR;break;case 12:s=i.LINEAR,r=i.NEAREST;break}return{min:r,mag:s,hasMipMaps:n}}_createTexture(){const e=this._gl.createTexture();if(!e)throw new Error("Unable to create texture");return e}_createHardwareTexture(){return new Ol(this._createTexture(),this._gl)}_createInternalTexture(e,t,i=!0,s=0){let r,n=!1,a=0,h=3,l=5,c=!1,u=1,f,d=!1,_=0,m=!1;t!==void 0&&typeof t=="object"?(r=!!t.generateMipMaps,n=!!t.createMipMaps,a=t.type===void 0?0:t.type,h=t.samplingMode===void 0?3:t.samplingMode,l=t.format===void 0?5:t.format,c=t.useSRGBBuffer===void 0?!1:t.useSRGBBuffer,u=t.samples??1,f=t.label,d=!!t.createMSAATexture,_=t.comparisonFunction||0,m=!!t.isCube):r=!!t,c&&(c=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU)),(a===1&&!this._caps.textureFloatLinearFiltering||a===2&&!this._caps.textureHalfFloatLinearFiltering)&&(h=1),a===1&&!this._caps.textureFloat&&(a=0,W.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const g=uh(l),T=er(l),R=this._gl,A=new xt(this,s),y=e.width||e,E=e.height||e,x=e.depth||0,b=e.layers||0,P=this._getSamplingParameters(h,(r||n)&&!g),v=b!==0?R.TEXTURE_2D_ARRAY:x!==0?R.TEXTURE_3D:m?R.TEXTURE_CUBE_MAP:R.TEXTURE_2D,O=g?this._getInternalFormatFromDepthTextureFormat(l,!0,T):this._getRGBABufferInternalSizedFormat(a,l,c),k=g?T?R.DEPTH_STENCIL:R.DEPTH_COMPONENT:this._getInternalFormat(l),Y=g?this._getWebGLTextureTypeFromDepthTextureFormat(l):this._getWebGLTextureType(a);if(this._bindTextureDirectly(v,A),b!==0)A.is2DArray=!0,R.texImage3D(v,0,O,y,E,b,0,k,Y,null);else if(x!==0)A.is3D=!0,R.texImage3D(v,0,O,y,E,x,0,k,Y,null);else if(m){A.isCube=!0;for(let q=0;q<6;q++)R.texImage2D(R.TEXTURE_CUBE_MAP_POSITIVE_X+q,0,O,y,E,0,k,Y,null)}else R.texImage2D(v,0,O,y,E,0,k,Y,null);if(R.texParameteri(v,R.TEXTURE_MAG_FILTER,P.mag),R.texParameteri(v,R.TEXTURE_MIN_FILTER,P.min),R.texParameteri(v,R.TEXTURE_WRAP_S,R.CLAMP_TO_EDGE),R.texParameteri(v,R.TEXTURE_WRAP_T,R.CLAMP_TO_EDGE),g&&this.webGLVersion>1&&(_===0?(R.texParameteri(v,R.TEXTURE_COMPARE_FUNC,515),R.texParameteri(v,R.TEXTURE_COMPARE_MODE,R.NONE)):(R.texParameteri(v,R.TEXTURE_COMPARE_FUNC,_),R.texParameteri(v,R.TEXTURE_COMPARE_MODE,R.COMPARE_REF_TO_TEXTURE))),(r||n)&&this._gl.generateMipmap(v),this._bindTextureDirectly(v,null),A._useSRGBBuffer=c,A.baseWidth=y,A.baseHeight=E,A.width=y,A.height=E,A.depth=b||x,A.isReady=!0,A.samples=u,A.generateMipMaps=r,A.samplingMode=h,A.type=a,A.format=l,A.label=f,A.comparisonFunction=_,this._internalTexturesCache.push(A),d){let q;if(uh(A.format)?q=this._setupFramebufferDepthAttachments(er(A.format),A.format!==19,A.width,A.height,u,A.format,!0):q=this._createRenderBuffer(A.width,A.height,u,-1,this._getRGBABufferInternalSizedFormat(A.type,A.format,A._useSRGBBuffer),-1),!q)throw new Error("Unable to create render buffer");A._autoMSAAManagement=!0;let L=A._hardwareTexture;L||(L=A._hardwareTexture=this._createHardwareTexture()),L.addMSAARenderBuffer(q)}return A}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,s,r=3,n=null,a=null,h=null,l=null,c=null,u=null,f,d,_,m){return this._createTextureBase(e,t,i,s,r,n,a,(...g)=>this._prepareWebGLTexture(...g,c),(g,T,R,A,y,E)=>{const x=this._gl,b=R.width===g&&R.height===T;y._creationFlags=_??0;const P=this._getTexImageParametersForCreateTexture(y.format,y._useSRGBBuffer);if(b)return x.texImage2D(x.TEXTURE_2D,0,P.internalFormat,P.format,P.type,R),!1;const v=this._caps.maxTextureSize;if(R.width>v||R.height>v||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=g,this._workingCanvas.height=T,this._workingContext.drawImage(R,0,0,R.width,R.height,0,0,g,T),x.texImage2D(x.TEXTURE_2D,0,P.internalFormat,P.format,P.type,this._workingCanvas),y.width=g,y.height=T),!1;{const O=new xt(this,2);this._bindTextureDirectly(x.TEXTURE_2D,O,!0),x.texImage2D(x.TEXTURE_2D,0,P.internalFormat,P.format,P.type,R),this._rescaleTexture(O,y,s,P.format,()=>{this._releaseTexture(O),this._bindTextureDirectly(x.TEXTURE_2D,y,!0),E()})}return!0},h,l,c,u,f,d,m)}_getTexImageParametersForCreateTexture(e,t){let i,s;return this.webGLVersion===1?(i=this._getInternalFormat(e,t),s=i):(i=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(0,e,t)),{internalFormat:s,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,s,r){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const s=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,r.min),i&&r.hasMipMaps&&(t.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),t.samplingMode=e}updateTextureDimensions(e,t,i,s=1){}updateTextureWrappingMode(e,t,i=null,s=null){const r=this._getTextureTarget(e);t!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),i!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&s!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(r,null)}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,a=0){const h=this._gl;let l=h.TEXTURE_2D;if(e.isCube&&(l=h.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=h.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=h.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=h.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=h.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=h.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=h.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=h.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1;break}if(e.generateMipMaps){const c=e._hardwareTexture;c.memoryAllocated||(h.texStorage2D(e.isCube?h.TEXTURE_CUBE_MAP:h.TEXTURE_2D,Math.floor(Math.log2(Math.max(i,s)))+1,t,e.width,e.height),c.memoryAllocated=!0),this._gl.compressedTexSubImage2D(l,a,0,0,i,s,t,r)}else this._gl.compressedTexImage2D(l,a,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const a=this._gl,h=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),c=r===void 0?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let u=a.TEXTURE_2D;e.isCube&&(u=a.TEXTURE_CUBE_MAP_POSITIVE_X+i);const f=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),_=n?e.width:Math.pow(2,Math.max(f-s,0)),m=n?e.height:Math.pow(2,Math.max(d-s,0));a.texImage2D(u,s,c,_,m,0,l,h,t)}updateTextureData(e,t,i,s,r,n,a=0,h=0,l=!1){const c=this._gl,u=this._getWebGLTextureType(e.type),f=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=c.TEXTURE_2D,_=c.TEXTURE_2D;e.isCube&&(_=c.TEXTURE_CUBE_MAP_POSITIVE_X+a,d=c.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),c.texSubImage2D(_,h,i,s,r,n,f,u,t),l&&this._gl.generateMipmap(_),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const r=this._gl,n=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,r){const n=this._gl;if(!n)return;const a=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,a.min),!i&&!s&&n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,r,n,a,h,l,c){const u=this.getCaps().maxTextureSize,f=Math.min(u,this.needPOTTextures?ni(s.width,u):s.width),d=Math.min(u,this.needPOTTextures?ni(s.height,u):s.height),_=this._gl;if(_){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(_.TEXTURE_2D,e,!0),this._unpackFlipY(r===void 0?!0:!!r),e.baseWidth=s.width,e.baseHeight=s.height,e.width=f,e.height=d,e.isReady=!0,e.type=e.type!==-1?e.type:0,e.format=e.format!==-1?e.format:c??(t===".jpg"&&!e._useSRGBBuffer?4:5),!h(f,d,s,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,n,a,l)})&&this._prepareWebGLTextureContinuation(e,i,n,a,l)}}_getInternalFormatFromDepthTextureFormat(e,t,i){const s=this._gl;if(!t)return s.STENCIL_INDEX8;let n=i?s.DEPTH_STENCIL:s.DEPTH_COMPONENT;return this.webGLVersion>1?e===15?n=s.DEPTH_COMPONENT16:e===16?n=s.DEPTH_COMPONENT24:e===17||e===13?n=i?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24:e===14?n=s.DEPTH_COMPONENT32F:e===18&&(n=i?s.DEPTH32F_STENCIL8:s.DEPTH_COMPONENT32F):n=s.DEPTH_COMPONENT16,n}_getWebGLTextureTypeFromDepthTextureFormat(e){const t=this._gl;let i=t.UNSIGNED_INT;return e===15?i=t.UNSIGNED_SHORT:e===17||e===13?i=t.UNSIGNED_INT_24_8:e===14?i=t.FLOAT:e===18?i=t.FLOAT_32_UNSIGNED_INT_24_8_REV:e===19&&(i=t.UNSIGNED_BYTE),i}_setupFramebufferDepthAttachments(e,t,i,s,r=1,n,a=!1){const h=this._gl;n=n??(e?13:14);const l=this._getInternalFormatFromDepthTextureFormat(n,t,e);return e&&t?this._createRenderBuffer(i,s,r,h.DEPTH_STENCIL,l,a?-1:h.DEPTH_STENCIL_ATTACHMENT):t?this._createRenderBuffer(i,s,r,l,l,a?-1:h.DEPTH_ATTACHMENT):e?this._createRenderBuffer(i,s,r,l,l,a?-1:h.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,r,n,a=!0){const l=this._gl.createRenderbuffer();return this._updateRenderBuffer(l,e,t,i,s,r,n,a)}_updateRenderBuffer(e,t,i,s,r,n,a,h=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),s>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,s,n,t,i):l.renderbufferStorage(l.RENDERBUFFER,r,t,i),a!==-1&&l.framebufferRenderbuffer(l.FRAMEBUFFER,a,l.RENDERBUFFER,e),h&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);t!==-1&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_deleteTexture(e){e?.release()}_setProgram(e){this._currentProgram!==e&&(qu(e,this._gl),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let s=0;s<i.length;s++){const r=e.getUniform(i[s]);r&&(this._boundUniforms[s]=r)}this._currentEffect=null}_activateCurrentTexture(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)}_bindTextureDirectly(e,t,i=!1,s=!1){let r=!1;const n=t&&t._associatedChannel>-1;if(i&&n&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw W.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,t?._hardwareTexture?.underlyingResource??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(r=!0,this._activateCurrentTexture());return n&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),r}_bindTexture(e,t,i){if(e===void 0)return;t&&(t._associatedChannel=e),this._activeChannel=e;const s=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(s,t)}unbindAllTextures(){for(let e=0;e<this._maxSimultaneousTextures;e++)this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,s){e!==void 0&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];!i||i._currentState===t||(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,s=!1,r=""){if(!t)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;const l=t.getInternalTexture();l&&(l._associatedChannel=e),t.update()}else if(t.delayLoadState===4)return t.delayLoad(),!1;let n;s?n=t.depthStencilTexture:t.isReady()?n=t.getInternalTexture():t.isCube?n=this.emptyCubeTexture:t.is3D?n=this.emptyTexture3D:t.is2DArray?n=this.emptyTexture2DArray:n=this.emptyTexture,!i&&n&&(n._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),a=!1),this._activeChannel=e;const h=this._getTextureTarget(n);if(a&&this._bindTextureDirectly(h,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const l=t.coordinatesMode!==3&&t.coordinatesMode!==5?1:0;t.wrapU=l,t.wrapV=l}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(h,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(h,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(h,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(h,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,s){if(!(e===void 0||!t)){(!this._textureUnits||this._textureUnits.length!==i.length)&&(this._textureUnits=new Int32Array(i.length));for(let r=0;r<i.length;r++){const n=i[r].getInternalTexture();n?(this._textureUnits[r]=e+r,n._associatedChannel=e+r):this._textureUnits[r]=-1}this._gl.uniform1iv(t,this._textureUnits);for(let r=0;r<i.length;r++)this._setTexture(this._textureUnits[r],i[r],!0)}}_setAnisotropicLevel(e,t,i){const s=this._caps.textureAnisotropicFilterExtension;t.samplingMode!==11&&t.samplingMode!==3&&t.samplingMode!==2&&(i=1),s&&t._cachedAnisotropicFilteringLevel!==i&&(this._setTextureParameterFloat(e,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(i,this._caps.maxAnisotropy),t),t._cachedAnisotropicFilteringLevel=i)}_setTextureParameterFloat(e,t,i,s){this._bindTextureDirectly(e,s,!0,!0),this._gl.texParameterf(e,t,i)}_setTextureParameterInteger(e,t,i,s){s&&this._bindTextureDirectly(e,s,!0,!0),this._gl.texParameteri(e,t,i)}unbindAllAttributes(){if(this._mustWipeVertexAttributes){this._mustWipeVertexAttributes=!1;for(let e=0;e<this._caps.maxVertexAttribs;e++)this.disableAttributeByIndex(e);return}for(let e=0,t=this._vertexAttribArraysEnabled.length;e<t;e++)e>=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){this._compiledEffects={},this.onReleaseEffectsObservable.notifyObservers(this)}dispose(){mt()&&this._renderingCanvas&&(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._onContextRestored&&this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&this._gl.getExtension("WEBGL_lose_context")?.loseContext(),xn(this._gl)}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const s=t.createTexture();t.bindTexture(t.TEXTURE_2D,s),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const n=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&n===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);const a=t.RGBA,h=t.UNSIGNED_BYTE,l=new Uint8Array(4);t.readPixels(0,0,1,1,a,h,l),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(r),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(this._webGLVersion===1){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:case 33322:case 36760:i=this._gl.RED;break;case 7:case 33324:case 36761:i=this._gl.RG;break;case 4:case 32852:case 36762:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:case 32859:case 36763:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;break}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER;break}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(this._webGLVersion===1){if(t!==void 0)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 36760:return this._gl.R16_SNORM_EXT;case 36761:return this._gl.RG16_SNORM_EXT;case 36762:return this._gl.RGB16_SNORM_EXT;case 36763:return this._gl.RGBA16_SNORM_EXT;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;case 11:return this._gl.RGBA16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 33322:return this._gl.R16_EXT;case 33324:return this._gl.RG16_EXT;case 32852:return this._gl.RGB16_EXT;case 32859:return this._gl.RGBA16_EXT;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;case 11:return this._gl.RGBA16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;case 11:return this._gl.RGBA32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;case 11:return this._gl.RGBA32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;case 5:return this._gl.RGBA32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;case 5:return this._gl.RGBA16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,s,r=!0,n=!0,a=null){const h=r?4:3,l=r?this._gl.RGBA:this._gl.RGB,c=i*s*h;if(!a)a=new Uint8Array(c);else if(a.length<c)return W.Error(`Data buffer is too small to store the read pixels (${a.length} should be more than ${c})`),Promise.resolve(a);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,l,this._gl.UNSIGNED_BYTE,a),Promise.resolve(a)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(this._HasMajorPerformanceCaveat!==null)return!this._HasMajorPerformanceCaveat;if(this._IsSupported===null)try{const e=J._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=t!=null&&!!globalThis.WebGLRenderingContext}catch{this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(this._HasMajorPerformanceCaveat===null)try{const e=J._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch{this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}}Ie._TempClearColorUint32=new Uint32Array(4);Ie._TempClearColorInt32=new Int32Array(4);Ie.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}];Ie._ConcatenateShader=Kh;Ie._IsSupported=null;Ie._HasMajorPerformanceCaveat=null;const rd=Object.freeze(Object.defineProperty({__proto__:null,ThinEngine:Ie},Symbol.toStringTag,{value:"Module"}));class nd{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new ad(e)}sampleFrame(e=Si.Now){if(this._enabled){if(this._lastFrameTimeMs!=null){const t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}}get averageFrameTime(){return this._rollingFrameTime.average}get averageFrameTimeVariance(){return this._rollingFrameTime.variance}get instantaneousFrameTime(){return this._rollingFrameTime.history(0)}get averageFPS(){return 1e3/this._rollingFrameTime.average}get instantaneousFPS(){const e=this._rollingFrameTime.history(0);return e===0?0:1e3/e}get isSaturated(){return this._rollingFrameTime.isSaturated()}enable(){this._enabled=!0}disable(){this._enabled=!1,this._lastFrameTimeMs=null}get isEnabled(){return this._enabled}reset(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()}}class ad{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const i=this._samples[this._pos];t=i-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(i-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length}history(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;const t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]}isSaturated(){return this._sampleCount>=this._samples.length}reset(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0}_wrapPosition(e){const t=this._samples.length;return(e%t+t)%t}}Ie.prototype.setAlphaMode=function(o,e=!1,t=0){if(this._alphaMode[t]===o){if(!e){const s=o===0;this.depthCullingState.depthMask!==s&&(this.depthCullingState.depthMask=s)}return}const i=o===0;this._alphaState.setAlphaBlend(!i,t),this._alphaState.setAlphaMode(o,t),e||(this.depthCullingState.depthMask=i),this._alphaMode[t]=o};Ie.prototype.updateRawTexture=function(o,e,t,i,s=null,r=0,n=!1){if(!o)return;const a=this._getRGBABufferInternalSizedFormat(r,t,n),h=this._getInternalFormat(t),l=this._getWebGLTextureType(r);this._bindTextureDirectly(this._gl.TEXTURE_2D,o,!0),this._unpackFlipY(i===void 0?!0:!!i),this._doNotHandleContextLost||(o._bufferView=e,o.format=t,o.type=r,o.invertY=i,o._compression=s),o.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),s&&e?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[s],o.width,o.height,0,e):this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,o.width,o.height,0,h,l,e),o.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),o.isReady=!0};Ie.prototype.createRawTexture=function(o,e,t,i,s,r,n,a=null,h=0,l=0,c=!1){const u=new xt(this,3);u.baseWidth=e,u.baseHeight=t,u.width=e,u.height=t,u.format=i,u.generateMipMaps=s,u.samplingMode=n,u.invertY=r,u._compression=a,u.type=h,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this._doNotHandleContextLost||(u._bufferView=o),this.updateRawTexture(u,o,i,r,a,h,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);const f=this._getSamplingParameters(n,s);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,f.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,f.min),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u};Ie.prototype.createRawCubeTexture=function(o,e,t,i,s,r,n,a=null){const h=this._gl,l=new xt(this,8);l.isCube=!0,l.format=t,l.type=i,this._doNotHandleContextLost||(l._bufferViewArray=o);const c=this._getWebGLTextureType(i);let u=this._getInternalFormat(t);u===h.RGB&&(u=h.RGBA),c===h.FLOAT&&!this._caps.textureFloatLinearFiltering?(s=!1,n=1,W.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):c===this._gl.HALF_FLOAT_OES&&!this._caps.textureHalfFloatLinearFiltering?(s=!1,n=1,W.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):c===h.FLOAT&&!this._caps.textureFloatRender?(s=!1,W.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):c===h.HALF_FLOAT&&!this._caps.colorBufferFloat&&(s=!1,W.Warn("Render to half float textures is not supported. Mipmap generation forced to false."));const f=e,d=f;if(l.width=f,l.height=d,l.invertY=r,l._compression=a,!this.needPOTTextures||Xs(l.width)&&Xs(l.height)||(s=!1),o)this.updateRawCubeTexture(l,o,t,i,r,a);else{const g=this._getRGBABufferInternalSizedFormat(i),T=0;this._bindTextureDirectly(h.TEXTURE_CUBE_MAP,l,!0);for(let R=0;R<6;R++)a?h.compressedTexImage2D(h.TEXTURE_CUBE_MAP_POSITIVE_X+R,T,this.getCaps().s3tc[a],l.width,l.height,0,void 0):h.texImage2D(h.TEXTURE_CUBE_MAP_POSITIVE_X+R,T,g,l.width,l.height,0,u,c,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,l,!0),o&&s&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const m=this._getSamplingParameters(n,s);return h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_MAG_FILTER,m.mag),h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_MIN_FILTER,m.min),h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this._bindTextureDirectly(h.TEXTURE_CUBE_MAP,null),l.generateMipMaps=s,l.samplingMode=n,l.isReady=!0,l};Ie.prototype.updateRawCubeTexture=function(o,e,t,i,s,r=null,n=0){o._bufferViewArray=e,o.format=t,o.type=i,o.invertY=s,o._compression=r;const a=this._gl,h=this._getWebGLTextureType(i);let l=this._getInternalFormat(t);const c=this._getRGBABufferInternalSizedFormat(i);let u=!1;l===a.RGB&&(l=a.RGBA,u=!0),this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,o,!0),this._unpackFlipY(s===void 0?!0:!!s),o.width%4!==0&&a.pixelStorei(a.UNPACK_ALIGNMENT,1);for(let d=0;d<6;d++){let _=e[d];r?a.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+d,n,this.getCaps().s3tc[r],o.width,o.height,0,_):(u&&(_=Fl(_,o.width,o.height,i)),a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+d,n,c,o.width,o.height,0,l,h,_))}(!this.needPOTTextures||Xs(o.width)&&Xs(o.height))&&o.generateMipMaps&&n===0&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),o.isReady=!0};Ie.prototype.createRawCubeTextureFromUrl=function(o,e,t,i,s,r,n,a,h=null,l=null,c=3,u=!1){const f=this._gl,d=this.createRawCubeTexture(null,t,i,s,!r,u,c,null);e?.addPendingData(d),d.url=o,d.isReady=!1,this._internalTexturesCache.push(d);const _=(g,T)=>{e?.removePendingData(d),l&&l(g?g.status+" "+g.statusText:"Failed to parse texture data",T)},m=async g=>{if(!d._hardwareTexture)return;const T=n(g);if(!T)return;const R=T instanceof Promise?await T:T,A=d.width;if(a){const y=this._getWebGLTextureType(s);let E=this._getInternalFormat(i);const x=this._getRGBABufferInternalSizedFormat(s);let b=!1;E===f.RGB&&(E=f.RGBA,b=!0),this._bindTextureDirectly(f.TEXTURE_CUBE_MAP,d,!0),this._unpackFlipY(!1);const P=a(R);for(let v=0;v<P.length;v++){const O=A>>v;for(let k=0;k<6;k++){let Y=P[v][k];b&&(Y=Fl(Y,O,O,s)),f.texImage2D(k,v,x,O,O,0,E,y,Y)}}this._bindTextureDirectly(f.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(d,R,i,s,u);d.isReady=!0,e?.removePendingData(d),d.onLoadedObservable.notifyObservers(d),d.onLoadedObservable.clear(),h&&h()};return this._loadFile(o,g=>{m(g).catch(T=>{_(void 0,T)})},void 0,e?.offlineProvider,!0,_),d};function Fl(o,e,t,i){let s,r=1;i===1?s=new Float32Array(e*t*4):i===2?(s=new Uint16Array(e*t*4),r=15360):i===7?s=new Uint32Array(e*t*4):s=new Uint8Array(e*t*4);for(let n=0;n<e;n++)for(let a=0;a<t;a++){const h=(a*e+n)*3,l=(a*e+n)*4;s[l+0]=o[h+0],s[l+1]=o[h+1],s[l+2]=o[h+2],s[l+3]=r}return s}function wl(o){return function(e,t,i,s,r,n,a,h,l=null,c=0){const u=o?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,f=o?10:11,d=new xt(this,f);d.baseWidth=t,d.baseHeight=i,d.baseDepth=s,d.width=t,d.height=i,d.depth=s,d.format=r,d.type=c,d.generateMipMaps=n,d.samplingMode=h,o?d.is3D=!0:d.is2DArray=!0,this._doNotHandleContextLost||(d._bufferView=e),o?this.updateRawTexture3D(d,e,r,a,l,c):this.updateRawTexture2DArray(d,e,r,a,l,c),this._bindTextureDirectly(u,d,!0);const _=this._getSamplingParameters(h,n);return this._gl.texParameteri(u,this._gl.TEXTURE_MAG_FILTER,_.mag),this._gl.texParameteri(u,this._gl.TEXTURE_MIN_FILTER,_.min),n&&this._gl.generateMipmap(u),this._bindTextureDirectly(u,null),this._internalTexturesCache.push(d),d}}Ie.prototype.createRawTexture2DArray=wl(!1);Ie.prototype.createRawTexture3D=wl(!0);function Ll(o){return function(e,t,i,s,r=null,n=0){const a=o?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,h=this._getWebGLTextureType(n),l=this._getInternalFormat(i),c=this._getRGBABufferInternalSizedFormat(n,i);this._bindTextureDirectly(a,e,!0),this._unpackFlipY(s===void 0?!0:!!s),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r),e.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&t?this._gl.compressedTexImage3D(a,0,this.getCaps().s3tc[r],e.width,e.height,e.depth,0,t):this._gl.texImage3D(a,0,c,e.width,e.height,e.depth,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(a),this._bindTextureDirectly(a,null),e.isReady=!0}}Ie.prototype.updateRawTexture2DArray=Ll(!1);Ie.prototype.updateRawTexture3D=Ll(!0);Ie.prototype._readTexturePixelsSync=function(o,e,t,i=-1,s=0,r=null,n=!0,a=!1,h=0,l=0){const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const f=c.createFramebuffer();if(!f)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=f}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),i>-1&&(o.is2DArray||o.is3D)?c.framebufferTextureLayer(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,o._hardwareTexture?.underlyingResource,s,i):i>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+i,o._hardwareTexture?.underlyingResource,s):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,o._hardwareTexture?.underlyingResource,s);let u=o.type!==void 0?this._getWebGLTextureType(o.type):c.UNSIGNED_BYTE;if(a)r||(r=wu(o.type,4*e*t));else switch(u){case c.UNSIGNED_BYTE:r||(r=new Uint8Array(4*e*t)),u=c.UNSIGNED_BYTE;break;default:r||(r=new Float32Array(4*e*t)),u=c.FLOAT;break}return n&&this.flushFramebuffer(),c.readPixels(h,l,e,t,c.RGBA,u,r),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),r};Ie.prototype._readTexturePixels=function(o,e,t,i=-1,s=0,r=null,n=!0,a=!1,h=0,l=0){return Promise.resolve(this._readTexturePixelsSync(o,e,t,i,s,r,n,a,h,l))};Ie.prototype.updateDynamicIndexBuffer=function(o,e,t=0){this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(o);let i;o.is32Bits?i=e instanceof Uint32Array?e:new Uint32Array(e):i=e instanceof Uint16Array?e:new Uint16Array(e),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,i,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()};Ie.prototype.updateDynamicVertexBuffer=function(o,e,t,i){this.bindArrayBuffer(o),t===void 0&&(t=0);const s=e.byteLength||e.length;i===void 0||i>=s&&t===0?e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,new Float32Array(e)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,e):e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,new Float32Array(e).subarray(0,i/4)):(ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,i):e=new Uint8Array(e,0,i),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,e)),this._resetVertexBufferBinding()};Ie.prototype._createDepthStencilCubeTexture=function(o,e){const t=new xt(this,12);if(t.isCube=!0,this.webGLVersion===1)return W.Error("Depth cube texture is not supported by WebGL 1."),t;const i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e},s=this._gl;this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,t,!0),this._setupDepthStencilTexture(t,o,i.bilinearFiltering,i.comparisonFunction);for(let r=0;r<6;r++)i.generateStencil?s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+r,0,s.DEPTH24_STENCIL8,o,o,0,s.DEPTH_STENCIL,s.UNSIGNED_INT_24_8,null):s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+r,0,s.DEPTH_COMPONENT24,o,o,0,s.DEPTH_COMPONENT,s.UNSIGNED_INT,null);return this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(t),t};Ie.prototype._setCubeMapTextureParams=function(o,e,t){const i=this._gl;i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MIN_FILTER,e?i.LINEAR_MIPMAP_LINEAR:i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),o.samplingMode=e?3:2,e&&this.getCaps().textureMaxLevel&&t!==void 0&&t>0&&(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAX_LEVEL,t),o._maxLodLevel=t),this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)};Ie.prototype.createCubeTexture=function(o,e,t,i,s=null,r=null,n,a=null,h=!1,l=0,c=0,u=null,f,d=!1,_=null){const m=this._gl;return this.createCubeTextureBase(o,e,t,!!i,s,r,n,a,h,l,c,u,g=>this._bindTextureDirectly(m.TEXTURE_CUBE_MAP,g,!0),(g,T)=>{const R=this.needPOTTextures?ni(T[0].width,this._caps.maxCubemapTextureSize):T[0].width,A=R,y=[m.TEXTURE_CUBE_MAP_POSITIVE_X,m.TEXTURE_CUBE_MAP_POSITIVE_Y,m.TEXTURE_CUBE_MAP_POSITIVE_Z,m.TEXTURE_CUBE_MAP_NEGATIVE_X,m.TEXTURE_CUBE_MAP_NEGATIVE_Y,m.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(m.TEXTURE_CUBE_MAP,g,!0),this._unpackFlipY(!1);const E=n?this._getInternalFormat(n,g._useSRGBBuffer):g._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:m.RGBA;let x=n?this._getInternalFormat(n):m.RGBA;g._useSRGBBuffer&&this.webGLVersion===1&&(x=E);for(let b=0;b<y.length;b++)if(T[b].width!==R||T[b].height!==A){if(this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext){W.Warn("Cannot create canvas to resize texture.");return}this._workingCanvas.width=R,this._workingCanvas.height=A,this._workingContext.drawImage(T[b],0,0,T[b].width,T[b].height,0,0,R,A),m.texImage2D(y[b],0,E,x,m.UNSIGNED_BYTE,this._workingCanvas)}else m.texImage2D(y[b],0,E,x,m.UNSIGNED_BYTE,T[b]);i||m.generateMipmap(m.TEXTURE_CUBE_MAP),this._setCubeMapTextureParams(g,!i),g.width=R,g.height=A,g.isReady=!0,n&&(g.format=n),g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear(),s&&s()},!!d,_)};Ie.prototype.generateMipMapsForCubemap=function(o,e=!0){if(o.generateMipMaps){const t=this._gl;this._bindTextureDirectly(t.TEXTURE_CUBE_MAP,o,!0),t.generateMipmap(t.TEXTURE_CUBE_MAP),e&&this._bindTextureDirectly(t.TEXTURE_CUBE_MAP,null)}};class od{get depthStencilTexture(){return this._depthStencilTexture}setDepthStencilTexture(e,t=!0){t&&this._depthStencilTexture&&this._depthStencilTexture.dispose(),this._depthStencilTexture=e,this._generateDepthBuffer=this._generateStencilBuffer=this._depthStencilTextureWithStencil=!1,e&&(this._generateDepthBuffer=!0,this._generateStencilBuffer=this._depthStencilTextureWithStencil=er(e.format))}get depthStencilTextureWithStencil(){return this._depthStencilTextureWithStencil}get isCube(){return this._isCube}get isMulti(){return this._isMulti}get is2DArray(){return this.layers>0}get is3D(){return this.depth>0}get size(){return this.width}get width(){return this._size.width??this._size}get height(){return this._size.height??this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){return this._textures?.[0]??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}getBaseArrayLayer(e){if(!this._textures)return-1;const t=this._textures[e],i=this._layerIndices?.[e]??0,s=this._faceIndices?.[e]??0;return t.isCube?i*6+s:t.is3D?0:i}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}resolveMSAATextures(){this.isMulti?this._engine.resolveMultiFramebuffer(this):this._engine.resolveFramebuffer(this)}generateMipMaps(){this._engine._currentRenderTarget===this&&(this.isMulti?this._engine.unBindMultiColorAttachmentFramebuffer(this,!0):this._engine.unBindFramebuffer(this,!0)),this.isMulti?this._engine.generateMipMapsMultiFramebuffer(this):this._engine.generateMipMapsFramebuffer(this)}constructor(e,t,i,s,r){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this.disableAutomaticMSAAResolve=!1,this.resolveMSAAColors=!0,this.resolveMSAADepth=!1,this.resolveMSAAStencil=!1,this.depthReadOnly=!1,this.stencilReadOnly=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=s,this._depthStencilTexture=null,this.label=r}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),t!==void 0&&t>=0&&(this._layerIndices[e]=t),i!==void 0&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){return this._depthStencilTexture?.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:s,depthTextureFormat:r,label:n},this),this._depthStencilTexture}_shareDepth(e){this.shareDepth(e)}shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){let e=null;if(this._isMulti){const t=this.textures;if(t&&t.length>0){let i=!1,s=t.length,r=-1;const n=t[t.length-1]._source;(n===14||n===12)&&(i=!0,r=t[t.length-1].format,s--);const a=[],h=[],l=[],c=[],u=[],f=[],d=[],_={};for(let T=0;T<s;++T){const R=t[T];a.push(R.samplingMode),h.push(R.type),l.push(R.format),_[R.uniqueId]!==void 0?(c.push(-1),d.push(0)):(_[R.uniqueId]=T,R.is2DArray?(c.push(35866),d.push(R.depth)):R.isCube?(c.push(34067),d.push(0)):R.is3D?(c.push(32879),d.push(R.depth)):(c.push(3553),d.push(0))),this._faceIndices&&u.push(this._faceIndices[T]??0),this._layerIndices&&f.push(this._layerIndices[T]??0)}const m={samplingModes:a,generateMipMaps:t[0].generateMipMaps,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:this._generateStencilBuffer,generateDepthTexture:i,depthTextureFormat:r,types:h,formats:l,textureCount:s,targetTypes:c,faceIndex:u,layerIndex:f,layerCounts:d,label:this.label},g={width:this.width,height:this.height,depth:this.depth};e=this._engine.createMultipleRenderTarget(g,m);for(let T=0;T<s;++T){if(c[T]!==-1)continue;const R=_[t[T].uniqueId];e.setTexture(e.textures[R],T)}}}else{const t={};if(t.generateDepthBuffer=this._generateDepthBuffer,t.generateMipMaps=this.texture?.generateMipMaps??!1,t.generateStencilBuffer=this._generateStencilBuffer,t.samplingMode=this.texture?.samplingMode,t.type=this.texture?.type,t.format=this.texture?.format,t.noColorAttachment=!this._textures,t.label=this.label,this.isCube)e=this._engine.createRenderTargetCubeTexture(this.width,t);else{const i={width:this.width,height:this.height,layers:this.is2DArray||this.is3D?this.texture?.depth:void 0};e=this._engine.createRenderTargetTexture(i,t)}e.texture&&(e.texture.isReady=!0)}return e}_swapRenderTargetWrapper(e){if(this._textures&&e._textures)for(let t=0;t<this._textures.length;++t)this._textures[t]._swapAndDie(e._textures[t],!1),e._textures[t].isReady=!0;this._depthStencilTexture&&e._depthStencilTexture&&(this._depthStencilTexture._swapAndDie(e._depthStencilTexture),e._depthStencilTexture.isReady=!0),this._textures=null,this._depthStencilTexture=null}_rebuild(){const e=this._cloneRenderTargetWrapper();if(e){if(this._depthStencilTexture){const t=this._depthStencilTexture.samplingMode,i=this._depthStencilTexture.format,s=t===2||t===3||t===11;e.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction,s,this._depthStencilTextureWithStencil,this._depthStencilTexture.samples,i,this._depthStencilTextureLabel)}this.samples>1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e<this._textures.length;++e)this._textures[e].dispose();this._textures=null}dispose(e=!1){e||(this._depthStencilTexture?.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class hd extends od{setDepthStencilTexture(e,t=!0){if(super.setDepthStencilTexture(e,t),!e)return;const i=this._engine,s=this._context,r=e._hardwareTexture;if(r&&e._autoMSAAManagement&&this._MSAAFramebuffer){const n=i._currentFramebuffer;i._bindUnboundFramebuffer(this._MSAAFramebuffer),s.framebufferRenderbuffer(s.FRAMEBUFFER,er(e.format)?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,s.RENDERBUFFER,r.getMSAARenderBuffer()),i._bindUnboundFramebuffer(n)}}constructor(e,t,i,s,r){super(e,t,i,s),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=r}_cloneRenderTargetWrapper(){let e;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height),e.texture.isReady=!0):e=super._cloneRenderTargetWrapper(),e}_swapRenderTargetWrapper(e){super._swapRenderTargetWrapper(e),e._framebuffer=this._framebuffer,e._depthStencilBuffer=this._depthStencilBuffer,e._MSAAFramebuffer=this._MSAAFramebuffer,e._colorTextureArray=this._colorTextureArray,e._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){if(this._depthStencilBuffer){const a=this._engine,h=a._currentFramebuffer,l=this._context;a._bindUnboundFramebuffer(this._framebuffer),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.DEPTH_STENCIL_ATTACHMENT,l.RENDERBUFFER,null),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.DEPTH_ATTACHMENT,l.RENDERBUFFER,null),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.STENCIL_ATTACHMENT,l.RENDERBUFFER,null),a._bindUnboundFramebuffer(h),l.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null}return super.createDepthStencilTexture(e,t,i,s,r,n)}shareDepth(e){super.shareDepth(e);const t=this._context,i=this._depthStencilBuffer,s=e._MSAAFramebuffer||e._framebuffer,r=this._engine;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;const n=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;r._bindUnboundFramebuffer(s),t.framebufferRenderbuffer(t.FRAMEBUFFER,n,t.RENDERBUFFER,i),r._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,s=0){const r=e._hardwareTexture;if(!r)return;const n=this._framebuffer,a=this._engine,h=a._currentFramebuffer;a._bindUnboundFramebuffer(n);let l;if(a.webGLVersion>1){const c=this._context;l=c["COLOR_ATTACHMENT"+t],e.is2DArray||e.is3D?(i=i??this.layerIndices?.[t]??0,c.framebufferTextureLayer(c.FRAMEBUFFER,l,r.underlyingResource,s,i)):e.isCube?(i=i??this.faceIndices?.[t]??0,c.framebufferTexture2D(c.FRAMEBUFFER,l,c.TEXTURE_CUBE_MAP_POSITIVE_X+i,r.underlyingResource,s)):c.framebufferTexture2D(c.FRAMEBUFFER,l,c.TEXTURE_2D,r.underlyingResource,s)}else{const c=this._context;l=c["COLOR_ATTACHMENT"+t+"_WEBGL"];const u=i!==void 0?c.TEXTURE_CUBE_MAP_POSITIVE_X+i:c.TEXTURE_2D;c.framebufferTexture2D(c.FRAMEBUFFER,l,u,r.underlyingResource,s)}if(e._autoMSAAManagement&&this._MSAAFramebuffer){const c=this._context;a._bindUnboundFramebuffer(this._MSAAFramebuffer),c.framebufferRenderbuffer(c.FRAMEBUFFER,l,c.RENDERBUFFER,r.getMSAARenderBuffer())}a._bindUnboundFramebuffer(h)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=this._attachments?.length??this.textures.length;for(let s=0;s<i;s++){const r=this.textures[s];r&&(r.is2DArray||r.is3D?this._bindTextureRenderTarget(r,s,this.layerIndices[s]):r.isCube?this._bindTextureRenderTarget(r,s,this.faceIndices[s]):this._bindTextureRenderTarget(r,s))}}setLayerAndFaceIndex(e=0,t,i){if(super.setLayerAndFaceIndex(e,t,i),!this.textures||!this.layerIndices||!this.faceIndices)return;const s=this.textures[e];s.is2DArray||s.is3D?this._bindTextureRenderTarget(this.textures[e],e,this.layerIndices[e]):s.isCube&&this._bindTextureRenderTarget(this.textures[e],e,this.faceIndices[e])}resolveMSAATextures(){const e=this._engine,t=e._currentFramebuffer;e._bindUnboundFramebuffer(this._MSAAFramebuffer),super.resolveMSAATextures(),e._bindUnboundFramebuffer(t)}dispose(e=this._disposeOnlyFramebuffers){const t=this._context;e||(this._colorTextureArray&&(this._context.deleteTexture(this._colorTextureArray),this._colorTextureArray=null),this._depthStencilTextureArray&&(this._context.deleteTexture(this._depthStencilTextureArray),this._depthStencilTextureArray=null)),this._framebuffer&&(t.deleteFramebuffer(this._framebuffer),this._framebuffer=null),this._depthStencilBuffer&&(t.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null),this._MSAAFramebuffer&&(t.deleteFramebuffer(this._MSAAFramebuffer),this._MSAAFramebuffer=null),super.dispose(e)}}J.prototype.createDepthStencilTexture=function(o,e,t){if(e.isCube){const i=o.width||o;return this._createDepthStencilCubeTexture(i,e)}else return this._createDepthStencilTexture(o,e,t)};Ie.prototype._createHardwareRenderTargetWrapper=function(o,e,t){const i=new hd(o,e,t,this,this._gl);return this._renderTargetWrapperCache.push(i),i};Ie.prototype.createRenderTargetTexture=function(o,e){const t=this._createHardwareRenderTargetWrapper(!1,!1,o);let i=!0,s=!1,r=!1,n,a=1,h;e!==void 0&&typeof e=="object"&&(i=e.generateDepthBuffer??!0,s=!!e.generateStencilBuffer,r=!!e.noColorAttachment,n=e.colorAttachment,a=e.samples??1,h=e.label);const l=n||(r?null:this._createInternalTexture(o,e,!0,5)),c=o.width||o,u=o.height||o,f=this._currentFramebuffer,d=this._gl,_=d.createFramebuffer();if(this._bindUnboundFramebuffer(_),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(s,i,c,u),l&&!l.is2DArray&&!l.is3D&&d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,l._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(f),t.label=h??"RenderTargetWrapper",t._framebuffer=_,t._generateDepthBuffer=i,t._generateStencilBuffer=s,t.setTextures(l),!n)this.updateRenderTargetTextureSampleCount(t,a);else if(t._samples=n.samples,n.samples>1){const m=n._hardwareTexture.getMSAARenderBuffer(0);t._MSAAFramebuffer=d.createFramebuffer(),this._bindUnboundFramebuffer(t._MSAAFramebuffer),d.framebufferRenderbuffer(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.RENDERBUFFER,m),this._bindUnboundFramebuffer(null)}return t};Ie.prototype._createDepthStencilTexture=function(o,e,t){const i=this._gl,s=o.layers||0,r=o.depth||0;let n=i.TEXTURE_2D;s!==0?n=i.TEXTURE_2D_ARRAY:r!==0&&(n=i.TEXTURE_3D);const a=new xt(this,12);if(a.label=e.label,!this._caps.depthTextureExtension)return W.Error("Depth texture is not supported by your browser or hardware."),a;const h={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e};if(this._bindTextureDirectly(n,a,!0),this._setupDepthStencilTexture(a,o,h.comparisonFunction===0?!1:h.bilinearFiltering,h.comparisonFunction,h.samples),h.depthTextureFormat!==void 0){if(h.depthTextureFormat!==15&&h.depthTextureFormat!==16&&h.depthTextureFormat!==17&&h.depthTextureFormat!==13&&h.depthTextureFormat!==14&&h.depthTextureFormat!==18)return W.Error(`Depth texture ${h.depthTextureFormat} format is not supported.`),a;a.format=h.depthTextureFormat}else a.format=h.generateStencil?13:16;const l=er(a.format),c=this._getWebGLTextureTypeFromDepthTextureFormat(a.format),u=l?i.DEPTH_STENCIL:i.DEPTH_COMPONENT,f=this._getInternalFormatFromDepthTextureFormat(a.format,!0,l);return a.is2DArray?i.texImage3D(n,0,f,a.width,a.height,s,0,u,c,null):a.is3D?i.texImage3D(n,0,f,a.width,a.height,r,0,u,c,null):i.texImage2D(n,0,f,a.width,a.height,0,u,c,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(a),t._depthStencilBuffer&&(i.deleteRenderbuffer(t._depthStencilBuffer),t._depthStencilBuffer=null),this._bindUnboundFramebuffer(t._MSAAFramebuffer??t._framebuffer),t._generateStencilBuffer=l,t._depthStencilTextureWithStencil=l,t._depthStencilBuffer=this._setupFramebufferDepthAttachments(t._generateStencilBuffer,t._generateDepthBuffer,t.width,t.height,t.samples,a.format),this._bindUnboundFramebuffer(null),a};Ie.prototype.updateRenderTargetTextureSampleCount=function(o,e){if(this.webGLVersion<2||!o)return 1;if(o.samples===e)return e;const t=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),o._depthStencilBuffer&&(t.deleteRenderbuffer(o._depthStencilBuffer),o._depthStencilBuffer=null),o._MSAAFramebuffer&&(t.deleteFramebuffer(o._MSAAFramebuffer),o._MSAAFramebuffer=null);const i=o.texture?._hardwareTexture;if(i?.releaseMSAARenderBuffers(),o.texture&&e>1&&typeof t.renderbufferStorageMultisample=="function"){const r=t.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");o._MSAAFramebuffer=r,this._bindUnboundFramebuffer(o._MSAAFramebuffer);const n=this._createRenderBuffer(o.texture.width,o.texture.height,e,-1,this._getRGBABufferInternalSizedFormat(o.texture.type,o.texture.format,o.texture._useSRGBBuffer),t.COLOR_ATTACHMENT0,!1);if(!n)throw new Error("Unable to create multi sampled framebuffer");i?.addMSAARenderBuffer(n)}this._bindUnboundFramebuffer(o._MSAAFramebuffer??o._framebuffer),o.texture&&(o.texture.samples=e),o._samples=e;const s=o._depthStencilTexture?o._depthStencilTexture.format:void 0;return o._depthStencilBuffer=this._setupFramebufferDepthAttachments(o._generateStencilBuffer,o._generateDepthBuffer,o.width,o.height,e,s),this._bindUnboundFramebuffer(null),e};Ie.prototype._setupDepthStencilTexture=function(o,e,t,i,s=1){const r=e.width??e,n=e.height??e,a=e.layers||0,h=e.depth||0;o.baseWidth=r,o.baseHeight=n,o.width=r,o.height=n,o.is2DArray=a>0,o.depth=a||h,o.isReady=!0,o.samples=s,o.generateMipMaps=!1,o.samplingMode=t?2:1,o.type=0,o._comparisonFunction=i;const l=this._gl,c=this._getTextureTarget(o),u=this._getSamplingParameters(o.samplingMode,!1);l.texParameteri(c,l.TEXTURE_MAG_FILTER,u.mag),l.texParameteri(c,l.TEXTURE_MIN_FILTER,u.min),l.texParameteri(c,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(c,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this.webGLVersion>1&&(i===0?(l.texParameteri(c,l.TEXTURE_COMPARE_FUNC,515),l.texParameteri(c,l.TEXTURE_COMPARE_MODE,l.NONE)):(l.texParameteri(c,l.TEXTURE_COMPARE_FUNC,i),l.texParameteri(c,l.TEXTURE_COMPARE_MODE,l.COMPARE_REF_TO_TEXTURE)))};Ie.prototype.setDepthStencilTexture=function(o,e,t,i){o!==void 0&&(e&&(this._boundUniforms[o]=e),!t||!t.depthStencilTexture?this._setTexture(o,null,void 0,void 0,i):this._setTexture(o,t,!1,!0,i))};Ie.prototype.createRenderTargetCubeTexture=function(o,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,o),i={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...e};i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,(i.type===1&&!this._caps.textureFloatLinearFiltering||i.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(i.samplingMode=1);const s=this._gl,r=new xt(this,5);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,r,!0);const n=this._getSamplingParameters(i.samplingMode,i.generateMipMaps);i.type===1&&!this._caps.textureFloat&&(i.type=0,W.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,n.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,n.min),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);for(let h=0;h<6;h++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+h,0,this._getRGBABufferInternalSizedFormat(i.type,i.format),o,o,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);const a=s.createFramebuffer();return this._bindUnboundFramebuffer(a),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,o,o),i.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),t._framebuffer=a,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer,r.width=o,r.height=o,r.isReady=!0,r.isCube=!0,r.samples=1,r.generateMipMaps=i.generateMipMaps,r.samplingMode=i.samplingMode,r.type=i.type,r.format=i.format,this._internalTexturesCache.push(r),t.setTextures(r),t};Ie.prototype.createPrefilteredCubeTexture=function(o,e,t,i,s=null,r=null,n,a=null,h=!0){const l=async c=>{if(!c){s&&s(null);return}const u=c.texture;if(h?c.info.sphericalPolynomial&&(u._sphericalPolynomial=c.info.sphericalPolynomial):u._sphericalPolynomial=u._sphericalPolynomial??new Ts,u._source=9,this.getCaps().textureLOD){s&&s(u);return}const f=3,d=this._gl,_=c.width;if(!_)return;const{DDSTools:m}=await he(async()=>{const{DDSTools:T}=await import("./dds-3J0FZYX1.js");return{DDSTools:T}},[],import.meta.url),g=[];for(let T=0;T<f;T++){const A=1-T/(f-1),y=i,E=Math.log2(_)*t+i,x=y+(E-y)*A,b=Math.round(Math.min(Math.max(x,0),E)),P=new xt(this,2);if(P.type=u.type,P.format=u.format,P.width=Math.pow(2,Math.max(Math.log2(_)-b,0)),P.height=P.width,P.isCube=!0,P._cachedWrapU=0,P._cachedWrapV=0,this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,P,!0),P.samplingMode=2,d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_MAG_FILTER,d.LINEAR),d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_MIN_FILTER,d.LINEAR),d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),c.isDDS){const O=c.info,k=c.data;this._unpackFlipY(O.isCompressed),m.UploadDDSLevels(this,P,k,O,!0,6,b)}else W.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null);const v=new Ve(e);v._isCube=!0,v._texture=P,P.isReady=!0,g.push(v)}u._lodTextureHigh=g[2],u._lodTextureMid=g[1],u._lodTextureLow=g[0],s&&s(u)};return this.createCubeTexture(o,e,null,!1,l,r,n,a,h,t,i)};Ie.prototype.createUniformBuffer=function(o,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");const i=new Js(t);return this.bindUniformBuffer(i),o instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,o,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(o),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};Ie.prototype.createDynamicUniformBuffer=function(o,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");const i=new Js(t);return this.bindUniformBuffer(i),o instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,o,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(o),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};Ie.prototype.updateUniformBuffer=function(o,e,t,i){this.bindUniformBuffer(o),t===void 0&&(t=0),i===void 0?e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,e):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,new Float32Array(e)):e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,e.subarray(t,t+i)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(e).subarray(t,t+i)),this.bindUniformBuffer(null)};Ie.prototype.bindUniformBuffer=function(o){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,o?o.underlyingResource:null)};Ie.prototype.bindUniformBufferBase=function(o,e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,e,o?o.underlyingResource:null)};Ie.prototype.bindUniformBlock=function(o,e,t){const i=o.program,s=this._gl.getUniformBlockIndex(i,e);s!==4294967295&&this._gl.uniformBlockBinding(i,s,t)};J.prototype.displayLoadingUI=function(){if(!mt())return;const o=this.loadingScreen;o&&o.displayLoadingUI()};J.prototype.hideLoadingUI=function(){if(!mt())return;const o=this._loadingScreen;o&&o.hideLoadingUI()};Object.defineProperty(J.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=J.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(o){this._loadingScreen=o},enumerable:!0,configurable:!0});Object.defineProperty(J.prototype,"loadingUIText",{set:function(o){this.loadingScreen.loadingUIText=o},enumerable:!0,configurable:!0});Object.defineProperty(J.prototype,"loadingUIBackgroundColor",{set:function(o){this.loadingScreen.loadingUIBackgroundColor=o},enumerable:!0,configurable:!0});J.prototype.getInputElement=function(){return this._renderingCanvas};J.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null};J.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null};J.prototype.getAspectRatio=function(o,e=!1){const t=o.viewport;return this.getRenderWidth(e)*t.width/(this.getRenderHeight(e)*t.height)};J.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)};J.prototype._verifyPointerLock=function(){this._onPointerLockChange?.()};J.prototype.setAlphaEquation=function(o,e=0){if(this._alphaEquation[e]!==o){switch(o){case 0:this._alphaState.setAlphaEquationParameters(32774,32774,e);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778,e);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779,e);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776,e);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775,e);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774,e);break}this._alphaEquation[e]=o}};J.prototype.getInputElement=function(){return this._renderingCanvas};J.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc};J.prototype.setDepthFunction=function(o){this._depthCullingState.depthFunc=o};J.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)};J.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)};J.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)};J.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)};J.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask};J.prototype.setDepthWrite=function(o){this._depthCullingState.depthMask=o};J.prototype.setAlphaConstants=function(o,e,t,i){this._alphaState.setAlphaBlendConstants(o,e,t,i)};J.prototype.getAlphaMode=function(o=0){return this._alphaMode[o]};J.prototype.getAlphaEquation=function(o=0){return this._alphaEquation[o]};J.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest};J.prototype.setStencilBuffer=function(o){this._stencilState.stencilTest=o};J.prototype.getStencilMask=function(){return this._stencilState.stencilMask};J.prototype.setStencilMask=function(o){this._stencilState.stencilMask=o};J.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc};J.prototype.getStencilBackFunction=function(){return this._stencilState.stencilBackFunc};J.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef};J.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask};J.prototype.setStencilFunction=function(o){this._stencilState.stencilFunc=o};J.prototype.setStencilBackFunction=function(o){this._stencilState.stencilBackFunc=o};J.prototype.setStencilFunctionReference=function(o){this._stencilState.stencilFuncRef=o};J.prototype.setStencilFunctionMask=function(o){this._stencilState.stencilFuncMask=o};J.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail};J.prototype.getStencilBackOperationFail=function(){return this._stencilState.stencilBackOpStencilFail};J.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail};J.prototype.getStencilBackOperationDepthFail=function(){return this._stencilState.stencilBackOpDepthFail};J.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass};J.prototype.getStencilBackOperationPass=function(){return this._stencilState.stencilBackOpStencilDepthPass};J.prototype.setStencilOperationFail=function(o){this._stencilState.stencilOpStencilFail=o};J.prototype.setStencilBackOperationFail=function(o){this._stencilState.stencilBackOpStencilFail=o};J.prototype.setStencilOperationDepthFail=function(o){this._stencilState.stencilOpDepthFail=o};J.prototype.setStencilBackOperationDepthFail=function(o){this._stencilState.stencilBackOpDepthFail=o};J.prototype.setStencilOperationPass=function(o){this._stencilState.stencilOpStencilDepthPass=o};J.prototype.setStencilBackOperationPass=function(o){this._stencilState.stencilBackOpStencilDepthPass=o};J.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()};J.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)};J.prototype.getRenderPassNames=function(){return this._renderPassNames};J.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]};J.prototype.createRenderPassId=function(o){const e=++J._RenderPassIdCounter;return this._renderPassNames[e]=o??"NONAME",e};J.prototype.releaseRenderPassId=function(o){this._renderPassNames[o]=void 0;for(let e=0;e<this.scenes.length;++e){const t=this.scenes[e];for(let i=0;i<t.meshes.length;++i){const s=t.meshes[i];if(s._releaseRenderPassId(o),s.subMeshes)for(let r=0;r<s.subMeshes.length;++r)s.subMeshes[r]._removeDrawWrapper(o)}}};J.prototype._loadFileAsync=async function(o,e,t){return await new Promise((i,s)=>{this._loadFile(o,r=>{i(r)},void 0,e,t,(r,n)=>{s(n)})})};J.GetCompatibleTextureLoader=bl;function ld(o){!o||!o.setAttribute||(o.setAttribute("touch-action","none"),o.style.touchAction="none",o.style.webkitTapHighlightColor="transparent")}function cd(o,e,t){o._onCanvasFocus=()=>{o.onCanvasFocusObservable.notifyObservers(o)},o._onCanvasBlur=()=>{o.onCanvasBlurObservable.notifyObservers(o)},o._onCanvasContextMenu=s=>{o.disableContextMenu&&s.preventDefault()},e.addEventListener("focus",o._onCanvasFocus),e.addEventListener("blur",o._onCanvasBlur),e.addEventListener("contextmenu",o._onCanvasContextMenu),o._onBlur=()=>{o.disablePerformanceMonitorInBackground&&o.performanceMonitor.disable(),o._windowIsBackground=!0},o._onFocus=()=>{o.disablePerformanceMonitorInBackground&&o.performanceMonitor.enable(),o._windowIsBackground=!1},o._onCanvasPointerOut=s=>{document.elementFromPoint(s.clientX,s.clientY)!==e&&o.onCanvasPointerOutObservable.notifyObservers(s)};const i=o.getHostWindow();i&&typeof i.addEventListener=="function"&&(i.addEventListener("blur",o._onBlur),i.addEventListener("focus",o._onFocus)),e.addEventListener("pointerout",o._onCanvasPointerOut),t.doNotHandleTouchAction||ld(e),!J.audioEngine&&t.audioEngine&&J.AudioEngineFactory&&(J.audioEngine=J.AudioEngineFactory(o.getRenderingCanvas(),o.getAudioContext(),o.getAudioDestination())),ls()&&(o._onFullscreenChange=()=>{o.isFullscreen=!!document.fullscreenElement,o.isFullscreen&&o._pointerLockRequested&&e&&Bl(e)},document.addEventListener("fullscreenchange",o._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",o._onFullscreenChange,!1),o._onPointerLockChange=()=>{o.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",o._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",o._onPointerLockChange,!1)),o.enableOfflineSupport=J.OfflineProviderFactory!==void 0,o._deterministicLockstep=!!t.deterministicLockstep,o._lockstepMaxSteps=t.lockstepMaxSteps||0,o._timeStep=t.timeStep||1/60}function ud(o,e){ye.Instances.length===1&&J.audioEngine&&(J.audioEngine.dispose(),J.audioEngine=null);const t=o.getHostWindow();t&&typeof t.removeEventListener=="function"&&(t.removeEventListener("blur",o._onBlur),t.removeEventListener("focus",o._onFocus)),e&&(e.removeEventListener("focus",o._onCanvasFocus),e.removeEventListener("blur",o._onCanvasBlur),e.removeEventListener("pointerout",o._onCanvasPointerOut),e.removeEventListener("contextmenu",o._onCanvasContextMenu)),ls()&&(document.removeEventListener("fullscreenchange",o._onFullscreenChange),document.removeEventListener("mozfullscreenchange",o._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",o._onFullscreenChange),document.removeEventListener("msfullscreenchange",o._onFullscreenChange),document.removeEventListener("pointerlockchange",o._onPointerLockChange),document.removeEventListener("mspointerlockchange",o._onPointerLockChange),document.removeEventListener("mozpointerlockchange",o._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",o._onPointerLockChange))}function fd(o){const e=document.createElement("span");e.textContent="Hg",e.style.font=o;const t=document.createElement("div");t.style.display="inline-block",t.style.width="1px",t.style.height="0px",t.style.verticalAlign="bottom";const i=document.createElement("div");i.style.whiteSpace="nowrap",i.appendChild(e),i.appendChild(t),document.body.appendChild(i);let s,r;try{r=t.getBoundingClientRect().top-e.getBoundingClientRect().top,t.style.verticalAlign="baseline",s=t.getBoundingClientRect().top-e.getBoundingClientRect().top}finally{document.body.removeChild(i)}return{ascent:s,height:r,descent:r-s}}async function dd(o,e,t){return await new Promise((i,s)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{o.createImageBitmap(r,t).then(n=>{i(n)})})},r.onerror=()=>{s(`Error loading image ${r.src}`)},r.src=e})}function _d(o,e,t,i){const r=o.createCanvas(t,i).getContext("2d");if(!r)throw new Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(e,0,0),r.getImageData(0,0,t,i).data}function gd(o){const e=o.requestFullscreen||o.webkitRequestFullscreen;e&&e.call(o)}function pd(){const o=document;document.exitFullscreen?document.exitFullscreen():o.webkitCancelFullScreen&&o.webkitCancelFullScreen()}function Bl(o){if(o.requestPointerLock){const e=o.requestPointerLock();e instanceof Promise?e.then(()=>{o.focus()}).catch(()=>{}):o.focus()}}function md(){document.exitPointerLock&&document.exitPointerLock()}class $ extends Ie{static get NpmPackage(){return J.NpmPackage}static get Version(){return J.Version}static get Instances(){return ye.Instances}static get LastCreatedEngine(){return ye.LastCreatedEngine}static get LastCreatedScene(){return ye.LastCreatedScene}static DefaultLoadingScreenFactory(e){return J.DefaultLoadingScreenFactory(e)}get _supportsHardwareTextureRescaling(){return!!$._RescalePostProcessFactory}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}get performanceMonitor(){return this._performanceMonitor}constructor(e,t,i,s=!1){super(e,t,i,s),this.customAnimationFrameRequester=null,this._performanceMonitor=new nd,this._drawCalls=new di,e&&(this._features.supportRenderPasses=!0)}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),cd(this,e,this._creationOptions)}resizeImageBitmap(e,t,i){return _d(this,e,t,i)}async _createImageBitmapFromSource(e,t){return await dd(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&gd(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&pd()}setDitheringState(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)}setRasterizerState(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)}setDirectViewport(e,t,i,s){const r=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,s),r}scissorClear(e,t,i,s,r){this.enableScissor(e,t,i,s),this.clear(r,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,s){const r=this._gl;r.enable(r.SCISSOR_TEST),r.scissor(e,t,i,s)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return fd(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(this._frameHandler!==0){this._frameHandler=0;const{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(e){this._processFrame(e),this._activeRenderLoops.length>0&&this._frameHandler===0&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}enterPointerlock(){this._renderingCanvas&&Bl(this._renderingCanvas)}exitPointerlock(){md()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){const t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,s,r,n=null){r=r||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const a=super.createShaderProgram(e,t,i,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),a}_createShaderProgram(e,t,i,s,r=null){const n=s.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");if(s.attachShader(n,t),s.attachShader(n,i),this.webGLVersion>1&&r){const a=this.createTransformFeedback();this.bindTransformFeedback(a),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=a}return s.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e);for(const t of this.scenes){for(const i of t.postProcesses)i._outputTexture===e&&(i._outputTexture=null);for(const i of t.cameras)for(const s of i._postProcesses)s&&s._outputTexture===e&&(s._outputTexture=null)}}_rescaleTexture(e,t,i,s,r){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);const n=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});if(!this._rescalePostProcess&&$._RescalePostProcessFactory&&(this._rescalePostProcess=$._RescalePostProcessFactory(this)),this._rescalePostProcess){this._rescalePostProcess.externalTextureSamplerBinding=!0;const a=()=>{this._rescalePostProcess.onApply=function(c){c._bindTexture("textureSampler",e)};let l=i;l||(l=this.scenes[this.scenes.length-1]),l.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()},h=this._rescalePostProcess.getEffect();h?h.executeWhenCompiled(a):this._rescalePostProcess.onEffectCreatedObservable.addOnce(l=>{l.executeWhenCompiled(a)})}}wrapWebGLTexture(e,t=!1,i=3,s=0,r=0){const n=new Ol(e,this._gl),a=new xt(this,0,!0);return a._hardwareTexture=n,a.baseWidth=s,a.baseHeight=r,a.width=s,a.height=r,a.isReady=!0,a.useMipMaps=t,this.updateTextureSamplingMode(i,a),a}_uploadImageToTexture(e,t,i=0,s=0){const r=this._gl,n=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),h=this._getRGBABufferInternalSizedFormat(e.type,a),l=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let c=r.TEXTURE_2D;e.isCube&&(c=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(c,s,h,a,n,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){W.Error("WebGL 1 does not support texture comparison.");return}const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),t===0?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),t===0?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");const i=new Js(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}async _clientWaitAsync(e,t=0,i=10){const s=this._gl;return await new Promise((r,n)=>{Yr(()=>{const a=s.clientWaitSync(e,t,0);if(a==s.WAIT_FAILED)throw new Error("clientWaitSync failed");return a!=s.TIMEOUT_EXPIRED},r,n,i)})}_readPixelsAsync(e,t,i,s,r,n,a){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const h=this._gl,l=h.createBuffer();h.bindBuffer(h.PIXEL_PACK_BUFFER,l),h.bufferData(h.PIXEL_PACK_BUFFER,a.byteLength,h.STREAM_READ),h.readPixels(e,t,i,s,r,n,0),h.bindBuffer(h.PIXEL_PACK_BUFFER,null);const c=h.fenceSync(h.SYNC_GPU_COMMANDS_COMPLETE,0);return c?(h.flush(),this._clientWaitAsync(c,0,10).then(()=>(h.deleteSync(c),h.bindBuffer(h.PIXEL_PACK_BUFFER,l),h.getBufferSubData(h.PIXEL_PACK_BUFFER,0,a),h.bindBuffer(h.PIXEL_PACK_BUFFER,null),h.deleteBuffer(l),a))):null}dispose(){this.hideLoadingUI(),this._rescalePostProcess&&this._rescalePostProcess.dispose(),ud(this,this._renderingCanvas),super.dispose()}}$.ALPHA_DISABLE=0;$.ALPHA_ADD=1;$.ALPHA_COMBINE=2;$.ALPHA_SUBTRACT=3;$.ALPHA_MULTIPLY=4;$.ALPHA_MAXIMIZED=5;$.ALPHA_ONEONE=6;$.ALPHA_PREMULTIPLIED=7;$.ALPHA_PREMULTIPLIED_PORTERDUFF=8;$.ALPHA_INTERPOLATE=9;$.ALPHA_SCREENMODE=10;$.DELAYLOADSTATE_NONE=0;$.DELAYLOADSTATE_LOADED=1;$.DELAYLOADSTATE_LOADING=2;$.DELAYLOADSTATE_NOTLOADED=4;$.NEVER=512;$.ALWAYS=519;$.LESS=513;$.EQUAL=514;$.LEQUAL=515;$.GREATER=516;$.GEQUAL=518;$.NOTEQUAL=517;$.KEEP=7680;$.REPLACE=7681;$.INCR=7682;$.DECR=7683;$.INVERT=5386;$.INCR_WRAP=34055;$.DECR_WRAP=34056;$.TEXTURE_CLAMP_ADDRESSMODE=0;$.TEXTURE_WRAP_ADDRESSMODE=1;$.TEXTURE_MIRROR_ADDRESSMODE=2;$.TEXTUREFORMAT_ALPHA=0;$.TEXTUREFORMAT_LUMINANCE=1;$.TEXTUREFORMAT_LUMINANCE_ALPHA=2;$.TEXTUREFORMAT_RGB=4;$.TEXTUREFORMAT_RGBA=5;$.TEXTUREFORMAT_RED=6;$.TEXTUREFORMAT_R=6;$.TEXTUREFORMAT_R16_UNORM=33322;$.TEXTUREFORMAT_RG16_UNORM=33324;$.TEXTUREFORMAT_RGB16_UNORM=32852;$.TEXTUREFORMAT_RGBA16_UNORM=32859;$.TEXTUREFORMAT_R16_SNORM=36760;$.TEXTUREFORMAT_RG16_SNORM=36761;$.TEXTUREFORMAT_RGB16_SNORM=36762;$.TEXTUREFORMAT_RGBA16_SNORM=36763;$.TEXTUREFORMAT_RG=7;$.TEXTUREFORMAT_RED_INTEGER=8;$.TEXTUREFORMAT_R_INTEGER=8;$.TEXTUREFORMAT_RG_INTEGER=9;$.TEXTUREFORMAT_RGB_INTEGER=10;$.TEXTUREFORMAT_RGBA_INTEGER=11;$.TEXTURETYPE_UNSIGNED_BYTE=0;$.TEXTURETYPE_UNSIGNED_INT=0;$.TEXTURETYPE_FLOAT=1;$.TEXTURETYPE_HALF_FLOAT=2;$.TEXTURETYPE_BYTE=3;$.TEXTURETYPE_SHORT=4;$.TEXTURETYPE_UNSIGNED_SHORT=5;$.TEXTURETYPE_INT=6;$.TEXTURETYPE_UNSIGNED_INTEGER=7;$.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;$.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;$.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;$.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;$.TEXTURETYPE_UNSIGNED_INT_24_8=12;$.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;$.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;$.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;$.TEXTURE_NEAREST_SAMPLINGMODE=1;$.TEXTURE_BILINEAR_SAMPLINGMODE=2;$.TEXTURE_TRILINEAR_SAMPLINGMODE=3;$.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;$.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;$.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;$.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;$.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;$.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;$.TEXTURE_NEAREST_LINEAR=7;$.TEXTURE_NEAREST_NEAREST=1;$.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;$.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;$.TEXTURE_LINEAR_LINEAR=2;$.TEXTURE_LINEAR_NEAREST=12;$.TEXTURE_EXPLICIT_MODE=0;$.TEXTURE_SPHERICAL_MODE=1;$.TEXTURE_PLANAR_MODE=2;$.TEXTURE_CUBIC_MODE=3;$.TEXTURE_PROJECTION_MODE=4;$.TEXTURE_SKYBOX_MODE=5;$.TEXTURE_INVCUBIC_MODE=6;$.TEXTURE_EQUIRECTANGULAR_MODE=7;$.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;$.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;$.SCALEMODE_FLOOR=1;$.SCALEMODE_NEAREST=2;$.SCALEMODE_CEILING=3;const Jp=Object.freeze(Object.defineProperty({__proto__:null,Engine:$},Symbol.toStringTag,{value:"Module"}));class Es extends Qe{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([he(()=>Promise.resolve().then(()=>I_),void 0,import.meta.url)]))):t.push(Promise.all([he(()=>Promise.resolve().then(()=>sc),void 0,import.meta.url)])),super._gatherImports(e,t)}constructor(e,t=null,i){const s={name:e,engine:t||$.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:Es.FragmentUrl,...i};s.engine||(s.engine=$.LastCreatedEngine),super(s)}}Es.FragmentUrl="pass";class Jr extends Qe{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([he(()=>import("./passCube.fragment-Ch6aeybh.js"),[],import.meta.url)]))):t.push(Promise.all([he(()=>import("./passCube.fragment-wvJ8mb6_.js"),[],import.meta.url)])),super._gatherImports(e,t)}constructor(e,t=null,i){super({...i,name:e,engine:t||$.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:Jr.FragmentUrl,defines:"#define POSITIVEX"}),this._face=0}get face(){return this._face}set face(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ");break}}}Jr.FragmentUrl="passCube";class lr extends Ne{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,r,n,a=0,h=!1){const l={size:typeof t=="number"?t:void 0,camera:i,samplingMode:s,engine:r,reusable:n,textureType:a,blockCompilation:h,...t};super(e,Es.FragmentUrl,{effectWrapper:typeof t=="number"||!t.effectWrapper?new Es(e,r,l):void 0,...l})}static _Parse(e,t,i,s){return me.Parse(()=>new lr(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,s)}}Ye("BABYLON.PassPostProcess",lr);class Qa extends Ne{get face(){return this._effectWrapper.face}set face(e){this._effectWrapper.face=e}getClassName(){return"PassCubePostProcess"}constructor(e,t,i=null,s,r,n,a=0,h=!1){const l={size:typeof t=="number"?t:void 0,camera:i,samplingMode:s,engine:r,reusable:n,textureType:a,blockCompilation:h,...t};super(e,Es.FragmentUrl,{effectWrapper:typeof t=="number"||!t.effectWrapper?new Jr(e,r,l):void 0,...l})}static _Parse(e,t,i,s){return me.Parse(()=>new Qa(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,s)}}M([C()],Qa.prototype,"face",null);J._RescalePostProcessFactory=o=>new lr("rescale",1,null,2,o,!1,0);function Td(o,e,t,i=!0){const s=o.getScene(),r=s.getEngine(),n=new yt("resized"+o.name,{width:e,height:t},s,!o.noMipmap,!0,o._texture.type,!1,o.samplingMode,!1);n.wrapU=o.wrapU,n.wrapV=o.wrapV,n.uOffset=o.uOffset,n.vOffset=o.vOffset,n.uScale=o.uScale,n.vScale=o.vScale,n.uAng=o.uAng,n.vAng=o.vAng,n.wAng=o.wAng,n.coordinatesIndex=o.coordinatesIndex,n.level=o.level,n.anisotropicFilteringLevel=o.anisotropicFilteringLevel,n._texture.isReady=!1,o.wrapU=G.CLAMP_ADDRESSMODE,o.wrapV=G.CLAMP_ADDRESSMODE;const a=new lr("pass",1,null,i?G.BILINEAR_SAMPLINGMODE:G.NEAREST_SAMPLINGMODE,r,!1,0);return a.externalTextureSamplerBinding=!0,a.onEffectCreatedObservable.addOnce(h=>{h.executeWhenCompiled(()=>{a.onApply=function(c){c.setTexture("textureSampler",o)};const l=n.renderTarget;l&&(s.postProcessManager.directRender([a],l),r.unBindFramebuffer(l),n.disposeFramebufferObjects(),a.dispose(),n.getInternalTexture().isReady=!0)})}),n}function Nl(o,e,t,i,s,r,n,a){const h=e.getEngine();return e.isReady=!1,s=s??e.samplingMode,i=i??e.type,r=r??e.format,n=n??e.width,a=a??e.height,i===-1&&(i=0),new Promise(l=>{const c=new Ne("postprocess",o,null,null,1,null,s,h,!1,void 0,i,void 0,null,!1,r);c.externalTextureSamplerBinding=!0;const u=h.createRenderTargetTexture({width:n,height:a},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:i,format:r});c.onEffectCreatedObservable.addOnce(f=>{f.executeWhenCompiled(()=>{c.onApply=d=>{d._bindTexture("textureSampler",e),d.setFloat2("scale",1,1)},t.postProcessManager.directRender([c],u,!0),h.restoreDefaultFramebuffer(),h._releaseTexture(e),c&&c.dispose(),u._swapAndDie(e),e.type=i,e.format=5,e.isReady=!0,l(e)})})})}let Sr,fh;function Ed(o){Sr||(Sr=new Float32Array(1),fh=new Int32Array(Sr.buffer)),Sr[0]=o;const e=fh[0];let t=e>>16&32768,i=e>>12&2047;const s=e>>23&255;return s<103?t:s>142?(t|=31744,t|=(s==255?0:1)&&e&8388607,t):s<113?(i|=2048,t|=(i>>114-s)+(i>>113-s&1),t):(t|=s-112<<10|i>>1,t+=i&1,t)}function xd(o){const e=(o&32768)>>15,t=(o&31744)>>10,i=o&1023;return t===0?(e?-1:1)*Math.pow(2,-14)*(i/Math.pow(2,10)):t==31?i?NaN:(e?-1:1)*(1/0):(e?-1:1)*Math.pow(2,t-15)*(1+i/Math.pow(2,10))}function bd(o){switch(o){case 36492:case 36493:case 36495:case 36494:case 33779:case 35919:case 33778:case 35918:case 33777:case 33776:case 35917:case 35916:case 37808:case 37840:case 36196:case 37492:case 37493:case 37494:case 37495:case 37496:case 37497:return!0;default:return!1}}async function Rd(o){if(o.isReady())return;if(o.loadingError)throw new Error(o.errorObject?.message||`Texture ${o.name} errored while loading.`);const e=o.onLoadObservable;if(e)return await new Promise(i=>e.addOnce(()=>i()));const t=o._texture?.onLoadedObservable;if(t)return await new Promise(i=>t.addOnce(()=>i()));throw new Error(`Cannot determine readiness of texture ${o.name}.`)}async function Sd(o,e,t,i,s){const r=o.getScene(),n=r.getEngine();n.isWebGPU?o.isCube?await he(()=>import("./lodCube.fragment-yDzV1teg.js"),[],import.meta.url):await he(()=>import("./lod.fragment-Cp0eqGjl.js"),[],import.meta.url):o.isCube?await he(()=>import("./lodCube.fragment-CI1eTppS.js"),[],import.meta.url):await he(()=>import("./lod.fragment-BuvQbBhE.js"),[],import.meta.url);let a;if(!o.isCube)a=new Ne("lod","lod",{uniforms:["lod","gamma"],samplingMode:G.NEAREST_NEAREST_MIPNEAREST,engine:n,shaderLanguage:n.isWebGPU?1:0});else{const c=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];a=new Ne("lodCube","lodCube",{uniforms:["lod","gamma"],samplingMode:G.NEAREST_NEAREST_MIPNEAREST,engine:n,defines:c[i],shaderLanguage:n.isWebGPU?1:0})}await new Promise(c=>{a.onEffectCreatedObservable.addOnce(u=>{u.executeWhenCompiled(()=>{c(0)})})});const h=new yt("temp",{width:e,height:t},r,!1);a.onApply=function(c){c.setTexture("textureSampler",o),c.setFloat("lod",s),c.setInt("gamma",o.gammaSpace?1:0)};const l=o.getInternalTexture();try{if(h.renderTarget&&l){const c=l.samplingMode;s!==0?o.updateSamplingMode(G.NEAREST_NEAREST_MIPNEAREST):o.updateSamplingMode(G.NEAREST_NEAREST),r.postProcessManager.directRender([a],h.renderTarget,!0),o.updateSamplingMode(c);const u=await n.readPixels(0,0,e,t),f=new Uint8Array(u.buffer,0,u.byteLength);return n.unBindFramebuffer(h.renderTarget),f}else throw Error("Render to texture failed.")}finally{h.dispose(),a.dispose()}}async function yd(o,e,t,i=0,s=0,r=!1){await Rd(o);const{width:n,height:a}=o.getSize(),h=e??n,l=t??a;if(r||bd(o.textureFormat)||h!==n||l!==a){if(o.is2DArray||o.is3D)throw new Error(`Reading pixels from 2D array or 3D textures with ${r?"RTT":"compression"} is not supported.`);return await Sd(o,h,l,i,s)}let c=await o.readPixels(i,s);if(!c)throw new Error(`Failed to read pixels from texture ${o.name}.`);if(c instanceof Float32Array){const u=new Uint8Array(c.length);let f=c.length;for(;f--;){const d=c[f];u[f]=Math.round(ke(d)*255)}c=u}return c}const em={CreateResizedCopy:Td,ApplyPostProcess:Nl,ToHalfFloat:Ed,FromHalfFloat:xd,GetTextureDataAsync:yd};class Ad{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),s=i.getCaps(),r=t.isReady;let n=!1;s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?(n=!0,t.type=2):s.textureFloatRender&&s.textureFloatLinearFiltering&&(n=!0,t.type=1),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const a=async()=>{const h=i.isWebGPU,l=h?1:0;t.isReady=!1,h?await he(()=>import("./rgbdDecode.fragment-D_2CJy2O.js"),[],import.meta.url):await he(()=>import("./rgbdDecode.fragment-BQ16CsAv.js"),[],import.meta.url);const c=new Ne("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1,void 0,l);c.externalTextureSamplerBinding=!0;const u=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});c.onEffectCreatedObservable.addOnce(f=>{f.executeWhenCompiled(()=>{c.onApply=d=>{d._bindTexture("textureSampler",t),d.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([c],u,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),c&&c.dispose(),u._swapAndDie(t),t.isReady=!0})})};n&&(r?a():e.onLoadObservable.addOnce(a))}static async EncodeTextureToRGBD(e,t,i=0){return t.getEngine().isWebGPU?await he(()=>import("./rgbdEncode.fragment-QRg2h8KC.js"),[],import.meta.url):await he(()=>import("./rgbdEncode.fragment-CmDv6yEZ.js"),[],import.meta.url),await Nl("rgbdEncode",e,t,i,1,5)}}let _s=null;async function Md(){const o=ye.LastCreatedEngine?.createCanvas(100,100)??new OffscreenCanvas(100,100);o instanceof OffscreenCanvas&&W.Warn("DumpData: OffscreenCanvas will be used for dumping data. This may result in lossy alpha values.");const{ThinEngine:e}=await he(async()=>{const{ThinEngine:a}=await Promise.resolve().then(()=>rd);return{ThinEngine:a}},void 0,import.meta.url);if(!e.IsSupported)throw new Error("DumpData: No WebGL context available. Cannot dump data.");const t={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1},i=new e(o,!1,t);ye.Instances.pop(),ye.OnEnginesDisposedObservable.add(a=>{i&&a!==i&&!i.isDisposed&&ye.Instances.length===0&&eo()}),i.getCaps().parallelShaderCompile=void 0;const s=new Jf(i),{passPixelShader:r}=await he(async()=>{const{passPixelShader:a}=await Promise.resolve().then(()=>sc);return{passPixelShader:a}},void 0,import.meta.url),n=new Qe({engine:i,name:r.name,fragmentShader:r.shader,samplerNames:["textureSampler"]});return{canvas:o,dumpEngine:{engine:i,renderer:s,wrapper:n}}}async function Pd(){return _s||(_s=Md()),await _s}class $a{static async EncodeImageAsync(e,t,i,s,r,n){const a=await Pd(),h=a.dumpEngine;h.engine.setSize(t,i,!0);const l=h.engine.createRawTexture(e,t,i,5,!1,!r,1);return h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",l),h.renderer.draw(),l.dispose(),await new Promise((c,u)=>{fe.ToBlob(a.canvas,f=>{f?c(f):u(new Error("EncodeImageAsync: Failed to convert canvas to blob."))},s,n)})}}M([_i],$a,"EncodeImageAsync",null);const Id=$a.EncodeImageAsync;async function Ja(o,e,t,i,s="image/png",r,n){const a=await t.readPixels(0,0,o,e),h=new Uint8Array(a.buffer);en(o,e,h,i,s,r,!0,void 0,n)}async function cr(o,e,t,i="image/png",s,r=!1,n=!1,a){if(t instanceof Float32Array){const c=new Uint8Array(t.length);let u=t.length;for(;u--;){const f=t[u];c[u]=Math.round(ke(f)*255)}t=c}const h=await $a.EncodeImageAsync(t,o,e,i,r,a);s!==void 0&&fe.DownloadBlob(h,s),h.type!==i&&W.Warn(`DumpData: The requested mimeType '${i}' is not supported. The result has mimeType '${h.type}' instead.`);const l=await h.arrayBuffer();return n?l:`data:${i};base64,${Kr(l)}`}function en(o,e,t,i,s="image/png",r,n=!1,a=!1,h){r===void 0&&!i&&(r=""),cr(o,e,t,s,r,n,a,h).then(l=>{i&&i(l)})}function eo(){_s&&(_s?.then(o=>{o.canvas instanceof HTMLCanvasElement&&o.canvas.remove(),o.dumpEngine&&(o.dumpEngine.engine.dispose(),o.dumpEngine.renderer.dispose(),o.dumpEngine.wrapper.dispose())}),_s=null)}const vd={DumpData:en,DumpDataAsync:cr,DumpFramebuffer:Ja,Dispose:eo},Cd=()=>{fe.DumpData=en,fe.DumpDataAsync=cr,fe.DumpFramebuffer=Ja};Cd();const Dd=Object.freeze(Object.defineProperty({__proto__:null,Dispose:eo,DumpData:en,DumpDataAsync:cr,DumpFramebuffer:Ja,DumpTools:vd,EncodeImageAsync:Id},Symbol.toStringTag,{value:"Module"}));class as{constructor(e,t,i,s){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=s}}class tn{static ConvertCubeMapTextureToSphericalPolynomial(e){if(!e.isCube)return null;e.getScene()?.getEngine().flushFramebuffer();const t=e.getSize().width,i=e.readPixels(0,void 0,void 0,!1),s=e.readPixels(1,void 0,void 0,!1);let r,n;e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),n=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),n=e.readPixels(3,void 0,void 0,!1));const a=e.readPixels(4,void 0,void 0,!1),h=e.readPixels(5,void 0,void 0,!1),l=e.gammaSpace,c=5;return new Promise(u=>{Promise.all([s,i,r,n,a,h]).then(([f,d,_,m,g,T])=>{const R={size:t,right:d,left:f,up:_,down:m,front:g,back:T,format:c,type:f instanceof Float32Array?1:0,gammaSpace:l};u(this.ConvertCubeMapToSphericalPolynomial(R))})})}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new js;let i=0;const s=2/e.size,r=s,n=.5*s,a=n-1;for(let f=0;f<6;f++){const d=this._FileFaces[f],_=e[d.name];let m=a;const g=e.format===5?4:3;for(let T=0;T<e.size;T++){let R=a;for(let A=0;A<e.size;A++){const y=d.worldAxisForFileX.scale(R).add(d.worldAxisForFileY.scale(m)).add(d.worldAxisForNormal);y.normalize();const E=this._AreaElement(R-n,m-n)-this._AreaElement(R-n,m+n)-this._AreaElement(R+n,m-n)+this._AreaElement(R+n,m+n);let x=_[T*e.size*g+A*g+0],b=_[T*e.size*g+A*g+1],P=_[T*e.size*g+A*g+2];isNaN(x)&&(x=0),isNaN(b)&&(b=0),isNaN(P)&&(P=0),e.type===0&&(x/=255,b/=255,P/=255),e.gammaSpace&&(x=Math.pow(ke(x),vr),b=Math.pow(ke(b),vr),P=Math.pow(ke(P),vr));const v=this.MAX_HDRI_VALUE;if(this.PRESERVE_CLAMPED_COLORS){const k=Math.max(x,b,P);if(k>v){const Y=v/k;x*=Y,b*=Y,P*=Y}}else x=ke(x,0,v),b=ke(b,0,v),P=ke(P,0,v);const O=new Re(x,b,P);t.addLight(y,O,E),i+=E,R+=s}m+=r}}const u=4*Math.PI*6/6/i;return t.scaleInPlace(u),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),Ts.FromHarmonics(t)}}tn._FileFaces=[new as("right",new p(1,0,0),new p(0,0,-1),new p(0,-1,0)),new as("left",new p(-1,0,0),new p(0,0,1),new p(0,-1,0)),new as("up",new p(0,1,0),new p(1,0,0),new p(0,0,1)),new as("down",new p(0,-1,0),new p(1,0,0),new p(0,0,-1)),new as("front",new p(0,0,1),new p(1,0,0),new p(0,-1,0)),new as("back",new p(0,0,-1),new p(-1,0,0),new p(0,-1,0))];tn.MAX_HDRI_VALUE=4096;tn.PRESERVE_CLAMPED_COLORS=!1;Ve.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)};Object.defineProperty(Ve.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=tn.ConvertCubeMapTextureToSphericalPolynomial(this),this._texture._sphericalPolynomialPromise===null?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(o=>{this._texture._sphericalPolynomial=o,this._texture._sphericalPolynomialComputed=!0})),null}return null},set:function(o){this._texture&&(this._texture._sphericalPolynomial=o)},enumerable:!0,configurable:!0});const ur="image/png",zn=2,Vs=[134,22,135,150,246,214,150,54];function Ul(o){const e=new DataView(o.buffer,o.byteOffset,o.byteLength);let t=0;for(let n=0;n<Vs.length;n++)if(e.getUint8(t++)!==Vs[n])return W.Error("Not a babylon environment map"),null;let i="",s;for(;s=e.getUint8(t++);)i+=String.fromCharCode(s);let r=JSON.parse(i);return r=fr(r),r.binaryDataPosition=t,r.specular&&(r.specular.lodGenerationScale=r.specular.lodGenerationScale||.8),r}function fr(o){if(o.version>zn)throw new Error(`Unsupported babylon environment map version "${o.version}". Latest supported version is "${zn}".`);return o.version===2||(o={...o,version:2,imageType:ur}),o}async function Od(o,e={}){const t=o.getInternalTexture();if(!t)return await Promise.reject("The cube texture is invalid.");const i=t.getEngine();if(o.textureType!==2&&o.textureType!==1&&o.textureType!==0&&o.textureType!==0&&o.textureType!==7&&o.textureType!==-1)return await Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");let s=1;if(!i.getCaps().textureFloatRender&&(s=2,!i.getCaps().textureHalfFloatRender))return await Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");o.sphericalPolynomial;const r=o.getInternalTexture()?._sphericalPolynomialPromise,n=t.width,a=new je(i),h={},l={};i.flushFramebuffer();const c=e.imageType??ur,u=Ka(t.width);for(let b=0;b<=u;b++){const P=Math.pow(2,u-b);for(let v=0;v<6;v++)h[b*6+v]=await dh(a,o,s,v,b,P,c,e.imageQuality)}const f=e.disableIrradianceTexture?null:o.irradianceTexture;if(f){const b=f.getSize().width;for(let P=0;P<6;P++)l[P]=await dh(a,f,s,P,0,b,c,e.imageQuality)}a.dispose(),r&&await r;const d={version:zn,width:n,imageType:c,irradiance:Fd(o),specular:{mipmaps:[],lodGenerationScale:o.lodGenerationScale}};let _=0;for(let b=0;b<=u;b++)for(let P=0;P<6;P++){const v=h[b*6+P].byteLength;d.specular.mipmaps.push({length:v,position:_}),_+=v}if(f){d.irradiance=d.irradiance||{x:[0,0,0],xx:[0,0,0],y:[0,0,0],yy:[0,0,0],z:[0,0,0],zz:[0,0,0],yz:[0,0,0],zx:[0,0,0],xy:[0,0,0]},d.irradiance.irradianceTexture={size:f.getSize().width,faces:[],dominantDirection:f._dominantDirection?.asArray()};for(let b=0;b<6;b++){const P=l[b].byteLength;d.irradiance.irradianceTexture.faces.push({length:P,position:_}),_+=P}}const m=JSON.stringify(d),g=new ArrayBuffer(m.length+1),T=new Uint8Array(g);for(let b=0,P=m.length;b<P;b++)T[b]=m.charCodeAt(b);T[m.length]=0;const R=Vs.length+_+g.byteLength,A=new ArrayBuffer(R),y=new Uint8Array(A),E=new DataView(A);let x=0;for(let b=0;b<Vs.length;b++)E.setUint8(x++,Vs[b]);y.set(new Uint8Array(g),x),x+=g.byteLength;for(let b=0;b<=u;b++)for(let P=0;P<6;P++){const v=h[b*6+P];y.set(new Uint8Array(v),x),x+=v.byteLength}if(f)for(let b=0;b<6;b++){const P=l[b];y.set(new Uint8Array(P),x),x+=P.byteLength}return A}async function dh(o,e,t,i,s,r,n,a){let h=await e.readPixels(i,s,void 0,!1);if(h&&h.byteLength===h.length){const d=new Float32Array(h.byteLength*4);for(let _=0;_<h.byteLength;_++)d[_]=h[_]/255,d[_]=Math.pow(d[_],2.2);h=d}else if(h&&e.gammaSpace){const d=h;for(let _=0;_<d.length;_++)d[_]=Math.pow(d[_],2.2)}const l=o.getEngine(),c=l.createRawTexture(h,r,r,5,!1,!0,1,null,t);await Ad.EncodeTextureToRGBD(c,o,t);const u=await l._readTexturePixels(c,r,r),f=await cr(r,r,u,n,void 0,!1,!0,a);return c.dispose(),f}function Fd(o){const e=o.sphericalPolynomial;return e==null?null:{x:[e.x.x,e.x.y,e.x.z],y:[e.y.x,e.y.y,e.y.z],z:[e.z.x,e.z.y,e.z.z],xx:[e.xx.x,e.xx.y,e.xx.z],yy:[e.yy.x,e.yy.y,e.yy.z],zz:[e.zz.x,e.zz.y,e.zz.z],yz:[e.yz.x,e.yz.y,e.yz.z],zx:[e.zx.x,e.zx.y,e.zx.z],xy:[e.xy.x,e.xy.y,e.xy.z]}}function kl(o,e){e=fr(e);const t=e.specular;let i=Math.log2(e.width);if(i=Math.round(i)+1,t.mipmaps.length!==6*i)throw new Error(`Unsupported specular mipmaps number "${t.mipmaps.length}"`);const s=new Array(i);for(let r=0;r<i;r++){s[r]=new Array(6);for(let n=0;n<6;n++){const a=t.mipmaps[r*6+n];s[r][n]=new Uint8Array(o.buffer,o.byteOffset+e.binaryDataPosition+a.position,a.length)}}return s}function Vl(o,e){e=fr(e);const t=new Array(6),i=e.irradiance?.irradianceTexture;if(i){if(i.faces.length!==6)throw new Error(`Incorrect irradiance texture faces number "${i.faces.length}"`);for(let s=0;s<6;s++){const r=i.faces[s];t[s]=new Uint8Array(o.buffer,o.byteOffset+e.binaryDataPosition+r.position,r.length)}}return t}function zl(o,e,t){t=fr(t);const i=t.specular;if(!i)return Promise.resolve([]);o._lodGenerationScale=i.lodGenerationScale;const s=[],r=kl(e,t);s.push(Gr(o,r,t.imageType));const n=t.irradiance?.irradianceTexture;if(n){const a=Vl(e,t);let h=null;t.irradiance?.irradianceTexture?.dominantDirection&&(h=p.FromArray(t.irradiance.irradianceTexture.dominantDirection)),s.push(Wl(o,a,n.size,t.imageType,h))}return Promise.all(s)}async function _h(o,e,t,i,s,r,n,a,h,l,c){return await new Promise((u,f)=>{if(t){const d=e.createTexture(null,!0,!0,null,1,null,_=>{f(_)},o);i?.onEffectCreatedObservable.addOnce(_=>{_.executeWhenCompiled(()=>{i.externalTextureSamplerBinding=!0,i.onApply=m=>{m._bindTexture("textureSampler",d),m.setFloat2("scale",1,e._features.needsInvertingBitmap&&o instanceof ImageBitmap?-1:1)},e.scenes.length&&(e.scenes[0].postProcessManager.directRender([i],l,!0,r,n),e.restoreDefaultFramebuffer(),d.dispose(),URL.revokeObjectURL(s),u())})})}else{if(e._uploadImageToTexture(c,o,r,n),a){const d=h[n];d&&e._uploadImageToTexture(d._texture,o,r,0)}u()}})}async function Gr(o,e,t=ur){const i=o.getEngine();o.format=5,o.type=0,o.generateMipMaps=!0,o._cachedAnisotropicFilteringLevel=null,i.updateTextureSamplingMode(3,o),await Gl(o,e,!0,t),o.isReady=!0}async function Wl(o,e,t,i=ur,s=null){const r=o.getEngine(),n=new xt(r,5),a=new Ve(r,n);o._irradianceTexture=a,a._dominantDirection=s,n.isCube=!0,n.format=5,n.type=0,n.generateMipMaps=!0,n._cachedAnisotropicFilteringLevel=null,n.generateMipMaps=!0,n.width=t,n.height=t,r.updateTextureSamplingMode(3,n),await Gl(n,[e],!1,i),r.generateMipMapsForCubemap(n),n.isReady=!0}async function Gl(o,e,t,i=ur){if(!fe.IsExponentOfTwo(o.width))throw new Error("Texture size must be a power of two");const s=Ka(o.width)+1,r=o.getEngine();let n=!1,a=!1,h=null,l=null,c=null;const u=r.getCaps();u.textureLOD?r._features.supportRenderAndCopyToLodForFloatTextures?u.textureHalfFloatRender&&u.textureHalfFloatLinearFiltering?(n=!0,o.type=2):u.textureFloatRender&&u.textureFloatLinearFiltering&&(n=!0,o.type=1):n=!1:(n=!1,a=t);let f=0;if(n)r.isWebGPU?(f=1,await he(()=>import("./rgbdDecode.fragment-D_2CJy2O.js"),[],import.meta.url)):await he(()=>import("./rgbdDecode.fragment-BQ16CsAv.js"),[],import.meta.url),h=new Ne("rgbdDecode","rgbdDecode",null,null,1,null,3,r,!1,void 0,o.type,void 0,null,!1,void 0,f),o._isRGBD=!1,o.invertY=!1,l=r.createRenderTargetCubeTexture(o.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:o.type,format:5});else if(o._isRGBD=!0,o.invertY=!0,a){c={};const m=o._lodGenerationScale,g=o._lodGenerationOffset;for(let T=0;T<3;T++){const A=1-T/2,y=g,E=(s-1)*m+g,x=y+(E-y)*A,b=Math.round(Math.min(Math.max(x,0),E)),P=new xt(r,2);P.isCube=!0,P.invertY=!0,P.generateMipMaps=!1,r.updateTextureSamplingMode(2,P);const v=new Ve(null);switch(v._isCube=!0,v._texture=P,c[b]=v,T){case 0:o._lodTextureLow=v;break;case 1:o._lodTextureMid=v;break;case 2:o._lodTextureHigh=v;break}}}const d=[];for(let _=0;_<e.length;_++)for(let m=0;m<6;m++){const g=e[_][m],T=sl(g),R=new Blob([T],{type:i}),A=URL.createObjectURL(R);let y;if(r._features.forceBitmapOverHTMLImageElement)y=r.createImageBitmap(R,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(async E=>await _h(E,r,n,h,A,m,_,a,c,l,o));else{const E=new Image;E.src=A,y=new Promise((x,b)=>{E.onload=()=>{_h(E,r,n,h,A,m,_,a,c,l,o).then(()=>x()).catch(P=>{b(P)})},E.onerror=P=>{b(P)}})}d.push(y)}if(await Promise.all(d),e.length<s){let _;const m=Math.pow(2,s-1-e.length),g=m*m*4;switch(o.type){case 0:{_=new Uint8Array(g);break}case 2:{_=new Uint16Array(g);break}case 1:{_=new Float32Array(g);break}}for(let T=e.length;T<s;T++)for(let R=0;R<6;R++)r._uploadArrayBufferViewToTexture(l?.texture||o,_,R,T)}if(l){const _=o._irradianceTexture;o._irradianceTexture=null,r._releaseTexture(o),l._swapAndDie(o),o._irradianceTexture=_}h&&h.dispose(),a&&(o._lodTextureHigh&&o._lodTextureHigh._texture&&(o._lodTextureHigh._texture.isReady=!0),o._lodTextureMid&&o._lodTextureMid._texture&&(o._lodTextureMid._texture.isReady=!0),o._lodTextureLow&&o._lodTextureLow._texture&&(o._lodTextureLow._texture.isReady=!0))}function Hl(o,e){e=fr(e);const t=e.irradiance;if(!t)return;const i=new Ts;p.FromArrayToRef(t.x,0,i.x),p.FromArrayToRef(t.y,0,i.y),p.FromArrayToRef(t.z,0,i.z),p.FromArrayToRef(t.xx,0,i.xx),p.FromArrayToRef(t.yy,0,i.yy),p.FromArrayToRef(t.zz,0,i.zz),p.FromArrayToRef(t.yz,0,i.yz),p.FromArrayToRef(t.zx,0,i.zx),p.FromArrayToRef(t.xy,0,i.xy),o._sphericalPolynomial=i}function tm(o,e,t,i,s){const r=o.getEngine().createRawCubeTexture(null,o.width,o.format,o.type,o.generateMipMaps,o.invertY,o.samplingMode,o._compression),n=Gr(r,e).then(()=>o);return o.onRebuildCallback=a=>({proxy:n,isReady:!0,isAsync:!0}),o._source=13,o._bufferViewArrayArray=e,o._lodGenerationScale=i,o._lodGenerationOffset=s,o._sphericalPolynomial=t,Gr(o,e).then(()=>(o.isReady=!0,o))}const im={GetEnvInfo:Ul,CreateEnvTextureAsync:Od,CreateRadianceImageDataArrayBufferViews:kl,CreateIrradianceImageDataArrayBufferViews:Vl,UploadEnvLevelsAsync:zl,UploadRadianceLevelsAsync:Gr,UploadIrradianceLevelsAsync:Wl,UploadEnvSpherical:Hl};class wd{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=Ul(e);if(n){t.width=n.width,t.height=n.width;try{Hl(t,n),zl(t,e,n).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()},a=>{r?.("Can not upload environment levels",a)})}catch(a){r?.("Can not upload environment file",a)}}else r&&r("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}const Ld=Object.freeze(Object.defineProperty({__proto__:null,_ENVTextureLoader:wd},Symbol.toStringTag,{value:"Module"})),Wn="imageProcessingDeclaration",Xl=`#ifdef EXPOSURE
|
|
48
|
+
uniform float exposureLinear;
|
|
49
|
+
#endif
|
|
50
|
+
#ifdef CONTRAST
|
|
51
|
+
uniform float contrast;
|
|
52
|
+
#endif
|
|
53
|
+
#if defined(VIGNETTE) || defined(DITHER)
|
|
54
|
+
uniform vec2 vInverseScreenSize;
|
|
55
|
+
#endif
|
|
56
|
+
#ifdef VIGNETTE
|
|
57
|
+
uniform vec4 vignetteSettings1;uniform vec4 vignetteSettings2;
|
|
58
|
+
#endif
|
|
59
|
+
#ifdef COLORCURVES
|
|
60
|
+
uniform vec4 vCameraColorCurveNegative;uniform vec4 vCameraColorCurveNeutral;uniform vec4 vCameraColorCurvePositive;
|
|
61
|
+
#endif
|
|
62
|
+
#ifdef COLORGRADING
|
|
63
|
+
#ifdef COLORGRADING3D
|
|
64
|
+
uniform highp sampler3D txColorTransform;
|
|
65
|
+
#else
|
|
66
|
+
uniform sampler2D txColorTransform;
|
|
67
|
+
#endif
|
|
68
|
+
uniform vec4 colorTransformSettings;
|
|
69
|
+
#endif
|
|
70
|
+
#ifdef DITHER
|
|
71
|
+
uniform float ditherIntensity;
|
|
72
|
+
#endif
|
|
73
|
+
`;Z.IncludesShadersStore[Wn]||(Z.IncludesShadersStore[Wn]=Xl);const Bd={name:Wn,shader:Xl},sm=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingDeclaration:Bd},Symbol.toStringTag,{value:"Module"})),Gn="helperFunctions",Kl=`const float PI=3.1415926535897932384626433832795;const float TWO_PI=6.283185307179586;const float HALF_PI=1.5707963267948966;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float RECIPROCAL_PI4=0.07957747154594767;const float HALF_MIN=5.96046448e-08;
|
|
74
|
+
const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001;
|
|
75
|
+
#define saturate(x) clamp(x,0.0,1.0)
|
|
76
|
+
#define absEps(x) abs(x)+Epsilon
|
|
77
|
+
#define maxEps(x) max(x,Epsilon)
|
|
78
|
+
#define saturateEps(x) clamp(x,Epsilon,1.0)
|
|
79
|
+
mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3(
|
|
80
|
+
vec3(i0.x,i1.x,i2.x),
|
|
81
|
+
vec3(i0.y,i1.y,i2.y),
|
|
82
|
+
vec3(i0.z,i1.z,i2.z)
|
|
83
|
+
);return outMatrix;}
|
|
84
|
+
mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),
|
|
85
|
+
b11,(a22*a00-a02*a20),(-a12*a00+a02*a10),
|
|
86
|
+
b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;}
|
|
87
|
+
#if USE_EXACT_SRGB_CONVERSIONS
|
|
88
|
+
vec3 toLinearSpaceExact(vec3 color)
|
|
89
|
+
{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));
|
|
90
|
+
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
|
|
91
|
+
return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));
|
|
92
|
+
#else
|
|
93
|
+
return
|
|
94
|
+
vec3(
|
|
95
|
+
color.r<=0.04045 ? nearZeroSection.r : remainingSection.r,
|
|
96
|
+
color.g<=0.04045 ? nearZeroSection.g : remainingSection.g,
|
|
97
|
+
color.b<=0.04045 ? nearZeroSection.b : remainingSection.b);
|
|
98
|
+
#endif
|
|
99
|
+
}
|
|
100
|
+
vec3 toGammaSpaceExact(vec3 color)
|
|
101
|
+
{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);
|
|
102
|
+
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
|
|
103
|
+
return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));
|
|
104
|
+
#else
|
|
105
|
+
return
|
|
106
|
+
vec3(
|
|
107
|
+
color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,
|
|
108
|
+
color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,
|
|
109
|
+
color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);
|
|
110
|
+
#endif
|
|
111
|
+
}
|
|
112
|
+
#endif
|
|
113
|
+
float toLinearSpace(float color)
|
|
114
|
+
{
|
|
115
|
+
#if USE_EXACT_SRGB_CONVERSIONS
|
|
116
|
+
float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection;
|
|
117
|
+
#else
|
|
118
|
+
return pow(color,LinearEncodePowerApprox);
|
|
119
|
+
#endif
|
|
120
|
+
}
|
|
121
|
+
vec3 toLinearSpace(vec3 color)
|
|
122
|
+
{
|
|
123
|
+
#if USE_EXACT_SRGB_CONVERSIONS
|
|
124
|
+
return toLinearSpaceExact(color);
|
|
125
|
+
#else
|
|
126
|
+
return pow(color,vec3(LinearEncodePowerApprox));
|
|
127
|
+
#endif
|
|
128
|
+
}
|
|
129
|
+
vec4 toLinearSpace(vec4 color)
|
|
130
|
+
{
|
|
131
|
+
#if USE_EXACT_SRGB_CONVERSIONS
|
|
132
|
+
return vec4(toLinearSpaceExact(color.rgb),color.a);
|
|
133
|
+
#else
|
|
134
|
+
return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);
|
|
135
|
+
#endif
|
|
136
|
+
}
|
|
137
|
+
float toGammaSpace(float color)
|
|
138
|
+
{
|
|
139
|
+
#if USE_EXACT_SRGB_CONVERSIONS
|
|
140
|
+
float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection;
|
|
141
|
+
#else
|
|
142
|
+
return pow(color,GammaEncodePowerApprox);
|
|
143
|
+
#endif
|
|
144
|
+
}
|
|
145
|
+
vec3 toGammaSpace(vec3 color)
|
|
146
|
+
{
|
|
147
|
+
#if USE_EXACT_SRGB_CONVERSIONS
|
|
148
|
+
return toGammaSpaceExact(color);
|
|
149
|
+
#else
|
|
150
|
+
return pow(color,vec3(GammaEncodePowerApprox));
|
|
151
|
+
#endif
|
|
152
|
+
}
|
|
153
|
+
vec4 toGammaSpace(vec4 color)
|
|
154
|
+
{
|
|
155
|
+
#if USE_EXACT_SRGB_CONVERSIONS
|
|
156
|
+
return vec4(toGammaSpaceExact(color.rgb),color.a);
|
|
157
|
+
#else
|
|
158
|
+
return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);
|
|
159
|
+
#endif
|
|
160
|
+
}
|
|
161
|
+
float square(float value)
|
|
162
|
+
{return value*value;}
|
|
163
|
+
vec3 square(vec3 value)
|
|
164
|
+
{return value*value;}
|
|
165
|
+
float pow5(float value) {float sq=value*value;return sq*sq*value;}
|
|
166
|
+
vec3 double_refract(vec3 I,vec3 N,float eta) {vec3 Tfront=refract(I,N,1.0/eta);vec3 Nback=normalize(reflect(N,Tfront));return refract(Tfront,-Nback,eta);}
|
|
167
|
+
float getLuminanceUnclamped(vec3 color)
|
|
168
|
+
{return dot(color,LuminanceEncodeApprox);}
|
|
169
|
+
float getLuminance(vec3 color)
|
|
170
|
+
{return saturate(getLuminanceUnclamped(color));}
|
|
171
|
+
float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}
|
|
172
|
+
float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;}
|
|
173
|
+
const float rgbdMaxRange=255.;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =saturate(floor(D)/255.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(saturate(rgb),D);}
|
|
174
|
+
vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;}
|
|
175
|
+
vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}
|
|
176
|
+
vec3 equirectangularToCubemapDirection(vec2 uv) {float longitude=uv.x*TWO_PI-PI;float latitude=HALF_PI-uv.y*PI;vec3 direction;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}
|
|
177
|
+
float sqrtClamped(float value) {return sqrt(max(value,0.));}
|
|
178
|
+
float avg(vec3 value) {return dot(value,vec3(0.333333333));}
|
|
179
|
+
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
|
|
180
|
+
uint extractBits(uint value,int offset,int width) {return (value>>offset) & ((1u<<width)-1u);}
|
|
181
|
+
int onlyBitPosition(uint value) {return (floatBitsToInt(float(value))>>23)-0x7f;}
|
|
182
|
+
vec3 singleScatterToMultiScatterAlbedo(vec3 rho_ss) {vec3 s=sqrt(max(vec3(1.0)-rho_ss,vec3(0.0)));return (vec3(1.0)-s)*(vec3(1.0)-vec3(0.139)*s)/(vec3(1.0)+vec3(1.17)*s);}
|
|
183
|
+
float min3(vec3 v) {return min(v.x,min(v.y,v.z));}
|
|
184
|
+
float max3(vec3 v) {return max(v.x,max(v.y,v.z));}
|
|
185
|
+
#endif
|
|
186
|
+
`;Z.IncludesShadersStore[Gn]||(Z.IncludesShadersStore[Gn]=Kl);const Nd={name:Gn,shader:Kl},rm=Object.freeze(Object.defineProperty({__proto__:null,helperFunctions:Nd},Symbol.toStringTag,{value:"Module"})),Hn="imageProcessingFunctions",Yl=`#if defined(COLORGRADING) && !defined(COLORGRADING3D)
|
|
187
|
+
/**
|
|
188
|
+
* Polyfill for SAMPLE_TEXTURE_3D,which is unsupported in WebGL.
|
|
189
|
+
* sampler3dSetting.x=textureOffset (0.5/textureSize).
|
|
190
|
+
* sampler3dSetting.y=textureSize.
|
|
191
|
+
*/
|
|
192
|
+
#define inline
|
|
193
|
+
vec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)
|
|
194
|
+
{float sliceSize=2.0*sampler3dSetting.x;
|
|
195
|
+
#ifdef SAMPLER3DGREENDEPTH
|
|
196
|
+
float sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;
|
|
197
|
+
#else
|
|
198
|
+
float sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;
|
|
199
|
+
#endif
|
|
200
|
+
float sliceInteger=floor(sliceContinuous);float sliceFraction=sliceContinuous-sliceInteger;
|
|
201
|
+
#ifdef SAMPLER3DGREENDEPTH
|
|
202
|
+
vec2 sliceUV=color.rb;
|
|
203
|
+
#else
|
|
204
|
+
vec2 sliceUV=color.rg;
|
|
205
|
+
#endif
|
|
206
|
+
sliceUV.x*=sliceSize;sliceUV.x+=sliceInteger*sliceSize;sliceUV=saturate(sliceUV);vec4 slice0Color=texture2D(colorTransform,sliceUV);sliceUV.x+=sliceSize;sliceUV=saturate(sliceUV);vec4 slice1Color=texture2D(colorTransform,sliceUV);vec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);
|
|
207
|
+
#ifdef SAMPLER3DBGRMAP
|
|
208
|
+
color.rgb=result.rgb;
|
|
209
|
+
#else
|
|
210
|
+
color.rgb=result.bgr;
|
|
211
|
+
#endif
|
|
212
|
+
return color;}
|
|
213
|
+
#endif
|
|
214
|
+
#if TONEMAPPING==3
|
|
215
|
+
const float PBRNeutralStartCompression=0.8-0.04;const float PBRNeutralDesaturation=0.15;vec3 PBRNeutralToneMapping( vec3 color ) {float x=min(color.r,min(color.g,color.b));float offset=x<0.08 ? x-6.25*x*x : 0.04;color-=offset;float peak=max(color.r,max(color.g,color.b));if (peak<PBRNeutralStartCompression) return color;float d=1.-PBRNeutralStartCompression;float newPeak=1.-d*d/(peak+d-PBRNeutralStartCompression);color*=newPeak/peak;float g=1.-1./(PBRNeutralDesaturation*(peak-newPeak)+1.);return mix(color,newPeak*vec3(1,1,1),g);}
|
|
216
|
+
#endif
|
|
217
|
+
#if TONEMAPPING==2
|
|
218
|
+
const mat3 ACESInputMat=mat3(
|
|
219
|
+
vec3(0.59719,0.07600,0.02840),
|
|
220
|
+
vec3(0.35458,0.90834,0.13383),
|
|
221
|
+
vec3(0.04823,0.01566,0.83777)
|
|
222
|
+
);const mat3 ACESOutputMat=mat3(
|
|
223
|
+
vec3( 1.60475,-0.10208,-0.00327),
|
|
224
|
+
vec3(-0.53108, 1.10813,-0.07276),
|
|
225
|
+
vec3(-0.07367,-0.00605, 1.07602)
|
|
226
|
+
);vec3 RRTAndODTFit(vec3 v)
|
|
227
|
+
{vec3 a=v*(v+0.0245786)-0.000090537;vec3 b=v*(0.983729*v+0.4329510)+0.238081;return a/b;}
|
|
228
|
+
vec3 ACESFitted(vec3 color)
|
|
229
|
+
{color=ACESInputMat*color;color=RRTAndODTFit(color);color=ACESOutputMat*color;color=saturate(color);return color;}
|
|
230
|
+
#endif
|
|
231
|
+
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS
|
|
232
|
+
vec4 applyImageProcessing(vec4 result) {
|
|
233
|
+
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART
|
|
234
|
+
#ifdef EXPOSURE
|
|
235
|
+
result.rgb*=exposureLinear;
|
|
236
|
+
#endif
|
|
237
|
+
#ifdef VIGNETTE
|
|
238
|
+
vec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;vec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);float vignetteTerm=dot(vignetteXY1,vignetteXY1);float vignette=pow(vignetteTerm,vignetteSettings2.w);vec3 vignetteColor=vignetteSettings2.rgb;
|
|
239
|
+
#ifdef VIGNETTEBLENDMODEMULTIPLY
|
|
240
|
+
vec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);result.rgb*=vignetteColorMultiplier;
|
|
241
|
+
#endif
|
|
242
|
+
#ifdef VIGNETTEBLENDMODEOPAQUE
|
|
243
|
+
result.rgb=mix(vignetteColor,result.rgb,vignette);
|
|
244
|
+
#endif
|
|
245
|
+
#endif
|
|
246
|
+
#if TONEMAPPING==3
|
|
247
|
+
result.rgb=PBRNeutralToneMapping(result.rgb);
|
|
248
|
+
#elif TONEMAPPING==2
|
|
249
|
+
result.rgb=ACESFitted(result.rgb);
|
|
250
|
+
#elif TONEMAPPING==1
|
|
251
|
+
const float tonemappingCalibration=1.590579;result.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);
|
|
252
|
+
#endif
|
|
253
|
+
result.rgb=toGammaSpace(result.rgb);result.rgb=saturate(result.rgb);
|
|
254
|
+
#ifdef CONTRAST
|
|
255
|
+
vec3 resultHighContrast=result.rgb*result.rgb*(3.0-2.0*result.rgb);if (contrast<1.0) {result.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);} else {result.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);}
|
|
256
|
+
result.rgb=max(result.rgb,0.);
|
|
257
|
+
#endif
|
|
258
|
+
#ifdef COLORGRADING
|
|
259
|
+
vec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;
|
|
260
|
+
#ifdef COLORGRADING3D
|
|
261
|
+
vec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;
|
|
262
|
+
#else
|
|
263
|
+
vec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;
|
|
264
|
+
#endif
|
|
265
|
+
result.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);
|
|
266
|
+
#endif
|
|
267
|
+
#ifdef COLORCURVES
|
|
268
|
+
float luma=getLuminance(result.rgb);vec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));vec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;result.rgb*=colorCurve.rgb;result.rgb=mix(vec3(luma),result.rgb,colorCurve.a);
|
|
269
|
+
#endif
|
|
270
|
+
#ifdef DITHER
|
|
271
|
+
float rand=getRand(gl_FragCoord.xy*vInverseScreenSize);float dither=mix(-ditherIntensity,ditherIntensity,rand);result.rgb=saturate(result.rgb+vec3(dither));
|
|
272
|
+
#endif
|
|
273
|
+
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND
|
|
274
|
+
return result;}`;Z.IncludesShadersStore[Hn]||(Z.IncludesShadersStore[Hn]=Yl);const Ud={name:Hn,shader:Yl},nm=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingFunctions:Ud},Symbol.toStringTag,{value:"Module"})),Xn="imageProcessingPixelShader",jl=`varying vec2 vUV;uniform sampler2D textureSampler;
|
|
275
|
+
#include<imageProcessingDeclaration>
|
|
276
|
+
#include<helperFunctions>
|
|
277
|
+
#include<imageProcessingFunctions>
|
|
278
|
+
#define CUSTOM_FRAGMENT_DEFINITIONS
|
|
279
|
+
void main(void)
|
|
280
|
+
{vec4 result=texture2D(textureSampler,vUV);result.rgb=max(result.rgb,vec3(0.));
|
|
281
|
+
#ifdef IMAGEPROCESSING
|
|
282
|
+
#ifndef FROMLINEARSPACE
|
|
283
|
+
result.rgb=toLinearSpace(result.rgb);
|
|
284
|
+
#endif
|
|
285
|
+
result=applyImageProcessing(result);
|
|
286
|
+
#else
|
|
287
|
+
#ifdef FROMLINEARSPACE
|
|
288
|
+
result=applyImageProcessing(result);
|
|
289
|
+
#endif
|
|
290
|
+
#endif
|
|
291
|
+
gl_FragColor=result;}`;Z.ShadersStore[Xn]||(Z.ShadersStore[Xn]=jl);const kd={name:Xn,shader:jl},Vd=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingPixelShader:kd},Symbol.toStringTag,{value:"Module"})),Kn="extractHighlightsPixelShader",Zl=`#include<helperFunctions>
|
|
292
|
+
varying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure;
|
|
293
|
+
#define CUSTOM_FRAGMENT_DEFINITIONS
|
|
294
|
+
void main(void)
|
|
295
|
+
{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`;Z.ShadersStore[Kn]||(Z.ShadersStore[Kn]=Zl);const zd={name:Kn,shader:Zl},Wd=Object.freeze(Object.defineProperty({__proto__:null,extractHighlightsPixelShader:zd},Symbol.toStringTag,{value:"Module"})),gh="kernelBlurVaryingDeclaration",Gd="varying vec2 sampleCoord{X};";Z.IncludesShadersStore[gh]||(Z.IncludesShadersStore[gh]=Gd);const Yn="packingFunctions",ql=`vec4 pack(float depth)
|
|
296
|
+
{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}
|
|
297
|
+
float unpack(vec4 color)
|
|
298
|
+
{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;Z.IncludesShadersStore[Yn]||(Z.IncludesShadersStore[Yn]=ql);const Hd={name:Yn,shader:ql},am=Object.freeze(Object.defineProperty({__proto__:null,packingFunctions:Hd},Symbol.toStringTag,{value:"Module"})),ph="kernelBlurFragment",Xd=`#ifdef DOF
|
|
299
|
+
factor=sampleCoC(sampleCoord{X});
|
|
300
|
+
computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
|
|
301
|
+
#else
|
|
302
|
+
computedWeight=KERNEL_WEIGHT{X};
|
|
303
|
+
#endif
|
|
304
|
+
#ifdef PACKEDFLOAT
|
|
305
|
+
blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;
|
|
306
|
+
#else
|
|
307
|
+
blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;
|
|
308
|
+
#endif
|
|
309
|
+
`;Z.IncludesShadersStore[ph]||(Z.IncludesShadersStore[ph]=Xd);const mh="kernelBlurFragment2",Kd=`#ifdef DOF
|
|
310
|
+
factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
|
|
311
|
+
#else
|
|
312
|
+
computedWeight=KERNEL_DEP_WEIGHT{X};
|
|
313
|
+
#endif
|
|
314
|
+
#ifdef PACKEDFLOAT
|
|
315
|
+
blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;
|
|
316
|
+
#else
|
|
317
|
+
blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;
|
|
318
|
+
#endif
|
|
319
|
+
`;Z.IncludesShadersStore[mh]||(Z.IncludesShadersStore[mh]=Kd);const jn="kernelBlurPixelShader",Ql=`uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;
|
|
320
|
+
#ifdef DOF
|
|
321
|
+
uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }
|
|
322
|
+
#endif
|
|
323
|
+
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
|
|
324
|
+
#ifdef PACKEDFLOAT
|
|
325
|
+
#include<packingFunctions>
|
|
326
|
+
#endif
|
|
327
|
+
#define CUSTOM_FRAGMENT_DEFINITIONS
|
|
328
|
+
void main(void)
|
|
329
|
+
{float computedWeight=0.0;
|
|
330
|
+
#ifdef PACKEDFLOAT
|
|
331
|
+
float blend=0.;
|
|
332
|
+
#else
|
|
333
|
+
vec4 blend=vec4(0.);
|
|
334
|
+
#endif
|
|
335
|
+
#ifdef DOF
|
|
336
|
+
float sumOfWeights=CENTER_WEIGHT;
|
|
337
|
+
float factor=0.0;
|
|
338
|
+
#ifdef PACKEDFLOAT
|
|
339
|
+
blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;
|
|
340
|
+
#else
|
|
341
|
+
blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;
|
|
342
|
+
#endif
|
|
343
|
+
#endif
|
|
344
|
+
#include<kernelBlurFragment>[0..varyingCount]
|
|
345
|
+
#include<kernelBlurFragment2>[0..depCount]
|
|
346
|
+
#ifdef PACKEDFLOAT
|
|
347
|
+
gl_FragColor=pack(blend);
|
|
348
|
+
#else
|
|
349
|
+
gl_FragColor=blend;
|
|
350
|
+
#endif
|
|
351
|
+
#ifdef DOF
|
|
352
|
+
gl_FragColor/=sumOfWeights;
|
|
353
|
+
#endif
|
|
354
|
+
}`;Z.ShadersStore[jn]||(Z.ShadersStore[jn]=Ql);const Yd={name:jn,shader:Ql},jd=Object.freeze(Object.defineProperty({__proto__:null,kernelBlurPixelShader:Yd},Symbol.toStringTag,{value:"Module"})),Th="kernelBlurVertex",Zd="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";Z.IncludesShadersStore[Th]||(Z.IncludesShadersStore[Th]=Zd);const Zn="kernelBlurVertexShader",$l=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;
|
|
355
|
+
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
|
|
356
|
+
const vec2 madd=vec2(0.5,0.5);
|
|
357
|
+
#define CUSTOM_VERTEX_DEFINITIONS
|
|
358
|
+
void main(void) {
|
|
359
|
+
#define CUSTOM_VERTEX_MAIN_BEGIN
|
|
360
|
+
sampleCenter=(position*madd+madd);
|
|
361
|
+
#include<kernelBlurVertex>[0..varyingCount]
|
|
362
|
+
gl_Position=vec4(position,0.0,1.0);
|
|
363
|
+
#define CUSTOM_VERTEX_MAIN_END
|
|
364
|
+
}`;Z.ShadersStore[Zn]||(Z.ShadersStore[Zn]=$l);const qd={name:Zn,shader:$l},Qd=Object.freeze(Object.defineProperty({__proto__:null,kernelBlurVertexShader:qd},Symbol.toStringTag,{value:"Module"})),qn="bloomMergePixelShader",Jl=`uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight;
|
|
365
|
+
#define CUSTOM_FRAGMENT_DEFINITIONS
|
|
366
|
+
void main(void)
|
|
367
|
+
{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); }
|
|
368
|
+
`;Z.ShadersStore[qn]||(Z.ShadersStore[qn]=Jl);const $d={name:qn,shader:Jl},Jd=Object.freeze(Object.defineProperty({__proto__:null,bloomMergePixelShader:$d},Symbol.toStringTag,{value:"Module"})),Qn="fxaaPixelShader",ec=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
|
|
369
|
+
#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)
|
|
370
|
+
#else
|
|
371
|
+
#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)
|
|
372
|
+
#endif
|
|
373
|
+
uniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);
|
|
374
|
+
#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)
|
|
375
|
+
void main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);
|
|
376
|
+
#ifndef MALI
|
|
377
|
+
if(range<rangeMaxClamped)
|
|
378
|
+
{gl_FragColor=rgbyM;return;}
|
|
379
|
+
#endif
|
|
380
|
+
float lumaNW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNW,0.0));float lumaSE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSE,0.0));float lumaNE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNE,0.0));float lumaSW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSW,0.0));float lumaNS=lumaN+lumaS;float lumaWE=lumaW+lumaE;float subpixRcpRange=1.0/range;float subpixNSWE=lumaNS+lumaWE;float edgeHorz1=(-2.0*lumaM)+lumaNS;float edgeVert1=(-2.0*lumaM)+lumaWE;float lumaNESE=lumaNE+lumaSE;float lumaNWNE=lumaNW+lumaNE;float edgeHorz2=(-2.0*lumaE)+lumaNESE;float edgeVert2=(-2.0*lumaN)+lumaNWNE;float lumaNWSW=lumaNW+lumaSW;float lumaSWSE=lumaSW+lumaSE;float edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);float edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);float edgeHorz3=(-2.0*lumaW)+lumaNWSW;float edgeVert3=(-2.0*lumaS)+lumaSWSE;float edgeHorz=abs(edgeHorz3)+edgeHorz4;float edgeVert=abs(edgeVert3)+edgeVert4;float subpixNWSWNESE=lumaNWSW+lumaNESE;float lengthSign=texelSize.x;bool horzSpan=edgeHorz>=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)
|
|
381
|
+
{lumaN=lumaW;}
|
|
382
|
+
if (!horzSpan)
|
|
383
|
+
{lumaS=lumaE;}
|
|
384
|
+
if (horzSpan)
|
|
385
|
+
{lengthSign=texelSize.y;}
|
|
386
|
+
float subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN)
|
|
387
|
+
{lengthSign=-lengthSign;}
|
|
388
|
+
float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan)
|
|
389
|
+
{posB.x+=lengthSign*0.5;}
|
|
390
|
+
if (horzSpan)
|
|
391
|
+
{posB.y+=lengthSign*0.5;}
|
|
392
|
+
vec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN)
|
|
393
|
+
{lumaNN=lumaSS;}
|
|
394
|
+
float gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN)
|
|
395
|
+
{posN.x-=offNP.x*3.0;}
|
|
396
|
+
if (!doneN)
|
|
397
|
+
{posN.y-=offNP.y*3.0;}
|
|
398
|
+
bool doneNP=(!doneN) || (!doneP);if (!doneP)
|
|
399
|
+
{posP.x+=offNP.x*3.0;}
|
|
400
|
+
if (!doneP)
|
|
401
|
+
{posP.y+=offNP.y*3.0;}
|
|
402
|
+
if (doneNP)
|
|
403
|
+
{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;}
|
|
404
|
+
float dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan)
|
|
405
|
+
{dstN=posM.y-posN.y;}
|
|
406
|
+
if (!horzSpan)
|
|
407
|
+
{dstP=posP.y-posM.y;}
|
|
408
|
+
bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN<dstP;float dst=min(dstN,dstP);bool goodSpan=directionN ? goodSpanN : goodSpanP;float subpixG=subpixF*subpixF;float pixelOffset=(dst*(-spanLengthRcp))+0.5;float subpixH=subpixG*fxaaQualitySubpix;float pixelOffsetGood=goodSpan ? pixelOffset : 0.0;float pixelOffsetSubpix=max(pixelOffsetGood,subpixH);if (!horzSpan)
|
|
409
|
+
{posM.x+=pixelOffsetSubpix*lengthSign;}
|
|
410
|
+
if (horzSpan)
|
|
411
|
+
{posM.y+=pixelOffsetSubpix*lengthSign;}
|
|
412
|
+
#ifdef MALI
|
|
413
|
+
if(range<rangeMaxClamped)
|
|
414
|
+
{gl_FragColor=rgbyM;}
|
|
415
|
+
else
|
|
416
|
+
{gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0);}
|
|
417
|
+
#else
|
|
418
|
+
gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0);
|
|
419
|
+
#endif
|
|
420
|
+
}`;Z.ShadersStore[Qn]||(Z.ShadersStore[Qn]=ec);const e_={name:Qn,shader:ec},t_=Object.freeze(Object.defineProperty({__proto__:null,fxaaPixelShader:e_},Symbol.toStringTag,{value:"Module"})),$n="fxaaVertexShader",tc=`attribute vec2 position;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const vec2 madd=vec2(0.5,0.5);
|
|
421
|
+
#define CUSTOM_VERTEX_DEFINITIONS
|
|
422
|
+
void main(void) {
|
|
423
|
+
#define CUSTOM_VERTEX_MAIN_BEGIN
|
|
424
|
+
vUV=(position*madd+madd);sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;gl_Position=vec4(position,0.0,1.0);
|
|
425
|
+
#define CUSTOM_VERTEX_MAIN_END
|
|
426
|
+
}`;Z.ShadersStore[$n]||(Z.ShadersStore[$n]=tc);const i_={name:$n,shader:tc},s_=Object.freeze(Object.defineProperty({__proto__:null,fxaaVertexShader:i_},Symbol.toStringTag,{value:"Module"})),Jn="passPixelShader",ic=`varying vec2 vUV;uniform sampler2D textureSampler;
|
|
427
|
+
#define CUSTOM_FRAGMENT_DEFINITIONS
|
|
428
|
+
void main(void)
|
|
429
|
+
{gl_FragColor=texture2D(textureSampler,vUV);}`;Z.ShadersStore[Jn]||(Z.ShadersStore[Jn]=ic);const r_={name:Jn,shader:ic},sc=Object.freeze(Object.defineProperty({__proto__:null,passPixelShader:r_},Symbol.toStringTag,{value:"Module"})),ea="imageProcessingDeclaration",rc=`#ifdef EXPOSURE
|
|
430
|
+
uniform exposureLinear: f32;
|
|
431
|
+
#endif
|
|
432
|
+
#ifdef CONTRAST
|
|
433
|
+
uniform contrast: f32;
|
|
434
|
+
#endif
|
|
435
|
+
#if defined(VIGNETTE) || defined(DITHER)
|
|
436
|
+
uniform vInverseScreenSize: vec2f;
|
|
437
|
+
#endif
|
|
438
|
+
#ifdef VIGNETTE
|
|
439
|
+
uniform vignetteSettings1: vec4f;uniform vignetteSettings2: vec4f;
|
|
440
|
+
#endif
|
|
441
|
+
#ifdef COLORCURVES
|
|
442
|
+
uniform vCameraColorCurveNegative: vec4f;uniform vCameraColorCurveNeutral: vec4f;uniform vCameraColorCurvePositive: vec4f;
|
|
443
|
+
#endif
|
|
444
|
+
#ifdef COLORGRADING
|
|
445
|
+
#ifdef COLORGRADING3D
|
|
446
|
+
var txColorTransformSampler: sampler;var txColorTransform: texture_3d<f32>;
|
|
447
|
+
#else
|
|
448
|
+
var txColorTransformSampler: sampler;var txColorTransform: texture_2d<f32>;
|
|
449
|
+
#endif
|
|
450
|
+
uniform colorTransformSettings: vec4f;
|
|
451
|
+
#endif
|
|
452
|
+
#ifdef DITHER
|
|
453
|
+
uniform ditherIntensity: f32;
|
|
454
|
+
#endif
|
|
455
|
+
`;Z.IncludesShadersStoreWGSL[ea]||(Z.IncludesShadersStoreWGSL[ea]=rc);const n_={name:ea,shader:rc},om=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingDeclarationWGSL:n_},Symbol.toStringTag,{value:"Module"})),ta="helperFunctions",nc=`const PI: f32=3.1415926535897932384626433832795;const TWO_PI: f32=6.283185307179586;const HALF_PI: f32=1.5707963267948966;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const RECIPROCAL_PI4: f32=0.07957747154594767;const HALF_MIN: f32=5.96046448e-08;
|
|
456
|
+
const LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3f=vec3f(0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;fn square(x: f32)->f32 {return x*x;}
|
|
457
|
+
fn saturate(x: f32)->f32 {return clamp(x,0.0,1.0);}
|
|
458
|
+
fn saturateVec3(x: vec3f)->vec3f {return clamp(x,vec3f(),vec3f(1.0));}
|
|
459
|
+
fn saturateEps(x: f32)->f32 {return clamp(x,Epsilon,1.0);}
|
|
460
|
+
fn maxEps(x: f32)->f32 {return max(x,Epsilon);}
|
|
461
|
+
fn maxEpsVec3(x: vec3f)->vec3f {return max(x,vec3f(Epsilon));}
|
|
462
|
+
fn absEps(x: f32)->f32 {return abs(x)+Epsilon;}
|
|
463
|
+
fn transposeMat3(inMatrix: mat3x3f)->mat3x3f {let i0: vec3f=inMatrix[0];let i1: vec3f=inMatrix[1];let i2: vec3f=inMatrix[2];let outMatrix:mat3x3f=mat3x3f(
|
|
464
|
+
vec3(i0.x,i1.x,i2.x),
|
|
465
|
+
vec3(i0.y,i1.y,i2.y),
|
|
466
|
+
vec3(i0.z,i1.z,i2.z)
|
|
467
|
+
);return outMatrix;}
|
|
468
|
+
fn inverseMat3(inMatrix: mat3x3f)->mat3x3f {let a00: f32=inMatrix[0][0];let a01: f32=inMatrix[0][1];let a02: f32=inMatrix[0][2];let a10: f32=inMatrix[1][0];let a11: f32=inMatrix[1][1];let a12: f32=inMatrix[1][2];let a20: f32=inMatrix[2][0];let a21: f32=inMatrix[2][1];let a22: f32=inMatrix[2][2];let b01: f32=a22*a11-a12*a21;let b11: f32=-a22*a10+a12*a20;let b21: f32=a21*a10-a11*a20;let det: f32=a00*b01+a01*b11+a02*b21;return mat3x3f(b01/det,(-a22*a01+a02*a21)/det,(a12*a01-a02*a11)/det,
|
|
469
|
+
b11/det,(a22*a00-a02*a20)/det,(-a12*a00+a02*a10)/det,
|
|
470
|
+
b21/det,(-a21*a00+a01*a20)/det,(a11*a00-a01*a10)/det);}
|
|
471
|
+
#if USE_EXACT_SRGB_CONVERSIONS
|
|
472
|
+
fn toLinearSpaceExact(color: vec3f)->vec3f
|
|
473
|
+
{let nearZeroSection: vec3f=0.0773993808*color;let remainingSection: vec3f=pow(0.947867299*(color+vec3f(0.055)),vec3f(2.4));return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3f(0.04045)));}
|
|
474
|
+
fn toGammaSpaceExact(color: vec3f)->vec3f
|
|
475
|
+
{let nearZeroSection: vec3f=12.92*color;let remainingSection: vec3f=1.055*pow(color,vec3f(0.41666))-vec3f(0.055);return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3f(0.0031308)));}
|
|
476
|
+
#endif
|
|
477
|
+
fn toLinearSpace(color: f32)->f32
|
|
478
|
+
{
|
|
479
|
+
#if USE_EXACT_SRGB_CONVERSIONS
|
|
480
|
+
var nearZeroSection=0.0773993808*color;var remainingSection=pow(0.947867299*(color+0.055),2.4);return select(remainingSection,nearZeroSection,color<=0.04045);
|
|
481
|
+
#else
|
|
482
|
+
return pow(color,LinearEncodePowerApprox);
|
|
483
|
+
#endif
|
|
484
|
+
}
|
|
485
|
+
fn toLinearSpaceVec3(color: vec3f)->vec3f
|
|
486
|
+
{
|
|
487
|
+
#if USE_EXACT_SRGB_CONVERSIONS
|
|
488
|
+
return toLinearSpaceExact(color);
|
|
489
|
+
#else
|
|
490
|
+
return pow(color,vec3f(LinearEncodePowerApprox));
|
|
491
|
+
#endif
|
|
492
|
+
}
|
|
493
|
+
fn toLinearSpaceVec4(color: vec4<f32>)->vec4<f32>
|
|
494
|
+
{
|
|
495
|
+
#if USE_EXACT_SRGB_CONVERSIONS
|
|
496
|
+
return vec4f(toLinearSpaceExact(color.rgb),color.a);
|
|
497
|
+
#else
|
|
498
|
+
return vec4f(pow(color.rgb,vec3f(LinearEncodePowerApprox)),color.a);
|
|
499
|
+
#endif
|
|
500
|
+
}
|
|
501
|
+
fn toGammaSpace(color: vec4<f32>)->vec4<f32>
|
|
502
|
+
{
|
|
503
|
+
#if USE_EXACT_SRGB_CONVERSIONS
|
|
504
|
+
return vec4<f32>(toGammaSpaceExact(color.rgb),color.a);
|
|
505
|
+
#else
|
|
506
|
+
return vec4<f32>(pow(color.rgb,vec3f(GammaEncodePowerApprox)),color.a);
|
|
507
|
+
#endif
|
|
508
|
+
}
|
|
509
|
+
fn toGammaSpaceVec3(color: vec3f)->vec3f
|
|
510
|
+
{
|
|
511
|
+
#if USE_EXACT_SRGB_CONVERSIONS
|
|
512
|
+
return toGammaSpaceExact(color);
|
|
513
|
+
#else
|
|
514
|
+
return pow(color,vec3f(GammaEncodePowerApprox));
|
|
515
|
+
#endif
|
|
516
|
+
}
|
|
517
|
+
fn squareVec3(value: vec3f)->vec3f
|
|
518
|
+
{return value*value;}
|
|
519
|
+
fn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;}
|
|
520
|
+
fn double_refract(I: vec3f,N: vec3f,eta: f32)->vec3f {let Tfront: vec3f=refract(I,N,1.0/eta);let Nback: vec3f=normalize(reflect(N,Tfront));return refract(Tfront,-Nback,eta);}
|
|
521
|
+
fn getLuminanceUnclamped(color: vec3f)->f32
|
|
522
|
+
{return dot(color,LuminanceEncodeApprox);}
|
|
523
|
+
fn getLuminance(color: vec3f)->f32
|
|
524
|
+
{return saturate(getLuminanceUnclamped(color));}
|
|
525
|
+
fn getRand(seed: vec2<f32>)->f32 {return fract(sin(dot(seed.xy ,vec2<f32>(12.9898,78.233)))*43758.5453);}
|
|
526
|
+
fn dither(seed: vec2<f32>,varianceAmount: f32)->f32 {let rand: f32=getRand(seed);let normVariance: f32=varianceAmount/255.0;let dither: f32=mix(-normVariance,normVariance,rand);return dither;}
|
|
527
|
+
const rgbdMaxRange: f32=255.0;fn toRGBD(color: vec3f)->vec4<f32> {let maxRGB: f32=max(max(color.r,max(color.g,color.b)),Epsilon);var D: f32 =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);var rgb: vec3f =color.rgb*D;rgb=toGammaSpaceVec3(rgb);return vec4<f32>(saturateVec3(rgb),D);}
|
|
528
|
+
fn fromRGBD(rgbd: vec4<f32>)->vec3f {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;}
|
|
529
|
+
fn parallaxCorrectNormal(vertexPos: vec3f,origVec: vec3f,cubeSize: vec3f,cubePos: vec3f)->vec3f {let invOrigVec: vec3f=vec3f(1.)/origVec;let halfSize: vec3f=cubeSize*0.5;let intersecAtMaxPlane: vec3f=(cubePos+halfSize-vertexPos)*invOrigVec;let intersecAtMinPlane: vec3f=(cubePos-halfSize-vertexPos)*invOrigVec;let largestIntersec: vec3f=max(intersecAtMaxPlane,intersecAtMinPlane);let distance: f32=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);let intersectPositionWS: vec3f=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}
|
|
530
|
+
fn equirectangularToCubemapDirection(uv : vec2f)->vec3f {var longitude : f32=uv.x*TWO_PI-PI;var latitude : f32=HALF_PI-uv.y*PI;var direction : vec3f;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}
|
|
531
|
+
fn sqrtClamped(value: f32)->f32 {return sqrt(max(value,0.));}
|
|
532
|
+
fn avg(value: vec3f)->f32 {return dot(value,vec3f(0.333333333));}
|
|
533
|
+
fn singleScatterToMultiScatterAlbedo(rho_ss: vec3f)->vec3f {let s: vec3f=sqrt(max(vec3f(1.0)-rho_ss,vec3f(0.0)));return (vec3f(1.0)-s)*(vec3f(1.0)-vec3f(0.139)*s)/(vec3f(1.0)+vec3f(1.17)*s);}
|
|
534
|
+
fn min3(v: vec3f)->f32 {return min(v.x,min(v.y,v.z));}
|
|
535
|
+
fn max3(v: vec3f)->f32 {return max(v.x,max(v.y,v.z));}
|
|
536
|
+
`;Z.IncludesShadersStoreWGSL[ta]||(Z.IncludesShadersStoreWGSL[ta]=nc);const a_={name:ta,shader:nc},hm=Object.freeze(Object.defineProperty({__proto__:null,helperFunctionsWGSL:a_},Symbol.toStringTag,{value:"Module"})),ia="imageProcessingFunctions",ac=`#if TONEMAPPING==3
|
|
537
|
+
const PBRNeutralStartCompression: f32=0.8-0.04;const PBRNeutralDesaturation: f32=0.15;fn PBRNeutralToneMapping( color: vec3f )->vec3f {var x: f32=min(color.r,min(color.g,color.b));var offset: f32=select(0.04,x-6.25*x*x,x<0.08);var result=color;result-=offset;var peak: f32=max(result.r,max(result.g,result.b));if (peak<PBRNeutralStartCompression) {return result;}
|
|
538
|
+
var d: f32=1.-PBRNeutralStartCompression;var newPeak: f32=1.-d*d/(peak+d-PBRNeutralStartCompression);result*=newPeak/peak;var g: f32=1.-1./(PBRNeutralDesaturation*(peak-newPeak)+1.);return mix(result,newPeak* vec3f(1,1,1),g);}
|
|
539
|
+
#endif
|
|
540
|
+
#if TONEMAPPING==2
|
|
541
|
+
const ACESInputMat: mat3x3f= mat3x3f(
|
|
542
|
+
vec3f(0.59719,0.07600,0.02840),
|
|
543
|
+
vec3f(0.35458,0.90834,0.13383),
|
|
544
|
+
vec3f(0.04823,0.01566,0.83777)
|
|
545
|
+
);const ACESOutputMat: mat3x3f= mat3x3f(
|
|
546
|
+
vec3f( 1.60475,-0.10208,-0.00327),
|
|
547
|
+
vec3f(-0.53108, 1.10813,-0.07276),
|
|
548
|
+
vec3f(-0.07367,-0.00605, 1.07602)
|
|
549
|
+
);fn RRTAndODTFit(v: vec3f)->vec3f
|
|
550
|
+
{var a: vec3f=v*(v+0.0245786)-0.000090537;var b: vec3f=v*(0.983729*v+0.4329510)+0.238081;return a/b;}
|
|
551
|
+
fn ACESFitted(color: vec3f)->vec3f
|
|
552
|
+
{var output=ACESInputMat*color;output=RRTAndODTFit(output);output=ACESOutputMat*output;output=saturateVec3(output);return output;}
|
|
553
|
+
#endif
|
|
554
|
+
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS
|
|
555
|
+
fn applyImageProcessing(result: vec4f)->vec4f {
|
|
556
|
+
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART
|
|
557
|
+
var rgb=result.rgb;;
|
|
558
|
+
#ifdef EXPOSURE
|
|
559
|
+
rgb*=uniforms.exposureLinear;
|
|
560
|
+
#endif
|
|
561
|
+
#ifdef VIGNETTE
|
|
562
|
+
var viewportXY: vec2f=fragmentInputs.position.xy*uniforms.vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;var vignetteXY1: vec3f= vec3f(viewportXY*uniforms.vignetteSettings1.xy+uniforms.vignetteSettings1.zw,1.0);var vignetteTerm: f32=dot(vignetteXY1,vignetteXY1);var vignette: f32=pow(vignetteTerm,uniforms.vignetteSettings2.w);var vignetteColor: vec3f=uniforms.vignetteSettings2.rgb;
|
|
563
|
+
#ifdef VIGNETTEBLENDMODEMULTIPLY
|
|
564
|
+
var vignetteColorMultiplier: vec3f=mix(vignetteColor, vec3f(1,1,1),vignette);rgb*=vignetteColorMultiplier;
|
|
565
|
+
#endif
|
|
566
|
+
#ifdef VIGNETTEBLENDMODEOPAQUE
|
|
567
|
+
rgb=mix(vignetteColor,rgb,vignette);
|
|
568
|
+
#endif
|
|
569
|
+
#endif
|
|
570
|
+
#if TONEMAPPING==3
|
|
571
|
+
rgb=PBRNeutralToneMapping(rgb);
|
|
572
|
+
#elif TONEMAPPING==2
|
|
573
|
+
rgb=ACESFitted(rgb);
|
|
574
|
+
#elif TONEMAPPING==1
|
|
575
|
+
const tonemappingCalibration: f32=1.590579;rgb=1.0-exp2(-tonemappingCalibration*rgb);
|
|
576
|
+
#endif
|
|
577
|
+
rgb=toGammaSpaceVec3(rgb);rgb=saturateVec3(rgb);
|
|
578
|
+
#ifdef CONTRAST
|
|
579
|
+
var resultHighContrast: vec3f=rgb*rgb*(3.0-2.0*rgb);if (uniforms.contrast<1.0) {rgb=mix( vec3f(0.5,0.5,0.5),rgb,uniforms.contrast);} else {rgb=mix(rgb,resultHighContrast,uniforms.contrast-1.0);}
|
|
580
|
+
rgb=max(rgb,vec3f(0.));
|
|
581
|
+
#endif
|
|
582
|
+
#ifdef COLORGRADING
|
|
583
|
+
var colorTransformInput: vec3f=rgb*uniforms.colorTransformSettings.xxx+uniforms.colorTransformSettings.yyy;
|
|
584
|
+
#ifdef COLORGRADING3D
|
|
585
|
+
var colorTransformOutput: vec3f=textureSample(txColorTransform,txColorTransformSampler,colorTransformInput).rgb;
|
|
586
|
+
#else
|
|
587
|
+
var colorTransformOutput: vec3f=textureSample(txColorTransform,txColorTransformSampler,colorTransformInput,uniforms.colorTransformSettings.yz).rgb;
|
|
588
|
+
#endif
|
|
589
|
+
rgb=mix(rgb,colorTransformOutput,uniforms.colorTransformSettings.www);
|
|
590
|
+
#endif
|
|
591
|
+
#ifdef COLORCURVES
|
|
592
|
+
var luma: f32=getLuminance(rgb);var curveMix: vec2f=clamp( vec2f(luma*3.0-1.5,luma*-3.0+1.5), vec2f(0.0), vec2f(1.0));var colorCurve: vec4f=uniforms.vCameraColorCurveNeutral+curveMix.x*uniforms.vCameraColorCurvePositive-curveMix.y*uniforms.vCameraColorCurveNegative;rgb*=colorCurve.rgb;rgb=mix( vec3f(luma),rgb,colorCurve.a);
|
|
593
|
+
#endif
|
|
594
|
+
#ifdef DITHER
|
|
595
|
+
var rand: f32=getRand(fragmentInputs.position.xy*uniforms.vInverseScreenSize);var dither: f32=mix(-uniforms.ditherIntensity,uniforms.ditherIntensity,rand);rgb=saturateVec3(rgb+ vec3f(dither));
|
|
596
|
+
#endif
|
|
597
|
+
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND
|
|
598
|
+
return vec4f(rgb,result.a);}`;Z.IncludesShadersStoreWGSL[ia]||(Z.IncludesShadersStoreWGSL[ia]=ac);const o_={name:ia,shader:ac},lm=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingFunctionsWGSL:o_},Symbol.toStringTag,{value:"Module"})),sa="imageProcessingPixelShader",oc=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;
|
|
599
|
+
#include<imageProcessingDeclaration>
|
|
600
|
+
#include<helperFunctions>
|
|
601
|
+
#include<imageProcessingFunctions>
|
|
602
|
+
#define CUSTOM_FRAGMENT_DEFINITIONS
|
|
603
|
+
@fragment
|
|
604
|
+
fn main(input: FragmentInputs)->FragmentOutputs {var result: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);result=vec4f(max(result.rgb,vec3f(0.)),result.a);
|
|
605
|
+
#ifdef IMAGEPROCESSING
|
|
606
|
+
#ifndef FROMLINEARSPACE
|
|
607
|
+
result=vec4f(toLinearSpaceVec3(result.rgb),result.a);
|
|
608
|
+
#endif
|
|
609
|
+
result=applyImageProcessing(result);
|
|
610
|
+
#else
|
|
611
|
+
#ifdef FROMLINEARSPACE
|
|
612
|
+
result=applyImageProcessing(result);
|
|
613
|
+
#endif
|
|
614
|
+
#endif
|
|
615
|
+
fragmentOutputs.color=result;}`;Z.ShadersStoreWGSL[sa]||(Z.ShadersStoreWGSL[sa]=oc);const h_={name:sa,shader:oc},l_=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingPixelShaderWGSL:h_},Symbol.toStringTag,{value:"Module"})),ra="extractHighlightsPixelShader",hc=`#include<helperFunctions>
|
|
616
|
+
varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform threshold: f32;uniform exposure: f32;
|
|
617
|
+
#define CUSTOM_FRAGMENT_DEFINITIONS
|
|
618
|
+
@fragment
|
|
619
|
+
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var luma: f32=dot(LuminanceEncodeApprox,fragmentOutputs.color.rgb*uniforms.exposure);fragmentOutputs.color=vec4f(step(uniforms.threshold,luma)*fragmentOutputs.color.rgb,fragmentOutputs.color.a);}`;Z.ShadersStoreWGSL[ra]||(Z.ShadersStoreWGSL[ra]=hc);const c_={name:ra,shader:hc},u_=Object.freeze(Object.defineProperty({__proto__:null,extractHighlightsPixelShaderWGSL:c_},Symbol.toStringTag,{value:"Module"})),Eh="kernelBlurVaryingDeclaration",f_="varying sampleCoord{X}: vec2f;";Z.IncludesShadersStoreWGSL[Eh]||(Z.IncludesShadersStoreWGSL[Eh]=f_);const na="packingFunctions",lc=`fn pack(depth: f32)->vec4f
|
|
620
|
+
{const bit_shift: vec4f= vec4f(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const bit_mask: vec4f= vec4f(0.0,1.0/255.0,1.0/255.0,1.0/255.0);var res: vec4f=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}
|
|
621
|
+
fn unpack(color: vec4f)->f32
|
|
622
|
+
{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;Z.IncludesShadersStoreWGSL[na]||(Z.IncludesShadersStoreWGSL[na]=lc);const d_={name:na,shader:lc},cm=Object.freeze(Object.defineProperty({__proto__:null,packingFunctionsWGSL:d_},Symbol.toStringTag,{value:"Module"})),xh="kernelBlurFragment",__=`#ifdef DOF
|
|
623
|
+
factor=sampleCoC(fragmentInputs.sampleCoord{X});
|
|
624
|
+
computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
|
|
625
|
+
#else
|
|
626
|
+
computedWeight=KERNEL_WEIGHT{X};
|
|
627
|
+
#endif
|
|
628
|
+
#ifdef PACKEDFLOAT
|
|
629
|
+
blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X}))*computedWeight;
|
|
630
|
+
#else
|
|
631
|
+
blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X})*computedWeight;
|
|
632
|
+
#endif
|
|
633
|
+
`;Z.IncludesShadersStoreWGSL[xh]||(Z.IncludesShadersStoreWGSL[xh]=__);const bh="kernelBlurFragment2",g_=`#ifdef DOF
|
|
634
|
+
factor=sampleCoC(fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
|
|
635
|
+
#else
|
|
636
|
+
computedWeight=KERNEL_DEP_WEIGHT{X};
|
|
637
|
+
#endif
|
|
638
|
+
#ifdef PACKEDFLOAT
|
|
639
|
+
blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X}))*computedWeight;
|
|
640
|
+
#else
|
|
641
|
+
blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X})*computedWeight;
|
|
642
|
+
#endif
|
|
643
|
+
`;Z.IncludesShadersStoreWGSL[bh]||(Z.IncludesShadersStoreWGSL[bh]=g_);const aa="kernelBlurPixelShader",cc=`var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform delta: vec2f;varying sampleCenter: vec2f;
|
|
644
|
+
#ifdef DOF
|
|
645
|
+
var circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d<f32>;fn sampleCoC(offset: vec2f)->f32 {var coc: f32=textureSample(circleOfConfusionSampler,circleOfConfusionSamplerSampler,offset).r;return coc; }
|
|
646
|
+
#endif
|
|
647
|
+
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
|
|
648
|
+
#ifdef PACKEDFLOAT
|
|
649
|
+
#include<packingFunctions>
|
|
650
|
+
#endif
|
|
651
|
+
#define CUSTOM_FRAGMENT_DEFINITIONS
|
|
652
|
+
@fragment
|
|
653
|
+
fn main(input: FragmentInputs)->FragmentOutputs {var computedWeight: f32=0.0;
|
|
654
|
+
#ifdef PACKEDFLOAT
|
|
655
|
+
var blend: f32=0.;
|
|
656
|
+
#else
|
|
657
|
+
var blend: vec4f= vec4f(0.);
|
|
658
|
+
#endif
|
|
659
|
+
#ifdef DOF
|
|
660
|
+
var sumOfWeights: f32=CENTER_WEIGHT;
|
|
661
|
+
var factor: f32=0.0;
|
|
662
|
+
#ifdef PACKEDFLOAT
|
|
663
|
+
blend+=unpack(textureSample(textureSampler,textureSamplerSampler,input.sampleCenter))*CENTER_WEIGHT;
|
|
664
|
+
#else
|
|
665
|
+
blend+=textureSample(textureSampler,textureSamplerSampler,input.sampleCenter)*CENTER_WEIGHT;
|
|
666
|
+
#endif
|
|
667
|
+
#endif
|
|
668
|
+
#include<kernelBlurFragment>[0..varyingCount]
|
|
669
|
+
#include<kernelBlurFragment2>[0..depCount]
|
|
670
|
+
#ifdef PACKEDFLOAT
|
|
671
|
+
fragmentOutputs.color=pack(blend);
|
|
672
|
+
#else
|
|
673
|
+
fragmentOutputs.color=blend;
|
|
674
|
+
#endif
|
|
675
|
+
#ifdef DOF
|
|
676
|
+
fragmentOutputs.color/=sumOfWeights;
|
|
677
|
+
#endif
|
|
678
|
+
}`;Z.ShadersStoreWGSL[aa]||(Z.ShadersStoreWGSL[aa]=cc);const p_={name:aa,shader:cc},m_=Object.freeze(Object.defineProperty({__proto__:null,kernelBlurPixelShaderWGSL:p_},Symbol.toStringTag,{value:"Module"})),Rh="kernelBlurVertex",T_="vertexOutputs.sampleCoord{X}=vertexOutputs.sampleCenter+uniforms.delta*KERNEL_OFFSET{X};";Z.IncludesShadersStoreWGSL[Rh]||(Z.IncludesShadersStoreWGSL[Rh]=T_);const oa="kernelBlurVertexShader",uc=`attribute position: vec2f;uniform delta: vec2f;varying sampleCenter: vec2f;
|
|
679
|
+
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
|
|
680
|
+
#define CUSTOM_VERTEX_DEFINITIONS
|
|
681
|
+
@vertex
|
|
682
|
+
fn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5);
|
|
683
|
+
#define CUSTOM_VERTEX_MAIN_BEGIN
|
|
684
|
+
vertexOutputs.sampleCenter=(vertexInputs.position*madd+madd);
|
|
685
|
+
#include<kernelBlurVertex>[0..varyingCount]
|
|
686
|
+
vertexOutputs.position= vec4f(vertexInputs.position,0.0,1.0);
|
|
687
|
+
#define CUSTOM_VERTEX_MAIN_END
|
|
688
|
+
}`;Z.ShadersStoreWGSL[oa]||(Z.ShadersStoreWGSL[oa]=uc);const E_={name:oa,shader:uc},x_=Object.freeze(Object.defineProperty({__proto__:null,kernelBlurVertexShaderWGSL:E_},Symbol.toStringTag,{value:"Module"})),ha="bloomMergePixelShader",fc=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;var bloomBlurSampler: sampler;var bloomBlur: texture_2d<f32>;uniform bloomWeight: f32;
|
|
689
|
+
#define CUSTOM_FRAGMENT_DEFINITIONS
|
|
690
|
+
@fragment
|
|
691
|
+
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var blurred: vec3f=textureSample(bloomBlur,bloomBlurSampler,input.vUV).rgb;fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb+(blurred.rgb*uniforms.bloomWeight),fragmentOutputs.color.a);}
|
|
692
|
+
`;Z.ShadersStoreWGSL[ha]||(Z.ShadersStoreWGSL[ha]=fc);const b_={name:ha,shader:fc},R_=Object.freeze(Object.defineProperty({__proto__:null,bloomMergePixelShaderWGSL:b_},Symbol.toStringTag,{value:"Module"})),la="fxaaPixelShader",dc=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform texelSize: vec2f;varying sampleCoordS: vec2f;varying sampleCoordE: vec2f;varying sampleCoordN: vec2f;varying sampleCoordW: vec2f;varying sampleCoordNW: vec2f;varying sampleCoordSE: vec2f;varying sampleCoordNE: vec2f;varying sampleCoordSW: vec2f;const fxaaQualitySubpix: f32=1.0;const fxaaQualityEdgeThreshold: f32=0.166;const fxaaQualityEdgeThresholdMin: f32=0.0833;const kLumaCoefficients: vec3f= vec3f(0.2126,0.7152,0.0722);fn FxaaLuma(rgba: vec4f)->f32 {return dot(rgba.rgb,kLumaCoefficients);}
|
|
693
|
+
@fragment
|
|
694
|
+
fn main(input: FragmentInputs)->FragmentOutputs {var posM: vec2f;posM.x=input.vUV.x;posM.y=input.vUV.y;var rgbyM: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var lumaM: f32=FxaaLuma(rgbyM);var lumaS: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordS,0.0));var lumaE: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordE,0.0));var lumaN: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordN,0.0));var lumaW: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordW,0.0));var maxSM: f32=max(lumaS,lumaM);var minSM: f32=min(lumaS,lumaM);var maxESM: f32=max(lumaE,maxSM);var minESM: f32=min(lumaE,minSM);var maxWN: f32=max(lumaN,lumaW);var minWN: f32=min(lumaN,lumaW);var rangeMax: f32=max(maxWN,maxESM);var rangeMin: f32=min(minWN,minESM);var rangeMaxScaled: f32=rangeMax*fxaaQualityEdgeThreshold;var range: f32=rangeMax-rangeMin;var rangeMaxClamped: f32=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);
|
|
695
|
+
#ifndef MALI
|
|
696
|
+
if(range<rangeMaxClamped)
|
|
697
|
+
{fragmentOutputs.color=rgbyM;return fragmentOutputs;}
|
|
698
|
+
#endif
|
|
699
|
+
var lumaNW: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordNW,0.0));var lumaSE: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordSE,0.0));var lumaNE: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordNE,0.0));var lumaSW: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordSW,0.0));var lumaNS: f32=lumaN+lumaS;var lumaWE: f32=lumaW+lumaE;var subpixRcpRange: f32=1.0/range;var subpixNSWE: f32=lumaNS+lumaWE;var edgeHorz1: f32=(-2.0*lumaM)+lumaNS;var edgeVert1: f32=(-2.0*lumaM)+lumaWE;var lumaNESE: f32=lumaNE+lumaSE;var lumaNWNE: f32=lumaNW+lumaNE;var edgeHorz2: f32=(-2.0*lumaE)+lumaNESE;var edgeVert2: f32=(-2.0*lumaN)+lumaNWNE;var lumaNWSW: f32=lumaNW+lumaSW;var lumaSWSE: f32=lumaSW+lumaSE;var edgeHorz4: f32=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);var edgeVert4: f32=(abs(edgeVert1)*2.0)+abs(edgeVert2);var edgeHorz3: f32=(-2.0*lumaW)+lumaNWSW;var edgeVert3: f32=(-2.0*lumaS)+lumaSWSE;var edgeHorz: f32=abs(edgeHorz3)+edgeHorz4;var edgeVert: f32=abs(edgeVert3)+edgeVert4;var subpixNWSWNESE: f32=lumaNWSW+lumaNESE;var lengthSign: f32=uniforms.texelSize.x;var horzSpan: bool=edgeHorz>=edgeVert;var subpixA: f32=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)
|
|
700
|
+
{lumaN=lumaW;}
|
|
701
|
+
if (!horzSpan)
|
|
702
|
+
{lumaS=lumaE;}
|
|
703
|
+
if (horzSpan)
|
|
704
|
+
{lengthSign=uniforms.texelSize.y;}
|
|
705
|
+
var subpixB: f32=(subpixA*(1.0/12.0))-lumaM;var gradientN: f32=lumaN-lumaM;var gradientS: f32=lumaS-lumaM;var lumaNN: f32=lumaN+lumaM;var lumaSS: f32=lumaS+lumaM;var pairN: bool=abs(gradientN)>=abs(gradientS);var gradient: f32=max(abs(gradientN),abs(gradientS));if (pairN)
|
|
706
|
+
{lengthSign=-lengthSign;}
|
|
707
|
+
var subpixC: f32=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);var posB: vec2f;posB.x=posM.x;posB.y=posM.y;var offNP: vec2f;offNP.x=select(uniforms.texelSize.x,0.0,(!horzSpan));offNP.y=select(uniforms.texelSize.y,0.0,(horzSpan));if (!horzSpan)
|
|
708
|
+
{posB.x+=lengthSign*0.5;}
|
|
709
|
+
if (horzSpan)
|
|
710
|
+
{posB.y+=lengthSign*0.5;}
|
|
711
|
+
var posN: vec2f;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;var posP: vec2f;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;var subpixD: f32=((-2.0)*subpixC)+3.0;var lumaEndN: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posN,0.0));var subpixE: f32=subpixC*subpixC;var lumaEndP: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posP,0.0));if (!pairN)
|
|
712
|
+
{lumaNN=lumaSS;}
|
|
713
|
+
var gradientScaled: f32=gradient*1.0/4.0;var lumaMM: f32=lumaM-lumaNN*0.5;var subpixF: f32=subpixD*subpixE;var lumaMLTZero: bool=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;var doneN: bool=abs(lumaEndN)>=gradientScaled;var doneP: bool=abs(lumaEndP)>=gradientScaled;if (!doneN)
|
|
714
|
+
{posN.x-=offNP.x*3.0;}
|
|
715
|
+
if (!doneN)
|
|
716
|
+
{posN.y-=offNP.y*3.0;}
|
|
717
|
+
var doneNP: bool=(!doneN) || (!doneP);if (!doneP)
|
|
718
|
+
{posP.x+=offNP.x*3.0;}
|
|
719
|
+
if (!doneP)
|
|
720
|
+
{posP.y+=offNP.y*3.0;}
|
|
721
|
+
if (doneNP)
|
|
722
|
+
{if (!doneN) {lumaEndN=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posN.xy,0.0));}
|
|
723
|
+
if (!doneP) {lumaEndP=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posP.xy,0.0));}
|
|
724
|
+
if (!doneN) {lumaEndN=lumaEndN-lumaNN*0.5;}
|
|
725
|
+
if (!doneP) {lumaEndP=lumaEndP-lumaNN*0.5;}
|
|
726
|
+
doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) {posN.x-=offNP.x*12.0;}
|
|
727
|
+
if (!doneN) {posN.y-=offNP.y*12.0;}
|
|
728
|
+
doneNP=(!doneN) || (!doneP);if (!doneP) {posP.x+=offNP.x*12.0;}
|
|
729
|
+
if (!doneP) {posP.y+=offNP.y*12.0;}}
|
|
730
|
+
var dstN: f32=posM.x-posN.x;var dstP: f32=posP.x-posM.x;if (!horzSpan)
|
|
731
|
+
{dstN=posM.y-posN.y;}
|
|
732
|
+
if (!horzSpan)
|
|
733
|
+
{dstP=posP.y-posM.y;}
|
|
734
|
+
var goodSpanN: bool=(lumaEndN<0.0) != lumaMLTZero;var spanLength: f32=(dstP+dstN);var goodSpanP: bool=(lumaEndP<0.0) != lumaMLTZero;var spanLengthRcp: f32=1.0/spanLength;var directionN: bool=dstN<dstP;var dst: f32=min(dstN,dstP);var goodSpan: bool=select(goodSpanP,goodSpanN,directionN);var subpixG: f32=subpixF*subpixF;var pixelOffset: f32=(dst*(-spanLengthRcp))+0.5;var subpixH: f32=subpixG*fxaaQualitySubpix;var pixelOffsetGood: f32=select(0.0,pixelOffset,goodSpan);var pixelOffsetSubpix: f32=max(pixelOffsetGood,subpixH);if (!horzSpan)
|
|
735
|
+
{posM.x+=pixelOffsetSubpix*lengthSign;}
|
|
736
|
+
if (horzSpan)
|
|
737
|
+
{posM.y+=pixelOffsetSubpix*lengthSign;}
|
|
738
|
+
#ifdef MALI
|
|
739
|
+
if(range<rangeMaxClamped)
|
|
740
|
+
{fragmentOutputs.color=rgbyM;}
|
|
741
|
+
else
|
|
742
|
+
{fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,posM,0.0);}
|
|
743
|
+
#else
|
|
744
|
+
fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,posM,0.0);
|
|
745
|
+
#endif
|
|
746
|
+
}`;Z.ShadersStoreWGSL[la]||(Z.ShadersStoreWGSL[la]=dc);const S_={name:la,shader:dc},y_=Object.freeze(Object.defineProperty({__proto__:null,fxaaPixelShaderWGSL:S_},Symbol.toStringTag,{value:"Module"})),ca="fxaaVertexShader",_c=`attribute position: vec2f;uniform texelSize: vec2f;varying vUV: vec2f;varying sampleCoordS: vec2f;varying sampleCoordE: vec2f;varying sampleCoordN: vec2f;varying sampleCoordW: vec2f;varying sampleCoordNW: vec2f;varying sampleCoordSE: vec2f;varying sampleCoordNE: vec2f;varying sampleCoordSW: vec2f;const madd: vec2f= vec2f(0.5,0.5);
|
|
747
|
+
#define CUSTOM_VERTEX_DEFINITIONS
|
|
748
|
+
@vertex
|
|
749
|
+
fn main(input : VertexInputs)->FragmentInputs {
|
|
750
|
+
#define CUSTOM_VERTEX_MAIN_BEGIN
|
|
751
|
+
vertexOutputs.vUV=(vertexInputs.position*madd+madd);vertexOutputs.sampleCoordS=vertexOutputs.vUV+ vec2f( 0.0,1.0)*uniforms.texelSize;vertexOutputs.sampleCoordE=vertexOutputs.vUV+ vec2f( 1.0,0.0)*uniforms.texelSize;vertexOutputs.sampleCoordN=vertexOutputs.vUV+ vec2f( 0.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordW=vertexOutputs.vUV+ vec2f(-1.0,0.0)*uniforms.texelSize;vertexOutputs.sampleCoordNW=vertexOutputs.vUV+ vec2f(-1.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordSE=vertexOutputs.vUV+ vec2f( 1.0,1.0)*uniforms.texelSize;vertexOutputs.sampleCoordNE=vertexOutputs.vUV+ vec2f( 1.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordSW=vertexOutputs.vUV+ vec2f(-1.0,1.0)*uniforms.texelSize;vertexOutputs.position=vec4f(vertexInputs.position,0.0,1.0);
|
|
752
|
+
#define CUSTOM_VERTEX_MAIN_END
|
|
753
|
+
}`;Z.ShadersStoreWGSL[ca]||(Z.ShadersStoreWGSL[ca]=_c);const A_={name:ca,shader:_c},M_=Object.freeze(Object.defineProperty({__proto__:null,fxaaVertexShaderWGSL:A_},Symbol.toStringTag,{value:"Module"})),ua="passPixelShader",gc=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;
|
|
754
|
+
#define CUSTOM_FRAGMENT_DEFINITIONS
|
|
755
|
+
@fragment
|
|
756
|
+
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);}`;Z.ShadersStoreWGSL[ua]||(Z.ShadersStoreWGSL[ua]=gc);const P_={name:ua,shader:gc},I_=Object.freeze(Object.defineProperty({__proto__:null,passPixelShaderWGSL:P_},Symbol.toStringTag,{value:"Module"}));class _t extends Qe{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([he(()=>Promise.resolve().then(()=>m_),void 0,import.meta.url),he(()=>Promise.resolve().then(()=>x_),void 0,import.meta.url)]))):t.push(Promise.all([he(()=>Promise.resolve().then(()=>jd),void 0,import.meta.url),he(()=>Promise.resolve().then(()=>Qd),void 0,import.meta.url)]))}constructor(e,t=null,i,s,r){const n=!!r?.blockCompilation;super({...r,name:e,engine:t||$.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:_t.FragmentUrl,uniforms:_t.Uniforms,samplers:_t.Samplers,vertexUrl:_t.VertexUrl,blockCompilation:!0}),this._packedFloat=!1,this._staticDefines="",this.textureWidth=0,this.textureHeight=0,this._staticDefines=r?Array.isArray(r.defines)?r.defines.join(`
|
|
757
|
+
`):r.defines||"":"",this.options.blockCompilation=n,i!==void 0&&(this.direction=i),s!==void 0&&(this.kernel=s)}set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this.options.blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this.options.blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}bind(e=!1){super.bind(e),this._drawWrapper.effect.setFloat2("delta",1/this.textureWidth*this.direction.x,1/this.textureHeight*this.direction.y)}_updateParameters(e,t){const i=this._kernel,s=(i-1)/2;let r=[],n=[],a=0;for(let g=0;g<i;g++){const T=g/(i-1),R=this._gaussianWeight(T*2-1);r[g]=g-s,n[g]=R,a+=R}for(let g=0;g<n.length;g++)n[g]/=a;const h=[],l=[],c=[];for(let g=0;g<=s;g+=2){const T=Math.min(g+1,Math.floor(s));if(g===T)c.push({o:r[g],w:n[g]});else{const A=T===s,y=n[g]+n[T]*(A?.5:1),E=r[g]+1/(1+n[g]/n[T]);E===0?(c.push({o:r[g],w:n[g]}),c.push({o:r[g+1],w:n[g+1]})):(c.push({o:E,w:y}),c.push({o:-E,w:y}))}}for(let g=0;g<c.length;g++)l[g]=c[g].o,h[g]=c[g].w;r=l,n=h;const u=this.options.engine.getCaps().maxVaryingVectors-(this.options.shaderLanguage===1?1:0),f=Math.max(u,0)-1;let d=Math.min(r.length,f),_="";_+=this._staticDefines,this._staticDefines.indexOf("DOF")!=-1&&(_+=`#define CENTER_WEIGHT ${this._glslFloat(n[d-1])}
|
|
758
|
+
`,d--);for(let g=0;g<d;g++)_+=`#define KERNEL_OFFSET${g} ${this._glslFloat(r[g])}
|
|
759
|
+
`,_+=`#define KERNEL_WEIGHT${g} ${this._glslFloat(n[g])}
|
|
760
|
+
`;let m=0;for(let g=f;g<r.length;g++)_+=`#define KERNEL_DEP_OFFSET${m} ${this._glslFloat(r[g])}
|
|
761
|
+
`,_+=`#define KERNEL_DEP_WEIGHT${m} ${this._glslFloat(n[g])}
|
|
762
|
+
`,m++;this.packedFloat&&(_+="#define PACKEDFLOAT 1"),this.options.blockCompilation=!1,this.updateEffect(_,null,null,{varyingCount:d,depCount:m},e,t)}_nearestBestKernel(e){const t=Math.round(e);for(const i of[t,t-1,t+1,t-2,t+2])if(i%2!==0&&Math.floor(i/2)%2===0&&i>0)return Math.max(i,3);return Math.max(t,3)}_gaussianWeight(e){const t=.3333333333333333,i=Math.sqrt(2*Math.PI)*t,s=-(e*e/(2*t*t));return 1/i*Math.exp(s)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}}_t.VertexUrl="kernelBlur";_t.FragmentUrl="kernelBlur";_t.Uniforms=["delta","direction"];_t.Samplers=["circleOfConfusionSampler"];class Ct extends Ne{get direction(){return this._effectWrapper.direction}set direction(e){this._effectWrapper.direction=e}set kernel(e){this._effectWrapper.kernel=e}get kernel(){return this._effectWrapper.kernel}set packedFloat(e){this._effectWrapper.packedFloat=e}get packedFloat(){return this._effectWrapper.packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,s,r=null,n=G.BILINEAR_SAMPLINGMODE,a,h,l=0,c="",u=!1,f=5){const d=typeof s=="number"?u:!!s.blockCompilation,_={uniforms:_t.Uniforms,samplers:_t.Samplers,size:typeof s=="number"?s:void 0,camera:r,samplingMode:n,engine:a,reusable:h,textureType:l,vertexUrl:_t.VertexUrl,indexParameters:{varyingCount:0,depCount:0},textureFormat:f,defines:c,...s,blockCompilation:!0};super(e,_t.FragmentUrl,{effectWrapper:typeof s=="number"||!s.effectWrapper?new _t(e,a,void 0,void 0,_):void 0,..._}),this._effectWrapper.options.blockCompilation=d,this.direction=t,this.onApplyObservable.add(()=>{this._effectWrapper.textureWidth=this._outputTexture?this._outputTexture.width:this.width,this._effectWrapper.textureHeight=this._outputTexture?this._outputTexture.height:this.height}),this.kernel=i}updateEffect(e=null,t=null,i=null,s,r,n){this._effectWrapper._updateParameters(r,n)}static _Parse(e,t,i,s){return me.Parse(()=>new Ct(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,s)}}M([uu()],Ct.prototype,"direction",null);M([C()],Ct.prototype,"kernel",null);M([C()],Ct.prototype,"packedFloat",null);Ye("BABYLON.BlurPostProcess",Ct);class Sh{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0,this._internalSubMeshId=0}}class bi{constructor(e,t,i){this.vectors=yi(8,p.Zero),this.center=p.Zero(),this.centerWorld=p.Zero(),this.extendSize=p.Zero(),this.extendSizeWorld=p.Zero(),this.directions=yi(3,p.Zero),this.vectorsWorld=yi(8,p.Zero),this.minimumWorld=p.Zero(),this.maximumWorld=p.Zero(),this.minimum=p.Zero(),this.maximum=p.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,r=e.y,n=e.z,a=t.x,h=t.y,l=t.z,c=this.vectors;this.minimum.copyFromFloats(s,r,n),this.maximum.copyFromFloats(a,h,l),c[0].copyFromFloats(s,r,n),c[1].copyFromFloats(a,h,l),c[2].copyFromFloats(a,r,n),c[3].copyFromFloats(s,h,n),c[4].copyFromFloats(s,r,l),c[5].copyFromFloats(a,h,n),c[6].copyFromFloats(s,h,l),c[7].copyFromFloats(a,r,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||D.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=bi._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const r=s*e,n=i.scaleInPlace(r*.5),a=this.center.subtractToRef(n,t[1]),h=this.center.addToRef(n,t[2]);return this.reConstruct(a,h,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,s=this.directions,r=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let a=0;a<8;++a)r[a].copyFrom(n[a]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let a=0;a<8;++a){const h=r[a];p.TransformCoordinatesToRef(n[a],e,h),t.minimizeInPlace(h),i.maximizeInPlace(h)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}p.FromArrayToRef(e.m,0,s[0]),p.FromArrayToRef(e.m,4,s[1]),p.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return bi.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return bi.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,r=t.y,n=t.z,a=i.x,h=i.y,l=i.z,c=e.x,u=e.y,f=e.z,d=-Ke;return!(a-c<d||d>c-s||h-u<d||d>u-r||l-f<d||d>f-n)}intersectsSphere(e){return bi.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,r=i.x,n=i.y,a=i.z,h=s.x,l=s.y,c=s.z,u=e.x,f=e.y,d=e.z,_=t.x,m=t.y,g=t.z;return!(h<u||r>_||l<f||n>m||c<d||a>g)}dispose(){this._drawWrapperFront?.dispose(),this._drawWrapperBack?.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const r=bi._TmpVector3[0];return p.ClampToRef(i,e,t,r),p.DistanceSquared(i,r)<=s*s}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const s=t[i];for(let r=0;r<8;++r)if(s.dotCoordinate(e[r])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let s=!0;const r=t[i];for(let n=0;n<8;++n)if(r.dotCoordinate(e[n])>=0){s=!1;break}if(s)return!1}return!0}}bi._TmpVector3=yi(3,p.Zero);class ts{constructor(e,t,i){this.center=p.Zero(),this.centerWorld=p.Zero(),this.minimum=p.Zero(),this.maximum=p.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=p.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=s*.5,this._update(i||D.IdentityReadOnly)}scale(e){const t=this.radius*e,i=ts._TmpVector3,s=i[0].setAll(t),r=this.center.subtractToRef(s,i[1]),n=this.center.addToRef(s,i[2]);return this.reConstruct(r,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{p.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=ts._TmpVector3[0];p.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,i=this.radiusWorld;for(let s=0;s<6;s++)if(e[s].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=p.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld<t)}static Intersects(e,t){const i=p.DistanceSquared(e.centerWorld,t.centerWorld),s=e.radiusWorld+t.radiusWorld;return!(s*s<i)}static CreateFromCenterAndRadius(e,t,i){this._TmpVector3[0].copyFrom(e),this._TmpVector3[1].copyFromFloats(0,0,t),this._TmpVector3[2].copyFrom(e),this._TmpVector3[0].addInPlace(this._TmpVector3[1]),this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);const s=new ts(this._TmpVector3[0],this._TmpVector3[2]);return i?s._worldMatrix=i:s._worldMatrix=D.Identity(),s}}ts._TmpVector3=yi(3,p.Zero);const Rn={min:0,max:0},Sn={min:0,max:0},yh=(o,e,t)=>{const i=p.Dot(e.centerWorld,o),s=Math.abs(p.Dot(e.directions[0],o))*e.extendSize.x,r=Math.abs(p.Dot(e.directions[1],o))*e.extendSize.y,n=Math.abs(p.Dot(e.directions[2],o))*e.extendSize.z,a=s+r+n;t.min=i-a,t.max=i+a},Mt=(o,e,t)=>(yh(o,e,Rn),yh(o,t,Sn),!(Rn.min>Sn.max||Sn.min>Rn.max));class wt{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new bi(e,t,i),this.boundingSphere=new ts(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}get minimum(){return this.boundingBox.minimum}get maximum(){return this.boundingBox.maximum}get isLocked(){return this._isLocked}set isLocked(e){this._isLocked=e}update(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))}centerOn(e,t){const i=wt._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=wt._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=p.Minimize(this.minimum,e),i=p.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=U.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=U.Vector3[0];return p.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),p.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return(t===2||t===3)&&this.boundingSphere.isCenterInFrustum(e)?!0:this.boundingSphere.isInFrustum(e)?t===1||t===3?!0:this.boundingBox.isInFrustum(e):!1}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,wt._TmpVector3[0]).length()}isCompletelyInFrustum(e){return this.boundingBox.isCompletelyInFrustum(e)}_checkCollision(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)}intersectsPoint(e){return!(!this.boundingSphere.centerWorld||!this.boundingSphere.intersectsPoint(e)||!this.boundingBox.intersectsPoint(e))}intersects(e,t){if(!ts.Intersects(this.boundingSphere,e.boundingSphere)||!bi.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!(!Mt(i.directions[0],i,s)||!Mt(i.directions[1],i,s)||!Mt(i.directions[2],i,s)||!Mt(s.directions[0],i,s)||!Mt(s.directions[1],i,s)||!Mt(s.directions[2],i,s)||!Mt(p.Cross(i.directions[0],s.directions[0]),i,s)||!Mt(p.Cross(i.directions[0],s.directions[1]),i,s)||!Mt(p.Cross(i.directions[0],s.directions[2]),i,s)||!Mt(p.Cross(i.directions[1],s.directions[0]),i,s)||!Mt(p.Cross(i.directions[1],s.directions[1]),i,s)||!Mt(p.Cross(i.directions[1],s.directions[2]),i,s)||!Mt(p.Cross(i.directions[2],s.directions[0]),i,s)||!Mt(p.Cross(i.directions[2],s.directions[1]),i,s)||!Mt(p.Cross(i.directions[2],s.directions[2]),i,s))}}wt._TmpVector3=yi(2,p.Zero);class sn{static extractMinAndMaxIndexed(e,t,i,s,r,n){for(let a=i;a<i+s;a++){const h=t[a]*3,l=e[h],c=e[h+1],u=e[h+2];r.minimizeInPlaceFromFloats(l,c,u),n.maximizeInPlaceFromFloats(l,c,u)}}static extractMinAndMax(e,t,i,s,r,n){for(let a=t,h=t*s;a<t+i;a++,h+=s){const l=e[h],c=e[h+1],u=e[h+2];r.minimizeInPlaceFromFloats(l,c,u),n.maximizeInPlaceFromFloats(l,c,u)}}}M([_i.filter((...[o,e])=>!Array.isArray(o)&&!Array.isArray(e))],sn,"extractMinAndMaxIndexed",null);M([_i.filter((...[o])=>!Array.isArray(o))],sn,"extractMinAndMax",null);function v_(o,e,t,i,s=null){const r=new p(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new p(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return sn.extractMinAndMaxIndexed(o,e,t,i,r,n),s&&(r.x-=r.x*s.x+s.y,r.y-=r.y*s.x+s.y,r.z-=r.z*s.x+s.y,n.x+=n.x*s.x+s.y,n.y+=n.y*s.x+s.y,n.z+=n.z*s.x+s.y),{minimum:r,maximum:n}}function to(o,e,t,i=null,s){const r=new p(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new p(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return s||(s=3),sn.extractMinAndMax(o,e,t,s,r,n),i&&(r.x-=r.x*i.x+i.y,r.y-=r.y*i.x+i.y,r.z-=r.z*i.x+i.y,n.x+=n.x*i.x+i.y,n.y+=n.y*i.x+i.y,n.z+=n.z*i.x+i.y),{minimum:r,maximum:n}}function um(o,e){const t=to(o,0,o.length/3),i=t.maximum.subtract(t.minimum).scale(.5).add(t.minimum),s=new p,r=new p,n=new p,a=new p,h=new p,l=new p,c=new p;for(let u=0;u<e.length;u+=3){const f=e[u],d=e[u+1],_=e[u+2];s.fromArray(o,f*3),r.fromArray(o,d*3),n.fromArray(o,_*3),r.subtractToRef(s,a),n.subtractToRef(s,h),p.CrossToRef(a,h,l),l.normalize();const m=s.x+r.x+n.x,g=s.y+r.y+n.y,T=s.z+r.z+n.z;c.set(m/3,g/3,T/3),c.subtractInPlace(i),c.normalize(),p.Dot(l,c)>=0&&(e[u]=_,e[u+2]=f)}}class Kt{get materialDefines(){const e=this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:this._getDrawWrapper()?.defines;return typeof e=="string"?null:e}set materialDefines(e){const t=this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0);t.defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new ys(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0,i=!1){t&&this._drawWrappers[e]?.dispose(i),this._drawWrappers[e]=void 0}get effect(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:this._getDrawWrapper()?.effect??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,s=!0){const r=this._drawWrapper;r.setEffect(e,t,s),i!==void 0&&(r.materialContext=i),e||(r.defines=null,r.materialContext=void 0)}resetDrawCache(e,t=!1){if(this._drawWrappers)if(e!==void 0){this._removeDrawWrapper(e,!0,t);return}else for(const i of this._drawWrappers)i?.dispose(t);this._drawWrappers=[]}static AddToMesh(e,t,i,s,r,n,a,h=!0){return new Kt(e,t,i,s,r,n,a,h)}constructor(e,t,i,s,r,n,a,h=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=s,this.indexCount=r,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=a||n,l&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,h&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return this.verticesStart===0&&this.verticesCount===this._mesh.getTotalVertices()&&this.indexStart===0&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){const e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(t){if(this._isMultiMaterial(t)){const i=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==i&&(this._currentMaterial=i,this.resetDrawCache()),i}}else return e&&this._mesh.getScene()._hasDefaultMaterial?this._mesh.getScene().defaultMaterial:null;return t}_isMultiMaterial(e){return e.getSubMaterial!==void 0}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(S.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(this.indexStart===0&&this.indexCount===t.length){const s=this._renderingMesh.getBoundingInfo();i={minimum:s.minimum.clone(),maximum:s.maximum.clone()}}else i=v_(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new wt(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return t?t.isInFrustum(e,this._mesh.cullingStrategy):!1}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return t?t.isCompletelyInFrustum(e):!1}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const i=Math.floor(this.indexCount/3)*6,r=this.verticesStart+this.verticesCount>65535?new Uint32Array(i):new Uint16Array(i);let n=0;if(e.length===0)for(let a=this.indexStart;a<this.indexStart+this.indexCount;a+=3)r[n++]=a,r[n++]=a+1,r[n++]=a+1,r[n++]=a+2,r[n++]=a+2,r[n++]=a;else for(let a=this.indexStart;a<this.indexStart+this.indexCount;a+=3)r[n++]=e[a],r[n++]=e[a+1],r[n++]=e[a+1],r[n++]=e[a+2],r[n++]=e[a+2],r[n++]=e[a];this._linesIndexBuffer=t.createIndexBuffer(r),this._linesIndexCount=r.length}return this._linesIndexBuffer}canIntersects(e){const t=this.getBoundingInfo();return t?e.intersectsBox(t.boundingBox):!1}intersects(e,t,i,s,r){const n=this.getMaterial();if(!n)return null;let a=3,h=!1;switch(n.fillMode){case 3:case 5:case 6:case 8:return null;case 7:a=1,h=!0;break}return n.fillMode===4?i.length?this._intersectLines(e,t,i,this._mesh.intersectionThreshold,s):this._intersectUnIndexedLines(e,t,i,this._mesh.intersectionThreshold,s):!i.length&&this._mesh._unIndexed?this._intersectUnIndexedTriangles(e,t,i,s,r):this._intersectTriangles(e,t,i,a,h,s,r)}_intersectLines(e,t,i,s,r){let n=null;for(let a=this.indexStart;a<this.indexStart+this.indexCount;a+=2){const h=t[i[a]],l=t[i[a+1]],c=e.intersectionSegment(h,l,s);if(!(c<0)&&(r||!n||c<n.distance)&&(n=new Sh(null,null,c),n.faceId=a/2,r))break}return n}_intersectUnIndexedLines(e,t,i,s,r){let n=null;for(let a=this.verticesStart;a<this.verticesStart+this.verticesCount;a+=2){const h=t[a],l=t[a+1],c=e.intersectionSegment(h,l,s);if(!(c<0)&&(r||!n||c<n.distance)&&(n=new Sh(null,null,c),n.faceId=a/2,r))break}return n}_intersectTriangles(e,t,i,s,r,n,a){let h=null,l=-1;for(let c=this.indexStart;c<this.indexStart+this.indexCount-(3-s);c+=s){l++;const u=i[c],f=i[c+1],d=i[c+2];if(r&&d===4294967295){c+=2;continue}const _=t[u],m=t[f],g=t[d];if(!_||!m||!g||a&&!a(_,m,g,e,u,f,d))continue;const T=e.intersectsTriangle(_,m,g);if(T){if(T.distance<0)continue;if((n||!h||T.distance<h.distance)&&(h=T,h.faceId=l,n))break}}return h}_intersectUnIndexedTriangles(e,t,i,s,r){let n=null;for(let a=this.verticesStart;a<this.verticesStart+this.verticesCount;a+=3){const h=t[a],l=t[a+1],c=t[a+2];if(r&&!r(h,l,c,e,-1,-1,-1))continue;const u=e.intersectsTriangle(h,l,c);if(u){if(u.distance<0)continue;if((s||!n||u.distance<n.distance)&&(n=u,n.faceId=a/3,s))break}}return n}_rebuild(){this._linesIndexBuffer&&(this._linesIndexBuffer=null)}clone(e,t){const i=new Kt(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,e,t,!1);if(!this.IsGlobal){const s=this.getBoundingInfo();if(!s)return i;i._boundingInfo=new wt(s.minimum,s.maximum)}return i}dispose(e=!1){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);const t=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(t,1),this.resetDrawCache(void 0,e)}getClassName(){return"SubMesh"}static CreateFromIndices(e,t,i,s,r,n=!0){let a=Number.MAX_VALUE,h=-Number.MAX_VALUE;const c=(r||s).getIndices();for(let u=t;u<t+i;u++){const f=c[u];f<a&&(a=f),f>h&&(h=f)}return new Kt(e,a,h-a+1,t,i,s,r,n)}}class kt{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.funcRef=1,this.funcMask=255,this.func=519,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681,this.backFunc=519,this.backOpStencilFail=7680,this.backOpDepthFail=7680,this.backOpStencilDepthPass=7681}get func(){return this._func}set func(e){this._func=e}get backFunc(){return this._backFunc}set backFunc(e){this._backFunc=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get backOpStencilFail(){return this._backOpStencilFail}set backOpStencilFail(e){this._backOpStencilFail=e}get backOpDepthFail(){return this._backOpDepthFail}set backOpDepthFail(e){this._backOpDepthFail=e}get backOpStencilDepthPass(){return this._backOpStencilDepthPass}set backOpStencilDepthPass(e){this._backOpStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){me.Clone(()=>e,this)}serialize(){return me.Serialize(this)}parse(e,t,i){me.Parse(()=>this,e,t,i)}}M([C()],kt.prototype,"func",null);M([C()],kt.prototype,"backFunc",null);M([C()],kt.prototype,"funcRef",null);M([C()],kt.prototype,"funcMask",null);M([C()],kt.prototype,"opStencilFail",null);M([C()],kt.prototype,"opDepthFail",null);M([C()],kt.prototype,"opStencilDepthPass",null);M([C()],kt.prototype,"backOpStencilFail",null);M([C()],kt.prototype,"backOpDepthFail",null);M([C()],kt.prototype,"backOpStencilDepthPass",null);M([C()],kt.prototype,"mask",null);M([C()],kt.prototype,"enabled",null);function As(o){o.indexOf("vClipPlane")===-1&&o.push("vClipPlane"),o.indexOf("vClipPlane2")===-1&&o.push("vClipPlane2"),o.indexOf("vClipPlane3")===-1&&o.push("vClipPlane3"),o.indexOf("vClipPlane4")===-1&&o.push("vClipPlane4"),o.indexOf("vClipPlane5")===-1&&o.push("vClipPlane5"),o.indexOf("vClipPlane6")===-1&&o.push("vClipPlane6")}function dr(o,e,t){const i=!!(o.clipPlane??e.clipPlane),s=!!(o.clipPlane2??e.clipPlane2),r=!!(o.clipPlane3??e.clipPlane3),n=!!(o.clipPlane4??e.clipPlane4),a=!!(o.clipPlane5??e.clipPlane5),h=!!(o.clipPlane6??e.clipPlane6);i&&t.push("#define CLIPPLANE"),s&&t.push("#define CLIPPLANE2"),r&&t.push("#define CLIPPLANE3"),n&&t.push("#define CLIPPLANE4"),a&&t.push("#define CLIPPLANE5"),h&&t.push("#define CLIPPLANE6")}function C_(o,e,t){let i=!1;const s=!!(o.clipPlane??e.clipPlane),r=!!(o.clipPlane2??e.clipPlane2),n=!!(o.clipPlane3??e.clipPlane3),a=!!(o.clipPlane4??e.clipPlane4),h=!!(o.clipPlane5??e.clipPlane5),l=!!(o.clipPlane6??e.clipPlane6);return t.CLIPPLANE!==s&&(t.CLIPPLANE=s,i=!0),t.CLIPPLANE2!==r&&(t.CLIPPLANE2=r,i=!0),t.CLIPPLANE3!==n&&(t.CLIPPLANE3=n,i=!0),t.CLIPPLANE4!==a&&(t.CLIPPLANE4=a,i=!0),t.CLIPPLANE5!==h&&(t.CLIPPLANE5=h,i=!0),t.CLIPPLANE6!==l&&(t.CLIPPLANE6=l,i=!0),i}function Ms(o,e,t){let i=e.clipPlane??t.clipPlane;os(o,"vClipPlane",i),i=e.clipPlane2??t.clipPlane2,os(o,"vClipPlane2",i),i=e.clipPlane3??t.clipPlane3,os(o,"vClipPlane3",i),i=e.clipPlane4??t.clipPlane4,os(o,"vClipPlane4",i),i=e.clipPlane5??t.clipPlane5,os(o,"vClipPlane5",i),i=e.clipPlane6??t.clipPlane6,os(o,"vClipPlane6",i)}function os(o,e,t){if(t){const i=zi.getScene()?.floatingOriginOffset||p.ZeroReadOnly;o.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d+p.Dot(t.normal,i))}}class Pe{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get BaseWeightTextureEnabled(){return this._BaseWeightTextureEnabled}static set BaseWeightTextureEnabled(e){this._BaseWeightTextureEnabled!==e&&(this._BaseWeightTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get BaseDiffuseRoughnessTextureEnabled(){return this._BaseDiffuseRoughnessTextureEnabled}static set BaseDiffuseRoughnessTextureEnabled(e){this._BaseDiffuseRoughnessTextureEnabled!==e&&(this._BaseDiffuseRoughnessTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,J.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._TranslucencyIntensityTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get TranslucencyColorTextureEnabled(){return this._TranslucencyColorTextureEnabled}static set TranslucencyColorTextureEnabled(e){this._TranslucencyColorTextureEnabled!==e&&(this._TranslucencyColorTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,J.MarkAllMaterialsAsDirty(1))}}Pe._DiffuseTextureEnabled=!0;Pe._BaseWeightTextureEnabled=!0;Pe._BaseDiffuseRoughnessTextureEnabled=!0;Pe._DetailTextureEnabled=!0;Pe._DecalMapEnabled=!0;Pe._AmbientTextureEnabled=!0;Pe._OpacityTextureEnabled=!0;Pe._ReflectionTextureEnabled=!0;Pe._EmissiveTextureEnabled=!0;Pe._SpecularTextureEnabled=!0;Pe._BumpTextureEnabled=!0;Pe._LightmapTextureEnabled=!0;Pe._RefractionTextureEnabled=!0;Pe._ColorGradingTextureEnabled=!0;Pe._FresnelEnabled=!0;Pe._ClearCoatTextureEnabled=!0;Pe._ClearCoatBumpTextureEnabled=!0;Pe._ClearCoatTintTextureEnabled=!0;Pe._SheenTextureEnabled=!0;Pe._AnisotropicTextureEnabled=!0;Pe._ThicknessTextureEnabled=!0;Pe._RefractionIntensityTextureEnabled=!0;Pe._TranslucencyIntensityTextureEnabled=!0;Pe._TranslucencyColorTextureEnabled=!0;Pe._IridescenceTextureEnabled=!0;function pc(o,e,t){if(!o||o.LOGARITHMICDEPTH||o.indexOf&&o.indexOf("LOGARITHMICDEPTH")>=0){const i=t.activeCamera;i.mode===1&&W.Error("Logarithmic depth is not compatible with orthographic cameras!",20),e.setFloat("logarithmicDepthConstant",2/(Math.log(i.maxZ+1)/Math.LN2))}}const Ah={r:0,g:0,b:0},Ot={NUM_MORPH_INFLUENCERS:0,NORMAL:!1,TANGENT:!1,UV:!1,UV2:!1,COLOR:!1};function mc(o,e,t,i=!1){t&&o.fogEnabled&&(!e||e.applyFog)&&o.fogMode!==0&&(t.setFloat4("vFogInfos",o.fogMode,o.fogStart,o.fogEnd,o.fogDensity),i?(o.fogColor.toLinearSpaceToRef(Ah,o.getEngine().useExactSrgbConversions),t.setColor3("vFogColor",Ah)):t.setColor3("vFogColor",o.fogColor))}function _r(o,e,t,i,s,r,n,a,h,l){const c=o.numMaxInfluencers||o.numInfluencers;return c<=0?0:(e.push("#define MORPHTARGETS"),o.hasPositions&&e.push("#define MORPHTARGETTEXTURE_HASPOSITIONS"),o.hasNormals&&e.push("#define MORPHTARGETTEXTURE_HASNORMALS"),o.hasTangents&&e.push("#define MORPHTARGETTEXTURE_HASTANGENTS"),o.hasUVs&&e.push("#define MORPHTARGETTEXTURE_HASUVS"),o.hasUV2s&&e.push("#define MORPHTARGETTEXTURE_HASUV2S"),o.hasColors&&e.push("#define MORPHTARGETTEXTURE_HASCOLORS"),o.supportsPositions&&s&&e.push("#define MORPHTARGETS_POSITION"),o.supportsNormals&&r&&e.push("#define MORPHTARGETS_NORMAL"),o.supportsTangents&&n&&e.push("#define MORPHTARGETS_TANGENT"),o.supportsUVs&&a&&e.push("#define MORPHTARGETS_UV"),o.supportsUV2s&&h&&e.push("#define MORPHTARGETS_UV2"),o.supportsColors&&l&&e.push("#define MORPHTARGETS_COLOR"),e.push("#define NUM_MORPH_INFLUENCERS "+c),o.isUsingTextureForTargets&&e.push("#define MORPHTARGETS_TEXTURE"),Ot.NUM_MORPH_INFLUENCERS=c,Ot.NORMAL=r,Ot.TANGENT=n,Ot.UV=a,Ot.UV2=h,Ot.COLOR=l,io(t,i,Ot,s),c)}function fm(o,e,t){Ot.NUM_MORPH_INFLUENCERS=t,Ot.NORMAL=!1,Ot.TANGENT=!1,Ot.UV=!1,Ot.UV2=!1,Ot.COLOR=!1,io(o,e,Ot,!0)}function io(o,e,t,i=!0){const s=t.NUM_MORPH_INFLUENCERS;if(s>0&&ye.LastCreatedEngine){const r=ye.LastCreatedEngine.getCaps().maxVertexAttribs,n=e.morphTargetManager;if(n?.isUsingTextureForTargets)return;const a=n&&n.supportsPositions&&i,h=n&&n.supportsNormals&&t.NORMAL,l=n&&n.supportsTangents&&t.TANGENT,c=n&&n.supportsUVs&&t.UV1,u=n&&n.supportsUV2s&&t.UV2,f=n&&n.supportsColors&&t.VERTEXCOLOR;for(let d=0;d<s;d++)a&&o.push("position"+d),h&&o.push("normal"+d),l&&o.push("tangent"+d),c&&o.push("uv_"+d),u&&o.push("uv2_"+d),f&&o.push("color"+d),o.length>r&&W.Error("Cannot add more vertex attributes for mesh "+e.name)}}function Ps(o,e=!1){o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"),e&&(o.push("previousWorld0"),o.push("previousWorld1"),o.push("previousWorld2"),o.push("previousWorld3"))}function Is(o,e){const t=o.morphTargetManager;!o||!t||e.setFloatArray("morphTargetInfluences",t.influences)}function so(o,e){e.bindToEffect(o,"Scene")}function D_(o,e,t,i,s=null,r=!1,n=!1,a=!1,h=!1,l=!1,c=!1,u=0){if(o.texturesEnabled&&s&&Pe.ReflectionTextureEnabled){if(t.updateMatrix("reflectionMatrix",s.getReflectionTextureMatrix()),t.updateFloat2("vReflectionInfos",s.level*o.iblIntensity,u),a&&s.boundingBoxSize){const f=s;t.updateVector3("vReflectionPosition",f.boundingBoxPosition),t.updateVector3("vReflectionSize",f.boundingBoxSize)}if(r){const f=s.getSize().width;t.updateFloat2("vReflectionFilteringInfo",f,Math.log2(f))}if(l&&!e.USEIRRADIANCEMAP){const f=s.sphericalPolynomial;if(e.USESPHERICALFROMREFLECTIONMAP&&f)if(e.SPHERICAL_HARMONICS){const d=f.preScaledHarmonics;t.updateVector3("vSphericalL00",d.l00),t.updateVector3("vSphericalL1_1",d.l1_1),t.updateVector3("vSphericalL10",d.l10),t.updateVector3("vSphericalL11",d.l11),t.updateVector3("vSphericalL2_2",d.l2_2),t.updateVector3("vSphericalL2_1",d.l2_1),t.updateVector3("vSphericalL20",d.l20),t.updateVector3("vSphericalL21",d.l21),t.updateVector3("vSphericalL22",d.l22)}else t.updateFloat3("vSphericalX",f.x.x,f.x.y,f.x.z),t.updateFloat3("vSphericalY",f.y.x,f.y.y,f.y.z),t.updateFloat3("vSphericalZ",f.z.x,f.z.y,f.z.z),t.updateFloat3("vSphericalXX_ZZ",f.xx.x-f.zz.x,f.xx.y-f.zz.y,f.xx.z-f.zz.z),t.updateFloat3("vSphericalYY_ZZ",f.yy.x-f.zz.x,f.yy.y-f.zz.y,f.yy.z-f.zz.z),t.updateFloat3("vSphericalZZ",f.zz.x,f.zz.y,f.zz.z),t.updateFloat3("vSphericalXY",f.xy.x,f.xy.y,f.xy.z),t.updateFloat3("vSphericalYZ",f.yz.x,f.yz.y,f.yz.z),t.updateFloat3("vSphericalZX",f.zx.x,f.zx.y,f.zx.z)}else h&&e.USEIRRADIANCEMAP&&e.USE_IRRADIANCE_DOMINANT_DIRECTION&&t.updateVector3("vReflectionDominantDirection",s.irradianceTexture._dominantDirection);n&&t.updateFloat3("vReflectionMicrosurfaceInfos",s.getSize().width,s.lodGenerationScale,s.lodGenerationOffset)}c&&t.updateColor3("vReflectionColor",i)}function dm(o,e,t,i=null,s=!1){if(i&&Pe.ReflectionTextureEnabled){e.LODBASEDMICROSFURACE?t.setTexture("reflectionSampler",i):(t.setTexture("reflectionSampler",i._lodTextureMid||i),t.setTexture("reflectionSamplerLow",i._lodTextureLow||i),t.setTexture("reflectionSamplerHigh",i._lodTextureHigh||i)),e.USEIRRADIANCEMAP&&t.setTexture("irradianceSampler",i.irradianceTexture);const r=o.iblCdfGenerator;s&&r&&t.setTexture("icdfSampler",r.getIcdfTexture())}}function Ci(o,e,t){e._needUVs=!0,e[t]=!0,o.optimizeUVAllocation&&o.getTextureMatrix().isIdentityAs3x2()?(e[t+"DIRECTUV"]=o.coordinatesIndex+1,e["MAINUV"+(o.coordinatesIndex+1)]=!0):e[t+"DIRECTUV"]=0}function Di(o,e,t){const i=o.getTextureMatrix();e.updateMatrix(t+"Matrix",i)}function O_(o,e,t){t.BAKED_VERTEX_ANIMATION_TEXTURE&&t.INSTANCES&&o.push("bakedVertexAnimationSettingsInstanced")}function F_(o,e){return e.set(o),e}function vs(o,e,t){if(!(!e||!o)&&(o.computeBonesUsingShaders&&e._bonesComputationForcedToCPU&&(o.computeBonesUsingShaders=!1),o.useBones&&o.computeBonesUsingShaders&&o.skeleton)){const i=o.skeleton;if(i.isUsingTextureForMatrices&&e.getUniformIndex("boneTextureWidth")>-1){const s=i.getTransformMatrixTexture(o);e.setTexture("boneSampler",s),e.setFloat("boneTextureWidth",4*(i.bones.length+1))}else{const s=i.getTransformMatrices(o);s&&(e.setMatrices("mBones",s),t&&o.getScene().prePassRenderer&&o.getScene().prePassRenderer.getIndex(2)&&(t.previousBones[o.uniqueId]||(t.previousBones[o.uniqueId]=s.slice()),e.setMatrices("mPreviousBones",t.previousBones[o.uniqueId]),F_(s,t.previousBones[o.uniqueId])))}}}function _m(o,e,t){o.transferToEffect(e,t+"")}function w_(o,e,t,i,s,r=!0){o._bindLight(e,t,i,s,r)}function L_(o,e,t,i,s=4){const r=Math.min(e.lightSources.length,s);for(let n=0;n<r;n++){const a=e.lightSources[n];w_(a,n,o,t,typeof i=="boolean"?i:i.SPECULARTERM,e.receiveShadows)}}function B_(o,e,t,i){t.NUM_BONE_INFLUENCERS>0&&(i.addCPUSkinningFallback(0,e),o.push("matricesIndices"),o.push("matricesWeights"),t.NUM_BONE_INFLUENCERS>4&&(o.push("matricesIndicesExtra"),o.push("matricesWeightsExtra")))}function N_(o,e){(e.INSTANCES||e.THIN_INSTANCES)&&Ps(o,!!e.PREPASS_VELOCITY),e.INSTANCESCOLOR&&o.push("instanceColor")}function U_(o,e,t=4,i=0){let s=0;for(let r=0;r<t&&o["LIGHT"+r];r++)r>0&&(s=i+r,e.addFallback(s,"LIGHT"+r)),o.SHADOWS||(o["SHADOW"+r]&&e.addFallback(i,"SHADOW"+r),o["SHADOWPCF"+r]&&e.addFallback(i,"SHADOWPCF"+r),o["SHADOWPCSS"+r]&&e.addFallback(i,"SHADOWPCSS"+r),o["SHADOWPOISSON"+r]&&e.addFallback(i,"SHADOWPOISSON"+r),o["SHADOWESM"+r]&&e.addFallback(i,"SHADOWESM"+r),o["SHADOWCLOSEESM"+r]&&e.addFallback(i,"SHADOWCLOSEESM"+r));return s}function k_(o,e){return e.fogEnabled&&o.applyFog&&e.fogMode!==0}function V_(o,e,t,i,s,r,n,a=!1,h=!1,l,c){if(n._areMiscDirty){n.LOGARITHMICDEPTH=t,n.POINTSIZE=i,n.FOG=s&&k_(o,e),n.NONUNIFORMSCALING=o.nonUniformScaling,n.ALPHATEST=r,n.DECAL_AFTER_DETAIL=a,n.USE_VERTEX_PULLING=h,n.RIGHT_HANDED=e.useRightHandedSystem;const u=l?.geometry?.getIndexBuffer();n.VERTEX_PULLING_USE_INDEX_BUFFER=!!u,n.VERTEX_PULLING_INDEX_BUFFER_32BITS=u?u.is32Bits:!1,n.VERTEXOUTPUT_INVARIANT=!!c}}function z_(o,e,t,i,s=4,r=!1){if(!t._areLightsDirty)return t._needNormals;let n=0;const a={needNormals:t._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(o.lightsEnabled&&!r){for(const c of e.lightSources)if(G_(o,e,c,n,t,i,a),n++,n===s)break}t.SPECULARTERM=a.specularEnabled,t.SHADOWS=a.shadowEnabled;const h=Math.max(s,t.MAXLIGHTCOUNT||0);for(let c=n;c<h;c++)t["LIGHT"+c]!==void 0&&(t["LIGHT"+c]=!1,t["HEMILIGHT"+c]=!1,t["POINTLIGHT"+c]=!1,t["DIRLIGHT"+c]=!1,t["SPOTLIGHT"+c]=!1,t["AREALIGHT"+c]=!1,t["CLUSTLIGHT"+c]=!1,t["SHADOW"+c]=!1,t["SHADOWCSM"+c]=!1,t["SHADOWCSMDEBUG"+c]=!1,t["SHADOWCSMNUM_CASCADES"+c]=!1,t["SHADOWCSMUSESHADOWMAXZ"+c]=!1,t["SHADOWCSMNOBLEND"+c]=!1,t["SHADOWCSM_RIGHTHANDED"+c]=!1,t["SHADOWPCF"+c]=!1,t["SHADOWPCSS"+c]=!1,t["SHADOWPOISSON"+c]=!1,t["SHADOWESM"+c]=!1,t["SHADOWCLOSEESM"+c]=!1,t["SHADOWCUBE"+c]=!1,t["SHADOWLOWQUALITY"+c]=!1,t["SHADOWMEDIUMQUALITY"+c]=!1);t.LIGHTCOUNT=n,t.MAXLIGHTCOUNT=s;const l=o.getEngine().getCaps();return t.SHADOWFLOAT===void 0&&(a.needRebuild=!0),t.SHADOWFLOAT=a.shadowEnabled&&(l.textureFloatRender&&l.textureFloatLinearFiltering||l.textureHalfFloatRender&&l.textureHalfFloatLinearFiltering),t.LIGHTMAPEXCLUDED=a.lightmapMode,a.needRebuild&&t.rebuild(),a.needNormals}function W_(o,e,t,i=!1,s=8,r=!1){if(e&&Pe.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;t._needNormals=!0,t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.linearSpecularLOD,t.USEIRRADIANCEMAP=!1;const n=o.getEngine();switch(i&&s>0?(t.NUM_SAMPLES=""+s,n._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0,o.iblCdfGenerator&&(t.IBL_CDF_FILTERING=!0)):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===G.INVCUBIC_MODE,t.REFLECTIONMAP_3D=e.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&o.useRightHandedSystem?!e.invertZ:e.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.coordinatesMode){case G.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case G.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case G.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case G.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case G.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case G.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case G.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case G.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case G.CUBIC_MODE:case G.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize;break}e.coordinatesMode!==G.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USESPHERICALINVERTEX=!1,e.irradianceTexture._dominantDirection?t.USE_IRRADIANCE_DOMINANT_DIRECTION=!0:t.USE_IRRADIANCE_DOMINANT_DIRECTION=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,t.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,t.USESPHERICALINVERTEX=r))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;return!0}function G_(o,e,t,i,s,r,n){switch(n.needNormals=!0,s["LIGHT"+i]===void 0&&(n.needRebuild=!0),s["LIGHT"+i]=!0,s["SPOTLIGHT"+i]=!1,s["HEMILIGHT"+i]=!1,s["POINTLIGHT"+i]=!1,s["DIRLIGHT"+i]=!1,s["AREALIGHT"+i]=!1,s["CLUSTLIGHT"+i]=!1,t.prepareLightSpecificDefines(s,i),s["LIGHT_FALLOFF_PHYSICAL"+i]=!1,s["LIGHT_FALLOFF_GLTF"+i]=!1,s["LIGHT_FALLOFF_STANDARD"+i]=!1,t.falloffType){case Be.FALLOFF_GLTF:s["LIGHT_FALLOFF_GLTF"+i]=!0;break;case Be.FALLOFF_PHYSICAL:s["LIGHT_FALLOFF_PHYSICAL"+i]=!0;break;case Be.FALLOFF_STANDARD:s["LIGHT_FALLOFF_STANDARD"+i]=!0;break}if(r&&!t.specular.equalsFloats(0,0,0)&&(n.specularEnabled=!0),s["SHADOW"+i]=!1,s["SHADOWCSM"+i]=!1,s["SHADOWCSMDEBUG"+i]=!1,s["SHADOWCSMNUM_CASCADES"+i]=!1,s["SHADOWCSMUSESHADOWMAXZ"+i]=!1,s["SHADOWCSMNOBLEND"+i]=!1,s["SHADOWCSM_RIGHTHANDED"+i]=!1,s["SHADOWPCF"+i]=!1,s["SHADOWPCSS"+i]=!1,s["SHADOWPOISSON"+i]=!1,s["SHADOWESM"+i]=!1,s["SHADOWCLOSEESM"+i]=!1,s["SHADOWCUBE"+i]=!1,s["SHADOWLOWQUALITY"+i]=!1,s["SHADOWMEDIUMQUALITY"+i]=!1,e&&e.receiveShadows&&o.shadowsEnabled&&t.shadowEnabled){const a=t.getShadowGenerator(o.activeCamera)??t.getShadowGenerator();if(a){const h=a.getShadowMap();h&&h.renderList&&h.renderList.length>0&&(n.shadowEnabled=!0,a.prepareDefines(s,i))}}t.lightmapMode!=Be.LIGHTMAP_DEFAULT?(n.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+i]=!0,s["LIGHTMAPNOSPECULAR"+i]=t.lightmapMode==Be.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+i]=!1,s["LIGHTMAPNOSPECULAR"+i]=!1)}function H_(o,e,t,i,s,r=null,n=!1){let a=$_(o,i);r!==!1&&(a=C_(t,o,i)),i.DEPTHPREPASS!==!e.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,a=!0),i.INSTANCES!==s&&(i.INSTANCES=s,a=!0),i.THIN_INSTANCES!==n&&(i.THIN_INSTANCES=n,a=!0),a&&i.markAsUnprocessed()}function X_(o,e){if(o.useBones&&o.computeBonesUsingShaders&&o.skeleton){e.NUM_BONE_INFLUENCERS=o.numBoneInfluencers;const t=e.BONETEXTURE!==void 0;if(o.skeleton.isUsingTextureForMatrices&&t)e.BONETEXTURE=!0;else{e.BonesPerMesh=o.skeleton.bones.length+1,e.BONETEXTURE=t?!1:void 0;const i=o.getScene().prePassRenderer;if(i&&i.enabled){const s=i.excludedSkinnedMesh.indexOf(o)===-1;e.BONES_VELOCITY_ENABLED=s}}}else e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.BONETEXTURE!==void 0&&(e.BONETEXTURE=!1)}function K_(o,e){const t=o.morphTargetManager;t?(e.MORPHTARGETS_UV=t.supportsUVs&&e.UV1,e.MORPHTARGETS_UV2=t.supportsUV2s&&e.UV2,e.MORPHTARGETS_TANGENT=t.supportsTangents&&e.TANGENT,e.MORPHTARGETS_NORMAL=t.supportsNormals&&e.NORMAL,e.MORPHTARGETS_POSITION=t.supportsPositions,e.MORPHTARGETS_COLOR=t.supportsColors,e.MORPHTARGETTEXTURE_HASUVS=t.hasUVs,e.MORPHTARGETTEXTURE_HASUV2S=t.hasUV2s,e.MORPHTARGETTEXTURE_HASTANGENTS=t.hasTangents,e.MORPHTARGETTEXTURE_HASNORMALS=t.hasNormals,e.MORPHTARGETTEXTURE_HASPOSITIONS=t.hasPositions,e.MORPHTARGETTEXTURE_HASCOLORS=t.hasColors,e.NUM_MORPH_INFLUENCERS=t.numMaxInfluencers||t.numInfluencers,e.MORPHTARGETS=e.NUM_MORPH_INFLUENCERS>0,e.MORPHTARGETS_TEXTURE=t.isUsingTextureForTargets):(e.MORPHTARGETS_UV=!1,e.MORPHTARGETS_UV2=!1,e.MORPHTARGETS_TANGENT=!1,e.MORPHTARGETS_NORMAL=!1,e.MORPHTARGETS_POSITION=!1,e.MORPHTARGETS_COLOR=!1,e.MORPHTARGETTEXTURE_HASUVS=!1,e.MORPHTARGETTEXTURE_HASUV2S=!1,e.MORPHTARGETTEXTURE_HASTANGENTS=!1,e.MORPHTARGETTEXTURE_HASNORMALS=!1,e.MORPHTARGETTEXTURE_HASPOSITIONS=!1,e.MORPHTARGETTEXTURE_HAS_COLORS=!1,e.MORPHTARGETS=!1,e.NUM_MORPH_INFLUENCERS=0)}function Y_(o,e){const t=o.bakedVertexAnimationManager;e.BAKED_VERTEX_ANIMATION_TEXTURE=!!(t&&t.isEnabled)}function j_(o,e,t,i,s=!1,r=!0,n=!0){if(!e._areAttributesDirty&&e._needNormals===e._normals&&e._needUVs===e._uvs)return!1;e._normals=e._needNormals,e._uvs=e._needUVs,e.NORMAL=e._needNormals&&o.isVerticesDataPresent("normal"),e._needNormals&&o.isVerticesDataPresent("tangent")&&(e.TANGENT=!0);for(let a=1;a<=6;++a)e["UV"+a]=e._needUVs?o.isVerticesDataPresent(`uv${a===1?"":a}`):!1;if(t){const a=o.useVertexColors&&o.isVerticesDataPresent("color");e.VERTEXCOLOR=a,e.VERTEXALPHA=o.hasVertexAlpha&&a&&r}return o.isVerticesDataPresent("instanceColor")&&(o.hasInstances||o.hasThinInstances)&&(e.INSTANCESCOLOR=!0),i&&X_(o,e),s&&K_(o,e),n&&Y_(o,e),!0}function Z_(o,e){if(o.activeCamera){const t=e.MULTIVIEW;e.MULTIVIEW=o.activeCamera.outputRenderTarget!==null&&o.activeCamera.outputRenderTarget.getViewCount()>1,e.MULTIVIEW!=t&&e.markAsUnprocessed()}}function q_(o,e,t){const i=e.ORDER_INDEPENDENT_TRANSPARENCY,s=e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;e.ORDER_INDEPENDENT_TRANSPARENCY=o.useOrderIndependentTransparency&&t,e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!o.getEngine().getCaps().textureFloatLinearFiltering,(i!==e.ORDER_INDEPENDENT_TRANSPARENCY||s!==e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&e.markAsUnprocessed()}function Q_(o,e,t){const i=e.PREPASS;if(!e._arePrePassDirty)return;const s=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:9,define:"PREPASS_LOCAL_POSITION",index:"PREPASS_LOCAL_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:11,define:"PREPASS_VELOCITY_LINEAR",index:"PREPASS_VELOCITY_LINEAR_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:10,define:"PREPASS_SCREENSPACE_DEPTH",index:"PREPASS_SCREENSPACE_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"},{type:8,define:"PREPASS_WORLD_NORMAL",index:"PREPASS_WORLD_NORMAL_INDEX"}];if(o.prePassRenderer&&o.prePassRenderer.enabled&&t){e.PREPASS=!0,e.SCENE_MRT_COUNT=o.prePassRenderer.mrtCount,e.PREPASS_NORMAL_WORLDSPACE=o.prePassRenderer.generateNormalsInWorldSpace,e.PREPASS_COLOR=!0,e.PREPASS_COLOR_INDEX=0;for(let r=0;r<s.length;r++){const n=o.prePassRenderer.getIndex(s[r].type);n!==-1?(e[s[r].define]=!0,e[s[r].index]=n):e[s[r].define]=!1}}else{e.PREPASS=!1;for(let r=0;r<s.length;r++)e[s[r].define]=!1}e.PREPASS!=i&&(e.markAsUnprocessed(),e.markAsImageProcessingDirty())}function $_(o,e){let t=!1;if(o.activeCamera){const i=e.CAMERA_ORTHOGRAPHIC?1:0,s=e.CAMERA_PERSPECTIVE?1:0,r=o.activeCamera.mode===1?1:0,n=o.activeCamera.mode===0?1:0;(i^r||s^n)&&(e.CAMERA_ORTHOGRAPHIC=r===1,e.CAMERA_PERSPECTIVE=n===1,t=!0)}return t}function J_(o,e,t,i,s=null,r=!1,n=!1,a=!1,h=!1){s&&s.push("Light"+o),!r&&(e.push("vLightData"+o,"vLightDiffuse"+o,"vLightSpecular"+o,"vLightDirection"+o,"vLightWidth"+o,"vLightHeight"+o,"vLightFalloff"+o,"vLightGround"+o,"vSliceData"+o,"vSliceRanges"+o,"lightMatrix"+o,"shadowsInfo"+o,"depthValues"+o),t.push("shadowTexture"+o),t.push("depthTexture"+o),e.push("viewFrustumZ"+o,"cascadeBlendFactor"+o,"lightSizeUVCorrection"+o,"depthCorrection"+o,"penumbraDarkness"+o,"frustumLengths"+o),i&&(t.push("projectionLightTexture"+o),e.push("textureProjectionMatrix"+o)),n&&t.push("iesLightTexture"+o),h&&t.push("rectAreaLightEmissionTexture"+o),a&&(t.push("lightDataTexture"+o),t.push("tileMaskTexture"+o)))}function eg(o,e,t){const i=["vReflectionMicrosurfaceInfos","vReflectionDominantDirection","reflectionMatrix","vReflectionInfos","vReflectionPosition","vReflectionSize","vReflectionColor","vReflectionFilteringInfo"];t&&i.push("vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22"),o.push(...i);const s=["reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","icdfSampler"];e.push(...s)}function tg(o,e,t,i=4){let s,r;if(o.uniformsNames){const n=o;s=n.uniformsNames,r=n.uniformBuffersNames,e=n.samplers,t=n.defines,i=n.maxSimultaneousLights||0}else s=o,e||(e=[]);for(let n=0;n<i&&t["LIGHT"+n];n++)J_(n,s,e,t["PROJECTEDLIGHTTEXTURE"+n],r,!1,t["IESLIGHTTEXTURE"+n],t["CLUSTLIGHT"+n],t["RECTAREALIGHTEMISSIONTEXTURE"+n]);t.NUM_MORPH_INFLUENCERS&&(s.push("morphTargetInfluences"),s.push("morphTargetCount")),t.BAKED_VERTEX_ANIMATION_TEXTURE&&(s.push("bakedVertexAnimationSettings"),s.push("bakedVertexAnimationTextureSizeInverted"),s.push("bakedVertexAnimationTime"),e.push("bakedVertexAnimationTexture"))}function ig(o,e=!1,t=!1,i=!1,s=!1,r=!1){o.addUniform("vReflectionInfos",2),o.addUniform("reflectionMatrix",16),e&&o.addUniform("vReflectionMicrosurfaceInfos",3),t&&(o.addUniform("vReflectionPosition",3),o.addUniform("vReflectionSize",3)),i&&(o.addUniform("vReflectionFilteringInfo",2),o.addUniform("vReflectionDominantDirection",3)),r&&o.addUniform("vReflectionColor",3),s&&(o.addUniform("vSphericalL00",3),o.addUniform("vSphericalL1_1",3),o.addUniform("vSphericalL10",3),o.addUniform("vSphericalL11",3),o.addUniform("vSphericalL2_2",3),o.addUniform("vSphericalL2_1",3),o.addUniform("vSphericalL20",3),o.addUniform("vSphericalL21",3),o.addUniform("vSphericalL22",3),o.addUniform("vSphericalX",3),o.addUniform("vSphericalY",3),o.addUniform("vSphericalZ",3),o.addUniform("vSphericalXX_ZZ",3),o.addUniform("vSphericalYY_ZZ",3),o.addUniform("vSphericalZZ",3),o.addUniform("vSphericalXY",3),o.addUniform("vSphericalYZ",3),o.addUniform("vSphericalZX",3))}class V{get useVertexPulling(){return this._useVertexPulling}set useVertexPulling(e){this._useVertexPulling!==e&&(this._useVertexPulling=e,this.markAsDirty(V.MiscDirtyFlag))}get _supportGlowLayer(){return!1}set _glowModeEnabled(e){}get shaderLanguage(){return this._shaderLanguage}get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;const t=this._alpha;this._alpha=e,(t===1||e===1)&&this.markAsDirty(V.MiscDirtyFlag+V.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(V.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(V.TextureDirtyFlag))}get cullBackFaces(){return this._cullBackFaces}get blockDirtyMechanism(){return this._blockDirtyMechanism}set blockDirtyMechanism(e){this._blockDirtyMechanism!==e&&(this._blockDirtyMechanism=e,e||this.markDirty())}atomicMaterialsUpdate(e){this.blockDirtyMechanism=!0;try{e(this)}finally{this.blockDirtyMechanism=!1}}get hasRenderTargetTextures(){return this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._eventInfo.hasRenderTargetTextures}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new z),this._onBindObservable}set onBind(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)}get onUnBindObservable(){return this._onUnBindObservable||(this._onUnBindObservable=new z),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new z),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode[0]!==e&&(this._alphaMode[0]=e,this.markAsDirty(V.TextureDirtyFlag))}get alphaMode(){return this._alphaMode[0]}get alphaModes(){return this._alphaMode}setAlphaMode(e,t=0){this._alphaMode[t]!==e&&(this._alphaMode[t]=e,this.markAsDirty(V.TextureDirtyFlag))}set needDepthPrePass(e){this._needDepthPrePass!==e&&(this._needDepthPrePass=e,this._needDepthPrePass&&(this.checkReadyOnEveryCall=!0))}get needDepthPrePass(){return this._needDepthPrePass}get isPrePassCapable(){return!1}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAsDirty(V.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case V.WireFrameFillMode:case V.LineListDrawMode:case V.LineLoopDrawMode:case V.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?V.WireFrameFillMode:V.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case V.PointFillMode:case V.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?V.PointFillMode:V.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(V.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&W.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._markAllSubMeshesAsMiscDirty()}get isVertexOutputInvariant(){return this._isVertexOutputInvariant}set isVertexOutputInvariant(e){this._isVertexOutputInvariant!==e&&(this._isVertexOutputInvariant=e,this._markAllSubMeshesAsMiscDirty())}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i,s=!1){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this._shaderLanguage=0,this._forceGLSL=!1,this._useVertexPulling=!1,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this._blockDirtyMechanism=!1,this.sideOrientation=null,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new z,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=[2],this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new kt,this._isVertexOutputInvariant=V.ForceVertexOutputInvariant,this._useUBO=!1,this._fillMode=V.TriangleFillMode,this._cachedDepthWriteState=!1,this._cachedColorWriteState=!1,this._cachedDepthFunctionState=0,this._indexInSceneMaterialArray=-1,this.meshMap=null,this._parentContainer=null,this._uniformBufferLayoutBuilt=!1,this._eventInfo={},this._callbackPluginEventGeneric=()=>{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._transparencyMode=null,this.name=e;const r=t||ye.LastCreatedScene;r&&(this._scene=r,this._dirtyCallbacks={},this._forceGLSL=s,this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[127]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||fe.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new ys(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._uniformBuffer=new oe(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,this._createUniformBuffer(),i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),V.OnEventObservable.notifyObservers(this,1))}_createUniformBuffer(){const e=this.getScene().getEngine();this._uniformBuffer?.dispose(),e.isWebGPU&&!this._forceGLSL?(this._uniformBuffer=new oe(e,void 0,void 0,this.name,!0),this._shaderLanguage=1):this._uniformBuffer=new oe(this._scene.getEngine(),void 0,void 0,this.name),this._uniformBufferLayoutBuilt=!1}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const s=t.materialDefines;return s?(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh):!1}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}_getEffectiveOrientation(e){return this.sideOrientation!==null?this.sideOrientation:e.sideOrientation}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _hasTransparencyMode(){return this._transparencyMode!=null}get _transparencyModeIsBlend(){return this._transparencyMode===V.MATERIAL_ALPHABLEND||this._transparencyMode===V.MATERIAL_ALPHATESTANDBLEND}get _transparencyModeIsTest(){return this._transparencyMode===V.MATERIAL_ALPHATEST||this._transparencyMode===V.MATERIAL_ALPHATESTANDBLEND}get _disableAlphaBlending(){return this._transparencyMode===V.MATERIAL_OPAQUE||this._transparencyMode===V.MATERIAL_ALPHATEST}needAlphaBlending(){return this._hasTransparencyMode?this._transparencyModeIsBlend:this._disableAlphaBlending?!1:this.alpha<1}needAlphaBlendingForMesh(e){return this._hasTransparencyMode?this._transparencyModeIsBlend:e.visibility<1?!0:this._disableAlphaBlending?!1:e.hasVertexAlpha||this.needAlphaBlending()}needAlphaTesting(){return this._hasTransparencyMode?this._transparencyModeIsTest:!1}needAlphaTestingForMesh(e){return this._hasTransparencyMode?this._transparencyModeIsTest:!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){const t=this.getScene().meshes;for(const i of t)if(i.subMeshes){for(const s of i.subMeshes)if(s.getMaterial()===this)for(const r of s._drawWrappers)r&&this._materialContext===r.materialContext&&(r._wasPreviouslyReady=!1,r._wasPreviouslyUsingInstances=null,r._forceRebindOnNextCall=e)}e&&this.markAsDirty(V.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),r=(t??this.sideOrientation)===V.ClockWiseSideOrientation,n=e||this._getDrawWrapper();return Dl(n)&&n.materialContext&&(n.materialContext.useVertexPulling=this.useVertexPulling),i.enableEffect(n),i.setState(this.backFaceCulling,this.zOffset,!1,r,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),r}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(8,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const s=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),s._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,so(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const s=this._scene.getEngine();this._cachedDepthWriteState=s.getDepthWrite(),s.setDepthWrite(!1)}if(this.disableColorWrite){const s=this._scene.getEngine();this._cachedColorWriteState=s.getColorWrite(),s.setColorWrite(!1)}if(this.depthFunction!==0){const s=this._scene.getEngine();this._cachedDepthFunctionState=s.getDepthFunction()||0,s.setDepthFunction(this.depthFunction)}}unbind(){this._scene.getSceneUniformBuffer().unbindEffect(),this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),this.depthFunction!==0&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(256,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(512,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(1024,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),V._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const s of this.pluginManager._plugins){const r=e.pluginManager.getPlugin(s.name);r&&s.copyTo(r)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}else return this._scene.meshes.filter(t=>t.material===this)}forceCompilation(e,t,i,s){const r={clipPlane:!1,useInstances:!1,...i},n=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const h=()=>{if(!this._scene||!this._scene.getEngine())return;const l=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new si(0,0,0,1)),this._storeEffectOnSubMeshes){let c=!0,u=null;if(e.subMeshes){const f=new Kt(0,0,0,0,0,e,void 0,!1,!1);f.materialDefines&&(f.materialDefines._renderId=-1),this.isReadyForSubMesh(e,f,r.useInstances)||(f.effect&&f.effect.getCompilationError()&&f.effect.allFallbacksProcessed()?u=f.effect.getCompilationError():(c=!1,setTimeout(h,16)))}c&&(this.allowShaderHotSwapping=a,u&&s&&s(u),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,t&&t(this)):setTimeout(h,16);r.clipPlane&&(n.clipPlane=l)};h()}async forceCompilationAsync(e,t){return await new Promise((i,s)=>{this.forceCompilation(e,()=>{i()},t,r=>{s(r)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(V._DirtyCallbackArray.length=0,e&V.ImageProcessingDirtyFlag&&V._DirtyCallbackArray.push(V._ImageProcessingDirtyCallBack),e&V.TextureDirtyFlag&&V._DirtyCallbackArray.push(V._TextureDirtyCallBack),e&V.LightDirtyFlag&&V._DirtyCallbackArray.push(V._LightsDirtyCallBack),e&V.FresnelDirtyFlag&&V._DirtyCallbackArray.push(V._FresnelDirtyCallBack),e&V.AttributesDirtyFlag&&V._DirtyCallbackArray.push(V._AttributeDirtyCallBack),e&V.MiscDirtyFlag&&V._DirtyCallbackArray.push(V._MiscDirtyCallBack),e&V.PrePassDirtyFlag&&V._DirtyCallbackArray.push(V._PrePassDirtyCallBack),V._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(V._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const i of t.subMeshes)i.getMaterial()===this&&i.resetDrawCache()}_markAllSubMeshesAsDirty(e){const t=this.getScene();if(t.blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const i=t.meshes;for(const s of i)if(s.subMeshes){for(const r of s.subMeshes)if((r.getMaterial()||(t._hasDefaultMaterial?t.defaultMaterial:null))===this)for(const a of r._drawWrappers)!a||!a.defines||!a.defines.markAllAsDirty||this._materialContext===a.materialContext&&e(a.defines)}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(V._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(V._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(V._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(V._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(V._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(V._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(V._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(V._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(V._PrePassDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(V._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==0){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,i){const s=this.getScene();if(s.stopAnimation(this),s.freeProcessedMaterials(),s.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(2,this._eventInfo),this._parentContainer){const r=this._parentContainer.materials.indexOf(this);r>-1&&this._parentContainer.materials.splice(r,1),this._parentContainer=null}if(i!==!0)if(this.meshMap)for(const r in this.meshMap){const n=this.meshMap[r];this._disposeMeshResources(n)}else{const r=s.meshes;for(const n of r)this._disposeMeshResources(n)}this._uniformBuffer.dispose(),this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}_disposeMeshResources(e){if(!e)return;const t=e.geometry,i=e._internalAbstractMeshDataInfo._materialForRenderPass;if(this._storeEffectOnSubMeshes){if(e.subMeshes&&i)for(const s of e.subMeshes){const r=s._drawWrappers;for(let n=0;n<r.length;n++){const a=r[n]?.effect;if(!a)continue;i[n]===this&&(t?._releaseVertexArrayObject(a),s._removeDrawWrapper(n,!0,!0))}}}else t?._releaseVertexArrayObject(this._drawWrapper.effect);e.material===this&&!e.sourceMesh&&(e.material=null)}serialize(){const e=me.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(const t of this.pluginManager._plugins)t.doNotSerialize||(e.plugins[t.getClassName()]=t.serialize())}static ParseAlphaMode(e,t){e._alphaMode!==void 0?t._alphaMode=Array.isArray(e._alphaMode)?e._alphaMode:[e._alphaMode]:e.alphaMode!==void 0?t._alphaMode=Array.isArray(e.alphaMode)?e.alphaMode:[e.alphaMode]:t._alphaMode=[2]}static Parse(e,t,i){if(!e.customType)e.customType="BABYLON.StandardMaterial";else if(e.customType==="BABYLON.PBRMaterial"&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return W.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null;const r=fe.Instantiate(e.customType).Parse(e,t,i);return r._loadedUniqueId=e.uniqueId,V.ParseAlphaMode(e,r),r}static _ParsePlugins(e,t,i,s){if(e.plugins)for(const r in e.plugins){const n=e.plugins[r];let a=t.pluginManager?.getPlugin(n.name);if(!a){const h=fe.Instantiate("BABYLON."+r);h&&(a=new h(t))}a?.parse(n,i,s)}}}V.TriangleFillMode=0;V.WireFrameFillMode=1;V.PointFillMode=2;V.PointListDrawMode=3;V.LineListDrawMode=4;V.LineLoopDrawMode=5;V.LineStripDrawMode=6;V.TriangleStripDrawMode=7;V.TriangleFanDrawMode=8;V.ClockWiseSideOrientation=0;V.CounterClockWiseSideOrientation=1;V.ImageProcessingDirtyFlag=64;V.TextureDirtyFlag=1;V.LightDirtyFlag=2;V.FresnelDirtyFlag=4;V.AttributesDirtyFlag=8;V.MiscDirtyFlag=16;V.PrePassDirtyFlag=32;V.AllDirtyFlag=127;V.MATERIAL_OPAQUE=0;V.MATERIAL_ALPHATEST=1;V.MATERIAL_ALPHABLEND=2;V.MATERIAL_ALPHATESTANDBLEND=3;V.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0;V.MATERIAL_NORMALBLENDMETHOD_RNM=1;V.LIGHTFALLOFF_PHYSICAL=0;V.LIGHTFALLOFF_GLTF=1;V.LIGHTFALLOFF_STANDARD=2;V.OnEventObservable=new z;V.ForceVertexOutputInvariant=!1;V._AllDirtyCallBack=o=>o.markAllAsDirty();V._ImageProcessingDirtyCallBack=o=>o.markAsImageProcessingDirty();V._TextureDirtyCallBack=o=>o.markAsTexturesDirty();V._FresnelDirtyCallBack=o=>o.markAsFresnelDirty();V._MiscDirtyCallBack=o=>o.markAsMiscDirty();V._PrePassDirtyCallBack=o=>o.markAsPrePassDirty();V._LightsDirtyCallBack=o=>o.markAsLightDirty();V._AttributeDirtyCallBack=o=>o.markAsAttributesDirty();V._FresnelAndMiscDirtyCallBack=o=>{V._FresnelDirtyCallBack(o),V._MiscDirtyCallBack(o)};V._TextureAndMiscDirtyCallBack=o=>{V._TextureDirtyCallBack(o),V._MiscDirtyCallBack(o)};V._DirtyCallbackArray=[];V._RunDirtyCallBacks=o=>{for(const e of V._DirtyCallbackArray)e(o)};M([C()],V.prototype,"id",void 0);M([C()],V.prototype,"uniqueId",void 0);M([C()],V.prototype,"name",void 0);M([C()],V.prototype,"metadata",void 0);M([C()],V.prototype,"checkReadyOnEveryCall",void 0);M([C()],V.prototype,"checkReadyOnlyOnce",void 0);M([C()],V.prototype,"state",void 0);M([C("alpha")],V.prototype,"_alpha",void 0);M([C("backFaceCulling")],V.prototype,"_backFaceCulling",void 0);M([C("cullBackFaces")],V.prototype,"_cullBackFaces",void 0);M([C()],V.prototype,"sideOrientation",void 0);M([C()],V.prototype,"_alphaMode",void 0);M([C()],V.prototype,"_needDepthPrePass",void 0);M([C()],V.prototype,"disableDepthWrite",void 0);M([C()],V.prototype,"disableColorWrite",void 0);M([C()],V.prototype,"forceDepthWrite",void 0);M([C()],V.prototype,"depthFunction",void 0);M([C()],V.prototype,"separateCullingPass",void 0);M([C("fogEnabled")],V.prototype,"_fogEnabled",void 0);M([C()],V.prototype,"pointSize",void 0);M([C()],V.prototype,"zOffset",void 0);M([C()],V.prototype,"zOffsetUnits",void 0);M([C()],V.prototype,"pointsCloud",null);M([C()],V.prototype,"fillMode",null);M([C()],V.prototype,"useLogarithmicDepth",null);M([C()],V.prototype,"_isVertexOutputInvariant",void 0);M([C()],V.prototype,"transparencyMode",null);class Cs{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let s=0;s<i.meshes.length;s++){const r=i.meshes[s];if(!r.material){!this._mesh.material&&r.computeBonesUsingShaders&&r.numBoneInfluencers>0&&(r.computeBonesUsingShaders=!1);continue}if(!(!r.computeBonesUsingShaders||r.numBoneInfluencers===0)){if(r.material.getEffect()===t)r.computeBonesUsingShaders=!1;else if(r.subMeshes){for(const n of r.subMeshes)if(n.effect===t){r.computeBonesUsingShaders=!1;break}}}}}else{const i=this._defines[this._currentRank];if(i)for(let s=0;s<i.length;s++)e=e.replace("#define "+i[s],"");this._currentRank++}return e}}class tr extends Qe{constructor(e,t=null,i,s,r){super({...r,name:e,engine:t||$.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:tr.FragmentUrl,uniforms:tr.Uniforms}),this.direction=i,this.kernel=s,this.textureWidth=0,this.textureHeight=0}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(he(()=>import("./glowBlurPostProcess.fragment-G_xfSiIr.js"),[],import.meta.url))):t.push(he(()=>import("./glowBlurPostProcess.fragment-CS_rTtUL.js"),[],import.meta.url)),super._gatherImports(e,t)}bind(){super.bind(),this._drawWrapper.effect.setFloat2("screenSize",this.textureWidth,this.textureHeight),this._drawWrapper.effect.setVector2("direction",this.direction),this._drawWrapper.effect.setFloat("blurWidth",this.kernel)}}tr.FragmentUrl="glowBlurPostProcess";tr.Uniforms=["screenSize","direction","blurWidth"];class is{get camera(){return this._options.camera}set camera(e){this._options.camera=e}get renderingGroupId(){return this._options.renderingGroupId}set renderingGroupId(e){this._options.renderingGroupId=e}get objectRenderer(){return this._objectRenderer}get shaderLanguage(){return this._shaderLanguage}setMaterialForRendering(e,t){if(this._objectRenderer.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i<e.length;++i){const s=e[i];t?this._materialForRendering[s.uniqueId]=[s,t]:delete this._materialForRendering[s.uniqueId]}else t?this._materialForRendering[e.uniqueId]=[e,t]:delete this._materialForRendering[e.uniqueId]}getEffectIntensity(e){return this._effectIntensity[e.uniqueId]??1}setEffectIntensity(e,t){this._effectIntensity[e.uniqueId]=t}constructor(e,t,i=!1,s=!1,r){this._additionalImportShadersAsync=r,this._vertexBuffers={},this._dontCheckIfReady=!1,this._shouldRender=!0,this._emissiveTextureAndColor={texture:null,color:new Ce},this._effectIntensity={},this._postProcesses=[],this.neutralColor=new Ce,this.isEnabled=!0,this.disableBoundingBoxesFromEffectLayer=!1,this.onDisposeObservable=new z,this.onBeforeRenderLayerObservable=new z,this.onBeforeComposeObservable=new z,this.onBeforeRenderMeshToEffect=new z,this.onAfterRenderMeshToEffect=new z,this.onAfterComposeObservable=new z,this.onBeforeBlurObservable=new z,this.onAfterBlurObservable=new z,this._shaderLanguage=0,this._materialForRendering={},this._shadersLoaded=!1,this.name=e,this._scene=t||ye.LastCreatedScene,this._dontCheckIfReady=s,this._scene.getEngine().isWebGPU&&!i&&!is.ForceGLSL&&(this._shaderLanguage=1),this._engine=this._scene.getEngine(),this._mergeDrawWrapper=[],this._generateIndexBuffer(),this._generateVertexBuffer()}getEffectName(){return""}isReady(e,t){return!0}needStencil(){return!1}_createMergeEffect(){throw new Error("Effect Layer: no merge effect defined")}_createTextureAndPostProcesses(){}_internalCompose(e,t){}_setEmissiveTextureAndColor(e,t,i){}_numInternalDraws(){return 1}_init(e){this._options={mainTextureRatio:.5,mainTextureFixedSize:0,mainTextureType:0,mainTextureFormat:5,alphaBlendingMode:2,camera:null,renderingGroupId:-1,...e},this._createObjectRenderer()}_generateIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._engine.createIndexBuffer(e)}_generateVertexBuffer(){const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1);const t=new S(this._engine,e,S.PositionKind,!1,!1,2);this._vertexBuffers[S.PositionKind]=t}_createObjectRenderer(){this._objectRenderer=new jt(`ObjectRenderer for thin effect layer ${this.name}`,this._scene,{doNotChangeAspectRatio:!0}),this._objectRenderer.activeCamera=this._options.camera,this._objectRenderer.renderParticles=!1,this._objectRenderer.renderList=null;const e=!!this._scene.getBoundingBoxRenderer;let t=!1;e&&(this._objectRenderer.onBeforeRenderObservable.add(()=>{t=this._scene.getBoundingBoxRenderer().enabled,this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&t}),this._objectRenderer.onAfterRenderObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=t})),this._objectRenderer.customIsReadyFunction=(i,s,r)=>{if((r||s===0)&&i.subMeshes)for(let n=0;n<i.subMeshes.length;++n){const a=i.subMeshes[n],h=a.getMaterial(),l=a.getRenderingMesh();if(!h)continue;const u=l._getInstancesRenderList(a._id,!!a.getReplacementMesh()).hardwareInstancedRendering[a._id]||l.hasThinInstances;if(this._setEmissiveTextureAndColor(l,a,h),!this._isSubMeshReady(a,u,this._emissiveTextureAndColor.texture))return!1}return!0},this._objectRenderer.customRenderFunction=(i,s,r,n)=>{this.onBeforeRenderLayerObservable.notifyObservers(this);let a;const h=this._scene.getEngine();if(n.length){for(h.setColorWrite(!1),a=0;a<n.length;a++)this._renderSubMesh(n.data[a]);h.setColorWrite(!0)}for(a=0;a<i.length;a++)this._renderSubMesh(i.data[a]);for(a=0;a<s.length;a++)this._renderSubMesh(s.data[a]);const l=h.getAlphaMode();for(a=0;a<r.length;a++){const c=r.data[a],u=c.getMaterial();if(u&&u.needDepthPrePass){const f=u.getScene().getEngine();f.setColorWrite(!1),this._renderSubMesh(c),f.setColorWrite(!0)}this._renderSubMesh(c,!0)}h.setAlphaMode(l)}}_addCustomEffectDefines(e){}_internalIsSubMeshReady(e,t,i){const s=this._scene.getEngine(),r=e.getMesh(),n=r._internalAbstractMeshDataInfo._materialForRenderPass?.[s.currentRenderPassId];if(n)return n.isReadyForSubMesh(r,e,t);const a=e.getMaterial();if(!a)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return a.isReadyForSubMesh(e.getMesh(),e,t);const h=[],l=[S.PositionKind];let c=!1,u=!1;const f=!1;if(a){const y=a.needAlphaTestingForMesh(r),E=a.getAlphaTestTexture(),x=E&&E.hasAlpha&&(a.useAlphaFromDiffuseTexture||a._useAlphaFromAlbedoTexture);E&&(y||x)&&(h.push("#define DIFFUSE"),r.isVerticesDataPresent(S.UV2Kind)&&E.coordinatesIndex===1?(h.push("#define DIFFUSEUV2"),u=!0):r.isVerticesDataPresent(S.UVKind)&&(h.push("#define DIFFUSEUV1"),c=!0),y&&(h.push("#define ALPHATEST"),h.push("#define ALPHATESTVALUE 0.4")),E.gammaSpace||h.push("#define DIFFUSE_ISLINEAR"));const b=a.opacityTexture;b&&(h.push("#define OPACITY"),r.isVerticesDataPresent(S.UV2Kind)&&b.coordinatesIndex===1?(h.push("#define OPACITYUV2"),u=!0):r.isVerticesDataPresent(S.UVKind)&&(h.push("#define OPACITYUV1"),c=!0))}i&&(h.push("#define EMISSIVE"),r.isVerticesDataPresent(S.UV2Kind)&&i.coordinatesIndex===1?(h.push("#define EMISSIVEUV2"),u=!0):r.isVerticesDataPresent(S.UVKind)&&(h.push("#define EMISSIVEUV1"),c=!0),i.gammaSpace||h.push("#define EMISSIVE_ISLINEAR")),r.useVertexColors&&r.isVerticesDataPresent(S.ColorKind)&&r.hasVertexAlpha&&a.transparencyMode!==V.MATERIAL_OPAQUE&&(l.push(S.ColorKind),h.push("#define VERTEXALPHA")),c&&(l.push(S.UVKind),h.push("#define UV1")),u&&(l.push(S.UV2Kind),h.push("#define UV2"));const d=new Cs;if(r.useBones&&r.computeBonesUsingShaders){l.push(S.MatricesIndicesKind),l.push(S.MatricesWeightsKind),r.numBoneInfluencers>4&&(l.push(S.MatricesIndicesExtraKind),l.push(S.MatricesWeightsExtraKind)),h.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers);const y=r.skeleton;y&&y.isUsingTextureForMatrices?h.push("#define BONETEXTURE"):h.push("#define BonesPerMesh "+(y?y.bones.length+1:0)),r.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,r)}else h.push("#define NUM_BONE_INFLUENCERS 0");const _=r.morphTargetManager?_r(r.morphTargetManager,h,l,r,!0,!1,!1,c,u,f):0;t&&(h.push("#define INSTANCES"),Ps(l),e.getRenderingMesh().hasThinInstances&&h.push("#define THIN_INSTANCES"));const m=r.bakedVertexAnimationManager;m&&m.isEnabled&&(h.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&l.push("bakedVertexAnimationSettingsInstanced")),dr(a,this._scene,h),this._addCustomEffectDefines(h);const g=e._getDrawWrapper(void 0,!0),T=g.defines,R=h.join(`
|
|
763
|
+
`);if(T!==R){const y=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture","glowIntensity"];As(y),g.setEffect(this._engine.createEffect("glowMapGeneration",l,y,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],R,d,void 0,void 0,{maxSimultaneousMorphTargets:_},this._shaderLanguage,this._shadersLoaded?void 0:async()=>{await this._importShadersAsync(),this._shadersLoaded=!0}),R)}return g.effect.isReady()&&(this._dontCheckIfReady||!this._dontCheckIfReady&&this.isLayerReady())}_isSubMeshReady(e,t,i){return this._internalIsSubMeshReady(e,t,i)}async _importShadersAsync(){this._shaderLanguage===1?await Promise.all([he(()=>import("./glowMapGeneration.vertex-BACa9-r4.js"),__vite__mapDeps([4,5,6,7]),import.meta.url),he(()=>import("./glowMapGeneration.fragment-mDEHNZRi.js"),__vite__mapDeps([8,9]),import.meta.url)]):await Promise.all([he(()=>import("./glowMapGeneration.vertex-mAWUJxSB.js"),[],import.meta.url),he(()=>import("./glowMapGeneration.fragment-DwJ3bpr6.js"),[],import.meta.url)]),this._additionalImportShadersAsync?.()}_internalIsLayerReady(){let e=!0;for(let i=0;i<this._postProcesses.length;i++)e=this._postProcesses[i].isReady()&&e;const t=this._numInternalDraws();for(let i=0;i<t;++i){let s=this._mergeDrawWrapper[i];s||(s=this._mergeDrawWrapper[i]=new ys(this._engine),s.setEffect(this._createMergeEffect())),e=s.effect.isReady()&&e}return e}isLayerReady(){return this._internalIsLayerReady()}compose(){if(!this._dontCheckIfReady&&!this.isLayerReady())return!1;const e=this._scene.getEngine(),t=this._numInternalDraws();this.onBeforeComposeObservable.notifyObservers(this);const i=e.getAlphaMode();for(let s=0;s<t;++s){const r=this._mergeDrawWrapper[s];e.enableEffect(r),e.setState(!1),e.bindBuffers(this._vertexBuffers,this._indexBuffer,r.effect),e.setAlphaMode(this._options.alphaBlendingMode),this._internalCompose(r.effect,s)}return e.setAlphaMode(i),this.onAfterComposeObservable.notifyObservers(this),!0}_internalHasMesh(e){return this.renderingGroupId===-1||e.renderingGroupId===this.renderingGroupId}hasMesh(e){return this._internalHasMesh(e)}_internalShouldRender(){return this.isEnabled&&this._shouldRender}shouldRender(){return this._internalShouldRender()}_shouldRenderMesh(e){return!0}_internalCanRenderMesh(e,t){return!t.needAlphaBlendingForMesh(e)}_canRenderMesh(e,t){return this._internalCanRenderMesh(e,t)}_renderSubMesh(e,t=!1){if(!this._internalShouldRender())return;const i=e.getMaterial(),s=e.getMesh(),r=e.getReplacementMesh(),n=e.getRenderingMesh(),a=e.getEffectiveMesh(),h=this._scene,l=h.getEngine();if(a._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!i||!this._canRenderMesh(n,i))return;let c=i._getEffectiveOrientation(n);a._getWorldMatrixDeterminant()<0&&(c=c===V.ClockWiseSideOrientation?V.CounterClockWiseSideOrientation:V.ClockWiseSideOrientation);const f=c===V.ClockWiseSideOrientation,d=n._getInstancesRenderList(e._id,!!r);if(d.mustReturn||!this._shouldRenderMesh(n))return;const _=d.hardwareInstancedRendering[e._id]||n.hasThinInstances;if(this._setEmissiveTextureAndColor(n,e,i),this.onBeforeRenderMeshToEffect.notifyObservers(s),this._useMeshMaterial(n))e.getMaterial()._glowModeEnabled=!0,n.render(e,t,r||void 0),e.getMaterial()._glowModeEnabled=!1;else if(this._isSubMeshReady(e,_,this._emissiveTextureAndColor.texture)){const m=a._internalAbstractMeshDataInfo._materialForRenderPass?.[l.currentRenderPassId];let g=e._getDrawWrapper();if(!g&&m&&(g=m._getDrawWrapper()),!g)return;const T=g.effect;l.enableEffect(g),l.setState(i.backFaceCulling,i.zOffset,void 0,f,i.cullBackFaces,i.stencil,i.zOffsetUnits);const R=l.getDepthWrite(),A=l.getColorWrite(),y=l.getDepthFunction()||0;if(i.disableDepthWrite?l.setDepthWrite(!1):i.forceDepthWrite&&l.setDepthWrite(!0),i.disableColorWrite&&l.setColorWrite(!1),i.depthFunction!==0&&l.setDepthFunction(i.depthFunction),_||n._bind(e,T,i.fillMode),m?m.bindForSubMesh(a.getWorldMatrix(),a,e):(T.setMatrix("viewProjection",h.getTransformMatrix()),T.setMatrix("world",a.getWorldMatrix()),T.setFloat4("glowColor",this._emissiveTextureAndColor.color.r,this._emissiveTextureAndColor.color.g,this._emissiveTextureAndColor.color.b,this._emissiveTextureAndColor.color.a)),!m){const E=i.needAlphaTestingForMesh(a),x=i.getAlphaTestTexture(),b=x&&x.hasAlpha&&(i.useAlphaFromDiffuseTexture||i._useAlphaFromAlbedoTexture);if(x&&(E||b)){T.setTexture("diffuseSampler",x);const O=x.getTextureMatrix();O&&T.setMatrix("diffuseMatrix",O)}const P=i.opacityTexture;if(P){T.setTexture("opacitySampler",P),T.setFloat("opacityIntensity",P.level);const O=P.getTextureMatrix();O&&T.setMatrix("opacityMatrix",O)}this._emissiveTextureAndColor.texture&&(T.setTexture("emissiveSampler",this._emissiveTextureAndColor.texture),T.setMatrix("emissiveMatrix",this._emissiveTextureAndColor.texture.getTextureMatrix())),vs(n,T),Is(n,T),n.morphTargetManager&&n.morphTargetManager.isUsingTextureForTargets&&n.morphTargetManager._bind(T);const v=e.getMesh().bakedVertexAnimationManager;v&&v.isEnabled&&v.bind(T,_),t&&l.setAlphaMode(i.alphaMode),T.setFloat("glowIntensity",this.getEffectIntensity(n)),Ms(T,i,h)}n._processRendering(a,e,T,i.fillMode,d,_,(E,x)=>T.setMatrix("world",x)),(i.disableDepthWrite||i.forceDepthWrite)&&l.setDepthWrite(R),i.disableColorWrite&&l.setColorWrite(A),i.depthFunction!==0&&l.setDepthFunction(y)}else this._objectRenderer.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(s)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[S.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}dispose(){const e=this._vertexBuffers[S.PositionKind];e&&(e.dispose(),this._vertexBuffers[S.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);for(const t of this._mergeDrawWrapper)t.dispose();this._mergeDrawWrapper=[],this._objectRenderer.dispose(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderLayerObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear()}}is.ForceGLSL=!1;class Qt{get _shouldRender(){return this._thinEffectLayer._shouldRender}set _shouldRender(e){this._thinEffectLayer._shouldRender=e}get _emissiveTextureAndColor(){return this._thinEffectLayer._emissiveTextureAndColor}set _emissiveTextureAndColor(e){this._thinEffectLayer._emissiveTextureAndColor=e}get _effectIntensity(){return this._thinEffectLayer._effectIntensity}set _effectIntensity(e){this._thinEffectLayer._effectIntensity=e}static get ForceGLSL(){return is.ForceGLSL}static set ForceGLSL(e){is.ForceGLSL=e}get name(){return this._thinEffectLayer.name}set name(e){this._thinEffectLayer.name=e}get neutralColor(){return this._thinEffectLayer.neutralColor}set neutralColor(e){this._thinEffectLayer.neutralColor=e}get isEnabled(){return this._thinEffectLayer.isEnabled}set isEnabled(e){this._thinEffectLayer.isEnabled=e}get camera(){return this._thinEffectLayer.camera}get renderingGroupId(){return this._thinEffectLayer.renderingGroupId}set renderingGroupId(e){this._thinEffectLayer.renderingGroupId=e}get disableBoundingBoxesFromEffectLayer(){return this._thinEffectLayer.disableBoundingBoxesFromEffectLayer}set disableBoundingBoxesFromEffectLayer(e){this._thinEffectLayer.disableBoundingBoxesFromEffectLayer=e}get mainTexture(){return this._mainTexture}get _shaderLanguage(){return this._thinEffectLayer.shaderLanguage}get shaderLanguage(){return this._thinEffectLayer.shaderLanguage}setMaterialForRendering(e,t){this._thinEffectLayer.setMaterialForRendering(e,t)}getEffectIntensity(e){return this._thinEffectLayer.getEffectIntensity(e)}setEffectIntensity(e,t){this._thinEffectLayer.setEffectIntensity(e,t)}constructor(e,t,i=!1,s){this._mainTextureCreatedSize={width:0,height:0},this._maxSize=0,this._mainTextureDesiredSize={width:0,height:0},this._postProcesses=[],this._textures=[],this.uniqueId=$r.UniqueId,this.onDisposeObservable=new z,this.onBeforeRenderMainTextureObservable=new z,this.onBeforeComposeObservable=new z,this.onBeforeRenderMeshToEffect=new z,this.onAfterRenderMeshToEffect=new z,this.onAfterComposeObservable=new z,this.onSizeChangedObservable=new z,this._internalThinEffectLayer=!s,s||(s=new is(e,t,i,!1,this._importShadersAsync.bind(this)),s.getEffectName=this.getEffectName.bind(this),s.isReady=this.isReady.bind(this),s._createMergeEffect=this._createMergeEffect.bind(this),s._createTextureAndPostProcesses=this._createTextureAndPostProcesses.bind(this),s._internalCompose=this._internalRender.bind(this),s._setEmissiveTextureAndColor=this._setEmissiveTextureAndColor.bind(this),s._numInternalDraws=this._numInternalDraws.bind(this),s._addCustomEffectDefines=this._addCustomEffectDefines.bind(this),s.hasMesh=this.hasMesh.bind(this),s.shouldRender=this.shouldRender.bind(this),s._shouldRenderMesh=this._shouldRenderMesh.bind(this),s._canRenderMesh=this._canRenderMesh.bind(this),s._useMeshMaterial=this._useMeshMaterial.bind(this)),this._thinEffectLayer=s,this.name=e,this._scene=t||ye.LastCreatedScene,Qt._SceneComponentInitialization(this._scene),this._engine=this._scene.getEngine(),this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.addEffectLayer(this),this._thinEffectLayer.onDisposeObservable.add(()=>{this.onDisposeObservable.notifyObservers(this)}),this._thinEffectLayer.onBeforeRenderLayerObservable.add(()=>{this.onBeforeRenderMainTextureObservable.notifyObservers(this)}),this._thinEffectLayer.onBeforeComposeObservable.add(()=>{this.onBeforeComposeObservable.notifyObservers(this)}),this._thinEffectLayer.onBeforeRenderMeshToEffect.add(r=>{this.onBeforeRenderMeshToEffect.notifyObservers(r)}),this._thinEffectLayer.onAfterRenderMeshToEffect.add(r=>{this.onAfterRenderMeshToEffect.notifyObservers(r)}),this._thinEffectLayer.onAfterComposeObservable.add(()=>{this.onAfterComposeObservable.notifyObservers(this)})}get _shadersLoaded(){return this._thinEffectLayer._shadersLoaded}set _shadersLoaded(e){this._thinEffectLayer._shadersLoaded=e}_numInternalDraws(){return this._internalThinEffectLayer?1:this._thinEffectLayer._numInternalDraws()}_init(e){this._effectLayerOptions={mainTextureRatio:.5,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,mainTextureFormat:5,generateStencilBuffer:!1,...e},this._setMainTextureSize(),this._thinEffectLayer._init(e),this._createMainTexture(),this._createTextureAndPostProcesses()}_setMainTextureSize(){this._effectLayerOptions.mainTextureFixedSize?(this._mainTextureDesiredSize.width=this._effectLayerOptions.mainTextureFixedSize,this._mainTextureDesiredSize.height=this._effectLayerOptions.mainTextureFixedSize):(this._mainTextureDesiredSize.width=this._engine.getRenderWidth()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.height=this._engine.getRenderHeight()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.width=this._engine.needPOTTextures?ni(this._mainTextureDesiredSize.width,this._maxSize):this._mainTextureDesiredSize.width,this._mainTextureDesiredSize.height=this._engine.needPOTTextures?ni(this._mainTextureDesiredSize.height,this._maxSize):this._mainTextureDesiredSize.height),this._mainTextureDesiredSize.width=Math.floor(this._mainTextureDesiredSize.width),this._mainTextureDesiredSize.height=Math.floor(this._mainTextureDesiredSize.height)}_createMainTexture(){this._mainTexture=new yt("EffectLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,{type:this._effectLayerOptions.mainTextureType,format:this._effectLayerOptions.mainTextureFormat,samplingMode:G.TRILINEAR_SAMPLINGMODE,generateStencilBuffer:this._effectLayerOptions.generateStencilBuffer,existingObjectRenderer:this._thinEffectLayer.objectRenderer}),this._mainTexture.activeCamera=this._effectLayerOptions.camera,this._mainTexture.wrapU=G.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=G.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(G.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._mainTexture.ignoreCameraViewport=!0,this._mainTexture.onClearObservable.add(e=>{e.clear(this.neutralColor,!0,!0,!0)})}_addCustomEffectDefines(e){}_isReady(e,t,i){return this._internalThinEffectLayer?this._thinEffectLayer._internalIsSubMeshReady(e,t,i):this._thinEffectLayer._isSubMeshReady(e,t,i)}async _importShadersAsync(){}_arePostProcessAndMergeReady(){return this._internalThinEffectLayer?this._thinEffectLayer._internalIsLayerReady():this._thinEffectLayer.isLayerReady()}isLayerReady(){return this._arePostProcessAndMergeReady()&&this._mainTexture.isReady()}render(){this._thinEffectLayer.compose()&&(this._setMainTextureSize(),(this._mainTextureCreatedSize.width!==this._mainTextureDesiredSize.width||this._mainTextureCreatedSize.height!==this._mainTextureDesiredSize.height)&&this._mainTextureDesiredSize.width!==0&&this._mainTextureDesiredSize.height!==0&&(this.onSizeChangedObservable.notifyObservers(this),this._disposeTextureAndPostProcesses(),this._createMainTexture(),this._createTextureAndPostProcesses(),this._mainTextureCreatedSize.width=this._mainTextureDesiredSize.width,this._mainTextureCreatedSize.height=this._mainTextureDesiredSize.height))}hasMesh(e){return this._internalThinEffectLayer?this._thinEffectLayer._internalHasMesh(e):this._thinEffectLayer.hasMesh(e)}shouldRender(){return this._internalThinEffectLayer?this._thinEffectLayer._internalShouldRender():this._thinEffectLayer.shouldRender()}_shouldRenderMesh(e){return this._internalThinEffectLayer?!0:this._thinEffectLayer._shouldRenderMesh(e)}_canRenderMesh(e,t){return this._internalThinEffectLayer?this._thinEffectLayer._internalCanRenderMesh(e,t):this._thinEffectLayer._canRenderMesh(e,t)}_shouldRenderEmissiveTextureForMesh(){return!0}_useMeshMaterial(e){return this._internalThinEffectLayer?!1:this._thinEffectLayer._useMeshMaterial(e)}_rebuild(){this._thinEffectLayer._rebuild()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e<this._postProcesses.length;e++)this._postProcesses[e]&&this._postProcesses[e].dispose();this._postProcesses=[];for(let e=0;e<this._textures.length;e++)this._textures[e]&&this._textures[e].dispose();this._textures=[]}dispose(){this._thinEffectLayer.dispose(),this._disposeTextureAndPostProcesses(),this._scene.removeEffectLayer(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return fe.Instantiate(e.customType).Parse(e,t,i)}}Qt._SceneComponentInitialization=o=>{throw pe("EffectLayerSceneComponent")};M([C()],Qt.prototype,"name",null);M([La()],Qt.prototype,"neutralColor",null);M([C()],Qt.prototype,"isEnabled",null);M([pu()],Qt.prototype,"camera",null);M([C()],Qt.prototype,"renderingGroupId",null);M([C()],Qt.prototype,"disableBoundingBoxesFromEffectLayer",null);class sg{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new z,this._onClonedObservable=new z,this._inheritVisibility=!1,this._isVisible=!0}}class lt{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,s){const r=this._NodeConstructors[e];return r?r(t,i,s):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return this._nodeDataStorage._doNotSerialize?!0:this._parentNode?this._parentNode.doNotSerialize:!1}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;const t=this._parentNode;if(this._parentNode&&this._parentNode._children!==void 0&&this._parentNode._children!==null){const i=this._parentNode._children.indexOf(this);i!==-1&&this._parentNode._children.splice(i,1),!e&&!this._nodeDataStorage._isDisposed&&this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&((this._parentNode._children===void 0||this._parentNode._children===null)&&(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}get inheritVisibility(){return this._nodeDataStorage._inheritVisibility}set inheritVisibility(e){this._nodeDataStorage._inheritVisibility=e}get isVisible(){return this.inheritVisibility&&this._parentNode&&!this._parentNode.isVisible?!1:this._nodeDataStorage._isVisible}set isVisible(e){this._nodeDataStorage._isVisible=e}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){this._nodeDataStorage._sceneRootNodesIndex===-1&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(this._nodeDataStorage._sceneRootNodesIndex!==-1){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null,i=!0){this._isDirty=!1,this._nodeDataStorage=new sg,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new z,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=D.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new z,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||ye.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),i&&this._addToSceneRootNodes()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return this._behaviors.indexOf(e)!==-1?this:(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce(()=>{this._behaviors.includes(e)&&e.attach(this)}):e.attach(this),this._behaviors.push(e),this)}removeBehavior(e){const t=this._behaviors.indexOf(e);return t===-1?this:(this._behaviors[t].detach(),this._behaviors.splice(t,1),this)}get behaviors(){return this._behaviors}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={}}updateCache(e){!e&&this.isSynchronized()||this._updateCache()}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return this._parentNode?this._parentNode._isDirty||this._parentUpdateId!==this._parentNode._childUpdateId?!1:this._parentNode.isSynchronized():!0}isSynchronized(){return this._parentNode&&!this.isSynchronizedWithParent()?!1:this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return e===!1?this._nodeDataStorage._isEnabled:this._nodeDataStorage._isEnabled?this._nodeDataStorage._isParentEnabled:!1}_syncParentEnabledState(){if(this._nodeDataStorage._isParentEnabled=this._parentNode?this._parentNode.isEnabled():!0,this._children)for(const e of this._children)e._syncParentEnabledState()}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return this.parent?this.parent===e?!0:this.parent.isDescendantOf(e):!1}_getDescendants(e,t=!1,i){if(this._children)for(let s=0;s<this._children.length;s++){const r=this._children[s];(!i||i(r))&&e.push(r),t||r._getDescendants(e,!1,i)}}getDescendants(e,t){const i=[];return this._getDescendants(i,e,t),i}getChildMeshes(e,t){const i=[];return this._getDescendants(i,e,s=>(!t||t(s))&&s.cullingStrategy!==void 0),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;t<this.animations.length;t++){const i=this.animations[t];if(i.name===e)return i}return null}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=lt._AnimationRangeFactory(e,t,i);for(let s=0,r=this.animations.length;s<r;s++)this.animations[s]&&this.animations[s].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,s=this.animations.length;i<s;i++)this.animations[i]&&this.animations[i].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}clone(e,t,i){const s=me.Clone(()=>new lt(e,this.getScene()),this);if(t&&(s.parent=t),!i){const r=this.getDescendants(!0);for(let n=0;n<r.length;n++){const a=r[n];a.clone(e+"."+a.name,s)}}return s}getAnimationRanges(){const e=[];let t;for(t in this._ranges)e.push(this._ranges[t]);return e}beginAnimation(e,t,i,s){const r=this.getAnimationRange(e);return r?this._scene.beginAnimation(this,r.from,r.to,t,i,s):null}serializeAnimationRanges(){const e=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const s={};s.name=t,s.from=i.from,s.to=i.to,e.push(s)}return e}computeWorldMatrix(e){return this._worldMatrix||(this._worldMatrix=D.Identity()),this._worldMatrix}dispose(e,t=!1){if(this._nodeDataStorage._isDisposed=!0,!e){const i=this.getDescendants(!0);for(const s of i)s.dispose(e,t)}this.parent?this.parent=null:this._removeFromSceneRootNodes(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onEnabledStateChangedObservable.clear(),this.onClonedObservable.clear();for(const i of this._behaviors)i.detach();this._behaviors.length=0,this.metadata=null}static ParseAnimationRanges(e,t,i){if(t.ranges)for(let s=0;s<t.ranges.length;s++){const r=t.ranges[s];e.createAnimationRange(r.name,r.from,r.to)}}getHierarchyBoundingVectors(e=!0,t=null){this.getScene().incrementRenderId(),this.computeWorldMatrix(!0);let i,s;const r=this;if(r.getBoundingInfo&&r.subMeshes){const n=r.getBoundingInfo();i=n.boundingBox.minimumWorld.clone(),s=n.boundingBox.maximumWorld.clone()}else i=new p(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new p(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(e){const n=this.getDescendants(!1);for(const a of n){const h=a;if(h.computeWorldMatrix(!0),t&&!t(h)||!h.getBoundingInfo||h.getTotalVertices()===0)continue;const c=h.getBoundingInfo().boundingBox,u=c.minimumWorld,f=c.maximumWorld;p.CheckExtends(u,i,s),p.CheckExtends(f,i,s)}}return{min:i,max:s}}}lt._AnimationRangeFactory=(o,e,t)=>{throw pe("AnimationRange")};lt._NodeConstructors={};M([C()],lt.prototype,"name",void 0);M([C()],lt.prototype,"id",void 0);M([C()],lt.prototype,"uniqueId",void 0);M([C()],lt.prototype,"state",void 0);M([C()],lt.prototype,"metadata",void 0);class be extends lt{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){let e,t;if(this.mode===be.PERSPECTIVE_CAMERA)this.fovMode===be.FOVMODE_VERTICAL_FIXED?(t=this.minZ*2*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=this.minZ*2*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const i=this.getEngine().getRenderWidth()/2,s=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??s)-(this.orthoBottom??-s)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}setFocalLength(e,t=36){this.fov=2*Math.atan(t/(2*e))}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,s=!0){super(e,i,!1),this._position=p.Zero(),this._upVector=p.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=be.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new Ys(0,0,1,1),this.layerMask=268435455,this.fovMode=be.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=be.RIG_MODE_NONE,this.ignoreCameraMaxZ=!1,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new z,this.onProjectionMatrixChangedObservable=new z,this.onAfterCheckInputsObservable=new z,this.onRestoreStateObservable=new z,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new D,this._postProcesses=new Array,this._activeMeshes=new Et(256),this._globalPosition=p.Zero(),this._computedViewMatrix=D.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=D.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=re.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),s&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}hasStateStored(){return!!this._stateStored}_restoreStateValues(){return this._stateStored?(this.fov=this._storedFov,!0):!1}restoreState(){return this._restoreStateValues()?(this.onRestoreStateObservable.notifyObservers(this),!0):!1}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}applyVerticalCorrection(){const e=this.absoluteRotation.toEulerAngles();this.projectionPlaneTilt=this._scene.useRightHandedSystem?-e.x:e.x}get globalPosition(){return this._globalPosition}getActiveMeshes(){return this._activeMeshes}isActiveMesh(e){return this._activeMeshes.indexOf(e)!==-1}isReady(e=!1){if(e){for(const t of this._postProcesses)if(t&&!t.isReady())return!1}return super.isReady(e)}_initCache(){super._initCache(),this._cache.position=new p(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new p(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.obliqueAngle=void 0,this._cache.obliqueLength=void 0,this._cache.obliqueOffset=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0}_updateCache(e){e||super._updateCache(),this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector)}_isSynchronized(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()}_isSynchronizedViewMatrix(){return super._isSynchronized()?this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent():!1}_isSynchronizedProjectionMatrix(){const e=this.ignoreCameraMaxZ?0:this.maxZ;let t=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===e;if(!t)return!1;const i=this.getEngine();return this.mode===be.PERSPECTIVE_CAMERA?t=this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===i.getAspectRatio(this)&&this._cache.projectionPlaneTilt===this.projectionPlaneTilt:(t=this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===i.getRenderWidth()&&this._cache.renderHeight===i.getRenderHeight(),this.oblique&&(t=t&&this._cache.obliqueAngle===this.oblique.angle&&this._cache.obliqueLength===this.oblique.length&&this._cache.obliqueOffset===this.oblique.offset)),t}attachControl(e,t){}detachControl(e){}update(){this._hasMoved=!1,this._checkInputs(),this.cameraRigMode!==be.RIG_MODE_NONE&&this._updateRigCameras(),this.getViewMatrix(),this.getProjectionMatrix()}_checkInputs(){this.onAfterCheckInputsObservable.notifyObservers(this)}get rigCameras(){return this._rigCameras}get rigPostProcess(){return this._rigPostProcess}_getFirstPostProcess(){for(let e=0;e<this._postProcesses.length;e++)if(this._postProcesses[e]!==null)return this._postProcesses[e];return null}_cascadePostProcessesToRigCams(){const e=this._getFirstPostProcess();e&&e.markTextureDirty();for(let t=0,i=this._rigCameras.length;t<i;t++){const s=this._rigCameras[t],r=s._rigPostProcess;r?(r.getEffectName()==="pass"&&(s.isIntermediate=this._postProcesses.length===0),s._postProcesses=this._postProcesses.slice(0).concat(r),r.markTextureDirty()):s._postProcesses=this._postProcesses.slice(0)}}attachPostProcess(e,t=null){return!e.isReusable()&&this._postProcesses.indexOf(e)>-1?(W.Error("You're trying to reuse a post process not defined as reusable."),0):(t==null||t<0?this._postProcesses.push(e):this._postProcesses[t]===null?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))}detachPostProcess(e){const t=this._postProcesses.indexOf(e);t!==-1&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()?this._worldMatrix:(this.getViewMatrix(),this._worldMatrix)}_getViewMatrix(){return D.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._worldMatrix.getTranslationToRef(this._globalPosition),this._computedViewMatrix)}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,e!==void 0&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;const t=this.ignoreCameraMaxZ?0:this.maxZ;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=t,this._refreshFrustumPlanes=!0;const i=this.getEngine(),s=this.getScene(),r=i.useReverseDepthBuffer;if(this.mode===be.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=i.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);let n;s.useRightHandedSystem?n=D.PerspectiveFovRHToRef:n=D.PerspectiveFovLHToRef,n(this.fov,i.getAspectRatio(this),r?t:this.minZ,r?this.minZ:t,this._projectionMatrix,this.fovMode===be.FOVMODE_VERTICAL_FIXED,i.isNDCHalfZRange,this.projectionPlaneTilt,r)}else{const n=i.getRenderWidth()/2,a=i.getRenderHeight()/2;s.useRightHandedSystem?this.oblique?D.ObliqueOffCenterRHToRef(this.orthoLeft??-n,this.orthoRight??n,this.orthoBottom??-a,this.orthoTop??a,r?t:this.minZ,r?this.minZ:t,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,i.isNDCHalfZRange):D.OrthoOffCenterRHToRef(this.orthoLeft??-n,this.orthoRight??n,this.orthoBottom??-a,this.orthoTop??a,r?t:this.minZ,r?this.minZ:t,this._projectionMatrix,i.isNDCHalfZRange):this.oblique?D.ObliqueOffCenterLHToRef(this.orthoLeft??-n,this.orthoRight??n,this.orthoBottom??-a,this.orthoTop??a,r?t:this.minZ,r?this.minZ:t,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,i.isNDCHalfZRange):D.OrthoOffCenterLHToRef(this.orthoLeft??-n,this.orthoRight??n,this.orthoBottom??-a,this.orthoTop??a,r?t:this.minZ,r?this.minZ:t,this._projectionMatrix,i.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=this.oblique?.angle,this._cache.obliqueLength=this.oblique?.length,this._cache.obliqueOffset=this.oblique?.offset,this._cache.renderWidth=i.getRenderWidth(),this._cache.renderHeight=i.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){const t=this,i=this;return(t.radius||(i.target?p.Distance(this.position,i.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?Gt.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Gt.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let i=!1;for(const s of this.rigCameras)s._updateFrustumPlanes(),i=i||e.isInFrustum(s._frustumPlanes);return i}else return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw pe("Ray")}getForwardRayToRef(e,t=100,i,s){throw pe("Ray")}dispose(e,t=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){const s=this._rigCameras.pop();s&&s.dispose()}if(this._parentContainer){const s=this._parentContainer.cameras.indexOf(this);s>-1&&this._parentContainer.cameras.splice(s,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==be.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let s=this._postProcesses.length;for(;--s>=0;){const r=this._postProcesses[s];r&&r.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),super.dispose(e,t)}get isLeftCamera(){return this._isLeftCamera}get isRightCamera(){return this._isRightCamera}get leftCamera(){return this._rigCameras.length<1?null:this._rigCameras[0]}get rightCamera(){return this._rigCameras.length<2?null:this._rigCameras[1]}getLeftTarget(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()}getRightTarget(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()}setCameraRigMode(e,t){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){const i=this._rigCameras.pop();i&&i.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=fe.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==be.RIG_MODE_NONE){const i=this.createRigCamera(this.name+"_L",0);i&&(i._isLeftCamera=!0);const s=this.createRigCamera(this.name+"_R",1);s&&(s._isRightCamera=!0),i&&s&&(this._rigCameras.push(i),this._rigCameras.push(s))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return D.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.ignoreCameraMaxZ?0:this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,e==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=fe.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.ignoreCameraMaxZ?0:this.maxZ,this._rigCameras[e].fov=this.fov,this._rigCameras[e].upVector.copyFrom(this.upVector);this.cameraRigMode===be.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)}_setupInputs(){}serialize(){const e=me.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getClassName(),this.parent&&this.parent._serializeAsParent(e),this.inputs&&this.inputs.serialize(e),me.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}clone(e,t=null){const i=me.Clone(be.GetConstructorFromName(this.getClassName(),e,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this);return i.name=e,i.parent=t,this.onClonedObservable.notifyObservers(i),i}getDirection(e){const t=p.Zero();return this.getDirectionToRef(e,t),t}get absoluteRotation(){return this.getWorldMatrix().decompose(void 0,this._absoluteRotation),this._absoluteRotation}getDirectionToRef(e,t){p.TransformNormalToRef(e,this.getWorldMatrix(),t)}static GetConstructorFromName(e,t,i,s=0,r=!0){const n=lt.Construct(e,t,i,{interaxial_distance:s,isStereoscopicSideBySide:r});return n||(()=>be._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=be.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=me.Parse(s,e,t);if(e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=p.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(p.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(p.FromArray(e.target)),e.cameraRigMode){const n=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,n)}if(e.animations){for(let n=0;n<e.animations.length;n++){const a=e.animations[n],h=Pi("BABYLON.Animation");h&&r.animations.push(h.Parse(a))}lt.ParseAnimationRanges(r,e,t)}return e.autoAnimate&&t.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.isEnabled!==void 0&&r.setEnabled(e.isEnabled),r}_calculateHandednessMultiplier(){let e=this.getScene().useRightHandedSystem?-1:1;return this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(e*=-1),e}}be._CreateDefaultParsedCamera=(o,e)=>{throw pe("UniversalCamera")};be.PERSPECTIVE_CAMERA=0;be.ORTHOGRAPHIC_CAMERA=1;be.FOVMODE_VERTICAL_FIXED=0;be.FOVMODE_HORIZONTAL_FIXED=1;be.RIG_MODE_NONE=0;be.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;be.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;be.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;be.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;be.RIG_MODE_STEREOSCOPIC_INTERLACED=14;be.RIG_MODE_VR=20;be.RIG_MODE_CUSTOM=22;be.ForceAttachControlToAlwaysPreventDefault=!1;M([Ut("position")],be.prototype,"_position",void 0);M([Ut("upVector")],be.prototype,"_upVector",void 0);M([C()],be.prototype,"orthoLeft",null);M([C()],be.prototype,"orthoRight",null);M([C()],be.prototype,"orthoBottom",null);M([C()],be.prototype,"orthoTop",null);M([C()],be.prototype,"fov",void 0);M([C()],be.prototype,"projectionPlaneTilt",void 0);M([C()],be.prototype,"minZ",void 0);M([C()],be.prototype,"maxZ",void 0);M([C()],be.prototype,"inertia",void 0);M([C()],be.prototype,"mode",null);M([C()],be.prototype,"layerMask",void 0);M([C()],be.prototype,"fovMode",void 0);M([C()],be.prototype,"cameraRigMode",void 0);M([C()],be.prototype,"interaxialDistance",void 0);M([C()],be.prototype,"isStereoscopicSideBySide",void 0);M([C()],be.prototype,"ignoreCameraMaxZ",void 0);const gs={},fa={};function Tc(o,e){gs[o]=e}function gm(o){return gs[o]?gs[o]:null}function pm(o,e){fa[o]=e}function mm(o){return fa[o]?fa[o]:null}function Tm(o,e,t,i){for(const s in gs)Object.prototype.hasOwnProperty.call(gs,s)&&gs[s](o,e,t,i)}Tc(ce.NAME_EFFECTLAYER,(o,e,t,i)=>{if(o.effectLayers){t.effectLayers||(t.effectLayers=[]);for(let s=0;s<o.effectLayers.length;s++){const r=Qt.Parse(o.effectLayers[s],e,i);t.effectLayers.push(r)}}});class rg{constructor(e){this.name=ce.NAME_EFFECTLAYER,this._renderEffects=!1,this._needStencil=!1,this._previousStencilState=!1,this.scene=e||ye.LastCreatedScene,this.scene&&(this._engine=this.scene.getEngine())}register(){this.scene._isReadyForMeshStage.registerStep(ce.STEP_ISREADYFORMESH_EFFECTLAYER,this,this._isReadyForMesh),this.scene._cameraDrawRenderTargetStage.registerStep(ce.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER,this,this._renderMainTexture),this.scene._beforeCameraDrawStage.registerStep(ce.STEP_BEFORECAMERADRAW_EFFECTLAYER,this,this._setStencil),this.scene._afterRenderingGroupDrawStage.registerStep(ce.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW,this,this._drawRenderingGroup),this.scene._afterCameraDrawStage.registerStep(ce.STEP_AFTERCAMERADRAW_EFFECTLAYER,this,this._setStencilBack),this.scene._afterCameraDrawStage.registerStep(ce.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW,this,this._drawCamera)}rebuild(){const e=this.scene.effectLayers;for(const t of e)t._rebuild()}serialize(e){e.effectLayers=[];const t=this.scene.effectLayers;for(const i of t)i.serialize&&e.effectLayers.push(i.serialize())}addFromContainer(e){if(e.effectLayers)for(const t of e.effectLayers)this.scene.addEffectLayer(t)}removeFromContainer(e,t){if(e.effectLayers)for(const i of e.effectLayers)this.scene.removeEffectLayer(i),t&&i.dispose()}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,s=this.scene.effectLayers;for(const r of s){if(!r.hasMesh(e))continue;const n=r._mainTexture;this._engine.currentRenderPassId=n.renderPassId;for(const a of e.subMeshes)if(!r.isReady(a,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const s of i)if(s.shouldRender()&&(!s.camera||s.camera.cameraRigMode===be.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==be.RIG_MODE_NONE&&s.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||s.needStencil();const r=s._mainTexture;r._shouldRender()&&(this.scene.incrementRenderId(),r.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i<t.length;i++){const s=t[i];s.renderingGroupId===e&&s.shouldRender()&&s.render()}this._engine.setDepthBuffer(!0)}}_drawCamera(){this._renderEffects&&this._draw(-1)}_drawRenderingGroup(e){!this.scene._isInIntermediateRendering()&&this._renderEffects&&this._draw(e)}}Qt._SceneComponentInitialization=o=>{let e=o._getComponent(ce.NAME_EFFECTLAYER);e||(e=new rg(o),o._addComponent(e))};class xs extends is{get ldrMerge(){return this._options.ldrMerge}set blurKernelSize(e){if(e===this._options.blurKernelSize)return;this._options.blurKernelSize=e;const t=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1.kernel=t,this._verticalBlurPostprocess1.kernel=t,this._horizontalBlurPostprocess2.kernel=t,this._verticalBlurPostprocess2.kernel=t}get blurKernelSize(){return this._options.blurKernelSize}set intensity(e){this._intensity=e}get intensity(){return this._intensity}constructor(e,t,i,s=!1){super(e,t,!1,s),this._intensity=1,this._includedOnlyMeshes=[],this._excludedMeshes=[],this._meshesUsingTheirOwnMaterials=[],this._renderPassId=0,this.neutralColor=new Ce(0,0,0,1),this._options={mainTextureRatio:.5,mainTextureFixedSize:0,mainTextureType:0,mainTextureFormat:5,blurKernelSize:32,camera:null,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:1,excludeByDefault:!1,...i},this._init(this._options),s&&this._createTextureAndPostProcesses()}getClassName(){return"GlowLayer"}async _importShadersAsync(){this._shaderLanguage===1?await Promise.all([he(()=>import("./glowMapMerge.fragment-BXHfrWgL.js"),[],import.meta.url),he(()=>import("./glowMapMerge.vertex-Cnm-5WLT.js"),[],import.meta.url),he(()=>import("./glowBlurPostProcess.fragment-G_xfSiIr.js"),[],import.meta.url)]):await Promise.all([he(()=>import("./glowMapMerge.fragment-0Im35OVD.js"),[],import.meta.url),he(()=>import("./glowMapMerge.vertex-8A2ntYoS.js"),[],import.meta.url),he(()=>import("./glowBlurPostProcess.fragment-CS_rTtUL.js"),[],import.meta.url)]),await super._importShadersAsync()}getEffectName(){return xs.EffectName}_internalShouldRender(){return this._options.excludeByDefault&&!this._includedOnlyMeshes.length?!1:super._internalShouldRender()}_createMergeEffect(){let e=`#define EMISSIVE
|
|
764
|
+
`;return this._options.ldrMerge&&(e+=`#define LDR
|
|
765
|
+
`),this._engine.createEffect("glowMapMerge",[S.PositionKind],["offset"],["textureSampler","textureSampler2"],e,void 0,void 0,void 0,void 0,this.shaderLanguage,this._shadersLoaded?void 0:async()=>{await this._importShadersAsync(),this._shadersLoaded=!0})}_createTextureAndPostProcesses(){const e=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new _t("GlowLayerHBP1",this._scene.getEngine(),new ie(1,0),e),this._verticalBlurPostprocess1=new _t("GlowLayerVBP1",this._scene.getEngine(),new ie(0,1),e),this._horizontalBlurPostprocess2=new _t("GlowLayerHBP2",this._scene.getEngine(),new ie(1,0),e),this._verticalBlurPostprocess2=new _t("GlowLayerVBP2",this._scene.getEngine(),new ie(0,1),e),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2]}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s)return!1;const r=i.emissiveTexture;return super._isSubMeshReady(e,t,r)}_canRenderMesh(e,t){return!0}_internalCompose(e){this.bindTexturesForCompose(e),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(V.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let s=1;if(this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector)this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color);else if(i.emissiveColor){const r=i.emissiveIntensity??1;s*=r,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)}else this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){this._excludedMeshes.indexOf(e.uniqueId)===-1&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);t!==-1&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){this._includedOnlyMeshes.indexOf(e.uniqueId)===-1&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);t!==-1&&this._includedOnlyMeshes.splice(t,1)}setExcludedByDefault(e){this._options.excludeByDefault=e}hasMesh(e){return super.hasMesh(e)?this._includedOnlyMeshes.length?this._includedOnlyMeshes.indexOf(e.uniqueId)!==-1:this._excludedMeshes.length?this._excludedMeshes.indexOf(e.uniqueId)===-1:!0:!1}_useMeshMaterial(e){return e.material?._supportGlowLayer?!0:this._meshesUsingTheirOwnMaterials.length==0?!1:this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add(()=>{this._disposeMesh(e)})}unReferenceMeshFromUsingItsOwnMaterial(e,t){let i=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;i>=0;)this._meshesUsingTheirOwnMaterials.splice(i,1),i=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(t)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}}xs.EffectName="GlowLayer";xs.DefaultBlurKernelSize=32;je.prototype.getGlowLayerByName=function(o){for(let e=0;e<this.effectLayers?.length;e++)if(this.effectLayers[e].name===o&&this.effectLayers[e].getEffectName()===Zt.EffectName)return this.effectLayers[e];return null};class Zt extends Qt{static get EffectName(){return xs.EffectName}set blurKernelSize(e){this._thinEffectLayer.blurKernelSize=e}get blurKernelSize(){return this._thinEffectLayer.blurKernelSize}set intensity(e){this._thinEffectLayer.intensity=e}get intensity(){return this._thinEffectLayer.intensity}get customEmissiveColorSelector(){return this._thinEffectLayer.customEmissiveColorSelector}set customEmissiveColorSelector(e){this._thinEffectLayer.customEmissiveColorSelector=e}get customEmissiveTextureSelector(){return this._thinEffectLayer.customEmissiveTextureSelector}set customEmissiveTextureSelector(e){this._thinEffectLayer.customEmissiveTextureSelector=e}constructor(e,t,i){super(e,t,!1,new xs(e,t,i)),this._options={mainTextureRatio:Zt.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:1,mainTextureType:0,generateStencilBuffer:!1,excludeByDefault:!1,...i},this._init(this._options)}getEffectName(){return Zt.EffectName}_createMergeEffect(){return this._thinEffectLayer._createMergeEffect()}_createTextureAndPostProcesses(){this._thinEffectLayer._renderPassId=this._mainTexture.renderPassId;let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?ni(e,this._maxSize):e,t=this._engine.needPOTTextures?ni(t,this._maxSize):t;let i;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture1=new yt("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=G.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=G.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(G.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;const s=Math.floor(e/2),r=Math.floor(t/2);this._blurTexture2=new yt("GlowLayerBlurRTT2",{width:s,height:r},this._scene,!1,!0,i),this._blurTexture2.wrapU=G.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=G.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(G.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2],this._thinEffectLayer.bindTexturesForCompose=c=>{c.setTexture("textureSampler",this._blurTexture1),c.setTexture("textureSampler2",this._blurTexture2),c.setFloat("offset",this.intensity)},this._thinEffectLayer._createTextureAndPostProcesses();const n=this._thinEffectLayer._postProcesses[0];this._horizontalBlurPostprocess1=new Ct("GlowLayerHBP1",n.direction,n.kernel,{samplingMode:G.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),width:e,height:t,textureType:i,effectWrapper:n}),this._horizontalBlurPostprocess1.width=e,this._horizontalBlurPostprocess1.height=t,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add(c=>{c.setTexture("textureSampler",this._mainTexture)});const a=this._thinEffectLayer._postProcesses[1];this._verticalBlurPostprocess1=new Ct("GlowLayerVBP1",a.direction,a.kernel,{samplingMode:G.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),width:e,height:t,textureType:i,effectWrapper:a});const h=this._thinEffectLayer._postProcesses[2];this._horizontalBlurPostprocess2=new Ct("GlowLayerHBP2",h.direction,h.kernel,{samplingMode:G.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),width:s,height:r,textureType:i,effectWrapper:h}),this._horizontalBlurPostprocess2.width=s,this._horizontalBlurPostprocess2.height=r,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(c=>{c.setTexture("textureSampler",this._blurTexture1)});const l=this._thinEffectLayer._postProcesses[3];this._verticalBlurPostprocess2=new Ct("GlowLayerVBP2",l.direction,l.kernel,{samplingMode:G.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),width:s,height:r,textureType:i,effectWrapper:l}),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add(()=>{const c=this._blurTexture1.renderTarget;if(c){this._scene.postProcessManager.directRender(this._postProcesses1,c,!0);const u=this._blurTexture2.renderTarget;u&&this._scene.postProcessManager.directRender(this._postProcesses2,u,!0),this._engine.unBindFramebuffer(u??c,!0)}}),this._postProcesses.map(c=>{c.autoClear=!1}),this._mainTextureCreatedSize.width=this._mainTextureDesiredSize.width,this._mainTextureCreatedSize.height=this._mainTextureDesiredSize.height}isReady(e,t){return this._thinEffectLayer.isReady(e,t)}needStencil(){return!1}_canRenderMesh(e,t){return this._thinEffectLayer._canRenderMesh(e,t)}_internalRender(e){this._thinEffectLayer._internalCompose(e)}_setEmissiveTextureAndColor(e,t,i){this._thinEffectLayer._setEmissiveTextureAndColor(e,t,i)}_shouldRenderMesh(e){return this._thinEffectLayer._shouldRenderMesh(e)}_addCustomEffectDefines(e){this._thinEffectLayer._addCustomEffectDefines(e)}addExcludedMesh(e){this._thinEffectLayer.addExcludedMesh(e)}removeExcludedMesh(e){this._thinEffectLayer.removeExcludedMesh(e)}addIncludedOnlyMesh(e){this._thinEffectLayer.addIncludedOnlyMesh(e)}removeIncludedOnlyMesh(e){this._thinEffectLayer.removeIncludedOnlyMesh(e)}setExcludedByDefault(e){this._thinEffectLayer.setExcludedByDefault(e)}hasMesh(e){return this._thinEffectLayer.hasMesh(e)}_useMeshMaterial(e){return this._thinEffectLayer._useMeshMaterial(e)}referenceMeshToUseItsOwnMaterial(e){this._thinEffectLayer.referenceMeshToUseItsOwnMaterial(e)}unReferenceMeshFromUsingItsOwnMaterial(e){this._thinEffectLayer.unReferenceMeshFromUsingItsOwnMaterial(e,this._mainTexture.renderPassId)}_disposeMesh(e){this._thinEffectLayer._disposeMesh(e)}getClassName(){return"GlowLayer"}serialize(){const e=me.Serialize(this);e.customType="BABYLON.GlowLayer";let t;e.includedMeshes=[];const i=this._thinEffectLayer._includedOnlyMeshes;if(i.length)for(t=0;t<i.length;t++){const r=this._scene.getMeshByUniqueId(i[t]);r&&e.includedMeshes.push(r.id)}e.excludedMeshes=[];const s=this._thinEffectLayer._excludedMeshes;if(s.length)for(t=0;t<s.length;t++){const r=this._scene.getMeshByUniqueId(s[t]);r&&e.excludedMeshes.push(r.id)}return e}static Parse(e,t,i){const s=me.Parse(()=>new Zt(e.name,t,e.options),e,t,i);let r;for(r=0;r<e.excludedMeshes.length;r++){const n=t.getMeshById(e.excludedMeshes[r]);n&&s.addExcludedMesh(n)}for(r=0;r<e.includedMeshes.length;r++){const n=t.getMeshById(e.includedMeshes[r]);n&&s.addIncludedOnlyMesh(n)}return s}}Zt.DefaultBlurKernelSize=32;Zt.DefaultTextureRatio=.5;M([C()],Zt.prototype,"blurKernelSize",null);M([C()],Zt.prototype,"intensity",null);M([C("options")],Zt.prototype,"_options",void 0);Ye("BABYLON.GlowLayer",Zt);const da="sharpenPixelShader",Ec=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts;
|
|
766
|
+
#define CUSTOM_FRAGMENT_DEFINITIONS
|
|
767
|
+
void main(void)
|
|
768
|
+
{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +
|
|
769
|
+
texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +
|
|
770
|
+
texture2D(textureSampler,vUV+onePixel*vec2(1,0)) +
|
|
771
|
+
texture2D(textureSampler,vUV+onePixel*vec2(0,1)) -
|
|
772
|
+
color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`;Z.ShadersStore[da]||(Z.ShadersStore[da]=Ec);const ng={name:da,shader:Ec},ag=Object.freeze(Object.defineProperty({__proto__:null,sharpenPixelShader:ng},Symbol.toStringTag,{value:"Module"}));class Li extends Qe{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(he(()=>import("./sharpen.fragment-CI40r28S.js"),[],import.meta.url))):t.push(he(()=>Promise.resolve().then(()=>ag),void 0,import.meta.url))}constructor(e,t=null,i){super({...i,name:e,engine:t||$.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:Li.FragmentUrl,uniforms:Li.Uniforms}),this.colorAmount=1,this.edgeAmount=.3,this.textureWidth=0,this.textureHeight=0}bind(e=!1){super.bind(e);const t=this._drawWrapper.effect;t.setFloat2("screenSize",this.textureWidth,this.textureHeight),t.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}Li.FragmentUrl="sharpen";Li.Uniforms=["sharpnessAmounts","screenSize"];class Ds extends Ne{get colorAmount(){return this._effectWrapper.colorAmount}set colorAmount(e){this._effectWrapper.colorAmount=e}get edgeAmount(){return this._effectWrapper.edgeAmount}set edgeAmount(e){this._effectWrapper.edgeAmount=e}getClassName(){return"SharpenPostProcess"}constructor(e,t,i,s,r,n,a=0,h=!1){const l={uniforms:Li.Uniforms,size:typeof t=="number"?t:void 0,camera:i,samplingMode:s,engine:r,reusable:n,textureType:a,blockCompilation:h,...t};super(e,Li.FragmentUrl,{effectWrapper:typeof t=="number"||!t.effectWrapper?new Li(e,r,l):void 0,...l}),this.onApply=c=>{this._effectWrapper.textureWidth=this.width,this._effectWrapper.textureHeight=this.height}}static _Parse(e,t,i,s){return me.Parse(()=>new Ds(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}M([C()],Ds.prototype,"colorAmount",null);M([C()],Ds.prototype,"edgeAmount",null);Ye("BABYLON.SharpenPostProcess",Ds);class ir extends Qe{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(he(()=>Promise.resolve().then(()=>l_),void 0,import.meta.url))):t.push(he(()=>Promise.resolve().then(()=>Vd),void 0,import.meta.url))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let i=this.options.scene;if(!i){const s=this.options.engine;if(s&&s.scenes){const r=s.scenes;i=r[r.length-1]}else i=ye.LastCreatedScene}i?this._imageProcessingConfiguration=i.imageProcessingConfiguration:this._imageProcessingConfiguration=new Oe}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateParameters()})),t||this._updateParameters()}}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}get outputTextureWidth(){return this.imageProcessingConfiguration.outputTextureWidth}set outputTextureWidth(e){this.imageProcessingConfiguration.outputTextureWidth=e}get outputTextureHeight(){return this.imageProcessingConfiguration.outputTextureHeight}set outputTextureHeight(e){this.imageProcessingConfiguration.outputTextureHeight=e}constructor(e,t=null,i){super({...i,name:e,engine:t||$.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:ir.FragmentUrl}),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:0,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1};const s=i?.imageProcessingConfiguration;s?(s.applyByPostProcess=!0,this._attachImageProcessingConfiguration(s,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0)}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const s in this._defines){const r=this._defines[s];switch(typeof r){case"number":case"string":e+=`#define ${s} ${r};
|
|
773
|
+
`;break;default:r&&(e+=`#define ${s};
|
|
774
|
+
`);break}}const t=["textureSampler"],i=["scale"];Oe&&(Oe.PrepareSamplers(t,this._defines),Oe.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}bind(e=!1){super.bind(e),this.imageProcessingConfiguration.bind(this.effect,this.overrideAspectRatio)}dispose(){super.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}ir.FragmentUrl="imageProcessing";class xc extends Ne{get _imageProcessingConfiguration(){return this._effectWrapper.imageProcessingConfiguration}get imageProcessingConfiguration(){return this._effectWrapper.imageProcessingConfiguration}set imageProcessingConfiguration(e){this._effectWrapper.imageProcessingConfiguration=e}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._effectWrapper.fromLinearSpace}set fromLinearSpace(e){this._effectWrapper.fromLinearSpace=e}constructor(e,t,i=null,s,r,n,a=0,h){const l={size:typeof t=="number"?t:void 0,camera:i,samplingMode:s,engine:r,reusable:n,textureType:a,imageProcessingConfiguration:h,scene:i?.getScene(),...t,blockCompilation:!0};super(e,ir.FragmentUrl,{effectWrapper:typeof t=="number"||!t.effectWrapper?new ir(e,r,l):void 0,...l}),this.onApply=()=>{this._effectWrapper.overrideAspectRatio=this.aspectRatio}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._effectWrapper._updateParameters()}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}M([C()],xc.prototype,"fromLinearSpace",null);class Bi extends Qe{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(he(()=>import("./chromaticAberration.fragment-D7t6Txg4.js"),[],import.meta.url))):t.push(he(()=>import("./chromaticAberration.fragment-BgX-2zxS.js"),[],import.meta.url))}constructor(e,t=null,i){super({...i,name:e,engine:t||$.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:Bi.FragmentUrl,uniforms:Bi.Uniforms}),this.aberrationAmount=30,this.radialIntensity=0,this.direction=new ie(.707,.707),this.centerPosition=new ie(.5,.5)}bind(e=!1){super.bind(e);const t=this._drawWrapper.effect;t.setFloat("chromatic_aberration",this.aberrationAmount),t.setFloat("screen_width",this.screenWidth),t.setFloat("screen_height",this.screenHeight),t.setFloat("radialIntensity",this.radialIntensity),t.setFloat2("direction",this.direction.x,this.direction.y),t.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)}}Bi.FragmentUrl="chromaticAberration";Bi.Uniforms=["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"];class gi extends Ne{get aberrationAmount(){return this._effectWrapper.aberrationAmount}set aberrationAmount(e){this._effectWrapper.aberrationAmount=e}get radialIntensity(){return this._effectWrapper.radialIntensity}set radialIntensity(e){this._effectWrapper.radialIntensity=e}get direction(){return this._effectWrapper.direction}set direction(e){this._effectWrapper.direction=e}get centerPosition(){return this._effectWrapper.centerPosition}set centerPosition(e){this._effectWrapper.centerPosition=e}get screenWidth(){return this._effectWrapper.screenWidth}set screenWidth(e){this._effectWrapper.screenWidth=e}get screenHeight(){return this._effectWrapper.screenHeight}set screenHeight(e){this._effectWrapper.screenHeight=e}getClassName(){return"ChromaticAberrationPostProcess"}constructor(e,t,i,s,r,n,a,h,l=0,c=!1){const u={uniforms:Bi.Uniforms,size:typeof s=="number"?s:void 0,camera:r,samplingMode:n,engine:a,reusable:h,textureType:l,blockCompilation:c,...s};super(e,Bi.FragmentUrl,{effectWrapper:typeof s=="number"||!s.effectWrapper?new Bi(e,a,u):void 0,...u}),this.screenWidth=t,this.screenHeight=i}static _Parse(e,t,i,s){return me.Parse(()=>new gi(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,s)}}M([C()],gi.prototype,"aberrationAmount",null);M([C()],gi.prototype,"radialIntensity",null);M([C()],gi.prototype,"direction",null);M([C()],gi.prototype,"centerPosition",null);M([C()],gi.prototype,"screenWidth",null);M([C()],gi.prototype,"screenHeight",null);Ye("BABYLON.ChromaticAberrationPostProcess",gi);class Ni extends Qe{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(he(()=>import("./grain.fragment-CH9zg05c.js"),[],import.meta.url))):t.push(he(()=>import("./grain.fragment-BMGi-Hgp.js"),[],import.meta.url))}constructor(e,t=null,i){super({...i,name:e,engine:t||$.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:Ni.FragmentUrl,uniforms:Ni.Uniforms}),this.intensity=30,this.animated=!1}bind(e=!1){super.bind(e),this._drawWrapper.effect.setFloat("intensity",this.intensity),this._drawWrapper.effect.setFloat("animatedSeed",this.animated?Math.random()+1:1)}}Ni.FragmentUrl="grain";Ni.Uniforms=["intensity","animatedSeed"];class Os extends Ne{get intensity(){return this._effectWrapper.intensity}set intensity(e){this._effectWrapper.intensity=e}get animated(){return this._effectWrapper.animated}set animated(e){this._effectWrapper.animated=e}getClassName(){return"GrainPostProcess"}constructor(e,t,i,s,r,n,a=0,h=!1){const l={uniforms:Ni.Uniforms,size:typeof t=="number"?t:void 0,camera:i,samplingMode:s,engine:r,reusable:n,textureType:a,blockCompilation:h,...t};super(e,Ni.FragmentUrl,{effectWrapper:typeof t=="number"||!t.effectWrapper?new Ni(e,r,l):void 0,...l})}static _Parse(e,t,i,s){return me.Parse(()=>new Os(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}M([C()],Os.prototype,"intensity",null);M([C()],Os.prototype,"animated",null);Ye("BABYLON.GrainPostProcess",Os);class ri extends Qe{static _GetDefines(e){return e&&e.extractDriverInfo().toLowerCase().indexOf("mali")>-1?`#define MALI 1
|
|
775
|
+
`:null}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([he(()=>Promise.resolve().then(()=>y_),void 0,import.meta.url),he(()=>Promise.resolve().then(()=>M_),void 0,import.meta.url)]))):t.push(Promise.all([he(()=>Promise.resolve().then(()=>t_),void 0,import.meta.url),he(()=>Promise.resolve().then(()=>s_),void 0,import.meta.url)]))}constructor(e,t=null,i){const s={...i,name:e,engine:t||$.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,vertexShader:ri.VertexUrl,fragmentShader:ri.FragmentUrl,uniforms:ri.Uniforms};super({...s,defines:ri._GetDefines(s.engine)}),this.texelSize=new ie(0,0)}bind(e=!1){super.bind(e),this._drawWrapper.effect.setFloat2("texelSize",this.texelSize.x,this.texelSize.y)}}ri.VertexUrl="fxaa";ri.FragmentUrl="fxaa";ri.Uniforms=["texelSize"];class rn extends Ne{getClassName(){return"FxaaPostProcess"}constructor(e,t,i=null,s,r,n,a=0){const h={uniforms:ri.Uniforms,size:typeof t=="number"?t:void 0,camera:i,samplingMode:s||G.BILINEAR_SAMPLINGMODE,engine:r,reusable:n,textureType:a,...t};super(e,ri.FragmentUrl,{effectWrapper:typeof t=="number"||!t.effectWrapper?new ri(e,r,h):void 0,...h}),this.onApplyObservable.add(l=>{this._effectWrapper.texelSize=this.texelSize})}static _Parse(e,t,i,s){return me.Parse(()=>new rn(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}Ye("BABYLON.FxaaPostProcess",rn);class bc{get name(){return this._name}get cameras(){return this._cameras}get engine(){return this._engine}constructor(e,t){this._engine=e,this.uniqueId=$r.UniqueId,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(const e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){const i=this._renderEffects[e];i&&i._enable(fe.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(fe.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=fe.MakeArray(e||this._cameras);if(!i)return;const s=[];let r;for(r=0;r<i.length;r++){const n=i[r];n&&(this._cameras.indexOf(n)===-1?this._cameras.push(n):t&&s.push(r))}for(r=0;r<s.length;r++)i.splice(s[r],1);for(const n in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,n)&&this._renderEffects[n]._attachCameras(i)}_detachCameras(e){const t=fe.MakeArray(e||this._cameras);if(t){for(const i in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,i)&&this._renderEffects[i]._detachCameras(t);for(let i=0;i<t.length;i++)this._cameras.splice(this._cameras.indexOf(t[i]),1)}}_update(){for(const e in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&this._renderEffects[e]._update();for(let e=0;e<this._cameras.length;e++){if(!this._cameras[e])continue;const t=this._cameras[e].name;this._renderEffectsForIsolatedPass[t]&&this._renderEffectsForIsolatedPass[t]._update()}}_reset(){this._renderEffects={},this._renderEffectsForIsolatedPass=new Array}_enableMSAAOnFirstPostProcess(e){if(!this._engine._features.supportMSAA)return!1;const t=Object.keys(this._renderEffects);if(t.length>0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){const e=Object.keys(this._renderEffects);for(const t of e){const i=this._renderEffects[t].getPostProcesses();if(i)for(const s of i)s.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}M([C()],bc.prototype,"_name",void 0);class $i{constructor(e,t,i,s=!0){this._name=t,this._singleInstance=s,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let i=0;i<t.length;i++)if(!t[i].isSupported)return!1}return!0}_update(){}_attachCameras(e){let t;const i=fe.MakeArray(e||this._cameras);if(i)for(let s=0;s<i.length;s++){const r=i[s];if(!r)continue;const n=r.name;if(this._singleInstance?t=0:t=n,!this._postProcesses[t]){const h=this._getPostProcesses();h&&(this._postProcesses[t]=Array.isArray(h)?h:[h])}this._indicesForCamera[n]||(this._indicesForCamera[n]=[]);const a=this._postProcesses[t];for(const h of a){const l=r.attachPostProcess(h);this._indicesForCamera[n].push(l)}this._cameras[n]||(this._cameras[n]=r)}}_detachCameras(e){const t=fe.MakeArray(e||this._cameras);if(t)for(let i=0;i<t.length;i++){const s=t[i],r=s.name,n=this._postProcesses[this._singleInstance?0:r];if(n)for(const a of n)s.detachPostProcess(a);this._cameras[r]&&(this._cameras[r]=null),delete this._indicesForCamera[r]}}_enable(e){const t=fe.MakeArray(e||this._cameras);if(t)for(let i=0;i<t.length;i++){const s=t[i],r=s.name,n=this._singleInstance?0:r;for(let a=0;a<this._indicesForCamera[r].length;a++){const h=this._indicesForCamera[r][a],l=s._postProcesses[h];l==null&&t[i].attachPostProcess(this._postProcesses[n][a],h)}}}_disable(e){const t=fe.MakeArray(e||this._cameras);if(t)for(let i=0;i<t.length;i++){const s=t[i],r=s.name,n=this._postProcesses[this._singleInstance?0:r];for(const a of n)s.detachPostProcess(a)}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}class It extends Qe{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(he(()=>import("./circleOfConfusion.fragment-D8geMRma.js"),[],import.meta.url))):t.push(he(()=>import("./circleOfConfusion.fragment-D1RtHaPm.js"),[],import.meta.url))}constructor(e,t=null,i){super({...i,name:e,engine:t||$.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:It.FragmentUrl,uniforms:It.Uniforms,samplers:It.Samplers,defines:i?.depthNotNormalized?It.DefinesDepthNotNormalized:void 0}),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50}bind(e=!1){super.bind(e);const t=this.options,i=this._drawWrapper.effect;t.depthNotNormalized||i.setFloat2("cameraMinMaxZ",this.camera.minZ,this.camera.maxZ-this.camera.minZ);const r=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);i.setFloat("focusDistance",this.focusDistance),i.setFloat("cocPrecalculation",r)}}It.FragmentUrl="circleOfConfusion";It.Uniforms=["cameraMinMaxZ","focusDistance","cocPrecalculation"];It.Samplers=["depthSampler"];It.DefinesDepthNotNormalized="#define COC_DEPTH_NOT_NORMALIZED";class Fs extends Ne{get lensSize(){return this._effectWrapper.lensSize}set lensSize(e){this._effectWrapper.lensSize=e}get fStop(){return this._effectWrapper.fStop}set fStop(e){this._effectWrapper.fStop=e}get focusDistance(){return this._effectWrapper.focusDistance}set focusDistance(e){this._effectWrapper.focusDistance=e}get focalLength(){return this._effectWrapper.focalLength}set focalLength(e){this._effectWrapper.focalLength=e}getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,s,r,n,a,h=0,l=!1){const c={uniforms:It.Uniforms,samplers:It.Samplers,defines:typeof i=="object"&&i.depthNotNormalized?It.DefinesDepthNotNormalized:void 0,size:typeof i=="number"?i:void 0,camera:s,samplingMode:r,engine:n,reusable:a,textureType:h,blockCompilation:l,...i};super(e,It.FragmentUrl,{effectWrapper:typeof i=="number"||!i.effectWrapper?new It(e,n,c):void 0,...c}),this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add(u=>{if(!this._depthTexture){W.Warn("No depth texture set on CircleOfConfusionPostProcess");return}u.setTexture("depthSampler",this._depthTexture),this._effectWrapper.camera=this._depthTexture.activeCamera})}set depthTexture(e){this._depthTexture=e}}M([C()],Fs.prototype,"lensSize",null);M([C()],Fs.prototype,"fStop",null);M([C()],Fs.prototype,"focusDistance",null);M([C()],Fs.prototype,"focalLength",null);Ye("BABYLON.CircleOfConfusionPostProcess",Fs);class _a extends _t{constructor(e,t=null,i,s,r){super(e,t,i,s,{...r,defines:`#define DOF 1
|
|
776
|
+
`})}}class ga extends Ct{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,s,r,n,a,h=null,l=G.BILINEAR_SAMPLINGMODE,c,u,f=0,d=!1,_=5){const m={size:typeof r=="number"?r:void 0,camera:n,samplingMode:l=2,engine:c,reusable:u,textureType:f,defines:`#define DOF 1
|
|
777
|
+
`,blockCompilation:d,textureFormat:_,...r};super(e,i,s,{effectWrapper:typeof r=="number"||!r.effectWrapper?new _a(e,c,i,s,m):void 0,...m}),this.externalTextureSamplerBinding=!!h,this.onApplyObservable.add(g=>{h!=null&&g.setTextureFromPostProcess("textureSampler",h),g.setTextureFromPostProcessOutput("circleOfConfusionSampler",a)})}}Ye("BABYLON.DepthOfFieldBlurPostProcess",ga);class Ai extends Qe{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(he(()=>import("./depthOfFieldMerge.fragment-Ds-g4Ln8.js"),[],import.meta.url))):t.push(he(()=>import("./depthOfFieldMerge.fragment-DCspcdWZ.js"),[],import.meta.url))}constructor(e,t=null,i){super({...i,name:e,engine:t||$.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:Ai.FragmentUrl,samplers:Ai.Samplers})}}Ai.FragmentUrl="depthOfFieldMerge";Ai.Samplers=["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"];class og extends Ne{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,s,r,n,a,h,l,c=0,u=!1){const f=typeof r=="number"?u:!!r.blockCompilation,d={samplers:Ai.Samplers,size:typeof r=="number"?r:void 0,camera:n,samplingMode:a,engine:h,reusable:l,textureType:c,...r,blockCompilation:!0};super(e,Ai.FragmentUrl,{effectWrapper:typeof r=="number"||!r.effectWrapper?new Ai(e,h,d):void 0,...d}),this._blurSteps=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(_=>{_.setTextureFromPostProcess("textureSampler",t),_.setTextureFromPostProcessOutput("circleOfConfusionSampler",i);for(let m=0;m<s.length;m++){const g=s[m];_.setTextureFromPostProcessOutput("blurStep"+(s.length-m-1),g)}}),f||this.updateEffect()}updateEffect(e=null,t=null,i=null,s,r,n){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+`
|
|
778
|
+
`),super.updateEffect(e,t,i,s,r,n)}}var Mh;(function(o){o[o.Low=0]="Low",o[o.Medium=1]="Medium",o[o.High=2]="High"})(Mh||(Mh={}));class hg{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=0,s=!1,r=!1){this._depthOfFieldBlurX=[],this._depthOfFieldBlurY=[],this._circleOfConfusion=new It(e,t,{depthNotNormalized:s,blockCompilation:r}),this.blurLevel=i;let n,a;switch(i){case 2:{n=3,a=51;break}case 1:{n=2,a=31;break}default:{a=15,n=1;break}}const h=a/Math.pow(2,n-1);let l=1;for(let c=0;c<n;c++)this._depthOfFieldBlurY.push([new _a(e,t,new ie(0,1),h,{blockCompilation:r}),l]),l=.75/Math.pow(2,c),this._depthOfFieldBlurX.push([new _a(e,t,new ie(1,0),h,{blockCompilation:r}),l]);this._dofMerge=new Ai(e,t,{blockCompilation:r})}isReady(){let e=this._circleOfConfusion.isReady()&&this._dofMerge.isReady();for(let t=0;t<this._depthOfFieldBlurX.length;t++)e=e&&this._depthOfFieldBlurX[t][0].isReady()&&this._depthOfFieldBlurY[t][0].isReady();return e}}var Ph;(function(o){o[o.Low=0]="Low",o[o.Medium=1]="Medium",o[o.High=2]="High"})(Ph||(Ph={}));class Ih extends $i{set focalLength(e){this._thinDepthOfFieldEffect.focalLength=e}get focalLength(){return this._thinDepthOfFieldEffect.focalLength}set fStop(e){this._thinDepthOfFieldEffect.fStop=e}get fStop(){return this._thinDepthOfFieldEffect.fStop}set focusDistance(e){this._thinDepthOfFieldEffect.focusDistance=e}get focusDistance(){return this._thinDepthOfFieldEffect.focusDistance}set lensSize(e){this._thinDepthOfFieldEffect.lensSize=e}get lensSize(){return this._thinDepthOfFieldEffect.lensSize}constructor(e,t,i=0,s=0,r=!1,n=!1){const a=e._renderForCamera?e.getEngine():e;super(a,"depth of field",()=>this._effects,!0),this._effects=[],this._thinDepthOfFieldEffect=new hg("Depth of Field",a,i,!1,r);const h=a.isWebGPU||a.version>1?6:5;this._circleOfConfusion=new Fs("circleOfConfusion",t,{size:1,samplingMode:G.BILINEAR_SAMPLINGMODE,engine:a,textureType:s,blockCompilation:r,depthNotNormalized:n,effectWrapper:this._thinDepthOfFieldEffect._circleOfConfusion},null),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];const l=this._thinDepthOfFieldEffect._depthOfFieldBlurX.length;for(let c=0;c<l;c++){const[u,f]=this._thinDepthOfFieldEffect._depthOfFieldBlurY[c],d=new ga("vertical blur",null,u.direction,u.kernel,{size:f,samplingMode:G.BILINEAR_SAMPLINGMODE,engine:a,textureType:s,blockCompilation:r,textureFormat:c==0?h:5,effectWrapper:u},null,this._circleOfConfusion,c==0?this._circleOfConfusion:null);d.autoClear=!1;const[_,m]=this._thinDepthOfFieldEffect._depthOfFieldBlurX[c],g=new ga("horizontal blur",null,_.direction,_.kernel,{size:m,samplingMode:G.BILINEAR_SAMPLINGMODE,engine:a,textureType:s,blockCompilation:r,effectWrapper:_},null,this._circleOfConfusion,null);g.autoClear=!1,this._depthOfFieldBlurY.push(d),this._depthOfFieldBlurX.push(g)}this._effects=[this._circleOfConfusion];for(let c=0;c<this._depthOfFieldBlurX.length;c++)this._effects.push(this._depthOfFieldBlurY[c]),this._effects.push(this._depthOfFieldBlurX[c]);this._dofMerge=new og("dofMerge",this._circleOfConfusion,this._circleOfConfusion,this._depthOfFieldBlurX,{size:this._thinDepthOfFieldEffect._depthOfFieldBlurX[l-1][1],samplingMode:G.BILINEAR_SAMPLINGMODE,engine:a,textureType:s,blockCompilation:r,effectWrapper:this._thinDepthOfFieldEffect._dofMerge},null),this._dofMerge.autoClear=!1,this._effects.push(this._dofMerge)}getClassName(){return"DepthOfFieldEffect"}set depthTexture(e){this._circleOfConfusion.depthTexture=e}disposeEffects(e){for(let t=0;t<this._effects.length;t++)this._effects[t].dispose(e)}_updateEffects(){for(let e=0;e<this._effects.length;e++)this._effects[e].updateEffect()}_isReady(){return this._thinDepthOfFieldEffect.isReady()}}class Mi extends Qe{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(he(()=>Promise.resolve().then(()=>u_),void 0,import.meta.url))):t.push(he(()=>Promise.resolve().then(()=>Wd),void 0,import.meta.url))}constructor(e,t=null,i){super({...i,name:e,engine:t||$.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:Mi.FragmentUrl,uniforms:Mi.Uniforms}),this.threshold=.9,this._exposure=1}bind(e=!1){super.bind(e);const t=this._drawWrapper.effect;t.setFloat("threshold",Math.pow(this.threshold,ul)),t.setFloat("exposure",this._exposure)}}Mi.FragmentUrl="extractHighlights";Mi.Uniforms=["threshold","exposure"];class ro extends Ne{get threshold(){return this._effectWrapper.threshold}set threshold(e){this._effectWrapper.threshold=e}get _exposure(){return this._effectWrapper._exposure}set _exposure(e){this._effectWrapper._exposure=e}getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i=null,s,r,n,a=0,h=!1){const l={uniforms:Mi.Uniforms,size:typeof t=="number"?t:void 0,camera:i,samplingMode:s,engine:r,reusable:n,textureType:a,blockCompilation:h,...t};super(e,Mi.FragmentUrl,{effectWrapper:typeof t=="number"||!t.effectWrapper?new Mi(e,r,l):void 0,...l}),this._inputPostProcess=null,this.onApplyObservable.add(c=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&c.setTextureFromPostProcess("textureSampler",this._inputPostProcess)})}}M([C()],ro.prototype,"threshold",null);Ye("BABYLON.ExtractHighlightsPostProcess",ro);class Yt extends Qe{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(he(()=>Promise.resolve().then(()=>R_),void 0,import.meta.url))):t.push(he(()=>Promise.resolve().then(()=>Jd),void 0,import.meta.url))}constructor(e,t=null,i){super({...i,name:e,engine:t||$.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:Yt.FragmentUrl,uniforms:Yt.Uniforms,samplers:Yt.Samplers}),this.weight=1}bind(e=!1){super.bind(e),this._drawWrapper.effect.setFloat("bloomWeight",this.weight)}}Yt.FragmentUrl="bloomMerge";Yt.Uniforms=["bloomWeight"];Yt.Samplers=["bloomBlur"];class no extends Ne{get weight(){return this._effectWrapper.weight}set weight(e){this._effectWrapper.weight=e}getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,s,r,n=null,a,h,l,c=0,u=!1){const f=typeof r=="number"?u:!!r.blockCompilation,d={uniforms:Yt.Uniforms,samplers:Yt.Samplers,size:typeof r=="number"?r:void 0,camera:n,samplingMode:a,engine:h,reusable:l,textureType:c,...r,blockCompilation:!0};super(e,Yt.FragmentUrl,{effectWrapper:typeof r=="number"||!r.effectWrapper?new Yt(e,h,d):void 0,...d}),this.weight=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(_=>{_.setTextureFromPostProcess("textureSampler",t),_.setTextureFromPostProcessOutput("bloomBlur",i)}),f||this.updateEffect()}}M([C()],no.prototype,"weight",null);Ye("BABYLON.BloomMergePostProcess",no);class lg{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this.scale}set kernel(e){this._blurX.kernel=e*this.scale,this._blurY.kernel=e*this.scale}constructor(e,t,i,s=!1){this.scale=i,this._downscale=new Mi(e+"_downscale",t,{blockCompilation:s}),this._blurX=new _t(e+"_blurX",t,new ie(1,0),10,{blockCompilation:s}),this._blurY=new _t(e+"_blurY",t,new ie(0,1),10,{blockCompilation:s}),this._merge=new Yt(e+"_merge",t,{blockCompilation:s})}isReady(){return this._downscale.isReady()&&this._blurX.isReady()&&this._blurY.isReady()&&this._merge.isReady()}}class vh extends $i{get threshold(){return this._thinBloomEffect.threshold}set threshold(e){this._thinBloomEffect.threshold=e}get weight(){return this._thinBloomEffect.weight}set weight(e){this._thinBloomEffect.weight=e}get kernel(){return this._thinBloomEffect.kernel}set kernel(e){this._thinBloomEffect.kernel=e}get bloomScale(){return this._thinBloomEffect.scale}constructor(e,t,i,s,r=0,n=!1){const a=e._renderForCamera?e.getEngine():e;super(a,"bloom",()=>this._effects,!0),this._effects=[],this._thinBloomEffect=new lg("bloom",a,t,n),this._downscale=new ro("highlights",{size:1,samplingMode:G.BILINEAR_SAMPLINGMODE,engine:a,textureType:r,blockCompilation:n,effectWrapper:this._thinBloomEffect._downscale}),this._blurX=new Ct("horizontal blur",this._thinBloomEffect._blurX.direction,this._thinBloomEffect._blurX.kernel,{size:t,samplingMode:G.BILINEAR_SAMPLINGMODE,engine:a,textureType:r,blockCompilation:n,effectWrapper:this._thinBloomEffect._blurX}),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new Ct("vertical blur",this._thinBloomEffect._blurY.direction,this._thinBloomEffect._blurY.kernel,{size:t,samplingMode:G.BILINEAR_SAMPLINGMODE,engine:a,textureType:r,blockCompilation:n,effectWrapper:this._thinBloomEffect._blurY}),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=s,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new no("bloomMerge",this._downscale,this._blurY,i,{size:t,samplingMode:G.BILINEAR_SAMPLINGMODE,engine:a,textureType:r,blockCompilation:n,effectWrapper:this._thinBloomEffect._merge}),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t<this._effects.length;t++)this._effects[t].dispose(e)}_updateEffects(){for(let e=0;e<this._effects.length;e++)this._effects[e].updateEffect()}_isReady(){return this._thinBloomEffect.isReady()}}class cg{constructor(){this._renderPipelines={},this._onNewPipelineAddedObservable=new z,this._onPipelineRemovedObservable=new z}get onNewPipelineAddedObservable(){return this._onNewPipelineAddedObservable}get onPipelineRemovedObservable(){return this._onPipelineRemovedObservable}get supportedPipelines(){const e=[];for(const t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){const i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this.removePipeline(e._name),this._renderPipelines[e._name]=e,this._onNewPipelineAddedObservable.notifyObservers(e)}removePipeline(e){const t=this._renderPipelines[e];t&&(this._onPipelineRemovedObservable.notifyObservers(t),delete this._renderPipelines[e])}attachCamerasToRenderPipeline(e,t,i=!1){const s=this._renderPipelines[e];s&&s._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._disableEffect(t,i)}update(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){const t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e]._rebuild()}dispose(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e].dispose()}}Object.defineProperty(je.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let o=this._getComponent(ce.NAME_POSTPROCESSRENDERPIPELINEMANAGER);o||(o=new ug(this),this._addComponent(o)),this._postProcessRenderPipelineManager=new cg}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class ug{constructor(e){this.name=ce.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ce.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}}const pa="clipPlaneFragmentDeclaration",Rc=`#ifdef CLIPPLANE
|
|
779
|
+
varying float fClipDistance;
|
|
780
|
+
#endif
|
|
781
|
+
#ifdef CLIPPLANE2
|
|
782
|
+
varying float fClipDistance2;
|
|
783
|
+
#endif
|
|
784
|
+
#ifdef CLIPPLANE3
|
|
785
|
+
varying float fClipDistance3;
|
|
786
|
+
#endif
|
|
787
|
+
#ifdef CLIPPLANE4
|
|
788
|
+
varying float fClipDistance4;
|
|
789
|
+
#endif
|
|
790
|
+
#ifdef CLIPPLANE5
|
|
791
|
+
varying float fClipDistance5;
|
|
792
|
+
#endif
|
|
793
|
+
#ifdef CLIPPLANE6
|
|
794
|
+
varying float fClipDistance6;
|
|
795
|
+
#endif
|
|
796
|
+
`;Z.IncludesShadersStore[pa]||(Z.IncludesShadersStore[pa]=Rc);const fg={name:pa,shader:Rc},Em=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneFragmentDeclaration:fg},Symbol.toStringTag,{value:"Module"})),ma="clipPlaneFragment",Sc=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
|
|
797
|
+
if (false) {}
|
|
798
|
+
#endif
|
|
799
|
+
#ifdef CLIPPLANE
|
|
800
|
+
else if (fClipDistance>0.0)
|
|
801
|
+
{discard;}
|
|
802
|
+
#endif
|
|
803
|
+
#ifdef CLIPPLANE2
|
|
804
|
+
else if (fClipDistance2>0.0)
|
|
805
|
+
{discard;}
|
|
806
|
+
#endif
|
|
807
|
+
#ifdef CLIPPLANE3
|
|
808
|
+
else if (fClipDistance3>0.0)
|
|
809
|
+
{discard;}
|
|
810
|
+
#endif
|
|
811
|
+
#ifdef CLIPPLANE4
|
|
812
|
+
else if (fClipDistance4>0.0)
|
|
813
|
+
{discard;}
|
|
814
|
+
#endif
|
|
815
|
+
#ifdef CLIPPLANE5
|
|
816
|
+
else if (fClipDistance5>0.0)
|
|
817
|
+
{discard;}
|
|
818
|
+
#endif
|
|
819
|
+
#ifdef CLIPPLANE6
|
|
820
|
+
else if (fClipDistance6>0.0)
|
|
821
|
+
{discard;}
|
|
822
|
+
#endif
|
|
823
|
+
`;Z.IncludesShadersStore[ma]||(Z.IncludesShadersStore[ma]=Sc);const dg={name:ma,shader:Sc},xm=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneFragment:dg},Symbol.toStringTag,{value:"Module"})),Ta="depthPixelShader",yc=`#ifdef ALPHATEST
|
|
824
|
+
varying vec2 vUV;uniform sampler2D diffuseSampler;
|
|
825
|
+
#endif
|
|
826
|
+
#include<clipPlaneFragmentDeclaration>
|
|
827
|
+
varying float vDepthMetric;
|
|
828
|
+
#ifdef PACKED
|
|
829
|
+
#include<packingFunctions>
|
|
830
|
+
#endif
|
|
831
|
+
#ifdef STORE_CAMERASPACE_Z
|
|
832
|
+
varying vec4 vViewPos;
|
|
833
|
+
#endif
|
|
834
|
+
#define CUSTOM_FRAGMENT_DEFINITIONS
|
|
835
|
+
void main(void)
|
|
836
|
+
{
|
|
837
|
+
#include<clipPlaneFragment>
|
|
838
|
+
#ifdef ALPHATEST
|
|
839
|
+
if (texture2D(diffuseSampler,vUV).a<0.4)
|
|
840
|
+
discard;
|
|
841
|
+
#endif
|
|
842
|
+
#ifdef STORE_CAMERASPACE_Z
|
|
843
|
+
#ifdef PACKED
|
|
844
|
+
gl_FragColor=pack(vViewPos.z);
|
|
845
|
+
#else
|
|
846
|
+
gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);
|
|
847
|
+
#endif
|
|
848
|
+
#else
|
|
849
|
+
#ifdef NONLINEARDEPTH
|
|
850
|
+
#ifdef PACKED
|
|
851
|
+
gl_FragColor=pack(gl_FragCoord.z);
|
|
852
|
+
#else
|
|
853
|
+
gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);
|
|
854
|
+
#endif
|
|
855
|
+
#else
|
|
856
|
+
#ifdef PACKED
|
|
857
|
+
gl_FragColor=pack(vDepthMetric);
|
|
858
|
+
#else
|
|
859
|
+
gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);
|
|
860
|
+
#endif
|
|
861
|
+
#endif
|
|
862
|
+
#endif
|
|
863
|
+
}`;Z.ShadersStore[Ta]||(Z.ShadersStore[Ta]=yc);const _g={name:Ta,shader:yc},gg=Object.freeze(Object.defineProperty({__proto__:null,depthPixelShader:_g},Symbol.toStringTag,{value:"Module"})),Ea="bonesDeclaration",Ac=`#if NUM_BONE_INFLUENCERS>0
|
|
864
|
+
attribute vec4 matricesIndices;attribute vec4 matricesWeights;
|
|
865
|
+
#if NUM_BONE_INFLUENCERS>4
|
|
866
|
+
attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra;
|
|
867
|
+
#endif
|
|
868
|
+
#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
|
|
869
|
+
#ifdef BONETEXTURE
|
|
870
|
+
uniform highp sampler2D boneSampler;
|
|
871
|
+
#if !defined(WEBGL2) && !defined(WEBGPU)
|
|
872
|
+
uniform float boneTextureWidth;
|
|
873
|
+
#endif
|
|
874
|
+
#else
|
|
875
|
+
uniform mat4 mBones[BonesPerMesh];
|
|
876
|
+
#endif
|
|
877
|
+
#ifdef BONES_VELOCITY_ENABLED
|
|
878
|
+
uniform mat4 mPreviousBones[BonesPerMesh];
|
|
879
|
+
#endif
|
|
880
|
+
#ifdef BONETEXTURE
|
|
881
|
+
#define inline
|
|
882
|
+
mat4 readMatrixFromRawSampler(sampler2D smp,float index)
|
|
883
|
+
{
|
|
884
|
+
#if defined(WEBGL2) || defined(WEBGPU)
|
|
885
|
+
int offset=int(index) *4;
|
|
886
|
+
vec4 m0=texelFetch(smp,ivec2(offset+0,0),0);vec4 m1=texelFetch(smp,ivec2(offset+1,0),0);vec4 m2=texelFetch(smp,ivec2(offset+2,0),0);vec4 m3=texelFetch(smp,ivec2(offset+3,0),0);return mat4(m0,m1,m2,m3);
|
|
887
|
+
#else
|
|
888
|
+
float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);
|
|
889
|
+
#endif
|
|
890
|
+
}
|
|
891
|
+
#endif
|
|
892
|
+
#endif
|
|
893
|
+
#endif
|
|
894
|
+
`;Z.IncludesShadersStore[Ea]||(Z.IncludesShadersStore[Ea]=Ac);const pg={name:Ea,shader:Ac},bm=Object.freeze(Object.defineProperty({__proto__:null,bonesDeclaration:pg},Symbol.toStringTag,{value:"Module"})),Ch="bakedVertexAnimationDeclaration",mg=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
|
|
895
|
+
uniform float bakedVertexAnimationTime;
|
|
896
|
+
#if !defined(WEBGL2) && !defined(WEBGPU)
|
|
897
|
+
uniform vec2 bakedVertexAnimationTextureSizeInverted;
|
|
898
|
+
#endif
|
|
899
|
+
uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture;
|
|
900
|
+
#ifdef INSTANCES
|
|
901
|
+
attribute vec4 bakedVertexAnimationSettingsInstanced;
|
|
902
|
+
#endif
|
|
903
|
+
#define inline
|
|
904
|
+
mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame)
|
|
905
|
+
{
|
|
906
|
+
#if defined(WEBGL2) || defined(WEBGPU)
|
|
907
|
+
int offset=int(index)*4;int frameUV=int(frame);vec4 m0=texelFetch(smp,ivec2(offset+0,frameUV),0);vec4 m1=texelFetch(smp,ivec2(offset+1,frameUV),0);vec4 m2=texelFetch(smp,ivec2(offset+2,frameUV),0);vec4 m3=texelFetch(smp,ivec2(offset+3,frameUV),0);return mat4(m0,m1,m2,m3);
|
|
908
|
+
#else
|
|
909
|
+
float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);
|
|
910
|
+
#endif
|
|
911
|
+
}
|
|
912
|
+
#endif
|
|
913
|
+
`;Z.IncludesShadersStore[Ch]||(Z.IncludesShadersStore[Ch]=mg);const xa="morphTargetsVertexGlobalDeclaration",Mc=`#ifdef MORPHTARGETS
|
|
914
|
+
uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];
|
|
915
|
+
#ifdef MORPHTARGETS_TEXTURE
|
|
916
|
+
uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex)
|
|
917
|
+
{
|
|
918
|
+
#if defined(WEBGL2) || defined(WEBGPU)
|
|
919
|
+
int textureWidth=int(morphTargetTextureInfo.y);int y=int(vertexIndex)/textureWidth;int x=int(vertexIndex) % textureWidth;return texelFetch(morphTargets,ivec3(x,y,int(morphTargetTextureIndices[targetIndex])),0).xyz;
|
|
920
|
+
#else
|
|
921
|
+
float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;
|
|
922
|
+
#endif
|
|
923
|
+
}
|
|
924
|
+
vec4 readVector4FromRawSampler(int targetIndex,float vertexIndex)
|
|
925
|
+
{
|
|
926
|
+
#if defined(WEBGL2) || defined(WEBGPU)
|
|
927
|
+
int textureWidth=int(morphTargetTextureInfo.y);int y=int(vertexIndex)/textureWidth;int x=int(vertexIndex) % textureWidth;return texelFetch(morphTargets,ivec3(x,y,int(morphTargetTextureIndices[targetIndex])),0);
|
|
928
|
+
#else
|
|
929
|
+
float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV);
|
|
930
|
+
#endif
|
|
931
|
+
}
|
|
932
|
+
#endif
|
|
933
|
+
#endif
|
|
934
|
+
`;Z.IncludesShadersStore[xa]||(Z.IncludesShadersStore[xa]=Mc);const Tg={name:xa,shader:Mc},Rm=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexGlobalDeclaration:Tg},Symbol.toStringTag,{value:"Module"})),ba="morphTargetsVertexDeclaration",Pc=`#ifdef MORPHTARGETS
|
|
935
|
+
#ifndef MORPHTARGETS_TEXTURE
|
|
936
|
+
#ifdef MORPHTARGETS_POSITION
|
|
937
|
+
attribute vec3 position{X};
|
|
938
|
+
#endif
|
|
939
|
+
#ifdef MORPHTARGETS_NORMAL
|
|
940
|
+
attribute vec3 normal{X};
|
|
941
|
+
#endif
|
|
942
|
+
#ifdef MORPHTARGETS_TANGENT
|
|
943
|
+
attribute vec3 tangent{X};
|
|
944
|
+
#endif
|
|
945
|
+
#ifdef MORPHTARGETS_UV
|
|
946
|
+
attribute vec2 uv_{X};
|
|
947
|
+
#endif
|
|
948
|
+
#ifdef MORPHTARGETS_UV2
|
|
949
|
+
attribute vec2 uv2_{X};
|
|
950
|
+
#endif
|
|
951
|
+
#ifdef MORPHTARGETS_COLOR
|
|
952
|
+
attribute vec4 color{X};
|
|
953
|
+
#endif
|
|
954
|
+
#elif {X}==0
|
|
955
|
+
uniform float morphTargetCount;
|
|
956
|
+
#endif
|
|
957
|
+
#endif
|
|
958
|
+
`;Z.IncludesShadersStore[ba]||(Z.IncludesShadersStore[ba]=Pc);const Eg={name:ba,shader:Pc},Sm=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexDeclaration:Eg},Symbol.toStringTag,{value:"Module"})),Ra="clipPlaneVertexDeclaration",Ic=`#ifdef CLIPPLANE
|
|
959
|
+
uniform vec4 vClipPlane;varying float fClipDistance;
|
|
960
|
+
#endif
|
|
961
|
+
#ifdef CLIPPLANE2
|
|
962
|
+
uniform vec4 vClipPlane2;varying float fClipDistance2;
|
|
963
|
+
#endif
|
|
964
|
+
#ifdef CLIPPLANE3
|
|
965
|
+
uniform vec4 vClipPlane3;varying float fClipDistance3;
|
|
966
|
+
#endif
|
|
967
|
+
#ifdef CLIPPLANE4
|
|
968
|
+
uniform vec4 vClipPlane4;varying float fClipDistance4;
|
|
969
|
+
#endif
|
|
970
|
+
#ifdef CLIPPLANE5
|
|
971
|
+
uniform vec4 vClipPlane5;varying float fClipDistance5;
|
|
972
|
+
#endif
|
|
973
|
+
#ifdef CLIPPLANE6
|
|
974
|
+
uniform vec4 vClipPlane6;varying float fClipDistance6;
|
|
975
|
+
#endif
|
|
976
|
+
`;Z.IncludesShadersStore[Ra]||(Z.IncludesShadersStore[Ra]=Ic);const xg={name:Ra,shader:Ic},ym=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneVertexDeclaration:xg},Symbol.toStringTag,{value:"Module"})),Dh="instancesDeclaration",bg=`#ifdef INSTANCES
|
|
977
|
+
attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;
|
|
978
|
+
#ifdef INSTANCESCOLOR
|
|
979
|
+
attribute vec4 instanceColor;
|
|
980
|
+
#endif
|
|
981
|
+
#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)
|
|
982
|
+
uniform mat4 world;
|
|
983
|
+
#endif
|
|
984
|
+
#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
|
|
985
|
+
attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3;
|
|
986
|
+
#ifdef THIN_INSTANCES
|
|
987
|
+
uniform mat4 previousWorld;
|
|
988
|
+
#endif
|
|
989
|
+
#endif
|
|
990
|
+
#else
|
|
991
|
+
#if !defined(WORLD_UBO)
|
|
992
|
+
uniform mat4 world;
|
|
993
|
+
#endif
|
|
994
|
+
#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
|
|
995
|
+
uniform mat4 previousWorld;
|
|
996
|
+
#endif
|
|
997
|
+
#endif
|
|
998
|
+
`;Z.IncludesShadersStore[Dh]||(Z.IncludesShadersStore[Dh]=bg);const Oh="pointCloudVertexDeclaration",Rg=`#ifdef POINTSIZE
|
|
999
|
+
uniform float pointSize;
|
|
1000
|
+
#endif
|
|
1001
|
+
`;Z.IncludesShadersStore[Oh]||(Z.IncludesShadersStore[Oh]=Rg);const Sa="morphTargetsVertexGlobal",vc=`#ifdef MORPHTARGETS
|
|
1002
|
+
#ifdef MORPHTARGETS_TEXTURE
|
|
1003
|
+
float vertexID;
|
|
1004
|
+
#endif
|
|
1005
|
+
#endif
|
|
1006
|
+
`;Z.IncludesShadersStore[Sa]||(Z.IncludesShadersStore[Sa]=vc);const Sg={name:Sa,shader:vc},Am=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexGlobal:Sg},Symbol.toStringTag,{value:"Module"})),ya="morphTargetsVertex",Cc=`#ifdef MORPHTARGETS
|
|
1007
|
+
#ifdef MORPHTARGETS_TEXTURE
|
|
1008
|
+
#if {X}==0
|
|
1009
|
+
for (int i=0; i<NUM_MORPH_INFLUENCERS; i++) {if (float(i)>=morphTargetCount) break;vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;
|
|
1010
|
+
#ifdef MORPHTARGETS_POSITION
|
|
1011
|
+
positionUpdated+=(readVector3FromRawSampler(i,vertexID)-position)*morphTargetInfluences[i];
|
|
1012
|
+
#endif
|
|
1013
|
+
#ifdef MORPHTARGETTEXTURE_HASPOSITIONS
|
|
1014
|
+
vertexID+=1.0;
|
|
1015
|
+
#endif
|
|
1016
|
+
#ifdef MORPHTARGETS_NORMAL
|
|
1017
|
+
normalUpdated+=(readVector3FromRawSampler(i,vertexID) -normal)*morphTargetInfluences[i];
|
|
1018
|
+
#endif
|
|
1019
|
+
#ifdef MORPHTARGETTEXTURE_HASNORMALS
|
|
1020
|
+
vertexID+=1.0;
|
|
1021
|
+
#endif
|
|
1022
|
+
#ifdef MORPHTARGETS_UV
|
|
1023
|
+
uvUpdated+=(readVector3FromRawSampler(i,vertexID).xy-uv)*morphTargetInfluences[i];
|
|
1024
|
+
#endif
|
|
1025
|
+
#ifdef MORPHTARGETTEXTURE_HASUVS
|
|
1026
|
+
vertexID+=1.0;
|
|
1027
|
+
#endif
|
|
1028
|
+
#ifdef MORPHTARGETS_TANGENT
|
|
1029
|
+
tangentUpdated.xyz+=(readVector3FromRawSampler(i,vertexID) -tangent.xyz)*morphTargetInfluences[i];
|
|
1030
|
+
#endif
|
|
1031
|
+
#ifdef MORPHTARGETTEXTURE_HASTANGENTS
|
|
1032
|
+
vertexID+=1.0;
|
|
1033
|
+
#endif
|
|
1034
|
+
#ifdef MORPHTARGETS_UV2
|
|
1035
|
+
uv2Updated+=(readVector3FromRawSampler(i,vertexID).xy-uv2)*morphTargetInfluences[i];
|
|
1036
|
+
#endif
|
|
1037
|
+
#ifdef MORPHTARGETTEXTURE_HASUV2S
|
|
1038
|
+
vertexID+=1.0;
|
|
1039
|
+
#endif
|
|
1040
|
+
#ifdef MORPHTARGETS_COLOR
|
|
1041
|
+
colorUpdated+=(readVector4FromRawSampler(i,vertexID)-color)*morphTargetInfluences[i];
|
|
1042
|
+
#endif
|
|
1043
|
+
}
|
|
1044
|
+
#endif
|
|
1045
|
+
#else
|
|
1046
|
+
#ifdef MORPHTARGETS_POSITION
|
|
1047
|
+
positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];
|
|
1048
|
+
#endif
|
|
1049
|
+
#ifdef MORPHTARGETS_NORMAL
|
|
1050
|
+
normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];
|
|
1051
|
+
#endif
|
|
1052
|
+
#ifdef MORPHTARGETS_TANGENT
|
|
1053
|
+
tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];
|
|
1054
|
+
#endif
|
|
1055
|
+
#ifdef MORPHTARGETS_UV
|
|
1056
|
+
uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}];
|
|
1057
|
+
#endif
|
|
1058
|
+
#ifdef MORPHTARGETS_UV2
|
|
1059
|
+
uv2Updated+=(uv2_{X}-uv2)*morphTargetInfluences[{X}];
|
|
1060
|
+
#endif
|
|
1061
|
+
#ifdef MORPHTARGETS_COLOR
|
|
1062
|
+
colorUpdated+=(color{X}-color)*morphTargetInfluences[{X}];
|
|
1063
|
+
#endif
|
|
1064
|
+
#endif
|
|
1065
|
+
#endif
|
|
1066
|
+
`;Z.IncludesShadersStore[ya]||(Z.IncludesShadersStore[ya]=Cc);const yg={name:ya,shader:Cc},Mm=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertex:yg},Symbol.toStringTag,{value:"Module"})),Fh="instancesVertex",Ag=`#ifdef INSTANCES
|
|
1067
|
+
mat4 finalWorld=mat4(world0,world1,world2,world3);
|
|
1068
|
+
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
|
|
1069
|
+
mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,
|
|
1070
|
+
previousWorld2,previousWorld3);
|
|
1071
|
+
#endif
|
|
1072
|
+
#ifdef THIN_INSTANCES
|
|
1073
|
+
finalWorld=world*finalWorld;
|
|
1074
|
+
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
|
|
1075
|
+
finalPreviousWorld=previousWorld*finalPreviousWorld;
|
|
1076
|
+
#endif
|
|
1077
|
+
#endif
|
|
1078
|
+
#else
|
|
1079
|
+
mat4 finalWorld=world;
|
|
1080
|
+
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
|
|
1081
|
+
mat4 finalPreviousWorld=previousWorld;
|
|
1082
|
+
#endif
|
|
1083
|
+
#endif
|
|
1084
|
+
`;Z.IncludesShadersStore[Fh]||(Z.IncludesShadersStore[Fh]=Ag);const Aa="bonesVertex",Dc=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
|
|
1085
|
+
#if NUM_BONE_INFLUENCERS>0
|
|
1086
|
+
mat4 influence;
|
|
1087
|
+
#ifdef BONETEXTURE
|
|
1088
|
+
influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];
|
|
1089
|
+
#if NUM_BONE_INFLUENCERS>1
|
|
1090
|
+
influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];
|
|
1091
|
+
#endif
|
|
1092
|
+
#if NUM_BONE_INFLUENCERS>2
|
|
1093
|
+
influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];
|
|
1094
|
+
#endif
|
|
1095
|
+
#if NUM_BONE_INFLUENCERS>3
|
|
1096
|
+
influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];
|
|
1097
|
+
#endif
|
|
1098
|
+
#if NUM_BONE_INFLUENCERS>4
|
|
1099
|
+
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];
|
|
1100
|
+
#endif
|
|
1101
|
+
#if NUM_BONE_INFLUENCERS>5
|
|
1102
|
+
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];
|
|
1103
|
+
#endif
|
|
1104
|
+
#if NUM_BONE_INFLUENCERS>6
|
|
1105
|
+
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];
|
|
1106
|
+
#endif
|
|
1107
|
+
#if NUM_BONE_INFLUENCERS>7
|
|
1108
|
+
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];
|
|
1109
|
+
#endif
|
|
1110
|
+
#else
|
|
1111
|
+
influence=mBones[int(matricesIndices[0])]*matricesWeights[0];
|
|
1112
|
+
#if NUM_BONE_INFLUENCERS>1
|
|
1113
|
+
influence+=mBones[int(matricesIndices[1])]*matricesWeights[1];
|
|
1114
|
+
#endif
|
|
1115
|
+
#if NUM_BONE_INFLUENCERS>2
|
|
1116
|
+
influence+=mBones[int(matricesIndices[2])]*matricesWeights[2];
|
|
1117
|
+
#endif
|
|
1118
|
+
#if NUM_BONE_INFLUENCERS>3
|
|
1119
|
+
influence+=mBones[int(matricesIndices[3])]*matricesWeights[3];
|
|
1120
|
+
#endif
|
|
1121
|
+
#if NUM_BONE_INFLUENCERS>4
|
|
1122
|
+
influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
|
|
1123
|
+
#endif
|
|
1124
|
+
#if NUM_BONE_INFLUENCERS>5
|
|
1125
|
+
influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
|
|
1126
|
+
#endif
|
|
1127
|
+
#if NUM_BONE_INFLUENCERS>6
|
|
1128
|
+
influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
|
|
1129
|
+
#endif
|
|
1130
|
+
#if NUM_BONE_INFLUENCERS>7
|
|
1131
|
+
influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
|
|
1132
|
+
#endif
|
|
1133
|
+
#endif
|
|
1134
|
+
finalWorld=finalWorld*influence;
|
|
1135
|
+
#endif
|
|
1136
|
+
#endif
|
|
1137
|
+
`;Z.IncludesShadersStore[Aa]||(Z.IncludesShadersStore[Aa]=Dc);const Mg={name:Aa,shader:Dc},Pm=Object.freeze(Object.defineProperty({__proto__:null,bonesVertex:Mg},Symbol.toStringTag,{value:"Module"})),wh="bakedVertexAnimation",Pg=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
|
|
1138
|
+
{
|
|
1139
|
+
#ifdef INSTANCES
|
|
1140
|
+
#define BVASNAME bakedVertexAnimationSettingsInstanced
|
|
1141
|
+
#else
|
|
1142
|
+
#define BVASNAME bakedVertexAnimationSettings
|
|
1143
|
+
#endif
|
|
1144
|
+
float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0];
|
|
1145
|
+
#if NUM_BONE_INFLUENCERS>1
|
|
1146
|
+
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];
|
|
1147
|
+
#endif
|
|
1148
|
+
#if NUM_BONE_INFLUENCERS>2
|
|
1149
|
+
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];
|
|
1150
|
+
#endif
|
|
1151
|
+
#if NUM_BONE_INFLUENCERS>3
|
|
1152
|
+
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];
|
|
1153
|
+
#endif
|
|
1154
|
+
#if NUM_BONE_INFLUENCERS>4
|
|
1155
|
+
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];
|
|
1156
|
+
#endif
|
|
1157
|
+
#if NUM_BONE_INFLUENCERS>5
|
|
1158
|
+
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];
|
|
1159
|
+
#endif
|
|
1160
|
+
#if NUM_BONE_INFLUENCERS>6
|
|
1161
|
+
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];
|
|
1162
|
+
#endif
|
|
1163
|
+
#if NUM_BONE_INFLUENCERS>7
|
|
1164
|
+
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];
|
|
1165
|
+
#endif
|
|
1166
|
+
finalWorld=finalWorld*VATInfluence;}
|
|
1167
|
+
#endif
|
|
1168
|
+
`;Z.IncludesShadersStore[wh]||(Z.IncludesShadersStore[wh]=Pg);const Ma="clipPlaneVertex",Oc=`#ifdef CLIPPLANE
|
|
1169
|
+
fClipDistance=dot(worldPos,vClipPlane);
|
|
1170
|
+
#endif
|
|
1171
|
+
#ifdef CLIPPLANE2
|
|
1172
|
+
fClipDistance2=dot(worldPos,vClipPlane2);
|
|
1173
|
+
#endif
|
|
1174
|
+
#ifdef CLIPPLANE3
|
|
1175
|
+
fClipDistance3=dot(worldPos,vClipPlane3);
|
|
1176
|
+
#endif
|
|
1177
|
+
#ifdef CLIPPLANE4
|
|
1178
|
+
fClipDistance4=dot(worldPos,vClipPlane4);
|
|
1179
|
+
#endif
|
|
1180
|
+
#ifdef CLIPPLANE5
|
|
1181
|
+
fClipDistance5=dot(worldPos,vClipPlane5);
|
|
1182
|
+
#endif
|
|
1183
|
+
#ifdef CLIPPLANE6
|
|
1184
|
+
fClipDistance6=dot(worldPos,vClipPlane6);
|
|
1185
|
+
#endif
|
|
1186
|
+
`;Z.IncludesShadersStore[Ma]||(Z.IncludesShadersStore[Ma]=Oc);const Ig={name:Ma,shader:Oc},Im=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneVertex:Ig},Symbol.toStringTag,{value:"Module"})),Lh="pointCloudVertex",vg=`#if defined(POINTSIZE) && !defined(WEBGPU)
|
|
1187
|
+
gl_PointSize=pointSize;
|
|
1188
|
+
#endif
|
|
1189
|
+
`;Z.IncludesShadersStore[Lh]||(Z.IncludesShadersStore[Lh]=vg);const Pa="depthVertexShader",Fc=`attribute vec3 position;
|
|
1190
|
+
#include<bonesDeclaration>
|
|
1191
|
+
#include<bakedVertexAnimationDeclaration>
|
|
1192
|
+
#include<morphTargetsVertexGlobalDeclaration>
|
|
1193
|
+
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
|
|
1194
|
+
#include<clipPlaneVertexDeclaration>
|
|
1195
|
+
#include<instancesDeclaration>
|
|
1196
|
+
uniform mat4 viewProjection;uniform vec2 depthValues;
|
|
1197
|
+
#if defined(ALPHATEST) || defined(NEED_UV)
|
|
1198
|
+
varying vec2 vUV;uniform mat4 diffuseMatrix;
|
|
1199
|
+
#ifdef UV1
|
|
1200
|
+
attribute vec2 uv;
|
|
1201
|
+
#endif
|
|
1202
|
+
#ifdef UV2
|
|
1203
|
+
attribute vec2 uv2;
|
|
1204
|
+
#endif
|
|
1205
|
+
#endif
|
|
1206
|
+
#ifdef STORE_CAMERASPACE_Z
|
|
1207
|
+
uniform mat4 view;varying vec4 vViewPos;
|
|
1208
|
+
#endif
|
|
1209
|
+
#include<pointCloudVertexDeclaration>
|
|
1210
|
+
varying float vDepthMetric;
|
|
1211
|
+
#define CUSTOM_VERTEX_DEFINITIONS
|
|
1212
|
+
void main(void)
|
|
1213
|
+
{vec3 positionUpdated=position;
|
|
1214
|
+
#ifdef UV1
|
|
1215
|
+
vec2 uvUpdated=uv;
|
|
1216
|
+
#endif
|
|
1217
|
+
#ifdef UV2
|
|
1218
|
+
vec2 uv2Updated=uv2;
|
|
1219
|
+
#endif
|
|
1220
|
+
#include<morphTargetsVertexGlobal>
|
|
1221
|
+
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
|
|
1222
|
+
#include<instancesVertex>
|
|
1223
|
+
#include<bonesVertex>
|
|
1224
|
+
#include<bakedVertexAnimation>
|
|
1225
|
+
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
|
|
1226
|
+
#include<clipPlaneVertex>
|
|
1227
|
+
gl_Position=viewProjection*worldPos;
|
|
1228
|
+
#ifdef STORE_CAMERASPACE_Z
|
|
1229
|
+
vViewPos=view*worldPos;
|
|
1230
|
+
#else
|
|
1231
|
+
#ifdef USE_REVERSE_DEPTHBUFFER
|
|
1232
|
+
vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));
|
|
1233
|
+
#else
|
|
1234
|
+
vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));
|
|
1235
|
+
#endif
|
|
1236
|
+
#endif
|
|
1237
|
+
#if defined(ALPHATEST) || defined(BASIC_RENDER)
|
|
1238
|
+
#ifdef UV1
|
|
1239
|
+
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
|
|
1240
|
+
#endif
|
|
1241
|
+
#ifdef UV2
|
|
1242
|
+
vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0));
|
|
1243
|
+
#endif
|
|
1244
|
+
#endif
|
|
1245
|
+
#include<pointCloudVertex>
|
|
1246
|
+
}
|
|
1247
|
+
`;Z.ShadersStore[Pa]||(Z.ShadersStore[Pa]=Fc);const Cg={name:Pa,shader:Fc},Dg=Object.freeze(Object.defineProperty({__proto__:null,depthVertexShader:Cg},Symbol.toStringTag,{value:"Module"}));class Wi{get shaderLanguage(){return this._shaderLanguage}get alphaBlendedDepth(){return this._alphaBlendedDepth}set alphaBlendedDepth(e){this._alphaBlendedDepth!==e&&(this._alphaBlendedDepth=e,this._alphaBlendedDepthMaterialCache.clear())}setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,s=!1,r=G.TRILINEAR_SAMPLINGMODE,n=!1,a,h){this._shaderLanguage=0,this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this._alphaBlendedDepth=!1,this._alphaBlendedDepthMaterialCache=new Map,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._shadersLoaded=!1,this._scene=e,this._storeNonLinearDepth=s,this._storeCameraSpaceZ=n,this.isPacked=t===0,this.isPacked?this.clearColor=new Ce(1,1,1,1):this.clearColor=new Ce(n?0:1,0,0,1),this._initShaderSourceAsync(),Wi._SceneComponentInitialization(this._scene);const l=e.getEngine();this._camera=i,r!==G.NEAREST_SAMPLINGMODE&&(t===1&&!l._caps.textureFloatLinearFiltering&&(r=G.NEAREST_SAMPLINGMODE),t===2&&!l._caps.textureHalfFloatLinearFiltering&&(r=G.NEAREST_SAMPLINGMODE));const c=this.isPacked||!l._features.supportExtendedTextureFormats?5:6;this._depthMap=h??new yt(a??"DepthRenderer",{width:l.getRenderWidth(),height:l.getRenderHeight()},this._scene,!1,!0,t,!1,r,void 0,void 0,void 0,c),this._depthMap.wrapU=G.CLAMP_ADDRESSMODE,this._depthMap.wrapV=G.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add(f=>{f.clear(this.clearColor,!0,!0,!0)}),this._depthMap.customIsReadyFunction=(f,d,_)=>{if((_||d===0)&&f.subMeshes)for(let m=0;m<f.subMeshes.length;++m){const g=f.subMeshes[m],T=g.getRenderingMesh(),R=T._getInstancesRenderList(g._id,!!g.getReplacementMesh()),A=l.getCaps().instancedArrays&&(R.visibleInstances[g._id]!==null&&R.visibleInstances[g._id]!==void 0||T.hasThinInstances);if(!this.isReady(g,A))return!1}return!0};const u=f=>{const d=f.getRenderingMesh(),_=f.getEffectiveMesh(),m=this._scene,g=m.getEngine(),T=f.getMaterial();if(_._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!T||_.infiniteDistance||T.disableDepthWrite||f.verticesCount===0||f._renderId===m.getRenderId())return;const R=_._getWorldMatrixDeterminant()<0;let A=T._getEffectiveOrientation(d);R&&(A=A===0?1:0);const y=A===0;g.setState(T.backFaceCulling,0,!1,y,this.reverseCulling?!T.cullBackFaces:T.cullBackFaces);const E=d._getInstancesRenderList(f._id,!!f.getReplacementMesh());if(E.mustReturn)return;const x=g.getCaps().instancedArrays&&(E.visibleInstances[f._id]!==null&&E.visibleInstances[f._id]!==void 0||d.hasThinInstances),b=this._camera||m.activeCamera;if(this.isReady(f,x)&&b){f._renderId=m.getRenderId();let P=_._internalAbstractMeshDataInfo._materialForRenderPass?.[g.currentRenderPassId];if(_.getClassName()==="GaussianSplattingMesh"){const L=this._alphaBlendedDepthMaterialCache.get(_.uniqueId),ee=_.isCompound;if((P===void 0||L!==this.alphaBlendedDepth)&&(P=_.material.makeDepthRenderingMaterial(this._scene,this._shaderLanguage,this.alphaBlendedDepth,ee),this.setMaterialForRendering(_,P),this._alphaBlendedDepthMaterialCache.set(_.uniqueId,this.alphaBlendedDepth),!P.isReady()))return}let v=f._getDrawWrapper();!v&&P&&(v=P._getDrawWrapper());const O=b.mode===be.ORTHOGRAPHIC_CAMERA;if(!v)return;const k=v.effect;g.enableEffect(v),x||d._bind(f,k,T.fillMode),P?P.bindForSubMesh(_.getWorldMatrix(),_,f):(k.setMatrix("viewProjection",m.getTransformMatrix()),k.setMatrix("world",_.getWorldMatrix()),this._storeCameraSpaceZ&&k.setMatrix("view",m.getViewMatrix()));let Y,q;if(O?(Y=!g.useReverseDepthBuffer&&g.isNDCHalfZRange?0:1,q=g.useReverseDepthBuffer&&g.isNDCHalfZRange?0:1):(Y=g.useReverseDepthBuffer&&g.isNDCHalfZRange?b.minZ:g.isNDCHalfZRange?0:b.minZ,q=g.useReverseDepthBuffer&&g.isNDCHalfZRange?0:b.maxZ),k.setFloat2("depthValues",Y,Y+q),!P){if(T.needAlphaTestingForMesh(_)){const ee=T.getAlphaTestTexture();ee&&(k.setTexture("diffuseSampler",ee),k.setMatrix("diffuseMatrix",ee.getTextureMatrix()))}vs(d,k),Ms(k,T,m),Is(d,k),d.morphTargetManager&&d.morphTargetManager.isUsingTextureForTargets&&d.morphTargetManager._bind(k);const L=f.getMesh().bakedVertexAnimationManager;L&&L.isEnabled&&L.bind(k,x),T.pointsCloud&&k.setFloat("pointSize",T.pointSize)}this.alphaBlendedDepth&&T.needAlphaBlendingForMesh(_)?g.setAlphaMode(2):g.setAlphaMode(0),d._processRendering(_,f,k,T.fillMode,E,x,(L,ee)=>k.setMatrix("world",ee))}};this._depthMap.customRenderFunction=(f,d,_,m)=>{const g=this._scene.getEngine(),T=g.getAlphaMode();let R;if(m.length)for(R=0;R<m.length;R++)u(m.data[R]);for(R=0;R<f.length;R++)u(f.data[R]);for(R=0;R<d.length;R++)u(d.data[R]);if(this.forceDepthWriteTransparentMeshes)for(R=0;R<_.length;R++)u(_.data[R]);else for(R=0;R<_.length;R++)_.data[R].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1;this.alphaBlendedDepth&&g.setAlphaMode(T)}}async _initShaderSourceAsync(e=!1){this._scene.getEngine().isWebGPU&&!e&&!Wi.ForceGLSL?(this._shaderLanguage=1,await Promise.all([he(()=>import("./depth.vertex-B2lrdlJh.js"),__vite__mapDeps([10,5,6,7]),import.meta.url),he(()=>import("./depth.fragment-Bn8G24s-.js"),__vite__mapDeps([11,9]),import.meta.url)])):await Promise.all([he(()=>Promise.resolve().then(()=>Dg),void 0,import.meta.url),he(()=>Promise.resolve().then(()=>gg),void 0,import.meta.url)]),this._shadersLoaded=!0}isReady(e,t){if(!this._shadersLoaded)return!1;const i=this._scene.getEngine(),s=e.getMesh(),r=s.getScene(),n=s._internalAbstractMeshDataInfo._materialForRenderPass?.[i.currentRenderPassId];if(n)return n.isReadyForSubMesh(s,e,t);const a=e.getMaterial();if(!a||a.disableDepthWrite)return!1;const h=[],l=[S.PositionKind];let c=!1,u=!1;const f=!1;a.needAlphaTestingForMesh(s)&&a.getAlphaTestTexture()&&(h.push("#define ALPHATEST"),s.isVerticesDataPresent(S.UVKind)&&(l.push(S.UVKind),h.push("#define UV1"),c=!0),s.isVerticesDataPresent(S.UV2Kind)&&(l.push(S.UV2Kind),h.push("#define UV2"),u=!0));const d=new Cs;if(s.useBones&&s.computeBonesUsingShaders&&s.skeleton){l.push(S.MatricesIndicesKind),l.push(S.MatricesWeightsKind),s.numBoneInfluencers>4&&(l.push(S.MatricesIndicesExtraKind),l.push(S.MatricesWeightsExtraKind)),h.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),s.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,s);const A=s.skeleton;A.isUsingTextureForMatrices?h.push("#define BONETEXTURE"):h.push("#define BonesPerMesh "+(A.bones.length+1))}else h.push("#define NUM_BONE_INFLUENCERS 0");const _=s.morphTargetManager?_r(s.morphTargetManager,h,l,s,!0,!1,!1,c,u,f):0;a.pointsCloud&&h.push("#define POINTSIZE"),t&&(h.push("#define INSTANCES"),Ps(l),e.getRenderingMesh().hasThinInstances&&h.push("#define THIN_INSTANCES"));const m=s.bakedVertexAnimationManager;m&&m.isEnabled&&(h.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&l.push("bakedVertexAnimationSettingsInstanced")),this._storeNonLinearDepth&&h.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&h.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&h.push("#define PACKED"),dr(a,r,h);const g=e._getDrawWrapper(void 0,!0),T=g.defines,R=h.join(`
|
|
1248
|
+
`);if(T!==R){const A=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],y=["diffuseSampler","morphTargets","boneSampler","bakedVertexAnimationTexture"];As(A),g.setEffect(i.createEffect("depth",{attributes:l,uniformsNames:A,uniformBuffersNames:[],samplers:y,defines:R,fallbacks:d,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:_},shaderLanguage:this._shaderLanguage},i),R)}return g.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}Wi.ForceGLSL=!1;Wi._SceneComponentInitialization=o=>{throw pe("DepthRendererSceneComponent")};je.prototype.enableDepthRenderer=function(o,e=!1,t=!1,i=3,s=!1,r){if(o=o||this.activeCamera,!o)throw"No camera available to enable depth renderer";if(this._depthRenderer||(this._depthRenderer={}),!this._depthRenderer[o.id]){const n=!!this.getEngine().getCaps().textureFloatRender;let a;this.getEngine().getCaps().textureHalfFloatRender&&(!t||!n)?a=2:n?a=1:a=0,this._depthRenderer[o.id]=new Wi(this,a,o,e,i,s,void 0,r)}return this._depthRenderer[o.id]};je.prototype.disableDepthRenderer=function(o){o=o||this.activeCamera,!(!o||!this._depthRenderer||!this._depthRenderer[o.id])&&this._depthRenderer[o.id].dispose()};class Og{constructor(e){this.name=ce.NAME_DEPTHRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ce.STEP_GATHERRENDERTARGETS_DEPTHRENDERER,this,this._gatherRenderTargets),this.scene._gatherActiveCameraRenderTargetsStage.registerStep(ce.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER,this,this._gatherActiveCameraRenderTargets)}rebuild(){}dispose(){for(const e in this.scene._depthRenderer)this.scene._depthRenderer[e].dispose()}_gatherRenderTargets(e){if(this.scene._depthRenderer)for(const t in this.scene._depthRenderer){const i=this.scene._depthRenderer[t];i.enabled&&!i.useOnlyInActiveCamera&&e.push(i.getDepthMap())}}_gatherActiveCameraRenderTargets(e){if(this.scene._depthRenderer)for(const t in this.scene._depthRenderer){const i=this.scene._depthRenderer[t];i.enabled&&i.useOnlyInActiveCamera&&this.scene.activeCamera.id===t&&e.push(i.getDepthMap())}}}Wi._SceneComponentInitialization=o=>{let e=o._getComponent(ce.NAME_DEPTHRENDERER);e||(e=new Og(o),o._addComponent(e))};class Tt extends bc{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){const e=this.bloom;this.bloom=new vh(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;t<this._cameras.length;t++)e.disposeEffects(this._cameras[t])}get depthOfFieldEnabled(){return this._depthOfFieldEnabled}set depthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get depthOfFieldBlurLevel(){return this._depthOfFieldBlurLevel}set depthOfFieldBlurLevel(e){if(this._depthOfFieldBlurLevel===e)return;this._depthOfFieldBlurLevel=e;const t=this.depthOfField;this.depthOfField=new Ih(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!1),this.depthOfField.focalLength=t.focalLength,this.depthOfField.focusDistance=t.focusDistance,this.depthOfField.fStop=t.fStop,this.depthOfField.lensSize=t.lensSize;for(let i=0;i<this._cameras.length;i++)t.disposeEffects(this._cameras[i]);this._buildPipeline()}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}set imageProcessingEnabled(e){this._imageProcessingEnabled!==e&&(this._scene.imageProcessingConfiguration.isEnabled=e)}get imageProcessingEnabled(){return this._imageProcessingEnabled}set glowLayerEnabled(e){e&&!this._glowLayer?this._glowLayer=new Zt("",this._scene):!e&&this._glowLayer&&(this._glowLayer.dispose(),this._glowLayer=null)}get glowLayerEnabled(){return this._glowLayer!=null}get glowLayer(){return this._glowLayer}set chromaticAberrationEnabled(e){this._chromaticAberrationEnabled!==e&&(this._chromaticAberrationEnabled=e,this._buildPipeline())}get chromaticAberrationEnabled(){return this._chromaticAberrationEnabled}set grainEnabled(e){this._grainEnabled!==e&&(this._grainEnabled=e,this._buildPipeline())}get grainEnabled(){return this._grainEnabled}constructor(e="",t=!0,i=ye.LastCreatedScene,s,r=!0){super(i.getEngine(),e),this._camerasToBeAttached=[],this.SharpenPostProcessId="SharpenPostProcessEffect",this.ImageProcessingPostProcessId="ImageProcessingPostProcessEffect",this.FxaaPostProcessId="FxaaPostProcessEffect",this.ChromaticAberrationPostProcessId="ChromaticAberrationPostProcessEffect",this.GrainPostProcessId="GrainPostProcessEffect",this._glowLayer=null,this.animations=[],this._imageProcessingConfigurationObserver=null,this._sharpenEnabled=!1,this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._depthOfFieldBlurLevel=0,this._fxaaEnabled=!1,this._imageProcessingEnabled=!0,this._bloomScale=.5,this._chromaticAberrationEnabled=!1,this._grainEnabled=!1,this._buildAllowed=!0,this.onBuildObservable=new z,this._resizeObserver=null,this._hardwareScaleLevel=1,this._bloomKernel=64,this._bloomWeight=.15,this._bloomThreshold=.9,this._samples=1,this._hasCleared=!1,this._prevPostProcess=null,this._prevPrevPostProcess=null,this._depthOfFieldSceneObserver=null,this._activeCameraChangedObserver=null,this._activeCamerasChangedObserver=null,this._cameras=s||i.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._buildAllowed=r,this._scene=i;const n=this._scene.getEngine().getCaps();this._hdr=t&&(n.textureHalfFloatRender||n.textureFloatRender),this._hdr?n.textureHalfFloatRender?this._defaultPipelineTextureType=2:n.textureFloatRender&&(this._defaultPipelineTextureType=1):this._defaultPipelineTextureType=0,i.postProcessRenderPipelineManager.addPipeline(this);const a=this._scene.getEngine();this.sharpen=new Ds("sharpen",1,null,G.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._sharpenEffect=new $i(a,this.SharpenPostProcessId,()=>this.sharpen,!0),this.depthOfField=new Ih(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=a.getHardwareScalingLevel(),this._resizeObserver=a.onResizeObservable.add(()=>{this._hardwareScaleLevel=a.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel}),this.bloom=new vh(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new gi("ChromaticAberration",a.getRenderWidth(),a.getRenderHeight(),1,null,G.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new $i(a,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new Os("Grain",1,null,G.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new $i(a,this.GrainPostProcessId,()=>this.grain,!0);let h=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add(()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,h?fe.SetImmediate(()=>{this._buildPipeline()}):this._buildPipeline())}),this._buildPipeline(),h=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){const e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;const e=this._scene.getEngine();if(this._disposePostProcesses(),this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(const t of this._cameras){const i=this._scene.enableDepthRenderer(t);i.useOnlyInActiveCamera=!0}this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add(t=>{this._cameras.indexOf(t.activeCamera)>-1&&(this.depthOfField.depthTexture=t.enableDepthRenderer(t.activeCamera).getDepthMap())})}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const t=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=t.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new xc("imageProcessing",1,null,G.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new $i(e,this.ImageProcessingPostProcessId,()=>this.imageProcessing,!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,(!this._cameras||this._cameras.length===0)&&(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new rn("fxaa",1,null,G.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new $i(e,this.FxaaPostProcessId,()=>this.fxaa,!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&this._cameras.indexOf(this._scene.activeCamera)===-1)&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add(()=>{this._scene.activeCamera&&this._cameras.indexOf(this._scene.activeCamera)===-1&&(this._scene.autoClear=!0)})),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add(()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)})),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&W.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;t<this._cameras.length;t++){const i=this._cameras[t];this.imageProcessing&&this.imageProcessing.dispose(i),this.fxaa&&this.fxaa.dispose(i),e&&(this.sharpen&&this.sharpen.dispose(i),this.depthOfField&&(this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver),this.depthOfField.disposeEffects(i)),this.bloom&&this.bloom.disposeEffects(i),this.chromaticAberration&&this.chromaticAberration.dispose(i),this.grain&&this.grain.dispose(i),this._glowLayer&&this._glowLayer.dispose())}this.imageProcessing=null,this.fxaa=null,e&&(this.sharpen=null,this._sharpenEffect=null,this.depthOfField=null,this.bloom=null,this.chromaticAberration=null,this._chromaticAberrationEffect=null,this.grain=null,this._grainEffect=null,this._glowLayer=null)}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._buildAllowed=!1,this.onBuildObservable.clear(),this._disposePostProcesses(!0),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._scene._postProcessRenderPipelineManager.removePipeline(this.name),this._scene.autoClear=!0,this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this._scene.onActiveCameraChanged.remove(this._activeCameraChangedObserver),this._scene.onActiveCamerasChanged.remove(this._activeCamerasChangedObserver),this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver),super.dispose()}serialize(){const e=me.Serialize(this);return e.customType="DefaultRenderingPipeline",e}static Parse(e,t,i){return me.Parse(()=>new Tt(e._name,e._name._hdr,t),e,t,i)}}M([C()],Tt.prototype,"sharpenEnabled",null);M([C()],Tt.prototype,"bloomKernel",null);M([C()],Tt.prototype,"_bloomWeight",void 0);M([C()],Tt.prototype,"_bloomThreshold",void 0);M([C()],Tt.prototype,"_hdr",void 0);M([C()],Tt.prototype,"bloomWeight",null);M([C()],Tt.prototype,"bloomThreshold",null);M([C()],Tt.prototype,"bloomScale",null);M([C()],Tt.prototype,"bloomEnabled",null);M([C()],Tt.prototype,"depthOfFieldEnabled",null);M([C()],Tt.prototype,"depthOfFieldBlurLevel",null);M([C()],Tt.prototype,"fxaaEnabled",null);M([C()],Tt.prototype,"samples",null);M([C()],Tt.prototype,"imageProcessingEnabled",null);M([C()],Tt.prototype,"glowLayerEnabled",null);M([C()],Tt.prototype,"chromaticAberrationEnabled",null);M([C()],Tt.prototype,"grainEnabled",null);Ye("BABYLON.DefaultRenderingPipeline",Tt);class De extends lt{get range(){return this._range}set range(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)}get intensityMode(){return this._intensityMode}set intensityMode(e){this._intensityMode=e,this._computePhotometricScale()}get radius(){return this._radius}set radius(e){this._radius=e,this._computePhotometricScale()}get shadowEnabled(){return this._shadowEnabled}set shadowEnabled(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())}get includedOnlyMeshes(){return this._includedOnlyMeshes}set includedOnlyMeshes(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)}get excludedMeshes(){return this._excludedMeshes}set excludedMeshes(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)}get excludeWithLayerMask(){return this._excludeWithLayerMask}set excludeWithLayerMask(e){this._excludeWithLayerMask=e,this._resyncMeshes()}get includeOnlyWithLayerMask(){return this._includeOnlyWithLayerMask}set includeOnlyWithLayerMask(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()}get lightmapMode(){return this._lightmapMode}set lightmapMode(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())}getViewMatrix(e){return null}getProjectionMatrix(e,t){return null}constructor(e,t,i){super(e,t,!1),this.diffuse=new Re(1,1,1),this.specular=new Re(1,1,1),this.falloffType=De.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=De.INTENSITYMODE_AUTOMATIC,this._radius=1e-5,this.renderPriority=0,this._shadowEnabled=!0,this._excludeWithLayerMask=0,this._includeOnlyWithLayerMask=0,this._lightmapMode=0,this._shadowGenerators=null,this._excludedMeshesIds=new Array,this._includedOnlyMeshesIds=new Array,this._currentViewDepth=0,this._isLight=!0,i||this.getScene().addLight(this),this._uniformBuffer=new oe(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=[],this.excludedMeshes=[],i||this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,s,r=!0){const n=e.toString();let a=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+n),this._renderId!==t.getRenderId()||this._lastUseSpecular!==s||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=s;const h=this.getScaledIntensity();this.transferToEffect(i,n),this.diffuse.scaleToRef(h,es.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",es.Color3[0],this.range,n),s&&(this.specular.scaleToRef(h,es.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",es.Color3[1],this.radius,n)),a=!0}if(this.transferTexturesToEffect(i,n),t.shadowsEnabled&&this.shadowEnabled&&r){const h=this.getShadowGenerator(t.activeCamera)??this.getShadowGenerator();h&&(h.bindShadowLight(n,i),a=!0)}a?this._uniformBuffer.update():this._uniformBuffer.bindUniformBuffer()}getClassName(){return"Light"}toString(e){let t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric","Clustered"][this.getTypeID()],this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}_syncParentEnabledState(){super._syncParentEnabledState(),this.isDisposed()||this._resyncMeshes()}setEnabled(e){super.setEnabled(e),this._resyncMeshes()}getShadowGenerator(e=null){return this._shadowGenerators===null?null:this._shadowGenerators.get(e)??null}getShadowGenerators(){return this._shadowGenerators}getAbsolutePosition(){return p.Zero()}canAffectMesh(e){return e?!(this.includedOnlyMeshes&&this.includedOnlyMeshes.length>0&&this.includedOnlyMeshes.indexOf(e)===-1||this.excludedMeshes&&this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1||this.includeOnlyWithLayerMask!==0&&!(this.includeOnlyWithLayerMask&e.layerMask)||this.excludeWithLayerMask!==0&&this.excludeWithLayerMask&e.layerMask):!0}dispose(e,t=!1){if(this._shadowGenerators){const i=this._shadowGenerators.values();for(let s=i.next();s.done!==!0;s=i.next())s.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const i=this._parentContainer.lights.indexOf(this);i>-1&&this._parentContainer.lights.splice(i,1),this._parentContainer=null}for(const i of this.getScene().meshes)i._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){const i=De.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=me.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=me.Serialize(this);if(e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0){e.excludedMeshesIds=[];for(const t of this.excludedMeshes)e.excludedMeshesIds.push(t.id)}if(this.includedOnlyMeshes.length>0){e.includedOnlyMeshesIds=[];for(const t of this.includedOnlyMeshes)e.includedOnlyMeshesIds.push(t.id)}return me.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const s=lt.Construct("Light_Type_"+e,t,i);return s||null}static Parse(e,t){const i=De.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=me.Parse(i,e,t);if(e.excludedMeshesIds&&(s._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(s._includedOnlyMeshesIds=e.includedOnlyMeshesIds),e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.falloffType!==void 0&&(s.falloffType=e.falloffType),e.lightmapMode!==void 0&&(s.lightmapMode=e.lightmapMode),e.animations){for(let r=0;r<e.animations.length;r++){const n=e.animations[r],a=Pi("BABYLON.Animation");a&&s.animations.push(a.Parse(n))}lt.ParseAnimationRanges(s,e,t)}return e.autoAnimate&&t.beginAnimation(s,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.isEnabled!==void 0&&s.setEnabled(e.isEnabled),s}_hookArrayForExcluded(e){const t=e.push;e.push=(...s)=>{const r=t.apply(e,s);for(const n of s)n._resyncLightSource(this);return r};const i=e.splice;e.splice=(s,r)=>{const n=i.apply(e,[s,r]);for(const a of n)a._resyncLightSource(this);return n};for(const s of e)s._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...s)=>{const r=t.apply(e,s);return this._resyncMeshes(),r};const i=e.splice;e.splice=(s,r)=>{const n=i.apply(e,[s,r]);return this._resyncMeshes(),n},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)e.lightSources.indexOf(this)!==-1&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===De.INTENSITYMODE_AUTOMATIC&&(t===De.LIGHTTYPEID_DIRECTIONALLIGHT?i=De.INTENSITYMODE_ILLUMINANCE:i=De.INTENSITYMODE_LUMINOUSINTENSITY),t){case De.LIGHTTYPEID_POINTLIGHT:case De.LIGHTTYPEID_SPOTLIGHT:switch(i){case De.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case De.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case De.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case De.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case De.INTENSITYMODE_ILLUMINANCE:e=1;break;case De.INTENSITYMODE_LUMINANCE:{let s=this.radius;s=Math.max(s,.001),e=2*Math.PI*(1-Math.cos(s));break}}break;case De.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e}_reorderLightsInScene(){const e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}_isReady(){return!0}}De.FALLOFF_DEFAULT=Be.FALLOFF_DEFAULT;De.FALLOFF_PHYSICAL=Be.FALLOFF_PHYSICAL;De.FALLOFF_GLTF=Be.FALLOFF_GLTF;De.FALLOFF_STANDARD=Be.FALLOFF_STANDARD;De.LIGHTMAP_DEFAULT=Be.LIGHTMAP_DEFAULT;De.LIGHTMAP_SPECULAR=Be.LIGHTMAP_SPECULAR;De.LIGHTMAP_SHADOWSONLY=Be.LIGHTMAP_SHADOWSONLY;De.INTENSITYMODE_AUTOMATIC=Be.INTENSITYMODE_AUTOMATIC;De.INTENSITYMODE_LUMINOUSPOWER=Be.INTENSITYMODE_LUMINOUSPOWER;De.INTENSITYMODE_LUMINOUSINTENSITY=Be.INTENSITYMODE_LUMINOUSINTENSITY;De.INTENSITYMODE_ILLUMINANCE=Be.INTENSITYMODE_ILLUMINANCE;De.INTENSITYMODE_LUMINANCE=Be.INTENSITYMODE_LUMINANCE;De.LIGHTTYPEID_POINTLIGHT=Be.LIGHTTYPEID_POINTLIGHT;De.LIGHTTYPEID_DIRECTIONALLIGHT=Be.LIGHTTYPEID_DIRECTIONALLIGHT;De.LIGHTTYPEID_SPOTLIGHT=Be.LIGHTTYPEID_SPOTLIGHT;De.LIGHTTYPEID_HEMISPHERICLIGHT=Be.LIGHTTYPEID_HEMISPHERICLIGHT;De.LIGHTTYPEID_RECT_AREALIGHT=Be.LIGHTTYPEID_RECT_AREALIGHT;M([ss()],De.prototype,"diffuse",void 0);M([ss()],De.prototype,"specular",void 0);M([C()],De.prototype,"falloffType",void 0);M([C()],De.prototype,"intensity",void 0);M([C()],De.prototype,"range",null);M([C()],De.prototype,"intensityMode",null);M([C()],De.prototype,"radius",null);M([C()],De.prototype,"_renderPriority",void 0);M([ze("_reorderLightsInScene")],De.prototype,"renderPriority",void 0);M([C("shadowEnabled")],De.prototype,"_shadowEnabled",void 0);M([C("excludeWithLayerMask")],De.prototype,"_excludeWithLayerMask",void 0);M([C("includeOnlyWithLayerMask")],De.prototype,"_includeOnlyWithLayerMask",void 0);M([C("lightmapMode")],De.prototype,"_lightmapMode",void 0);class gr extends De{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=D.Identity(),this._projectionMatrix=D.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return this.parent&&this.parent.getWorldMatrix?(this.transformedPosition||(this.transformedPosition=p.Zero()),p.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=p.Zero()),p.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0):!1}getDepthScale(){return 50}getShadowDirection(e){return this.transformedDirection?this.transformedDirection:this.direction}getAbsolutePosition(){return this.transformedPosition?this.transformedPosition:this.position}setDirectionToTarget(e){return this.direction=p.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=p.Cross(this.direction,Vi.Y),t=p.Cross(e,this.direction);return p.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=p.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=D.Identity()),D.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return this.shadowMinZ!==void 0?this.shadowMinZ:e?.minZ||0}getDepthMaxZ(e){return this.shadowMaxZ!==void 0?this.shadowMaxZ:e?.maxZ||1e4}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){const t=U.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),p.NormalizeToRef(this.getShadowDirection(e),t),Math.abs(p.Dot(t,p.Up()))===1&&(t.z=1e-13);const s=U.Vector3[1];return i.addToRef(t,s),D.LookAtLHToRef(i,s,p.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}M([Ut()],gr.prototype,"position",null);M([Ut()],gr.prototype,"direction",null);M([C()],gr.prototype,"shadowMinZ",null);M([C()],gr.prototype,"shadowMaxZ",null);lt.AddNodeConstructor("Light_Type_1",(o,e)=>()=>new ai(o,p.Zero(),e));class ai extends gr{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,i,s){super(e,i,s),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return De.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){const t=this.getScene().activeCamera;D.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,this.shadowMinZ!==void 0?this.shadowMinZ:t?t.minZ:0,this.shadowMaxZ!==void 0?this.shadowMaxZ:t?t.maxZ:1e4,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const c=p.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let u=Number.MAX_VALUE,f=-Number.MAX_VALUE;for(let d=0;d<i.length;d++){const _=i[d];if(!_)continue;const g=_.getBoundingInfo().boundingBox;for(let T=0;T<g.vectorsWorld.length;T++)p.TransformCoordinatesToRef(g.vectorsWorld[T],t,c),c.x<this._orthoLeft&&(this._orthoLeft=c.x),c.y<this._orthoBottom&&(this._orthoBottom=c.y),c.x>this._orthoRight&&(this._orthoRight=c.x),c.y>this._orthoTop&&(this._orthoTop=c.y),this.autoCalcShadowZBounds&&(c.z<u&&(u=c.z),c.z>f&&(f=c.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=u,this._shadowMaxZ=f)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,a=this.shadowMinZ!==void 0?this.shadowMinZ:s?.minZ||0,h=this.shadowMaxZ!==void 0?this.shadowMaxZ:s?.maxZ||1e4,l=this.getScene().getEngine().useReverseDepthBuffer;D.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,l?h:a,l?a:h,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}M([C()],ai.prototype,"shadowFrustumSize",null);M([C()],ai.prototype,"shadowOrthoScale",null);M([C()],ai.prototype,"autoUpdateExtends",void 0);M([C()],ai.prototype,"autoCalcShadowZBounds",void 0);M([C("orthoLeft")],ai.prototype,"_orthoLeft",void 0);M([C("orthoRight")],ai.prototype,"_orthoRight",void 0);M([C("orthoTop")],ai.prototype,"_orthoTop",void 0);M([C("orthoBottom")],ai.prototype,"_orthoBottom",void 0);Ye("BABYLON.DirectionalLight",ai);const vm=Object.freeze(Object.defineProperty({__proto__:null,DirectionalLight:ai},Symbol.toStringTag,{value:"Module"}));class de{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return this._depthScale!==void 0?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===de.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}else if(e===de.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}else if(e===de.FILTER_PCF||e===de.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===de.FILTER_PCF||e===de.FILTER_PCSS)&&!this._scene.getEngine()._features.supportShadowSamplers){this.usePoissonSampling=!0;return}this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get usePoissonSampling(){return this.filter===de.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(de.FILTER_POISSONSAMPLING);!e&&this.filter!==de.FILTER_POISSONSAMPLING||(this.filter=e?t:de.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===de.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(de.FILTER_EXPONENTIALSHADOWMAP);!e&&this.filter!==de.FILTER_EXPONENTIALSHADOWMAP||(this.filter=e?t:de.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===de.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(de.FILTER_BLUREXPONENTIALSHADOWMAP);!e&&this.filter!==de.FILTER_BLUREXPONENTIALSHADOWMAP||(this.filter=e?t:de.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===de.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(de.FILTER_CLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==de.FILTER_CLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:de.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===de.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(de.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==de.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:de.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===de.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(de.FILTER_PCF);!e&&this.filter!==de.FILTER_PCF||(this.filter=e?t:de.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===de.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(de.FILTER_PCSS);!e&&this.filter!==de.FILTER_PCSS||(this.filter=e?t:de.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return de.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),this._shadowMap.renderList.indexOf(e)===-1&&this._shadowMap.renderList.push(e),t)for(const i of e.getChildMeshes())this._shadowMap.renderList.indexOf(i)===-1&&this._shadowMap.renderList.push(i);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(i!==-1&&this._shadowMap.renderList.splice(i,1),t)for(const s of e.getChildren())this.removeShadowCaster(s);return this}getLight(){return this._light}get shaderLanguage(){return this._shaderLanguage}_getCamera(){return this._camera??this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}get light(){return this._light}set light(e){this._light!==e&&(this.dispose(!1),this._light=e,this._createInstance())}get useFloat32TextureType(){return this._usefullFloatFirst}set useFloat32TextureType(e){this._usefullFloatFirst!==e&&(this.dispose(!1),this._usefullFloatFirst=e,this._createInstance())}get camera(){return this._camera}set camera(e){this._camera!==e&&(this.dispose(!1),this._camera=e,this._createInstance())}get useRedTextureFormat(){return this._useRedTextureType}set useRedTextureFormat(e){this._useRedTextureType!==e&&(this.dispose(!1),this._useRedTextureType=e,this._createInstance())}constructor(e,t,i,s,r,n=!1){this.onBeforeShadowMapRenderObservable=new z,this.onAfterShadowMapRenderObservable=new z,this.onBeforeShadowMapRenderMeshObservable=new z,this.onAfterShadowMapRenderMeshObservable=new z,this.doNotSerialize=!1,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=de.FILTER_NONE,this._filteringQuality=de.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this._shaderLanguage=0,this.forceBackFacesOnly=!1,this._lightDirection=p.Zero(),this._viewMatrix=D.Zero(),this._projectionMatrix=D.Zero(),this._transformMatrix=D.Zero(),this._cachedPosition=new p(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new p(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=D.Identity(),this._shadersLoaded=!1,this._mapSize=e,this._light=t,this._usefullFloatFirst=!!i,this._scene=t.getScene(),this._camera=s??null,this._useRedTextureType=!!r,this._forceGLSL=n,this._createInstance()}_createInstance(){this._initShaderSourceAsync(this._forceGLSL);let e=this._light._shadowGenerators;e||(e=this._light._shadowGenerators=new Map),e.set(this._camera,this),this.id=this._light.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`,{forceMono:!0})]),de._SceneComponentInitialization(this._scene);const t=this._scene.getEngine().getCaps();this._usefullFloatFirst?t.textureFloatRender&&t.textureFloatLinearFiltering?this._textureType=1:t.textureHalfFloatRender&&t.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:t.textureHalfFloatRender&&t.textureHalfFloatLinearFiltering?this._textureType=2:t.textureFloatRender&&t.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();this._shadowMap?.dispose(),e._features.supportDepthStencilTexture?(this._shadowMap=new yt(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForShadowGenerator-${this._light.name}`)):this._shadowMap=new yt(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),this._shadowMap===null)return;this._shadowMap.wrapU=G.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=G.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(G.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(s,r,n,a)=>this._renderForShadowMap(s,r,n,a),this._shadowMap.customIsReadyFunction=(s,r,n)=>{if(!n||!s.subMeshes)return!0;let a=!0;for(const h of s.subMeshes){const l=h.getRenderingMesh(),u=this._scene.getEngine(),f=h.getMaterial();if(!f||h.verticesCount===0||this.customAllowRendering&&!this.customAllowRendering(h))continue;const d=l._getInstancesRenderList(h._id,!!h.getReplacementMesh());if(d.mustReturn)continue;const _=u.getCaps().instancedArrays&&(d.visibleInstances[h._id]!==null&&d.visibleInstances[h._id]!==void 0||l.hasThinInstances),m=f.needAlphaBlendingForMesh(l);a=this.isReady(h,_,m)&&a}return a};const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add(()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._enableGPUDebugMarkers&&e._debugPushGroup?.(`Shadow map generation for pass id ${e.currentRenderPassId}`)}),this._shadowMap.onBeforeRenderObservable.add(s=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=s,this._filter===de.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),zi.eyeAtCamera=!1,this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._sceneUBOs&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onAfterUnbindObservable.add(()=>{if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),zi.eyeAtCamera=!0,this._scene.updateTransformMatrix(),this._filter===de.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){e._debugPopGroup?.();return}const s=this.getShadowMapForRendering();s&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,s.renderTarget,!0),e.unBindFramebuffer(s.renderTarget,!0)),e._enableGPUDebugMarkers&&e._debugPopGroup?.()});const t=new Ce(0,0,0,0),i=new Ce(1,1,1,1);this._shadowMap.onClearObservable.add(s=>{this._filter===de.FILTER_PCF?s.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?s.clear(t,!0,!0,!1):s.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(s=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=s.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let s=pt.MIN_RENDERINGGROUPS;s<pt.MAX_RENDERINGGROUPS;s++)this._shadowMap.setRenderingAutoClearDepthStencil(s,!1)}async _initShaderSourceAsync(e=!1){this._scene.getEngine().isWebGPU&&!e&&!de.ForceGLSL?(this._shaderLanguage=1,await Promise.all([he(()=>import("./shadowMap.fragment-BEwhnKOg.js").then(i=>i.c),__vite__mapDeps([12,9]),import.meta.url),he(()=>import("./shadowMap.vertex-ImOoSjTb.js").then(i=>i.c),__vite__mapDeps([13,5,6,14]),import.meta.url),he(()=>import("./depthBoxBlur.fragment-BtTv8wid.js"),[],import.meta.url),he(()=>import("./shadowMapFragmentSoftTransparentShadow-BmxybqRD.js"),[],import.meta.url)])):await Promise.all([he(()=>import("./shadowMap.fragment-CVar4C4N.js").then(i=>i.c),[],import.meta.url),he(()=>import("./shadowMap.vertex-Q2d15P5z.js").then(i=>i.c),__vite__mapDeps([15,16]),import.meta.url),he(()=>import("./depthBoxBlur.fragment-DViDG6Vb.js"),[],import.meta.url),he(()=>import("./shadowMapFragmentSoftTransparentShadow-D6ZvWsNy.js"),[],import.meta.url)]),this._shadersLoaded=!0}_initializeBlurRTTAndPostProcesses(){const e=this._scene.getEngine(),t=this._mapSize/this.blurScale;(!this.useKernelBlur||this.blurScale!==1)&&(this._shadowMap2=new yt(this._light.name+"_shadowMap2",t,this._scene,!1,!0,this._textureType,void 0,void 0,!1),this._shadowMap2.wrapU=G.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=G.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(G.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new Ct(this._light.name+"KernelBlurX",new ie(1,0),this.blurKernel,1,null,G.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.width=t,this._kernelBlurXPostprocess.height=t,this._kernelBlurXPostprocess.externalTextureSamplerBinding=!0,this._kernelBlurXPostprocess.onApplyObservable.add(i=>{i.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new Ct(this._light.name+"KernelBlurY",new ie(0,1),this.blurKernel,1,null,G.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===0&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new Ne(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,G.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType,void 0,void 0,void 0,void 0,this._shaderLanguage),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",t,t),i.setTexture("textureSampler",this._shadowMap)}),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,s){let r;if(s.length)for(r=0;r<s.length;r++)this._renderSubMeshForShadowMap(s.data[r]);for(r=0;r<e.length;r++)this._renderSubMeshForShadowMap(e.data[r]);for(r=0;r<t.length;r++)this._renderSubMeshForShadowMap(t.data[r]);if(this._transparencyShadow)for(r=0;r<i.length;r++)this._renderSubMeshForShadowMap(i.data[r],!0);else for(r=0;r<i.length;r++)i.data[r].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1}_bindCustomEffectForRenderSubMeshForShadowMap(e,t,i){t.setMatrix("viewProjection",this.getTransformMatrix())}_renderSubMeshForShadowMap(e,t=!1){const i=e.getRenderingMesh(),s=e.getEffectiveMesh(),r=this._scene,n=r.getEngine(),a=e.getMaterial();if(s._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!a||e.verticesCount===0||e._renderId===r.getRenderId())return;const h=r.useRightHandedSystem,l=s._getWorldMatrixDeterminant()<0;let c=a._getEffectiveOrientation(i);(l&&!h||!l&&h)&&(c=c===0?1:0);const u=c===0;n.setState(a.backFaceCulling,void 0,void 0,u,a.cullBackFaces);const f=i._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(f.mustReturn)return;const d=n.getCaps().instancedArrays&&(f.visibleInstances[e._id]!==null&&f.visibleInstances[e._id]!==void 0||i.hasThinInstances);if(!(this.customAllowRendering&&!this.customAllowRendering(e)))if(this.isReady(e,d,t)){e._renderId=r.getRenderId();const _=a.shadowDepthWrapper,m=_?.getEffect(e,this,n.currentRenderPassId)??e._getDrawWrapper(),g=ys.GetEffect(m);n.enableEffect(m),d||i._bind(e,g,a.fillMode),this.getTransformMatrix(),g.setFloat3("biasAndScaleSM",this.bias,this.normalBias,this.depthScale),this.getLight().getTypeID()===De.LIGHTTYPEID_DIRECTIONALLIGHT?g.setVector3("lightDataSM",this._cachedDirection):g.setVector3("lightDataSM",this._cachedPosition.subtractToRef(this._scene.floatingOriginOffset,U.Vector3[0]));const T=this._getCamera();if(g.setFloat2("depthValuesSM",this.getLight().getDepthMinZ(T),this.getLight().getDepthMinZ(T)+this.getLight().getDepthMaxZ(T)),t&&this.enableSoftTransparentShadow&&g.setFloat2("softTransparentShadowSM",s.visibility*a.alpha,this._opacityTexture?.getAlphaFromRGB?1:0),_)e._setMainDrawWrapperOverride(m),_.standalone?_.baseMaterial.bindForSubMesh(s.getWorldMatrix(),i,e):a.bindForSubMesh(s.getWorldMatrix(),i,e),e._setMainDrawWrapperOverride(null);else{this._opacityTexture&&(g.setTexture("diffuseSampler",this._opacityTexture),g.setMatrix("diffuseMatrix",this._opacityTexture.getTextureMatrix()||this._defaultTextureMatrix)),vs(i,g),Is(i,g),i.morphTargetManager&&i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(g);const A=e.getMesh().bakedVertexAnimationManager;A&&A.isEnabled&&A.bind(g,d),Ms(g,a,r)}!this._useUBO&&!_&&this._bindCustomEffectForRenderSubMeshForShadowMap(e,g,s),so(g,this._scene.getSceneUniformBuffer()),this._scene.getSceneUniformBuffer().bindUniformBuffer();const R=s.getWorldMatrix();d&&(s.getMeshUniformBuffer().bindToEffect(g,"Mesh"),s.transferToEffect(R)),this.forceBackFacesOnly&&n.setState(!0,0,!1,!0,a.cullBackFaces),this.onBeforeShadowMapRenderMeshObservable.notifyObservers(i),this.onBeforeShadowMapRenderObservable.notifyObservers(g),i._processRendering(s,e,g,a.fillMode,f,d,(A,y)=>{s!==i&&!A?(i.getMeshUniformBuffer().bindToEffect(g,"Mesh"),i.transferToEffect(y)):(s.getMeshUniformBuffer().bindToEffect(g,"Mesh"),s.transferToEffect(A?y:R))}),this.forceBackFacesOnly&&n.setState(!0,0,!1,!1,a.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(g),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===de.FILTER_NONE||this.filter===de.FILTER_PCSS?this._shadowMap.updateSamplingMode(G.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(G.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},s=this.getShadowMap();if(!s){e&&e(this);return}const r=s.renderList;if(!r){e&&e(this);return}const n=[];for(const l of r)n.push(...l.subMeshes);if(n.length===0){e&&e(this);return}let a=0;const h=()=>{if(!(!this._scene||!this._scene.getEngine())){for(;this.isReady(n[a],i.useInstances,n[a].getMaterial()?.needAlphaBlendingForMesh(n[a].getMesh())??!1);)if(a++,a>=n.length){e&&e(this);return}setTimeout(h,16)}};h()}async forceCompilationAsync(e){return await new Promise(t=>{this.forceCompilation(()=>{t()},e)})}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,s){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(this._textureType!==0?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const r=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&r.isVerticesDataPresent(S.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===De.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&s?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){if(!this._shadersLoaded)return!1;const s=e.getMaterial(),r=s?.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;const n=[];if(this._prepareShadowDefines(e,t,n,i),r){if(!r.isReadyForSubMesh(e,n,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const a=e._getDrawWrapper(void 0,!0);let h=a.effect,l=a.defines;const c=[S.PositionKind],u=e.getMesh();let f=!1,d=!1,_=!1;const m=!1;this.normalBias&&u.isVerticesDataPresent(S.NormalKind)&&(c.push(S.NormalKind),n.push("#define NORMAL"),f=!0,u.nonUniformScaling&&n.push("#define NONUNIFORMSCALING"));const g=s.needAlphaTestingForMesh(u);if((g||s.needAlphaBlendingForMesh(u))&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const E=s.alphaCutOff??de.DEFAULT_ALPHA_CUTOFF;n.push("#define ALPHATEXTURE"),g&&n.push(`#define ALPHATESTVALUE ${E}${E%1===0?".":""}`),u.isVerticesDataPresent(S.UVKind)&&(c.push(S.UVKind),n.push("#define UV1"),d=!0),u.isVerticesDataPresent(S.UV2Kind)&&this._opacityTexture.coordinatesIndex===1&&(c.push(S.UV2Kind),n.push("#define UV2"),_=!0)}const T=new Cs;if(u.useBones&&u.computeBonesUsingShaders&&u.skeleton){c.push(S.MatricesIndicesKind),c.push(S.MatricesWeightsKind),u.numBoneInfluencers>4&&(c.push(S.MatricesIndicesExtraKind),c.push(S.MatricesWeightsExtraKind));const E=u.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+u.numBoneInfluencers),u.numBoneInfluencers>0&&T.addCPUSkinningFallback(0,u),E.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(E.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");const R=u.morphTargetManager?_r(u.morphTargetManager,n,c,u,!0,f,!1,d,_,m):0;if(dr(s,this._scene,n),t&&(n.push("#define INSTANCES"),Ps(c),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const E of this.customShaderOptions.defines)n.indexOf(E)===-1&&n.push(E);const A=u.bakedVertexAnimationManager;A&&A.isEnabled&&(n.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&c.push("bakedVertexAnimationSettingsInstanced"));const y=n.join(`
|
|
1249
|
+
`);if(l!==y){l=y;let E="shadowMap";const x=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],b=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],P=["Scene","Mesh"];if(As(x),this.customShaderOptions){if(E=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const O of this.customShaderOptions.attributes)c.indexOf(O)===-1&&c.push(O);if(this.customShaderOptions.uniforms)for(const O of this.customShaderOptions.uniforms)x.indexOf(O)===-1&&x.push(O);if(this.customShaderOptions.samplers)for(const O of this.customShaderOptions.samplers)b.indexOf(O)===-1&&b.push(O)}const v=this._scene.getEngine();h=v.createEffect(E,{attributes:c,uniformsNames:x,uniformBuffersNames:P,samplers:b,defines:y,fallbacks:T,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:R},shaderLanguage:this._shaderLanguage},v),a.setEffect(h,l)}if(!h.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(!this._blurPostProcesses||!this._blurPostProcesses.length)&&this._initializeBlurRTTAndPostProcesses(),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){const i=this._scene,s=this._light;!i.shadowsEnabled||!s.shadowEnabled||(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===de.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===de.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===de.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===de.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),s.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light,s=this._scene;if(!s.shadowsEnabled||!i.shadowEnabled)return;const r=this._getCamera(),n=this.getShadowMap();if(!n)return;if(!i.needCube()){const h=s.floatingOriginOffset,l=this.getTransformMatrix(),c=s.floatingOriginMode?yl(h,this._viewMatrix,this._projectionMatrix,U.Matrix[0]):l;t.setMatrix("lightMatrix"+e,c)}const a=this.getShadowMapForRendering();this._filter===de.FILTER_PCF?(t.setDepthStencilTexture("shadowTexture"+e,a),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n.getSize().width,1/n.getSize().width,this.frustumEdgeFalloff,e)):this._filter===de.FILTER_PCSS?(t.setDepthStencilTexture("shadowTexture"+e,a),t.setTexture("depthTexture"+e,a),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/n.getSize().width,this._contactHardeningLightSizeUVRatio*n.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowTexture"+e,a),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/n.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(r),this.getLight().getDepthMinZ(r)+this.getLight().getDepthMaxZ(r),e)}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){const e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),p.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),Math.abs(p.Dot(this._lightDirection,p.Up()))===1&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),D.LookAtLHToRef(t,t.add(this._lightDirection),p.Up(),this._viewMatrix);const i=this.getShadowMap();if(i){const s=i.renderList;s&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,s)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){const e=this._shadowMap;if(!e)return;const t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(const i of t)this._shadowMap.renderList.push(i)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(e=!0){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){const t=this._light._shadowGenerators.entries();for(let i=t.next();i.done!==!0;i=t.next()){const[s,r]=i.value;r===this&&this._light._shadowGenerators.delete(s)}this._light._shadowGenerators.size===0&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}e&&(this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear())}serialize(){const e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=this._camera?.id,e.id=this.id,e.mapSize=t.getRenderSize(),e.forceBackFacesOnly=this.forceBackFacesOnly,e.darkness=this.getDarkness(),e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.filteringQuality=this.filteringQuality,e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.depthScale=this.depthScale,e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.renderList=[],t.renderList)for(let i=0;i<t.renderList.length;i++){const s=t.renderList[i];e.renderList.push(s.id)}return e}static Parse(e,t,i){const s=t.getLightById(e.lightId),r=e.cameraId!==void 0?t.getCameraById(e.cameraId):null,n=i?i(e.mapSize,s,r):new de(e.mapSize,s,void 0,r),a=n.getShadowMap();if(e.renderList.length&&a){const h=new Set(e.renderList);let l=a.renderList;l||(l=a.renderList=[]);const c=t.meshes;for(const u of c)h.has(u.id)&&l.push(u)}return e.id!==void 0&&(n.id=e.id),n.forceBackFacesOnly=!!e.forceBackFacesOnly,e.darkness!==void 0&&n.setDarkness(e.darkness),e.transparencyShadow&&n.setTransparencyShadow(!0),e.frustumEdgeFalloff!==void 0&&(n.frustumEdgeFalloff=e.frustumEdgeFalloff),e.bias!==void 0&&(n.bias=e.bias),e.normalBias!==void 0&&(n.normalBias=e.normalBias),e.usePercentageCloserFiltering?n.usePercentageCloserFiltering=!0:e.useContactHardeningShadow?n.useContactHardeningShadow=!0:e.usePoissonSampling?n.usePoissonSampling=!0:e.useExponentialShadowMap?n.useExponentialShadowMap=!0:e.useBlurExponentialShadowMap?n.useBlurExponentialShadowMap=!0:e.useCloseExponentialShadowMap?n.useCloseExponentialShadowMap=!0:e.useBlurCloseExponentialShadowMap?n.useBlurCloseExponentialShadowMap=!0:e.useVarianceShadowMap?n.useExponentialShadowMap=!0:e.useBlurVarianceShadowMap&&(n.useBlurExponentialShadowMap=!0),e.contactHardeningLightSizeUVRatio!==void 0&&(n.contactHardeningLightSizeUVRatio=e.contactHardeningLightSizeUVRatio),e.filteringQuality!==void 0&&(n.filteringQuality=e.filteringQuality),e.depthScale&&(n.depthScale=e.depthScale),e.blurScale&&(n.blurScale=e.blurScale),e.blurBoxOffset&&(n.blurBoxOffset=e.blurBoxOffset),e.useKernelBlur&&(n.useKernelBlur=e.useKernelBlur),e.blurKernel&&(n.blurKernel=e.blurKernel),n}}de.CLASSNAME="ShadowGenerator";de.ForceGLSL=!1;de.FILTER_NONE=0;de.FILTER_EXPONENTIALSHADOWMAP=1;de.FILTER_POISSONSAMPLING=2;de.FILTER_BLUREXPONENTIALSHADOWMAP=3;de.FILTER_CLOSEEXPONENTIALSHADOWMAP=4;de.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP=5;de.FILTER_PCF=6;de.FILTER_PCSS=7;de.QUALITY_HIGH=0;de.QUALITY_MEDIUM=1;de.QUALITY_LOW=2;de.DEFAULT_ALPHA_CUTOFF=.5;de._SceneComponentInitialization=o=>{throw pe("ShadowGeneratorSceneComponent")};lt.AddNodeConstructor("TargetCamera",(o,e)=>()=>new ut(o,p.Zero(),e));const yr=D.Zero(),yn=re.Identity();class ut extends be{constructor(e,t,i,s=!0){super(e,t,i,s),this.cameraDirection=new p(0,0,0),this.cameraRotation=new ie(0,0),this.updateUpVectorFromRotation=!1,this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this._panningEpsilon=Ke,this._rotationEpsilon=Ke,this.lockedTarget=null,this._currentTarget=p.Zero(),this._initialFocalDistance=1,this._viewMatrix=D.Zero(),this._cameraTransformMatrix=D.Zero(),this._cameraRotationMatrix=D.Zero(),this._transformedReferencePoint=p.Zero(),this._deferredPositionUpdate=new p,this._deferredRotationQuaternionUpdate=new re,this._deferredRotationUpdate=new p,this._deferredUpdated=!1,this._deferOnly=!1,this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0,this._referencePoint=p.Forward(this.getScene().useRightHandedSystem),this.rotation=new p(0,this.getScene().useRightHandedSystem?Math.PI:0,0)}getFrontPosition(e){this.getWorldMatrix();const t=U.Vector3[0],i=U.Vector3[1];return i.set(0,0,this._scene.useRightHandedSystem?-1:1),this.getDirectionToRef(i,t),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){const e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return super._restoreStateValues()?(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&this._storedRotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0):!1}_initCache(){super._initCache(),this._cache.lockedTarget=new p(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new p(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new re(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();const t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;const e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){const e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(e.getFps()*100))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=Ke),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),this.getScene().useRightHandedSystem?D.LookAtRHToRef(this.position,e,p.UpReadOnly,yr):D.LookAtLHToRef(this.position,e,p.UpReadOnly,yr),yr.invert();const t=this.rotationQuaternion||yn;re.FromRotationMatrixToRef(yr,t),t.toEulerAnglesToRef(this.rotation),this.rotation.z=0}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent){this.parent.getWorldMatrix().invertToRef(U.Matrix[0]),p.TransformNormalToRef(this.cameraDirection,U.Matrix[0],U.Vector3[0]),this._deferredPositionUpdate.addInPlace(U.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,this.noRotationConstraint||(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(re.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)));const s=this.speed*this._panningEpsilon,r=this.speed*this._rotationEpsilon;t&&(Math.abs(this.cameraDirection.x)<s&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<s&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<s&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),i&&(Math.abs(this.cameraRotation.x)<r&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<r&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),super._checkInputs()}_updateCameraRotationMatrix(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):D.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)}_rotateUpVectorWithCameraRotationMatrix(){return p.TransformNormalToRef(p.UpReadOnly,this._cameraRotationMatrix,this.upVector),this}_getViewMatrix(){return this.lockedTarget&&this.setTarget(this._getLockedTargetPosition()),this._updateCameraRotationMatrix(),this.rotationQuaternion&&this._cachedQuaternionRotationZ!=this.rotationQuaternion.z?(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedQuaternionRotationZ=this.rotationQuaternion.z):this._cachedRotationZ!==this.rotation.z&&(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedRotationZ=this.rotation.z),p.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?Vi.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(re.FromEulerVectorToRef(this.rotation,yn),Vi.Y.rotateByQuaternionToRef(yn,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix}_computeViewMatrix(e,t,i){if(this.getScene().useRightHandedSystem?D.LookAtRHToRef(e,t,i,this._viewMatrix):D.LookAtLHToRef(e,t,i,this._viewMatrix),this.parent){const s=this.parent.getWorldMatrix();this._viewMatrix.invert(),this._viewMatrix.multiplyToRef(s,this._viewMatrix),this._viewMatrix.invert(),this._markSyncedWithParent()}}createRigCamera(e,t){if(this.cameraRigMode!==be.RIG_MODE_NONE){const i=new ut(e,this.position.clone(),this.getScene());return i.isRigCamera=!0,i.rigParent=this,this.cameraRigMode===be.RIG_MODE_VR&&(this.rotationQuaternion||(this.rotationQuaternion=new re),i._cameraRigParams={},i.rotationQuaternion=new re),i.mode=this.mode,i.orthoLeft=this.orthoLeft,i.orthoRight=this.orthoRight,i.orthoTop=this.orthoTop,i.orthoBottom=this.orthoBottom,i}return null}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case be.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case be.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case be.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case be.RIG_MODE_STEREOSCOPIC_OVERUNDER:case be.RIG_MODE_STEREOSCOPIC_INTERLACED:{const i=this.cameraRigMode===be.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,s=this.cameraRigMode===be.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*i,e),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*s,t);break}case be.RIG_MODE_VR:e.rotationQuaternion&&t.rotationQuaternion&&this.rotationQuaternion?(e.rotationQuaternion.copyFrom(this.rotationQuaternion),t.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.rotation.copyFrom(this.rotation),t.rotation.copyFrom(this.rotation)),e.position.copyFrom(this.position),t.position.copyFrom(this.position);break}super._updateRigCameras()}_getRigCamPositionAndTarget(e,t){this.getTarget().subtractToRef(this.position,ut._TargetFocalPoint),ut._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);const s=ut._TargetFocalPoint.addInPlace(this.position);D.TranslationToRef(-s.x,-s.y,-s.z,ut._TargetTransformMatrix),ut._TargetTransformMatrix.multiplyToRef(D.RotationAxis(t.upVector,e),ut._RigCamTransformMatrix),D.TranslationToRef(s.x,s.y,s.z,ut._TargetTransformMatrix),ut._RigCamTransformMatrix.multiplyToRef(ut._TargetTransformMatrix,ut._RigCamTransformMatrix),p.TransformCoordinatesToRef(this.position,ut._RigCamTransformMatrix,t.position),t.setTarget(s)}getClassName(){return"TargetCamera"}}ut._RigCamTransformMatrix=new D;ut._TargetTransformMatrix=new D;ut._TargetFocalPoint=new p;M([C()],ut.prototype,"updateUpVectorFromRotation",void 0);M([Ut()],ut.prototype,"rotation",void 0);M([C()],ut.prototype,"speed",void 0);M([fu("lockedTargetId")],ut.prototype,"lockedTarget",void 0);var bs={};class Fg{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();if(this.attached[t]){W.Warn("camera input of type "+t+" already exists on camera");return}this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault)}remove(e){for(const t in this.attached){const i=this.attached[t];if(i===e){i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck();return}}}removeByType(e){for(const t in this.attached){const i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){const t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=be.ForceAttachControlToAlwaysPreventDefault?!1:e,this.attachedToElement=!0,this.noPreventDefault=e;for(const t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(const t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(const e in this.attached){const t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){const t={};for(const i in this.attached){const s=this.attached[i],r=me.Serialize(s);t[s.getClassName()]=r}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const i in t){const s=bs[i];if(s){const r=t[i],n=me.Parse(()=>new s,r,null);this.add(n)}}}else for(const i in this.attached){const s=bs[this.attached[i].getClassName()];if(s){const r=me.Parse(()=>new s,e,null);this.remove(this.attached[i]),this.add(r)}}}}class Vt{constructor(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}attachControl(e){e=fe.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{const i=t.event;if(!i.metaKey){if(t.type===$s.KEYDOWN)(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysUpward.indexOf(i.keyCode)!==-1||this.keysDownward.indexOf(i.keyCode)!==-1||this.keysRotateLeft.indexOf(i.keyCode)!==-1||this.keysRotateRight.indexOf(i.keyCode)!==-1||this.keysRotateUp.indexOf(i.keyCode)!==-1||this.keysRotateDown.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),e||i.preventDefault());else if(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysUpward.indexOf(i.keyCode)!==-1||this.keysDownward.indexOf(i.keyCode)!==-1||this.keysRotateLeft.indexOf(i.keyCode)!==-1||this.keysRotateRight.indexOf(i.keyCode)!==-1||this.keysRotateUp.indexOf(i.keyCode)!==-1||this.keysRotateDown.indexOf(i.keyCode)!==-1){const s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,1),e||i.preventDefault()}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t<this._keys.length;t++){const i=this._keys[t],s=e._computeLocalCameraSpeed();this.keysLeft.indexOf(i)!==-1?e._localDirection.copyFromFloats(-s,0,0):this.keysUp.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,0,s):this.keysRight.indexOf(i)!==-1?e._localDirection.copyFromFloats(s,0,0):this.keysDown.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,0,-s):this.keysUpward.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,s,0):this.keysDownward.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,-s,0):this.keysRotateLeft.indexOf(i)!==-1?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y-=this._getLocalRotation()):this.keysRotateRight.indexOf(i)!==-1?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y+=this._getLocalRotation()):this.keysRotateUp.indexOf(i)!==-1?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x-=this._getLocalRotation()):this.keysRotateDown.indexOf(i)!==-1&&(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x+=this._getLocalRotation()),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),p.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}}}getClassName(){return"FreeCameraKeyboardMoveInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}_getLocalRotation(){const e=this.camera._calculateHandednessMultiplier();return this.rotationSpeed*this._engine.getDeltaTime()/1e3*e}}M([C()],Vt.prototype,"keysUp",void 0);M([C()],Vt.prototype,"keysUpward",void 0);M([C()],Vt.prototype,"keysDown",void 0);M([C()],Vt.prototype,"keysDownward",void 0);M([C()],Vt.prototype,"keysLeft",void 0);M([C()],Vt.prototype,"keysRight",void 0);M([C()],Vt.prototype,"rotationSpeed",void 0);M([C()],Vt.prototype,"keysRotateLeft",void 0);M([C()],Vt.prototype,"keysRotateRight",void 0);M([C()],Vt.prototype,"keysRotateUp",void 0);M([C()],Vt.prototype,"keysRotateDown",void 0);bs.FreeCameraKeyboardMoveInput=Vt;class nn{constructor(e=!0){this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3,this._previousPosition=null,this.onPointerMovedObservable=new z,this._allowCameraRotation=!0,this._currentActiveButton=-1,this._activePointerId=-1}attachControl(e){e=fe.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();this._pointerInput||(this._pointerInput=s=>{const r=s.event,n=r.pointerType==="touch";if(!this.touchEnabled&&n||s.type!==ve.POINTERMOVE&&this.buttons.indexOf(r.button)===-1)return;const a=r.target;if(s.type===ve.POINTERDOWN){if(n&&this._activePointerId!==-1||!n&&this._currentActiveButton!==-1)return;this._activePointerId=r.pointerId;try{a?.setPointerCapture(r.pointerId)}catch{}this._currentActiveButton===-1&&(this._currentActiveButton=r.button),this._previousPosition={x:r.clientX,y:r.clientY},e||(r.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(s.event)}else if(s.type===ve.POINTERUP){if(n&&this._activePointerId!==r.pointerId||!n&&this._currentActiveButton!==r.button)return;try{a?.releasePointerCapture(r.pointerId)}catch{}this._currentActiveButton=-1,this._previousPosition=null,e||r.preventDefault(),this._activePointerId=-1}else if(s.type===ve.POINTERMOVE&&(this._activePointerId===r.pointerId||!n)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(s.event);else if(this._previousPosition){const h=this.camera._calculateHandednessMultiplier(),l=(r.clientX-this._previousPosition.x)*h,c=(r.clientY-this._previousPosition.y)*h;this._allowCameraRotation&&(this.camera.cameraRotation.y+=l/this.angularSensibility,this.camera.cameraRotation.x+=c/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:l,offsetY:c}),this._previousPosition={x:r.clientX,y:r.clientY},e||r.preventDefault()}}}),this._onMouseMove=s=>{if(!t.isPointerLock)return;const r=this.camera._calculateHandednessMultiplier();this.camera.cameraRotation.y+=s.movementX*r/this.angularSensibility,this.camera.cameraRotation.x+=s.movementY*r/this.angularSensibility,this._previousPosition=null,e||s.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,ve.POINTERDOWN|ve.POINTERUP|ve.POINTERMOVE),i&&(this._contextMenuBind=s=>this.onContextMenu(s),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){const t=this.camera.getEngine().getInputElement();t&&t.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}M([C()],nn.prototype,"buttons",void 0);M([C()],nn.prototype,"angularSensibility",void 0);bs.FreeCameraMouseInput=nn;class an{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new z,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=fe.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==ve.POINTERWHEEL)return;const i=t.event,s=i.deltaMode===hr.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*s*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*s*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*s*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,ve.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}M([C()],an.prototype,"wheelPrecisionX",void 0);M([C()],an.prototype,"wheelPrecisionY",void 0);M([C()],an.prototype,"wheelPrecisionZ",void 0);var He;(function(o){o[o.MoveRelative=0]="MoveRelative",o[o.RotateRelative=1]="RotateRelative",o[o.MoveScene=2]="MoveScene"})(He||(He={}));class oi extends an{constructor(){super(...arguments),this._moveRelative=p.Zero(),this._rotateRelative=p.Zero(),this._moveScene=p.Zero(),this._wheelXAction=He.MoveRelative,this._wheelXActionCoordinate=0,this._wheelYAction=He.MoveRelative,this._wheelYActionCoordinate=2,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){e===null&&this._wheelXAction!==He.MoveRelative||(this._wheelXAction=He.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==He.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){e===null&&this._wheelYAction!==He.MoveRelative||(this._wheelYAction=He.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==He.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){e===null&&this._wheelZAction!==He.MoveRelative||(this._wheelZAction=He.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==He.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){e===null&&this._wheelXAction!==He.RotateRelative||(this._wheelXAction=He.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==He.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){e===null&&this._wheelYAction!==He.RotateRelative||(this._wheelYAction=He.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==He.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){e===null&&this._wheelZAction!==He.RotateRelative||(this._wheelZAction=He.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==He.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){e===null&&this._wheelXAction!==He.MoveScene||(this._wheelXAction=He.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==He.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){e===null&&this._wheelYAction!==He.MoveScene||(this._wheelYAction=He.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==He.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){e===null&&this._wheelZAction!==He.MoveScene||(this._wheelZAction=He.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==He.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(this._wheelDeltaX===0&&this._wheelDeltaY===0&&this._wheelDeltaZ==0)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);const e=D.Zero();this.camera.getViewMatrix().invertToRef(e);const t=p.Zero();p.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,i){if(e===0||t===null||i===null)return;let s=null;switch(t){case He.MoveRelative:s=this._moveRelative;break;case He.RotateRelative:s=this._rotateRelative;break;case He.MoveScene:s=this._moveScene;break}switch(i){case 0:s.set(e,0,0);break;case 1:s.set(0,e,0);break;case 2:s.set(0,0,e);break}}}M([C()],oi.prototype,"wheelXMoveRelative",null);M([C()],oi.prototype,"wheelYMoveRelative",null);M([C()],oi.prototype,"wheelZMoveRelative",null);M([C()],oi.prototype,"wheelXRotateRelative",null);M([C()],oi.prototype,"wheelYRotateRelative",null);M([C()],oi.prototype,"wheelZRotateRelative",null);M([C()],oi.prototype,"wheelXMoveScene",null);M([C()],oi.prototype,"wheelYMoveScene",null);M([C()],oi.prototype,"wheelZMoveScene",null);bs.FreeCameraMouseWheelInput=oi;class on{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=fe.IsSafari()}attachControl(e){e=fe.BackCompatCameraNoPreventDefault(arguments);let t=null;if(this._pointerInput===void 0&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const s=i.event,r=s.pointerType==="mouse"||this._isSafari&&typeof s.pointerType>"u";if(!(!this.allowMouse&&r)){if(i.type===ve.POINTERDOWN){if(e||s.preventDefault(),this._pointerPressed.push(s.pointerId),this._pointerPressed.length!==1)return;t={x:s.clientX,y:s.clientY}}else if(i.type===ve.POINTERUP){e||s.preventDefault();const n=this._pointerPressed.indexOf(s.pointerId);if(n===-1||(this._pointerPressed.splice(n,1),n!=0))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===ve.POINTERMOVE){if(e||s.preventDefault(),!t||this._pointerPressed.indexOf(s.pointerId)!=0)return;this._offsetX=s.clientX-t.x,this._offsetY=-(s.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,ve.POINTERDOWN|ve.POINTERUP|ve.POINTERMOVE),this._onLostFocus){const s=this.camera.getEngine().getInputElement();s&&s.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){const t=this.camera.getEngine().getInputElement();t&&t.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(this._offsetX===null||this._offsetY===null||this._offsetX===0&&this._offsetY===0)return;const e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=this._offsetX*t/this.touchAngularSensibility,this.singleFingerRotate&&this._pointerPressed.length===1||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-(this._offsetY*t)/this.touchAngularSensibility;else{const s=e._computeLocalCameraSpeed(),r=new p(0,0,this.touchMoveSensibility!==0?s*this._offsetY/this.touchMoveSensibility:0);D.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(p.TransformCoordinates(r,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}M([C()],on.prototype,"touchAngularSensibility",void 0);M([C()],on.prototype,"touchMoveSensibility",void 0);bs.FreeCameraTouchInput=on;class wg extends Fg{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new Vt),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new nn(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new oi,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new on),this}clear(){super.clear(),this._mouseInput=null}}class pr extends ut{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysUpward(){const e=this.inputs.attached.keyboard;return e?e.keysUpward:[]}set keysUpward(e){const t=this.inputs.attached.keyboard;t&&(t.keysUpward=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysDownward(){const e=this.inputs.attached.keyboard;return e?e.keysDownward:[]}set keysDownward(e){const t=this.inputs.attached.keyboard;t&&(t.keysDownward=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get keysRotateLeft(){const e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]}set keysRotateLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateLeft=e)}get keysRotateRight(){const e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]}set keysRotateRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateRight=e)}get keysRotateUp(){const e=this.inputs.attached.keyboard;return e?e.keysRotateUp:[]}set keysRotateUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateUp=e)}get keysRotateDown(){const e=this.inputs.attached.keyboard;return e?e.keysRotateDown:[]}set keysRotateDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateDown=e)}constructor(e,t,i,s=!0){super(e,t,i,s),this.ellipsoid=new p(.5,1,.5),this.ellipsoidOffset=new p(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=p.Zero(),this._diffPosition=p.Zero(),this._newPosition=p.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(r,n,a=null)=>{this._newPosition.copyFrom(n),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>J.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&a&&this.onCollide(a))},this.inputs=new wg(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=fe.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new p(0,0,0),this.cameraRotation=new ie(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=p.TransformCoordinates(this.position,this.parent.getWorldMatrix()):t=this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=p.Zero(),this._transformedDirection=p.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}}M([Ut()],pr.prototype,"ellipsoid",void 0);M([Ut()],pr.prototype,"ellipsoidOffset",void 0);M([C()],pr.prototype,"checkCollisions",void 0);M([C()],pr.prototype,"applyGravity",void 0);Ye("BABYLON.FreeCamera",pr);function Ia(o,e,t){try{const i=o.next();i.done?e(i):i.value?i.value.then(()=>{i.value=void 0,e(i)},t):e(i)}catch(i){t(i)}}function Lg(o=25){let e;return(t,i,s)=>{const r=performance.now();e===void 0||r-e>o?(e=r,setTimeout(()=>{Ia(t,i,s)},0)):Ia(t,i,s)}}function wc(o,e,t,i,s){const r=()=>{let n;const a=h=>{h.done?t(h.value):n===void 0?n=!0:r()};do n=void 0,!s||!s.aborted?e(o,a,i):i(new Error("Aborted")),n===void 0&&(n=!1);while(n)};r()}function ao(o,e){let t;return wc(o,Ia,i=>t=i,i=>{throw i},e),t}async function Lc(o,e,t){return await new Promise((i,s)=>{wc(o,e,i,s,t)})}function Bg(o,e){return(...t)=>ao(o(...t),e)}function Cm(o,e,t){return(...i)=>Lc(o(...i),e,t)}class An{}class j{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=Bg(this._applyToCoroutine.bind(this)),this.uniqueId=j._UniqueIdGenerator,j._UniqueIdGenerator++}set(e,t){switch(e.length||W.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case S.PositionKind:this.positions=e;break;case S.NormalKind:this.normals=e;break;case S.TangentKind:this.tangents=e;break;case S.UVKind:this.uvs=e;break;case S.UV2Kind:this.uvs2=e;break;case S.UV3Kind:this.uvs3=e;break;case S.UV4Kind:this.uvs4=e;break;case S.UV5Kind:this.uvs5=e;break;case S.UV6Kind:this.uvs6=e;break;case S.ColorKind:this.colors=e;break;case S.MatricesIndicesKind:this.matricesIndices=e;break;case S.MatricesWeightsKind:this.matricesWeights=e;break;case S.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case S.MatricesWeightsExtraKind:this.matricesWeightsExtra=e;break}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){if(this.positions&&(e.setVerticesData(S.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(S.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(S.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(S.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(S.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(S.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(S.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(S.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(S.UV6Kind,this.uvs6,t),i&&(yield)),this.colors){const s=this.positions&&this.colors.length===this.positions.length?3:4;e.setVerticesData(S.ColorKind,this.colors,t,s),this.hasVertexAlpha&&e.hasVertexAlpha!==void 0&&(e.hasVertexAlpha=!0),i&&(yield)}if(this.matricesIndices&&(e.setVerticesData(S.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(S.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(S.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(S.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){const s=e;s.subMeshes=[];for(const r of this.materialInfos)new Kt(r.materialIndex,r.verticesStart,r.verticesCount,r.indexStart,r.indexCount,s)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(S.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(S.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(S.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(S.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(S.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(S.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(S.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(S.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(S.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(S.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(S.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(S.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(S.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(S.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const r=U.Vector3[0],n=U.Vector3[1];for(let a=i;a<i+s;a+=3)p.FromArrayToRef(e,a,r),p.TransformCoordinatesToRef(r,t,n),e[a]=n.x,e[a+1]=n.y,e[a+2]=n.z}static _TransformVector3Normals(e,t,i=0,s=e.length){const r=U.Vector3[0],n=U.Vector3[1];for(let a=i;a<i+s;a+=3)p.FromArrayToRef(e,a,r),p.TransformNormalToRef(r,t,n),e[a]=n.x,e[a+1]=n.y,e[a+2]=n.z}static _TransformVector4Normals(e,t,i=0,s=e.length){const r=U.Vector4[0],n=U.Vector4[1];for(let a=i;a<i+s;a+=4)Me.FromArrayToRef(e,a,r),Me.TransformNormalToRef(r,t,n),e[a]=n.x,e[a+1]=n.y,e[a+2]=n.z,e[a+3]=n.w}static _FlipFaces(e,t=0,i=e.length){for(let s=t;s<t+i;s+=3){const r=e[s+1];e[s+1]=e[s+2],e[s+2]=r}}transform(e){const t=e.determinant()<0;return this.positions&&j._TransformVector3Coordinates(this.positions,e),this.normals&&j._TransformVector3Normals(this.normals,e),this.tangents&&j._TransformVector4Normals(this.tangents,e),t&&this.indices&&j._FlipFaces(this.indices),this}splitBasedOnMaterialID(){if(!this.materialInfos||this.materialInfos.length<2)return[this];const e=[];for(const t of this.materialInfos){const i=new j;if(this.positions&&(i.positions=this.positions.slice(t.verticesStart*3,(t.verticesCount+t.verticesStart)*3)),this.normals&&(i.normals=this.normals.slice(t.verticesStart*3,(t.verticesCount+t.verticesStart)*3)),this.tangents&&(i.tangents=this.tangents.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.colors&&(i.colors=this.colors.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.uvs&&(i.uvs=this.uvs.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.uvs2&&(i.uvs2=this.uvs2.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.uvs3&&(i.uvs3=this.uvs3.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.uvs4&&(i.uvs4=this.uvs4.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.uvs5&&(i.uvs5=this.uvs5.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.uvs6&&(i.uvs6=this.uvs6.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.matricesIndices&&(i.matricesIndices=this.matricesIndices.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.matricesIndicesExtra&&(i.matricesIndicesExtra=this.matricesIndicesExtra.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.matricesWeights&&(i.matricesWeights=this.matricesWeights.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.matricesWeightsExtra&&(i.matricesWeightsExtra=this.matricesWeightsExtra.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.indices){i.indices=[];for(let r=t.indexStart;r<t.indexStart+t.indexCount;r++)i.indices.push(this.indices[r]-t.verticesStart)}const s=new An;s.indexStart=0,s.indexCount=i.indices?i.indices.length:0,s.materialIndex=t.materialIndex,s.verticesStart=0,s.verticesCount=(i.positions?i.positions.length:0)/3,i.materialInfos=[s],e.push(i)}return e}merge(e,t=!1,i=!1,s=!1,r=!1){const n=Array.isArray(e)?e.map(a=>({vertexData:a})):[{vertexData:e}];return ao(this._mergeCoroutine(void 0,n,t,!1,i,s,r))}*_mergeCoroutine(e,t,i=!1,s,r,n=!1,a=!1){this._validate();let h=t.map(d=>d.vertexData),l=this;if(a)for(const d of h)d&&(d._validate(),!this.normals&&d.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&d.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&d.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&d.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&d.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&d.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&d.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&d.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&d.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&d.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&d.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&d.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&d.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const d of h)if(d){if(a)this.normals&&!d.normals&&(d.normals=new Float32Array(d.positions.length)),this.tangents&&!d.tangents&&(d.tangents=new Float32Array(d.positions.length/3*4)),this.uvs&&!d.uvs&&(d.uvs=new Float32Array(d.positions.length/3*2)),this.uvs2&&!d.uvs2&&(d.uvs2=new Float32Array(d.positions.length/3*2)),this.uvs3&&!d.uvs3&&(d.uvs3=new Float32Array(d.positions.length/3*2)),this.uvs4&&!d.uvs4&&(d.uvs4=new Float32Array(d.positions.length/3*2)),this.uvs5&&!d.uvs5&&(d.uvs5=new Float32Array(d.positions.length/3*2)),this.uvs6&&!d.uvs6&&(d.uvs6=new Float32Array(d.positions.length/3*2)),this.colors&&!d.colors&&(d.colors=new Float32Array(d.positions.length/3*4),d.colors.fill(1)),this.matricesIndices&&!d.matricesIndices&&(d.matricesIndices=new Float32Array(d.positions.length/3*4)),this.matricesWeights&&!d.matricesWeights&&(d.matricesWeights=new Float32Array(d.positions.length/3*4)),this.matricesIndicesExtra&&!d.matricesIndicesExtra&&(d.matricesIndicesExtra=new Float32Array(d.positions.length/3*4)),this.matricesWeightsExtra&&!d.matricesWeightsExtra&&(d.matricesWeightsExtra=new Float32Array(d.positions.length/3*4));else if(d._validate(),!this.normals!=!d.normals||!this.tangents!=!d.tangents||!this.uvs!=!d.uvs||!this.uvs2!=!d.uvs2||!this.uvs3!=!d.uvs3||!this.uvs4!=!d.uvs4||!this.uvs5!=!d.uvs5||!this.uvs6!=!d.uvs6||!this.colors!=!d.colors||!this.matricesIndices!=!d.matricesIndices||!this.matricesWeights!=!d.matricesWeights||!this.matricesIndicesExtra!=!d.matricesIndicesExtra||!this.matricesWeightsExtra!=!d.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes")}if(n){let d,_=0,m=0;const g=[];let T=null;const R=[];for(const y of this.splitBasedOnMaterialID())R.push({vertexData:y,transform:e});for(const y of t)if(y.vertexData)for(const E of y.vertexData.splitBasedOnMaterialID())R.push({vertexData:E,transform:y.transform});R.sort((y,E)=>{const x=y.vertexData.materialInfos?y.vertexData.materialInfos[0].materialIndex:0,b=E.vertexData.materialInfos?E.vertexData.materialInfos[0].materialIndex:0;return x>b?1:x===b?0:-1});for(const y of R){const E=y.vertexData;if(E.materialInfos?d=E.materialInfos[0].materialIndex:d=0,T&&T.materialIndex===d)T.indexCount+=E.indices.length,T.verticesCount+=E.positions.length/3;else{const x=new An;x.materialIndex=d,x.indexStart=_,x.indexCount=E.indices.length,x.verticesStart=m,x.verticesCount=E.positions.length/3,g.push(x),T=x}_+=E.indices.length,m+=E.positions.length/3}const A=R.splice(0,1)[0];l=A.vertexData,e=A.transform,h=R.map(y=>y.vertexData),t=R,this.materialInfos=g}const c=h.reduce((d,_)=>d+(_.indices?.length??0),l.indices?.length??0);let f=r||h.some(d=>d.indices===l.indices)?l.indices?.slice():l.indices;if(c>0){let d=f?.length??0;if(f||(f=new Array(c)),f.length!==c){if(Array.isArray(f))f.length=c;else{const m=i||f instanceof Uint32Array?new Uint32Array(c):new Uint16Array(c);m.set(f),f=m}e&&e.determinant()<0&&j._FlipFaces(f,0,d)}let _=l.positions?l.positions.length/3:0;for(const{vertexData:m,transform:g}of t)if(m.indices){for(let T=0;T<m.indices.length;T++)f[d+T]=m.indices[T]+_;g&&g.determinant()<0&&j._FlipFaces(f,d,m.indices.length),_+=m.positions.length/3,d+=m.indices.length,s&&(yield)}}return this.indices=f,this.positions=j._MergeElement(S.PositionKind,l.positions,e,t.map(d=>[d.vertexData.positions,d.transform])),s&&(yield),l.normals&&(this.normals=j._MergeElement(S.NormalKind,l.normals,e,t.map(d=>[d.vertexData.normals,d.transform])),s&&(yield)),l.tangents&&(this.tangents=j._MergeElement(S.TangentKind,l.tangents,e,t.map(d=>[d.vertexData.tangents,d.transform])),s&&(yield)),l.uvs&&(this.uvs=j._MergeElement(S.UVKind,l.uvs,e,t.map(d=>[d.vertexData.uvs,d.transform])),s&&(yield)),l.uvs2&&(this.uvs2=j._MergeElement(S.UV2Kind,l.uvs2,e,t.map(d=>[d.vertexData.uvs2,d.transform])),s&&(yield)),l.uvs3&&(this.uvs3=j._MergeElement(S.UV3Kind,l.uvs3,e,t.map(d=>[d.vertexData.uvs3,d.transform])),s&&(yield)),l.uvs4&&(this.uvs4=j._MergeElement(S.UV4Kind,l.uvs4,e,t.map(d=>[d.vertexData.uvs4,d.transform])),s&&(yield)),l.uvs5&&(this.uvs5=j._MergeElement(S.UV5Kind,l.uvs5,e,t.map(d=>[d.vertexData.uvs5,d.transform])),s&&(yield)),l.uvs6&&(this.uvs6=j._MergeElement(S.UV6Kind,l.uvs6,e,t.map(d=>[d.vertexData.uvs6,d.transform])),s&&(yield)),l.colors&&(this.colors=j._MergeElement(S.ColorKind,l.colors,e,t.map(d=>[d.vertexData.colors,d.transform])),(l.hasVertexAlpha!==void 0||t.some(d=>d.vertexData.hasVertexAlpha!==void 0))&&(this.hasVertexAlpha=l.hasVertexAlpha||t.some(d=>d.vertexData.hasVertexAlpha)),s&&(yield)),l.matricesIndices&&(this.matricesIndices=j._MergeElement(S.MatricesIndicesKind,l.matricesIndices,e,t.map(d=>[d.vertexData.matricesIndices,d.transform])),s&&(yield)),l.matricesWeights&&(this.matricesWeights=j._MergeElement(S.MatricesWeightsKind,l.matricesWeights,e,t.map(d=>[d.vertexData.matricesWeights,d.transform])),s&&(yield)),l.matricesIndicesExtra&&(this.matricesIndicesExtra=j._MergeElement(S.MatricesIndicesExtraKind,l.matricesIndicesExtra,e,t.map(d=>[d.vertexData.matricesIndicesExtra,d.transform])),s&&(yield)),l.matricesWeightsExtra&&(this.matricesWeightsExtra=j._MergeElement(S.MatricesWeightsExtraKind,l.matricesWeightsExtra,e,t.map(d=>[d.vertexData.matricesWeightsExtra,d.transform]))),this}static _MergeElement(e,t,i,s){const r=s.filter(h=>h[0]!==null&&h[0]!==void 0);if(!t&&r.length==0)return t;if(!t)return this._MergeElement(e,r[0][0],r[0][1],r.slice(1));const n=r.reduce((h,l)=>h+l[0].length,t.length),a=e===S.PositionKind?j._TransformVector3Coordinates:e===S.NormalKind?j._TransformVector3Normals:e===S.TangentKind?j._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const h=new Float32Array(n);h.set(t),i&&a(h,i,0,t.length);let l=t.length;for(const[c,u]of r)h.set(c,l),u&&a(h,u,l,c.length),l+=c.length;return h}else{const h=new Array(n);for(let c=0;c<t.length;c++)h[c]=t[c];i&&a(h,i,0,t.length);let l=t.length;for(const[c,u]of r){for(let f=0;f<c.length;f++)h[l+f]=c[f];u&&a(h,u,l,c.length),l+=c.length}return h}}_validate(){if(!this.positions)throw new Ss("Positions are required",Xr.MeshInvalidPositionsError);const e=(s,r)=>{const n=S.DeduceStride(s);if(r.length%n!==0)throw new Error("The "+s+"s array count must be a multiple of "+n);return r.length/n},t=e(S.PositionKind,this.positions),i=(s,r)=>{const n=e(s,r);if(n!==t)throw new Error("The "+s+"s element count ("+n+") does not match the positions count ("+t+")")};this.normals&&i(S.NormalKind,this.normals),this.tangents&&i(S.TangentKind,this.tangents),this.uvs&&i(S.UVKind,this.uvs),this.uvs2&&i(S.UV2Kind,this.uvs2),this.uvs3&&i(S.UV3Kind,this.uvs3),this.uvs4&&i(S.UV4Kind,this.uvs4),this.uvs5&&i(S.UV5Kind,this.uvs5),this.uvs6&&i(S.UV6Kind,this.uvs6),this.colors&&i(S.ColorKind,this.colors),this.matricesIndices&&i(S.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(S.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(S.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(S.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return j.Parse(e)}serialize(){const e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndicesExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtraExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=this.indices?Array.from(this.indices):[],this.materialInfos){e.materialInfos=[];for(const t of this.materialInfos){const i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return j._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return j._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new j;if(e.isVerticesDataPresent(S.PositionKind)&&(s.positions=e.getVerticesData(S.PositionKind,t,i)),e.isVerticesDataPresent(S.NormalKind)&&(s.normals=e.getVerticesData(S.NormalKind,t,i)),e.isVerticesDataPresent(S.TangentKind)&&(s.tangents=e.getVerticesData(S.TangentKind,t,i)),e.isVerticesDataPresent(S.UVKind)&&(s.uvs=e.getVerticesData(S.UVKind,t,i)),e.isVerticesDataPresent(S.UV2Kind)&&(s.uvs2=e.getVerticesData(S.UV2Kind,t,i)),e.isVerticesDataPresent(S.UV3Kind)&&(s.uvs3=e.getVerticesData(S.UV3Kind,t,i)),e.isVerticesDataPresent(S.UV4Kind)&&(s.uvs4=e.getVerticesData(S.UV4Kind,t,i)),e.isVerticesDataPresent(S.UV5Kind)&&(s.uvs5=e.getVerticesData(S.UV5Kind,t,i)),e.isVerticesDataPresent(S.UV6Kind)&&(s.uvs6=e.getVerticesData(S.UV6Kind,t,i)),e.isVerticesDataPresent(S.ColorKind)){const r=e.geometry||e,n=r.getVertexBuffer(S.ColorKind),a=r.getVerticesData(S.ColorKind,t,i);if(n.getSize()===3){const h=new Float32Array(a.length*4/3);for(let l=0,c=0;l<a.length;l+=3,c+=4)h[c]=a[l],h[c+1]=a[l+1],h[c+2]=a[l+2],h[c+3]=1;s.colors=h}else if(n.getSize()===4)s.colors=a;else throw new Error(`Unexpected number of color components: ${n.getSize()}`)}return e.isVerticesDataPresent(S.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(S.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(S.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(S.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(S.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(S.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(S.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(S.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw pe("ribbonBuilder")}static CreateBox(e){throw pe("boxBuilder")}static CreateTiledBox(e){throw pe("tiledBoxBuilder")}static CreateTiledPlane(e){throw pe("tiledPlaneBuilder")}static CreateSphere(e){throw pe("sphereBuilder")}static CreateCylinder(e){throw pe("cylinderBuilder")}static CreateTorus(e){throw pe("torusBuilder")}static CreateLineSystem(e){throw pe("linesBuilder")}static CreateDashedLines(e){throw pe("linesBuilder")}static CreateGround(e){throw pe("groundBuilder")}static CreateTiledGround(e){throw pe("groundBuilder")}static CreateGroundFromHeightMap(e){throw pe("groundBuilder")}static CreatePlane(e){throw pe("planeBuilder")}static CreateDisc(e){throw pe("discBuilder")}static CreatePolygon(e,t,i,s,r,n,a){throw pe("polygonBuilder")}static CreateIcoSphere(e){throw pe("icoSphereBuilder")}static CreatePolyhedron(e){throw pe("polyhedronBuilder")}static CreateCapsule(e={orientation:p.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw pe("capsuleBuilder")}static CreateTorusKnot(e){throw pe("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let r,n,a,h,l,c,u,f,d,_,m,g,T,R,A,y,E,x,b,P,v=!1,O=!1,k=!1,Y=!1,q=1,L=0,ee=null;s&&(v=!!s.facetNormals,O=!!s.facetPositions,k=!!s.facetPartitioning,q=s.useRightHandedSystem===!0?-1:1,L=s.ratio||0,Y=!!s.depthSort,ee=s.distanceTo,Y&&ee===void 0&&(ee=p.Zero()));let Q=0,se=0,le=0,H=0;for(k&&s&&s.bbSize&&(Q=s.subDiv.X*L/s.bbSize.x,se=s.subDiv.Y*L/s.bbSize.y,le=s.subDiv.Z*L/s.bbSize.z,H=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),r=0;r<e.length;r++)i[r]=0;const K=t.length/3|0;for(r=0;r<K;r++){if(g=t[r*3]*3,T=g+1,R=g+2,A=t[r*3+1]*3,y=A+1,E=A+2,x=t[r*3+2]*3,b=x+1,P=x+2,n=e[g]-e[A],a=e[T]-e[y],h=e[R]-e[E],l=e[x]-e[A],c=e[b]-e[y],u=e[P]-e[E],f=q*(a*u-h*c),d=q*(h*l-n*u),_=q*(n*c-a*l),m=Math.sqrt(f*f+d*d+_*_),m=m===0?1:m,f/=m,d/=m,_/=m,v&&s&&(s.facetNormals[r].x=f,s.facetNormals[r].y=d,s.facetNormals[r].z=_),O&&s&&(s.facetPositions[r].x=(e[g]+e[A]+e[x])/3,s.facetPositions[r].y=(e[T]+e[y]+e[b])/3,s.facetPositions[r].z=(e[R]+e[E]+e[P])/3),k&&s){const w=Math.floor((s.facetPositions[r].x-s.bInfo.minimum.x*L)*Q),B=Math.floor((s.facetPositions[r].y-s.bInfo.minimum.y*L)*se),N=Math.floor((s.facetPositions[r].z-s.bInfo.minimum.z*L)*le),X=Math.floor((e[g]-s.bInfo.minimum.x*L)*Q),Ee=Math.floor((e[T]-s.bInfo.minimum.y*L)*se),ae=Math.floor((e[R]-s.bInfo.minimum.z*L)*le),Se=Math.floor((e[A]-s.bInfo.minimum.x*L)*Q),We=Math.floor((e[y]-s.bInfo.minimum.y*L)*se),nt=Math.floor((e[E]-s.bInfo.minimum.z*L)*le),ct=Math.floor((e[x]-s.bInfo.minimum.x*L)*Q),Ge=Math.floor((e[b]-s.bInfo.minimum.y*L)*se),_e=Math.floor((e[P]-s.bInfo.minimum.z*L)*le),Fe=X+s.subDiv.max*Ee+H*ae,Xe=Se+s.subDiv.max*We+H*nt,Ae=ct+s.subDiv.max*Ge+H*_e,$e=w+s.subDiv.max*B+H*N;s.facetPartitioning[$e]=s.facetPartitioning[$e]?s.facetPartitioning[$e]:[],s.facetPartitioning[Fe]=s.facetPartitioning[Fe]?s.facetPartitioning[Fe]:[],s.facetPartitioning[Xe]=s.facetPartitioning[Xe]?s.facetPartitioning[Xe]:[],s.facetPartitioning[Ae]=s.facetPartitioning[Ae]?s.facetPartitioning[Ae]:[],s.facetPartitioning[Fe].push(r),Xe!=Fe&&s.facetPartitioning[Xe].push(r),Ae==Xe||Ae==Fe||s.facetPartitioning[Ae].push(r),$e==Fe||$e==Xe||$e==Ae||s.facetPartitioning[$e].push(r)}if(Y&&s&&s.facetPositions){const w=s.depthSortedFacets[r];w.ind=r*3,w.sqDistance=p.DistanceSquared(s.facetPositions[r],ee)}i[g]+=f,i[T]+=d,i[R]+=_,i[A]+=f,i[y]+=d,i[E]+=_,i[x]+=f,i[b]+=d,i[P]+=_}for(r=0;r<i.length/3;r++)f=i[r*3],d=i[r*3+1],_=i[r*3+2],m=Math.sqrt(f*f+d*d+_*_),m=m===0?1:m,f/=m,d/=m,_/=m,i[r*3]=f,i[r*3+1]=d,i[r*3+2]=_}static _ComputeSides(e,t,i,s,r,n,a){const h=i.length,l=s.length;let c,u;switch(e=e||j.DEFAULTSIDE,e){case j.FRONTSIDE:break;case j.BACKSIDE:for(c=0;c<h;c+=3){const f=i[c];i[c]=i[c+2],i[c+2]=f}for(u=0;u<l;u++)s[u]=-s[u];break;case j.DOUBLESIDE:{const f=t.length,d=f/3;for(let g=0;g<f;g++)t[f+g]=t[g];for(c=0;c<h;c+=3)i[c+h]=i[c+2]+d,i[c+1+h]=i[c+1]+d,i[c+2+h]=i[c]+d;for(u=0;u<l;u++)s[l+u]=-s[u];const _=r.length;let m;for(m=0;m<_;m++)r[m+_]=r[m];for(n=n||new Me(0,0,1,1),a=a||new Me(0,0,1,1),m=0,c=0;c<_/2;c++)r[m]=n.x+(n.z-n.x)*r[m],r[m+1]=n.y+(n.w-n.y)*r[m+1],r[m+_]=a.x+(a.z-a.x)*r[m+_],r[m+_+1]=a.y+(a.w-a.y)*r[m+_+1],m+=2;break}}}static Parse(e){const t=new j,i=e.positions;i&&t.set(i,S.PositionKind);const s=e.normals;s&&t.set(s,S.NormalKind);const r=e.tangents;r&&t.set(r,S.TangentKind);const n=e.uvs;n&&t.set(n,S.UVKind);const a=e.uvs2;a&&t.set(a,S.UV2Kind);const h=e.uvs3;h&&t.set(h,S.UV3Kind);const l=e.uvs4;l&&t.set(l,S.UV4Kind);const c=e.uvs5;c&&t.set(c,S.UV5Kind);const u=e.uvs6;u&&t.set(u,S.UV6Kind);const f=e.colors;f&&(t.set(Ce.CheckColors4(f,i.length/3),S.ColorKind),e.hasVertexAlpha!==void 0&&(t.hasVertexAlpha=e.hasVertexAlpha));const d=e.matricesIndices;d&&t.set(d,S.MatricesIndicesKind);const _=e.matricesWeights;_&&t.set(_,S.MatricesWeightsKind);const m=e.indices;m&&(t.indices=m);const g=e.materialInfos;if(g){t.materialInfos=[];for(const T of g){const R=new An;R.indexCount=T.indexCount,R.indexStart=T.indexStart,R.verticesCount=T.verticesCount,R.verticesStart=T.verticesStart,R.materialIndex=T.materialIndex,t.materialInfos.push(R)}}return t}static ImportVertexData(e,t){const i=j.Parse(e);t.setAllVerticesData(i,e.updatable)}}j.FRONTSIDE=0;j.BACKSIDE=1;j.DOUBLESIDE=2;j.DEFAULTSIDE=0;j._UniqueIdGenerator=0;M([_i.filter((...[o])=>!Array.isArray(o))],j,"_TransformVector3Coordinates",null);M([_i.filter((...[o])=>!Array.isArray(o))],j,"_TransformVector3Normals",null);M([_i.filter((...[o])=>!Array.isArray(o))],j,"_TransformVector4Normals",null);M([_i.filter((...[o])=>!Array.isArray(o))],j,"_FlipFaces",null);class Pt{static get ForceFullSceneLoadingForIncremental(){return Pt._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Pt._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Pt._ShowLoadingScreen}static set ShowLoadingScreen(e){Pt._ShowLoadingScreen=e}static get loggingLevel(){return Pt._LoggingLevel}static set loggingLevel(e){Pt._LoggingLevel=e}static get CleanBoneMatrixWeights(){return Pt._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Pt._CleanBoneMatrixWeights=e}}Pt._ForceFullSceneLoadingForIncremental=!1;Pt._ShowLoadingScreen=!0;Pt._CleanBoneMatrixWeights=!1;Pt._LoggingLevel=0;class Rt{get boundingBias(){return this._boundingBias}set boundingBias(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)}static CreateGeometryForMesh(e){const t=new Rt(Rt.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,s=!1,r=null,n=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._extend={minimum:new p(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),maximum:new p(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||ye.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=s,n!==null&&(this._totalVertices=n),i?this.setAllVerticesData(i,s):n===null&&(this._totalVertices=0),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return this.delayLoadState===1||this.delayLoadState===0}get doNotSerialize(){for(let e=0;e<this._meshes.length;e++)if(!this._meshes[e].doNotSerialize)return!1;return!0}_rebuild(){this._vertexArrayObjects&&(this._vertexArrayObjects={}),this._meshes.length!==0&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer"));const e=new Set;for(const t in this._vertexBuffers)e.add(this._vertexBuffers[t].getWrapperBuffer());e.forEach(t=>{t._rebuild()})}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,s){i&&Array.isArray(t)&&(t=new Float32Array(t));const r=new S(this._engine,t,e,{updatable:i,postponeInternalCreation:this._meshes.length===0,stride:s,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(r)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const s=e.getKind();this._vertexBuffers[s]&&i&&this._vertexBuffers[s].dispose(),e._buffer&&e._ownsBuffer&&e._buffer._increaseReferences(),this._vertexBuffers[s]=e;const r=this._meshes,n=r.length;if(s===S.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(this.useBoundingInfoFromGeometry&&this._boundingInfo?null:e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const a=this._extend&&this._extend.minimum||new p(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),h=this._extend&&this._extend.maximum||new p(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let l=0;l<n;l++){const c=r[l];c.buildBoundingInfo(a,h),c._createGlobalSubMesh(c.isUnIndexed),c.computeWorldMatrix(!0),c.synchronizeInstances()}}this._notifyUpdate(s)}updateVerticesDataDirectly(e,t,i,s=!1){const r=this.getVertexBuffer(e);r&&(r.updateDirectly(t,i,s),this._notifyUpdate(e))}updateVerticesData(e,t,i=!1){const s=this.getVertexBuffer(e);s&&(s.update(t),e===S.PositionKind&&this._updateBoundingInfo(i,t),this._notifyUpdate(e))}_updateBoundingInfo(e,t){if(e&&this._updateExtend(t),this._resetPointsArrayCache(),e){const i=this._meshes;for(const s of i){s.hasBoundingInfo?s.getBoundingInfo().reConstruct(this._extend.minimum,this._extend.maximum):s.buildBoundingInfo(this._extend.minimum,this._extend.maximum);const r=s.subMeshes;for(const n of r)n.refreshBoundingInfo()}}}_bind(e,t,i,s){if(!e)return;t===void 0&&(t=this._indexBuffer);const r=this.getVertexBuffers();if(!r)return;if(t!=this._indexBuffer||!this._vertexArrayObjects&&!s){this._engine.bindBuffers(r,t,e,i);return}const n=s||this._vertexArrayObjects,a=this._engine;n[e.key]||(n[e.key]=a.recordVertexArrayObject(r,t,e,i)),a.bindVertexArrayObject(n[e.key],t)}getTotalVertices(){return this.isReady()?this._totalVertices:0}getVerticesData(e,t,i){const s=this.getVertexBuffer(e);return s?s.getFloatData(this._totalVertices,i||t&&this._meshes.length!==1):null}copyVerticesData(e,t){const i=this.getVertexBuffer(e);if(!i)return;t[e]||(t[e]=new Float32Array(this._totalVertices*i.getSize()));const s=i.getData();s&&cf(s,i.getSize(),i.type,i.byteOffset,i.byteStride,i.normalized,this._totalVertices,t[e])}isVertexBufferUpdatable(e){const t=this._vertexBuffers[e];return t?t.isUpdatable():!1}getVertexBuffer(e){return this.isReady()?this._vertexBuffers[e]:null}getVertexBuffers(){return this.isReady()?this._vertexBuffers:null}isVerticesDataPresent(e){return this._vertexBuffers?this._vertexBuffers[e]!==void 0:this._delayInfo?this._delayInfo.indexOf(e)!==-1:!1}getVerticesDataKinds(){const e=[];let t;if(!this._vertexBuffers&&this._delayInfo)for(t in this._delayInfo)e.push(t);else for(t in this._vertexBuffers)e.push(t);return e}updateIndices(e,t,i=!1){if(this._indexBuffer)if(!this._indexBufferIsUpdatable)this.setIndices(e,null,!0);else{const s=e.length!==this._indices.length;if(i||(this._indices=e.slice()),this._engine.updateDynamicIndexBuffer(this._indexBuffer,e,t),s)for(const r of this._meshes)r._createGlobalSubMesh(!0)}}setIndexBuffer(e,t,i,s=null){this._indices=[],this._indexBufferIsUpdatable=!1,this._indexBuffer=e,this._totalVertices=t,this._totalIndices=i,s===null?e.is32Bits=t>65535:e.is32Bits=s;for(const r of this._meshes)r._createGlobalSubMesh(!0),r.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1,s=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,this._meshes.length!==0&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),t!=null&&(this._totalVertices=t);for(const r of this._meshes)r._createGlobalSubMesh(!s),r.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?this._totalIndices!==void 0?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return!t&&(!e||this._meshes.length===1)?i:i.slice()}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){!e||!this._vertexArrayObjects||this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const i=this._meshes,s=i.indexOf(e);s!==-1&&(i.splice(s,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,i.length===0&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;const t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();const i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&(e=this.getVerticesData(S.PositionKind),!e))return;this._extend=to(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){for(const t in this._vertexBuffers){const i=this._vertexBuffers[t];i._buffer.getBuffer()||i.create(),t===S.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo())}!this._indexBuffer&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const t of this._meshes)t._markSubMeshesAsAttributesDirty()}load(e,t){if(this.delayLoadState!==2){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const s=this._meshes,r=s.length;for(let n=0;n<r;n++)this._applyToMesh(s[n]);t&&t()},void 0,!0))}toLeftHanded(){const e=this.getIndices(!1);if(e!=null&&e.length>0){for(let s=0;s<e.length;s+=3){const r=e[s+0];e[s+0]=e[s+2],e[s+2]=r}this.setIndices(e)}const t=this.getVerticesData(S.PositionKind,!1);if(t!=null&&t.length>0){for(let s=0;s<t.length;s+=3)t[s+2]=-t[s+2];this.setVerticesData(S.PositionKind,t,!1)}const i=this.getVerticesData(S.NormalKind,!1);if(i!=null&&i.length>0){for(let s=0;s<i.length;s+=3)i[s+2]=-i[s+2];this.setVerticesData(S.NormalKind,i,!1)}}_resetPointsArrayCache(){this._positions=null}_generatePointsArray(){if(this._positions)return!0;const e=this.getVerticesData(S.PositionKind);if(!e||e.length===0)return!1;for(let t=this._positionsCache.length*3,i=this._positionsCache.length;t<e.length;t+=3,++i)this._positionsCache[i]=p.FromArray(e,t);for(let t=0,i=0;t<e.length;t+=3,++i)this._positionsCache[i].set(e[0+t],e[1+t],e[2+t]);return this._positionsCache.length=e.length/3,this._positions=this._positionsCache,!0}isDisposed(){return this._isDisposed}_disposeVertexArrayObjects(){if(this._vertexArrayObjects){for(const i in this._vertexArrayObjects)this._engine.releaseVertexArrayObject(this._vertexArrayObjects[i]);this._vertexArrayObjects={};const e=this._meshes,t=e.length;for(let i=0;i<t;i++)e[i]._invalidateInstanceVertexArrayObject()}}dispose(){const e=this._meshes,t=e.length;let i;for(i=0;i<t;i++)this.releaseForMesh(e[i]);this._meshes.length=0,this._disposeVertexArrayObjects();for(const s in this._vertexBuffers)this._vertexBuffers[s].dispose();if(this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=0,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._parentContainer){const s=this._parentContainer.geometries.indexOf(this);s>-1&&this._parentContainer.geometries.splice(s,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new Rt(e,this._scene),i=this.getIndices(void 0,!0);i&&t.setIndices(i);let s=!1,r;for(r in this._vertexBuffers){const n=this.getVertexBuffer(r),a=n.getData();if(!a)continue;const h=n.isUpdatable(),l=n.getSize(),{type:c,byteOffset:u,byteStride:f,normalized:d}=n;s=s||h;let _=this._totalVertices;if(n.getIsInstanced()){let T;a instanceof Array?T=a.length*4:T=a.byteLength,_=T/f}const m=lf(a,l,c,u,f,_,!0),g=new S(this._engine,m,r,{updatable:h,useBytes:!1,stride:l,size:l,offset:0,type:c,normalized:d,takeBufferOwnership:!0,instanced:n.getIsInstanced()});t.setVerticesBuffer(g,_)}t._updatable=s,t.delayLoadState=this.delayLoadState,t.delayLoadingFile=this.delayLoadingFile,t._delayLoadingFunction=this._delayLoadingFunction;for(r in this._delayInfo)t._delayInfo=t._delayInfo||[],t._delayInfo.push(r);return t._boundingInfo=new wt(this._extend.minimum,this._extend.maximum),t}serialize(){const e={};return e.id=this.id,e.uniqueId=this.uniqueId,e.updatable=this._updatable,Le&&Le.HasTags(this)&&(e.tags=Le.GetTags(this)),e}_toNumberArray(e){return Array.isArray(e)?e:Array.prototype.slice.call(e)}clearCachedData(){this._totalIndices=this._indices.length,this._indices=[],this._resetPointsArrayCache();for(const e in this._vertexBuffers)Object.prototype.hasOwnProperty.call(this._vertexBuffers,e)&&(this._vertexBuffers[e]._buffer._data=null)}serializeVerticeData(){const e=this.serialize();return this.isVerticesDataPresent(S.PositionKind)&&(e.positions=this._toNumberArray(this.getVerticesData(S.PositionKind)),this.isVertexBufferUpdatable(S.PositionKind)&&(e.positionsUpdatable=!0)),this.isVerticesDataPresent(S.NormalKind)&&(e.normals=this._toNumberArray(this.getVerticesData(S.NormalKind)),this.isVertexBufferUpdatable(S.NormalKind)&&(e.normalsUpdatable=!0)),this.isVerticesDataPresent(S.TangentKind)&&(e.tangents=this._toNumberArray(this.getVerticesData(S.TangentKind)),this.isVertexBufferUpdatable(S.TangentKind)&&(e.tangentsUpdatable=!0)),this.isVerticesDataPresent(S.UVKind)&&(e.uvs=this._toNumberArray(this.getVerticesData(S.UVKind)),this.isVertexBufferUpdatable(S.UVKind)&&(e.uvsUpdatable=!0)),this.isVerticesDataPresent(S.UV2Kind)&&(e.uvs2=this._toNumberArray(this.getVerticesData(S.UV2Kind)),this.isVertexBufferUpdatable(S.UV2Kind)&&(e.uvs2Updatable=!0)),this.isVerticesDataPresent(S.UV3Kind)&&(e.uvs3=this._toNumberArray(this.getVerticesData(S.UV3Kind)),this.isVertexBufferUpdatable(S.UV3Kind)&&(e.uvs3Updatable=!0)),this.isVerticesDataPresent(S.UV4Kind)&&(e.uvs4=this._toNumberArray(this.getVerticesData(S.UV4Kind)),this.isVertexBufferUpdatable(S.UV4Kind)&&(e.uvs4Updatable=!0)),this.isVerticesDataPresent(S.UV5Kind)&&(e.uvs5=this._toNumberArray(this.getVerticesData(S.UV5Kind)),this.isVertexBufferUpdatable(S.UV5Kind)&&(e.uvs5Updatable=!0)),this.isVerticesDataPresent(S.UV6Kind)&&(e.uvs6=this._toNumberArray(this.getVerticesData(S.UV6Kind)),this.isVertexBufferUpdatable(S.UV6Kind)&&(e.uvs6Updatable=!0)),this.isVerticesDataPresent(S.ColorKind)&&(e.colors=this._toNumberArray(this.getVerticesData(S.ColorKind)),this.isVertexBufferUpdatable(S.ColorKind)&&(e.colorsUpdatable=!0)),this.isVerticesDataPresent(S.MatricesIndicesKind)&&(e.matricesIndices=this._toNumberArray(this.getVerticesData(S.MatricesIndicesKind)),e.matricesIndicesExpanded=!0,this.isVertexBufferUpdatable(S.MatricesIndicesKind)&&(e.matricesIndicesUpdatable=!0)),this.isVerticesDataPresent(S.MatricesWeightsKind)&&(e.matricesWeights=this._toNumberArray(this.getVerticesData(S.MatricesWeightsKind)),this.isVertexBufferUpdatable(S.MatricesWeightsKind)&&(e.matricesWeightsUpdatable=!0)),e.indices=this._toNumberArray(this.getIndices()),e}static ExtractFromMesh(e,t){const i=e._geometry;return i?i.copy(t):null}static RandomId(){return fe.RandomId()}static _GetGeometryByLoadedUniqueId(e,t){for(let i=0;i<t.geometries.length;i++)if(t.geometries[i]._loadedUniqueId===e)return t.geometries[i];return null}static _ImportGeometry(e,t){const i=t.getScene(),s=e.geometryUniqueId,r=e.geometryId;if(s||r){const n=s?this._GetGeometryByLoadedUniqueId(s,i):i.getGeometryById(r);n&&n.applyToMesh(t)}else if(e instanceof ArrayBuffer){const n=t._binaryInfo;if(n.positionsAttrDesc&&n.positionsAttrDesc.count>0){const a=new Float32Array(e,n.positionsAttrDesc.offset,n.positionsAttrDesc.count);t.setVerticesData(S.PositionKind,a,!1)}if(n.normalsAttrDesc&&n.normalsAttrDesc.count>0){const a=new Float32Array(e,n.normalsAttrDesc.offset,n.normalsAttrDesc.count);t.setVerticesData(S.NormalKind,a,!1)}if(n.tangetsAttrDesc&&n.tangetsAttrDesc.count>0){const a=new Float32Array(e,n.tangetsAttrDesc.offset,n.tangetsAttrDesc.count);t.setVerticesData(S.TangentKind,a,!1)}if(n.uvsAttrDesc&&n.uvsAttrDesc.count>0){const a=new Float32Array(e,n.uvsAttrDesc.offset,n.uvsAttrDesc.count);if(we)for(let h=1;h<a.length;h+=2)a[h]=1-a[h];t.setVerticesData(S.UVKind,a,!1)}if(n.uvs2AttrDesc&&n.uvs2AttrDesc.count>0){const a=new Float32Array(e,n.uvs2AttrDesc.offset,n.uvs2AttrDesc.count);if(we)for(let h=1;h<a.length;h+=2)a[h]=1-a[h];t.setVerticesData(S.UV2Kind,a,!1)}if(n.uvs3AttrDesc&&n.uvs3AttrDesc.count>0){const a=new Float32Array(e,n.uvs3AttrDesc.offset,n.uvs3AttrDesc.count);if(we)for(let h=1;h<a.length;h+=2)a[h]=1-a[h];t.setVerticesData(S.UV3Kind,a,!1)}if(n.uvs4AttrDesc&&n.uvs4AttrDesc.count>0){const a=new Float32Array(e,n.uvs4AttrDesc.offset,n.uvs4AttrDesc.count);if(we)for(let h=1;h<a.length;h+=2)a[h]=1-a[h];t.setVerticesData(S.UV4Kind,a,!1)}if(n.uvs5AttrDesc&&n.uvs5AttrDesc.count>0){const a=new Float32Array(e,n.uvs5AttrDesc.offset,n.uvs5AttrDesc.count);if(we)for(let h=1;h<a.length;h+=2)a[h]=1-a[h];t.setVerticesData(S.UV5Kind,a,!1)}if(n.uvs6AttrDesc&&n.uvs6AttrDesc.count>0){const a=new Float32Array(e,n.uvs6AttrDesc.offset,n.uvs6AttrDesc.count);if(we)for(let h=1;h<a.length;h+=2)a[h]=1-a[h];t.setVerticesData(S.UV6Kind,a,!1)}if(n.colorsAttrDesc&&n.colorsAttrDesc.count>0){const a=new Float32Array(e,n.colorsAttrDesc.offset,n.colorsAttrDesc.count);t.setVerticesData(S.ColorKind,a,!1,n.colorsAttrDesc.stride)}if(n.matricesIndicesAttrDesc&&n.matricesIndicesAttrDesc.count>0){const a=new Int32Array(e,n.matricesIndicesAttrDesc.offset,n.matricesIndicesAttrDesc.count),h=[];for(let l=0;l<a.length;l++){const c=a[l];h.push(c&255),h.push((c&65280)>>8),h.push((c&16711680)>>16),h.push(c>>24&255)}t.setVerticesData(S.MatricesIndicesKind,h,!1)}if(n.matricesIndicesExtraAttrDesc&&n.matricesIndicesExtraAttrDesc.count>0){const a=new Int32Array(e,n.matricesIndicesExtraAttrDesc.offset,n.matricesIndicesExtraAttrDesc.count),h=[];for(let l=0;l<a.length;l++){const c=a[l];h.push(c&255),h.push((c&65280)>>8),h.push((c&16711680)>>16),h.push(c>>24&255)}t.setVerticesData(S.MatricesIndicesExtraKind,h,!1)}if(n.matricesWeightsAttrDesc&&n.matricesWeightsAttrDesc.count>0){const a=new Float32Array(e,n.matricesWeightsAttrDesc.offset,n.matricesWeightsAttrDesc.count);t.setVerticesData(S.MatricesWeightsKind,a,!1)}if(n.indicesAttrDesc&&n.indicesAttrDesc.count>0){const a=new Int32Array(e,n.indicesAttrDesc.offset,n.indicesAttrDesc.count);t.setIndices(a,null)}if(n.subMeshesAttrDesc&&n.subMeshesAttrDesc.count>0){const a=new Int32Array(e,n.subMeshesAttrDesc.offset,n.subMeshesAttrDesc.count*5);t.subMeshes=[];for(let h=0;h<n.subMeshesAttrDesc.count;h++){const l=a[h*5+0],c=a[h*5+1],u=a[h*5+2],f=a[h*5+3],d=a[h*5+4];Kt.AddToMesh(l,c,u,f,d,t)}}}else if(e.positions&&e.normals&&e.indices){if(t.setVerticesData(S.PositionKind,e.positions,e.positions._updatable||e.positionsUpdatable),t.setVerticesData(S.NormalKind,e.normals,e.normals._updatable||e.normalsUpdatable),e.tangents&&t.setVerticesData(S.TangentKind,e.tangents,e.tangents._updatable||e.tangentsUpdatable),e.uvs&&t.setVerticesData(S.UVKind,e.uvs,e.uvs._updatable||e.uvsUpdatable),e.uvs2&&t.setVerticesData(S.UV2Kind,e.uvs2,e.uvs2._updatable||e.uvs2Updatable),e.uvs3&&t.setVerticesData(S.UV3Kind,e.uvs3,e.uvs3._updatable||e.uvs3Updatable),e.uvs4&&t.setVerticesData(S.UV4Kind,e.uvs4,e.uvs4._updatable||e.uvs4Updatable),e.uvs5&&t.setVerticesData(S.UV5Kind,e.uvs5,e.uvs5._updatable||e.uvs5Updatable),e.uvs6&&t.setVerticesData(S.UV6Kind,e.uvs6,e.uvs6._updatable||e.uvs6Updatable),e.colors&&t.setVerticesData(S.ColorKind,Ce.CheckColors4(e.colors,e.positions.length/3),e.colors._updatable),e.matricesIndices)if(!e.matricesIndices._isExpanded&&!e.matricesIndicesExpanded){const n=[];for(let a=0;a<e.matricesIndices.length;a++){const h=e.matricesIndices[a];n.push(h&255),n.push((h&65280)>>8),n.push((h&16711680)>>16),n.push(h>>24&255)}t.setVerticesData(S.MatricesIndicesKind,n,e.matricesIndices._updatable||e.matricesIndicesUpdatable)}else delete e.matricesIndices._isExpanded,delete e.matricesIndicesExpanded,t.setVerticesData(S.MatricesIndicesKind,e.matricesIndices,e.matricesIndices._updatable||e.matricesIndicesUpdatable);if(e.matricesIndicesExtra)if(e.matricesIndicesExtraExpanded||e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,delete e.matricesIndicesExtraExpanded,t.setVerticesData(S.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable||e.matricesIndicesExtraUpdatable);else{const n=[];for(let a=0;a<e.matricesIndicesExtra.length;a++){const h=e.matricesIndicesExtra[a];n.push(h&255),n.push((h&65280)>>8),n.push((h&16711680)>>16),n.push(h>>24&255)}t.setVerticesData(S.MatricesIndicesExtraKind,n,e.matricesIndicesExtra._updatable||e.matricesIndicesExtraUpdatable)}e.matricesWeights&&(Rt._CleanMatricesWeights(e,t),t.setVerticesData(S.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(S.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let n=0;n<e.subMeshes.length;n++){const a=e.subMeshes[n];Kt.AddToMesh(a.materialIndex,a.verticesStart,a.verticesCount,a.indexStart,a.indexCount,t)}}t._shouldGenerateFlatShading&&(t.convertToFlatShadedMesh(),t._shouldGenerateFlatShading=!1),t.computeWorldMatrix(!0),i.onMeshImportedObservable.notifyObservers(t)}static _CleanMatricesWeights(e,t){if(!Pt.CleanBoneMatrixWeights)return;let s;if(e.skeletonId>-1){const u=t.getScene().getLastSkeletonById(e.skeletonId);if(!u)return;s=u.bones.length}else return;const r=t.getVerticesData(S.MatricesIndicesKind),n=t.getVerticesData(S.MatricesIndicesExtraKind),a=e.matricesWeights,h=e.matricesWeightsExtra,l=e.numBoneInfluencer,c=a.length;for(let u=0;u<c;u+=4){let f=0,d=-1;for(let _=0;_<4;_++){const m=a[u+_];f+=m,m<.001&&d<0&&(d=_)}if(h)for(let _=0;_<4;_++){const m=h[u+_];f+=m,m<.001&&d<0&&(d=_+4)}if((d<0||d>l-1)&&(d=l-1),f>.001){const _=1/f;for(let m=0;m<4;m++)a[u+m]*=_;if(h)for(let m=0;m<4;m++)h[u+m]*=_}else d>=4?(h[u+d-4]=1-f,n[u+d-4]=s):(a[u+d]=1-f,r[u+d]=s)}t.setVerticesData(S.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(S.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const s=new Rt(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,Le&&Le.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new wt(p.FromArray(e.boundingBoxMinimum),p.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(S.UVKind),e.hasUVs2&&s._delayInfo.push(S.UV2Kind),e.hasUVs3&&s._delayInfo.push(S.UV3Kind),e.hasUVs4&&s._delayInfo.push(S.UV4Kind),e.hasUVs5&&s._delayInfo.push(S.UV5Kind),e.hasUVs6&&s._delayInfo.push(S.UV6Kind),e.hasColors&&s._delayInfo.push(S.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(S.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(S.MatricesWeightsKind),s._delayLoadingFunction=j.ImportVertexData):j.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}class xe extends lt{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&xe.BILLBOARDMODE_USE_POSITION)!==0)}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t,!1),this._forward=new p(0,0,1),this._up=new p(0,1,0),this._right=new p(1,0,0),this._position=p.Zero(),this._rotation=p.Zero(),this._rotationQuaternion=null,this._scaling=p.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=xe.BILLBOARDMODE_NONE,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=D.Zero(),this._usePivotMatrix=!1,this._absolutePosition=p.Zero(),this._absoluteScaling=p.Zero(),this._absoluteRotationQuaternion=re.Identity(),this._pivotMatrix=D.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new z,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._markAsDirtyInternal()}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._markAsDirtyInternal()}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._markAsDirtyInternal()}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._markAsDirtyInternal()}_markAsDirtyInternal(){this._isDirty||(this._isDirty=!0,this.customMarkAsDirty&&this.customMarkAsDirty())}get forward(){return p.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return p.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return p.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()}updatePoseMatrix(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=D.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==xe.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this._infiniteDistance||this._position._isDirty||this._scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)}_initCache(){super._initCache();const e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=D.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const s=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);s&&i&&i(this,s);for(const r of this.getChildTransformNodes(!0))r.instantiateHierarchy(s,t,i);return s}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||re.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,s;if(e.x===void 0){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],s=arguments[2]}else t=e.x,i=e.y,s=e.z;if(this.parent){const r=U.Matrix[0];this.parent.getWorldMatrix().invertToRef(r),p.TransformCoordinatesFromFloatsToRef(t,i,s,r,this.position)}else this.position.x=t,this.position.y=i,this.position.z=s;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=p.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=U.Matrix[0];return this._localMatrix.invertToRef(e),p.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=p.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,r=0){const n=xe._LookAtVectorCache,a=r===0?this.position:this.getAbsolutePosition();if(e.subtractToRef(a,n),this.setDirection(n,t,i,s),r===1&&this.parent)if(this.rotationQuaternion){const h=U.Matrix[0];this.rotationQuaternion.toRotationMatrix(h);const l=U.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(l),l.invert(),h.multiplyToRef(l,h),this.rotationQuaternion.fromRotationMatrix(h)}else{const h=U.Quaternion[0];re.FromEulerVectorToRef(this.rotation,h);const l=U.Matrix[0];h.toRotationMatrix(l);const c=U.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(c),c.invert(),l.multiplyToRef(c,l),h.fromRotationMatrix(l),h.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=p.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return p.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,n);return this.rotationQuaternion?re.RotationYawPitchRollToRef(r+t,a+i,s,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=r+t,this.rotation.z=s),this}setPivotPoint(e,t=0){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==1){const s=U.Matrix[0];i.invertToRef(s),e=p.TransformCoordinates(e,s)}return this.setPivotMatrix(D.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=p.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){const e=p.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),p.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;const s=U.Quaternion[0],r=U.Vector3[0],n=U.Vector3[1],a=U.Matrix[1];D.IdentityToRef(a);const h=U.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=xe._TmpRotation,re.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),D.ComposeToRef(this.scaling,l,this.position,h),this.parent&&h.multiplyToRef(this.parent.computeWorldMatrix(!0),h),e&&(e.computeWorldMatrix(!0).invertToRef(a),h.multiplyToRef(a,h)),h.decompose(n,s,r,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(r),this.parent=e,i&&this.setPivotMatrix(D.Identity()),this}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.parent!==this?this:(e.setParent(null,t),this)}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling===e?!1:(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0));let s;if(!i||i===0)s=re.RotationAxisToRef(e,t,xe._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);else{if(this.parent){const r=this.parent.getWorldMatrix(),n=U.Matrix[0];r.invertToRef(n),e=p.TransformNormal(e,n),r.determinant()<0&&(t*=-1)}s=re.RotationAxisToRef(e,t,xe._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=re.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=U.Vector3[0],r=U.Vector3[1],n=U.Vector3[2],a=U.Quaternion[0],h=U.Matrix[0],l=U.Matrix[1],c=U.Matrix[2],u=U.Matrix[3];return e.subtractToRef(this.position,s),D.TranslationToRef(s.x,s.y,s.z,h),D.TranslationToRef(-s.x,-s.y,-s.z,l),D.RotationAxisToRef(t,i,c),l.multiplyToRef(c,u),u.multiplyToRef(h,u),u.decompose(r,a,n),this.position.addInPlace(n),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(!i||i===0){const r=this.getPositionExpressedInLocalSpace().add(s);this.setPositionWithLocalVector(r)}else this.setAbsolutePosition(this.getAbsolutePosition().add(s));return this}addRotation(e,t,i){let s;this.rotationQuaternion?s=this.rotationQuaternion:(s=U.Quaternion[1],re.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const r=U.Quaternion[0];return re.RotationYawPitchRollToRef(t,e,i,r),s.multiplyInPlace(r),this.rotationQuaternion||s.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==xe.BILLBOARDMODE_NONE}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const r=this._getEffectiveParent(),n=xe._TmpScaling;let a=this._position;if(this._infiniteDistance&&!this.parent&&t){const l=t.getWorldMatrix(),c=new p(l.m[12],l.m[13],l.m[14]);a=xe._TmpTranslation,a.copyFromFloats(this._position.x+c.x,this._position.y+c.y,this._position.z+c.z)}n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant);let h;if(this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,h=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(re.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(h=xe._TmpRotation,re.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),this._usePivotMatrix){const l=U.Matrix[1];D.ScalingToRef(n.x,n.y,n.z,l);const c=U.Matrix[0];h.toRotationMatrix(c),this._pivotMatrix.multiplyToRef(l,U.Matrix[4]),U.Matrix[4].multiplyToRef(c,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(a.x,a.y,a.z)}else D.ComposeToRef(n,h,a,this._localMatrix);if(r&&r.getWorldMatrix){if(e&&r.computeWorldMatrix(e),this.billboardMode){if(this._transformToBoneReferal){const f=this.parent;f.getSkeleton().prepare(),f.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),U.Matrix[7])}else U.Matrix[7].copyFrom(r.getWorldMatrix());const l=U.Vector3[5],c=U.Vector3[6],u=U.Quaternion[0];U.Matrix[7].decompose(c,u,l),D.ScalingToRef(c.x,c.y,c.z,U.Matrix[7]),U.Matrix[7].setTranslation(l),xe.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(u,l),this._localMatrix.setTranslation(l)),this._localMatrix.multiplyToRef(U.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const l=this.parent;l.getSkeleton().prepare(),this._localMatrix.multiplyToRef(l.getFinalMatrix(),U.Matrix[6]),U.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(r.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(t&&this.billboardMode)if(s.useBillboardPosition){const l=U.Vector3[0];this._worldMatrix.getTranslationToRef(l);const c=t.globalPosition;this._worldMatrix.invertToRef(U.Matrix[1]);const u=U.Vector3[1];p.TransformCoordinatesToRef(c,U.Matrix[1],u),u.normalize();const f=-Math.atan2(u.z,u.x)+Math.PI/2,d=Math.sqrt(u.x*u.x+u.z*u.z),_=-Math.atan2(u.y,d);if(re.RotationYawPitchRollToRef(f,_,0,U.Quaternion[0]),(this.billboardMode&xe.BILLBOARDMODE_ALL)!==xe.BILLBOARDMODE_ALL){const m=U.Vector3[1];U.Quaternion[0].toEulerAnglesToRef(m),(this.billboardMode&xe.BILLBOARDMODE_X)!==xe.BILLBOARDMODE_X&&(m.x=0),(this.billboardMode&xe.BILLBOARDMODE_Y)!==xe.BILLBOARDMODE_Y&&(m.y=0),(this.billboardMode&xe.BILLBOARDMODE_Z)!==xe.BILLBOARDMODE_Z&&(m.z=0),D.RotationYawPitchRollToRef(m.y,m.x,m.z,U.Matrix[0])}else D.FromQuaternionToRef(U.Quaternion[0],U.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(U.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(U.Vector3[0])}else{const l=U.Vector3[0];this._worldMatrix.getTranslationToRef(l),U.Matrix[1].copyFrom(t.getViewMatrix());const c=this.getScene().useRightHandedSystem;if(c&&U.Matrix[1].multiplyToRef(xe._TmpRHRestore,U.Matrix[1]),U.Matrix[1].setTranslationFromFloats(0,0,0),U.Matrix[1].invertToRef(U.Matrix[0]),(this.billboardMode&xe.BILLBOARDMODE_ALL)!==xe.BILLBOARDMODE_ALL){U.Matrix[0].decompose(void 0,U.Quaternion[0],void 0);const u=U.Vector3[1];U.Quaternion[0].toEulerAnglesToRef(u),(this.billboardMode&xe.BILLBOARDMODE_X)!==xe.BILLBOARDMODE_X&&(u.x=0),(this.billboardMode&xe.BILLBOARDMODE_Y)!==xe.BILLBOARDMODE_Y&&(u.y=0),(this.billboardMode&xe.BILLBOARDMODE_Z)!==xe.BILLBOARDMODE_Z&&(u.z=0),c&&(u.y+=Math.PI),D.RotationYawPitchRollToRef(u.y,u.x,u.z,U.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(U.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(U.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):r&&r._nonUniformScaling?this._updateNonUniformScalingState(r._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=D.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const t=this.getChildren();for(let i=0;i<t.length;++i){const s=t[i];if(s){s.computeWorldMatrix();const r=U.Matrix[0];s._localMatrix.multiplyToRef(this._localMatrix,r);const n=U.Quaternion[0];r.decompose(s.scaling,n,s.position),s.rotationQuaternion?s.rotationQuaternion.copyFrom(n):n.toEulerAnglesToRef(s.rotation)}}}this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=re.Identity()),this._worldMatrix=D.Identity()}_afterComputeWorldMatrix(){}registerAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this}unregisterAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this}getPositionInCameraSpace(e=null){return e||(e=this.getScene().activeCamera),p.TransformCoordinates(this.getAbsolutePosition(),e.getViewMatrix())}getDistanceToCamera(e=null){return e||(e=this.getScene().activeCamera),this.getAbsolutePosition().subtract(e.globalPosition).length()}clone(e,t,i){const s=me.Clone(()=>new xe(e,this.getScene()),this);if(s.name=e,s.id=e,t&&(s.parent=t),!i){const r=this.getDescendants(!0);for(let n=0;n<r.length;n++){const a=r[n];a.clone&&a.clone(e+"."+a.name,s)}}return s}serialize(e){const t=me.Serialize(this,e);return t.type=this.getClassName(),t.uniqueId=this.uniqueId,this.parent&&this.parent._serializeAsParent(t),t.localMatrix=this.getPivotMatrix().asArray(),t.isEnabled=this.isEnabled(),me.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t}static Parse(e,t,i){const s=me.Parse(()=>new xe(e.name,t),e,t,i);if(e.localMatrix?s.setPreTransformMatrix(D.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(D.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let r=0;r<e.animations.length;r++){const n=e.animations[r],a=Pi("BABYLON.Animation");a&&s.animations.push(a.Parse(n))}lt.ParseAnimationRanges(s,e,t)}return e.autoAnimate&&t.beginAnimation(s,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),s}getChildTransformNodes(e,t){const i=[];return this._getDescendants(i,e,s=>(!t||t(s))&&s instanceof xe),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const i=this._parentContainer.transformNodes.indexOf(this);i>-1&&this._parentContainer.transformNodes.splice(i,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const i=this.getChildTransformNodes(!0);for(const s of i)s.parent=null,s.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let s=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),a=n.max.subtract(n.min),h=Math.max(a.x,a.y,a.z);if(h===0)return this;const l=1/h;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&s&&this.rotation.copyFrom(s)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}xe.BILLBOARDMODE_NONE=0;xe.BILLBOARDMODE_X=1;xe.BILLBOARDMODE_Y=2;xe.BILLBOARDMODE_Z=4;xe.BILLBOARDMODE_ALL=7;xe.BILLBOARDMODE_USE_POSITION=128;xe.BillboardUseParentOrientation=!1;xe._TmpRotation=re.Zero();xe._TmpScaling=p.Zero();xe._TmpTranslation=p.Zero();xe._TmpRHRestore=D.Scaling(1,1,-1);xe._LookAtVectorCache=new p(0,0,0);xe._RotationAxisCache=new re;M([Ut("position")],xe.prototype,"_position",void 0);M([Ut("rotation")],xe.prototype,"_rotation",void 0);M([gu("rotationQuaternion")],xe.prototype,"_rotationQuaternion",void 0);M([Ut("scaling")],xe.prototype,"_scaling",void 0);M([C("billboardMode")],xe.prototype,"_billboardMode",void 0);M([C()],xe.prototype,"scalingDeterminant",void 0);M([C("infiniteDistance")],xe.prototype,"_infiniteDistance",void 0);M([C()],xe.prototype,"ignoreNonUniformScaling",void 0);M([C()],xe.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class Ng{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new p(0,0,0),this._diffPositionForCollisions=new p(0,0,0),this._collisionResponse=!0}}function Ug(o,e,t){let i;switch(e){case S.PositionKind:i=s=>s.getPositions();break;case S.NormalKind:i=s=>s.getNormals();break;case S.TangentKind:i=s=>s.getTangents();break;case S.UVKind:i=s=>s.getUVs();break;case S.UV2Kind:i=s=>s.getUV2s();break;case S.ColorKind:i=s=>s.getColors();break;default:return}for(let s=0;s<o.length;s++){let r=o[s];for(let n=0;n<t.numTargets;n++){const a=t.getTarget(n),h=a.influence;if(h!==0){const l=i(a);l&&(r+=(l[s]-o[s])*h)}}o[s]=r}}function kg(o,e,t,i,s,r,n){const a=U.Vector3[0],h=U.Matrix[0],l=U.Matrix[1],c=e===S.NormalKind?p.TransformNormalFromFloatsToRef:p.TransformCoordinatesFromFloatsToRef;for(let u=0,f=0;u<o.length;u+=3,f+=4){h.reset();let d,_;for(d=0;d<4;d++)_=s[f+d],_>0&&(D.FromFloat32ArrayToRefScaled(t,Math.floor(i[f+d]*16),_,l),h.addToSelf(l));if(r&&n)for(d=0;d<4;d++)_=n[f+d],_>0&&(D.FromFloat32ArrayToRefScaled(t,Math.floor(r[f+d]*16),_,l),h.addToSelf(l));c(o[u],o[u+1],o[u+2],h,a),a.toArray(o,u)}}class Vg{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=p.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class zg{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Vg,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=new Map,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new Ng,this._enableDistantPicking=!1,this._rawBoundingInfo=null,this._sideOrientationHint=!1,this._wasActiveLastFrame=!1}}class At extends xe{static get BILLBOARDMODE_NONE(){return xe.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return xe.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return xe.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return xe.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return xe.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return xe.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return super._updateNonUniformScalingState(e)?(this._markSubMeshesAsMiscDirty(),!0):!1}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;const t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(t===1&&e!==1||t!==1&&e===1)&&this._markSubMeshesAsDirty(i=>{i.markAsMiscDirty(),i.markAsPrePassDirty()})}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._setMaterial(e)}_setMaterial(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(void 0,e==null),this._unBindEffect()))}getMaterialForRenderPass(e){return this._internalAbstractMeshDataInfo._materialForRenderPass?.[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]);const i=this._internalAbstractMeshDataInfo._materialForRenderPass[e];i?.meshMap?.[this.uniqueId]&&(i.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t,t&&t.meshMap&&(t.meshMap[this.uniqueId]=this)}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new zg,this._waitingMaterialId=null,this._waitingMorphTargetManagerId=null,this._waitingSkeletonId=null,this._waitingSkeletonUniqueId=null,this.cullingStrategy=At.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new z,this.onCollisionPositionChangeObservable=new z,this.onMaterialChangedObservable=new z,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this.isPickable=!0,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=Re.Red(),this.outlineWidth=.02,this.overlayColor=Re.Red(),this.overlayAlpha=.5,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.alwaysSelectAsActiveMesh=!1,this.doNotSyncBoundingInfo=!1,this.actionManager=null,this.ellipsoid=new p(.5,1,.5),this.ellipsoidOffset=new p(0,0,0),this.edgesWidth=1,this.edgesColor=new Ce(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new z,this._onCollisionPositionChange=(i,s,r=null)=>{s.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>J.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),r&&this.onCollideObservable.notifyObservers(r),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},t=this.getScene(),t.addMesh(this),this._resyncLightSources(),this._uniformBuffer=new oe(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case 2:this.doNotSyncBoundingInfo=!0;case 1:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1;break}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){const t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()}getMeshUniformBuffer(){return this._uniformBuffer}getClassName(){return"AbstractMesh"}toString(e){let t="Name: "+this.name+", isInstance: "+(this.getClassName()==="InstancedMesh"?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);const i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==xe.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive))if(e){if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}else return this.actionManager;return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_releaseRenderPassId(e){}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),this._occlusionQuery!==null&&(this._occlusionQuery=null),!!this.subMeshes){for(const t of this.subMeshes)t._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let s=!1;if(i===-1){if(!t)return;this._lightSources.push(e)}else{if(t)return;s=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(s)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);i!==-1&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;i<t._drawWrappers.length;++i){const s=t._drawWrappers[i];!s||!s.defines||!s.defines.markAllAsDirty||e(s.defines)}}_markSubMeshesAsLightDirty(e=!1){this._markSubMeshesAsDirty(t=>t.markAsLightDirty(e))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty(e=>e.markAsAttributesDirty())}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty(e=>e.markAsMiscDirty())}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,super.markAsDirty(e),this._isDirty=!0,this}resetDrawCache(e,t=!1){if(this.subMeshes)for(const i of this.subMeshes)i.resetDrawCache(e,t)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,s){return this}updateVerticesData(e,t,i,s){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return this._boundingInfo!==null}buildBoundingInfo(e,t,i){return this._boundingInfo=new wt(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(S.MatricesIndicesKind)&&this.isVerticesDataPresent(S.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===xe.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){const s=new D;(this.rotationQuaternion?this.rotationQuaternion:re.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const n=p.Zero(),a=this.definedFacingForward?-1:1;return p.TransformCoordinatesFromFloatsToRef(e*a,t,i*a,s,n),n}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const s=this.definedFacingForward?1:-1;return new p(e*s,t,i*s)}_refreshBoundingInfo(e,t){if(e){const i=to(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new wt(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i<this.subMeshes.length;i++)this.subMeshes[i].refreshBoundingInfo(e);this._updateBoundingInfo()}_refreshBoundingInfoDirect(e){if(this._boundingInfo?this._boundingInfo.reConstruct(e.minimum,e.maximum):this._boundingInfo=new wt(e.minimum,e.maximum),this.subMeshes)for(let t=0;t<this.subMeshes.length;t++)this.subMeshes[t].refreshBoundingInfo(null);this._updateBoundingInfo()}static _ApplySkeleton(e,t,i,s,r,n,a){kg(e,t,i,s,r,n,a)}_getData(e,t,i=S.PositionKind){const s=e.cache,r=n=>{if(s){const a=s._vertexData||(s._vertexData={});return a[n]||this.copyVerticesData(n,a),a[n]}return this.getVerticesData(n)};if(t||(t=r(i)),!t)return null;if(s?(s._outputData?s._outputData.set(t):s._outputData=new Float32Array(t),t=s._outputData):(e.applyMorph&&this.morphTargetManager||e.applySkeleton&&this.skeleton)&&(t=t.slice()),e.applyMorph&&this.morphTargetManager&&Ug(t,i,this.morphTargetManager),e.applySkeleton&&this.skeleton){const n=r(S.MatricesIndicesKind),a=r(S.MatricesWeightsKind);if(a&&n){const h=this.numBoneInfluencers>4,l=h?r(S.MatricesIndicesExtraKind):null,c=h?r(S.MatricesWeightsExtraKind):null,u=this.skeleton.getTransformMatrices(this);At._ApplySkeleton(t,i,u,n,a,l,c)}}if(e.updatePositionsArray!==!1&&i===S.PositionKind){const n=this._internalAbstractMeshDataInfo._positions||[],a=n.length;if(n.length=t.length/3,a<n.length)for(let h=a;h<n.length;h++)n[h]=new p;for(let h=0,l=0;h<n.length;h++,l+=3)n[h].copyFromFloats(t[l],t[l+1],t[l+2]);this._internalAbstractMeshDataInfo._positions=n}return t}getNormalsData(e=!1,t=!1){return this._getData({applySkeleton:e,applyMorph:t,updatePositionsArray:!1},null,S.NormalKind)}getPositionData(e=!1,t=!1,i=null){return this._getData({applySkeleton:e,applyMorph:t,updatePositionsArray:!1},i,S.PositionKind)}_updateBoundingInfo(){return this._boundingInfo?this._boundingInfo.update(this.worldMatrixFromCache):this._boundingInfo=new wt(p.Zero(),p.Zero(),this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}_updateSubMeshesBoundingInfo(e){if(!this.subMeshes)return this;const t=this.subMeshes.length;for(let i=0;i<t;i++){const s=this.subMeshes[i];(t>1||!s.IsGlobal)&&s.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const s=this.getBoundingInfo(),r=e.getBoundingInfo();if(s.intersects(r,t))return!0;if(i){for(const n of this.getChildMeshes())if(n.intersectsMesh(e,t,!0))return!0}return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e,t=!0){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);const s=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=s.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,s.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId,t),this}_collideForSubMesh(e,t,i){if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const s=e.verticesStart,r=e.verticesStart+e.verticesCount;for(let n=s;n<r;n++)e._lastColliderWorldVertices.push(p.TransformCoordinates(this._positions[n],t))}return i._collide(e._trianglePlanes,e._lastColliderWorldVertices,this.getIndices(),e.indexStart,e.indexStart+e.indexCount,e.verticesStart,!!e.getMaterial(),this,this._shouldConvertRHS(),e.getMaterial()?.fillMode===7),this}_processCollisionsForSubMeshes(e,t){const i=this._scene.getCollidingSubMeshCandidates(this,e),s=i.length;for(let r=0;r<s;r++){const n=i.data[r];s>1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=U.Matrix[0],i=U.Matrix[1];return D.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,s=!1,r,n=!1){const a=new Zs,h=this.getClassName(),l=h==="InstancedLinesMesh"||h==="LinesMesh"||h==="GreasedLineMesh"?this.intersectionThreshold:0,c=this.getBoundingInfo();if(!this.subMeshes||!n&&(!e.intersectsSphere(c.boundingSphere,l)||!e.intersectsBox(c.boundingBox,l)))return a;if(s)return a.hit=!n,a.pickedMesh=n?null:this,a.distance=n?0:p.Distance(e.origin,c.boundingSphere.center),a.subMeshId=0,a;if(!this._generatePointsArray())return a;let u=null;const f=this._scene.getIntersectingSubMeshCandidates(this,e),d=f.length;let _=!1;for(let m=0;m<d;m++){const T=f.data[m].getMaterial();if(T&&(T.fillMode==7||T.fillMode==0||T.fillMode==1||T.fillMode==2||T.fillMode==4)){_=!0;break}}if(!_)return a.hit=!0,a.pickedMesh=this,a.distance=p.Distance(e.origin,c.boundingSphere.center),a.subMeshId=-1,a;for(let m=0;m<d;m++){const g=f.data[m];if(d>1&&!n&&!g.canIntersects(e))continue;const T=g.intersects(e,this._positions,this.getIndices(),t,i);if(T&&(t||!u||T.distance<u.distance)&&(u=T,u.subMeshId=g._id,u._internalSubMeshId=m,t))break}if(u){const m=r??this.getWorldMatrix(),g=U.Vector3[0],T=U.Vector3[1];p.TransformCoordinatesToRef(e.origin,m,g),e.direction.scaleToRef(u.distance,T);const A=p.TransformNormal(T,m).addInPlace(g);return a.hit=!0,a.distance=p.Distance(g,A),a.pickedPoint=A,a.pickedMesh=this,a.bu=u.bu||0,a.bv=u.bv||0,a.subMeshFaceId=u.faceId,a.faceId=u.faceId+f.data[u._internalSubMeshId].indexStart/(this.getClassName().indexOf("LinesMesh")!==-1?2:3),a.subMeshId=u.subMeshId,a}return a}clone(e,t,i){return null}releaseSubMeshes(e=!1){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose(e);else this.subMeshes=[];return this}dispose(e,t=!1){let i;const s=this.getScene();for(this._scene.useMaterialMeshMap&&this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),s.freeActiveMeshes(),s.freeRenderingGroups(),s.renderingManager.maintainStateBetweenFrames&&s.renderingManager.restoreDispachedFlags(),this.actionManager!==void 0&&this.actionManager!==null&&(this.actionManager.disposeWhenUnowned&&!this._scene.meshes.some(a=>a!==this&&a.actionManager===this.actionManager)&&this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i<this._intersectionsInProgress.length;i++){const a=this._intersectionsInProgress[i],h=a._intersectionsInProgress.indexOf(this);a._intersectionsInProgress.splice(h,1)}this._intersectionsInProgress.length=0;const r=s.lights;for(const a of r){let h=a.includedOnlyMeshes.indexOf(this);h!==-1&&a.includedOnlyMeshes.splice(h,1),h=a.excludedMeshes.indexOf(this),h!==-1&&a.excludedMeshes.splice(h,1);const l=a.getShadowGenerators();if(l){const c=l.values();for(let u=c.next();u.done!==!0;u=c.next()){const d=u.value.getShadowMap();d&&d.renderList&&(h=d.renderList.indexOf(this),h!==-1&&d.renderList.splice(h,1))}}}(this.getClassName()!=="InstancedMesh"||this.getClassName()!=="InstancedLinesMesh")&&this.releaseSubMeshes(!0);const n=s.getEngine();if(this._occlusionQuery!==null&&(this.isOcclusionQueryInProgress=!1,n.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),n.wipeCaches(),s.removeMesh(this),this._parentContainer){const a=this._parentContainer.meshes.indexOf(this);a>-1&&this._parentContainer.meshes.splice(a,1),this._parentContainer=null}if(t&&this.material&&(this.material.getClassName()==="MultiMaterial"?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i<s.particleSystems.length;i++)s.particleSystems[i].emitter===this&&(s.particleSystems[i].dispose(),i--);this._internalAbstractMeshDataInfo._facetData.facetDataEnabled&&this.disableFacetData(),this._uniformBuffer.dispose(),this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this.onRebuildObservable.clear(),super.dispose(e,t)}_initFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;e.facetNormals||(e.facetNormals=[]),e.facetPositions||(e.facetPositions=[]),e.facetPartitioning||(e.facetPartitioning=new Array),e.facetNb=this.getIndices().length/3|0,e.partitioningSubdivisions=e.partitioningSubdivisions?e.partitioningSubdivisions:10,e.partitioningBBoxRatio=e.partitioningBBoxRatio?e.partitioningBBoxRatio:1.01;for(let t=0;t<e.facetNb;t++)e.facetNormals[t]=p.Zero(),e.facetPositions[t]=p.Zero();return e.facetDataEnabled=!0,this}updateFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;e.facetDataEnabled||this._initFacetData();const t=this.getVerticesData(S.PositionKind),i=this.getIndices(),s=this.getVerticesData(S.NormalKind)?.slice(),r=this.getBoundingInfo();if(e.facetDepthSort&&!e.facetDepthSortEnabled){if(e.facetDepthSortEnabled=!0,i instanceof Uint16Array)e.depthSortedIndices=new Uint16Array(i);else if(i instanceof Uint32Array)e.depthSortedIndices=new Uint32Array(i);else{let a=!1;for(let h=0;h<i.length;h++)if(i[h]>65535){a=!0;break}a?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(a,h){return h.sqDistance-a.sqDistance},!e.facetDepthSortFrom){const a=this.getScene().activeCamera;e.facetDepthSortFrom=a?a.position:p.Zero()}e.depthSortedFacets=[];for(let a=0;a<e.facetNb;a++){const h={ind:a*3,sqDistance:0};e.depthSortedFacets.push(h)}e.invertedMatrix=D.Identity(),e.facetDepthSortOrigin=p.Zero()}e.bbSize.x=r.maximum.x-r.minimum.x>Ke?r.maximum.x-r.minimum.x:Ke,e.bbSize.y=r.maximum.y-r.minimum.y>Ke?r.maximum.y-r.minimum.y:Ke,e.bbSize.z=r.maximum.z-r.minimum.z>Ke?r.maximum.z-r.minimum.z:Ke;let n=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(n=n>e.bbSize.z?n:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/n),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/n),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/n),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=r,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),p.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&j.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const a=e.depthSortedIndices.length/3|0;for(let h=0;h<a;h++){const l=e.depthSortedFacets[h].ind;e.depthSortedIndices[h*3]=i[l],e.depthSortedIndices[h*3+1]=i[l+1],e.depthSortedIndices[h*3+2]=i[l+2]}this.updateIndices(e.depthSortedIndices,void 0,!0)}return this}getFacetLocalNormals(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetNormals||this.updateFacetData(),e.facetNormals}getFacetLocalPositions(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetPositions||this.updateFacetData(),e.facetPositions}getFacetLocalPartitioning(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetPartitioning||this.updateFacetData(),e.facetPartitioning}getFacetPosition(e){const t=p.Zero();return this.getFacetPositionToRef(e,t),t}getFacetPositionToRef(e,t){const i=this.getFacetLocalPositions()[e],s=this.getWorldMatrix();return p.TransformCoordinatesToRef(i,s,t),this}getFacetNormal(e){const t=p.Zero();return this.getFacetNormalToRef(e,t),t}getFacetNormalToRef(e,t){const i=this.getFacetLocalNormals()[e];return p.TransformNormalToRef(i,this.getWorldMatrix(),t),this}getFacetsAtLocalCoordinates(e,t,i){const s=this.getBoundingInfo(),r=this._internalAbstractMeshDataInfo._facetData,n=Math.floor((e-s.minimum.x*r.partitioningBBoxRatio)*r.subDiv.X*r.partitioningBBoxRatio/r.bbSize.x),a=Math.floor((t-s.minimum.y*r.partitioningBBoxRatio)*r.subDiv.Y*r.partitioningBBoxRatio/r.bbSize.y),h=Math.floor((i-s.minimum.z*r.partitioningBBoxRatio)*r.subDiv.Z*r.partitioningBBoxRatio/r.bbSize.z);return n<0||n>r.subDiv.max||a<0||a>r.subDiv.max||h<0||h>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*a+r.subDiv.max*r.subDiv.max*h]}getClosestFacetAtCoordinates(e,t,i,s,r=!1,n=!0){const a=this.getWorldMatrix(),h=U.Matrix[5];a.invertToRef(h);const l=U.Vector3[8];p.TransformCoordinatesFromFloatsToRef(e,t,i,h,l);const c=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,s,r,n);return s&&p.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,a,s),c}getClosestFacetAtLocalCoordinates(e,t,i,s,r=!1,n=!0){let a=null,h,l,c,u,f,d,_,m;const g=this.getFacetLocalPositions(),T=this.getFacetLocalNormals(),R=this.getFacetsAtLocalCoordinates(e,t,i);if(!R)return null;let A=Number.MAX_VALUE,y,E,x,b;for(let P=0;P<R.length;P++)E=R[P],x=T[E],b=g[E],u=(e-b.x)*x.x+(t-b.y)*x.y+(i-b.z)*x.z,(!r||r&&n&&u>=0||r&&!n&&u<=0)&&(u=x.x*b.x+x.y*b.y+x.z*b.z,f=-(x.x*e+x.y*t+x.z*i-u)/(x.x*x.x+x.y*x.y+x.z*x.z),d=e+x.x*f,_=t+x.y*f,m=i+x.z*f,h=d-e,l=_-t,c=m-i,y=h*h+l*l+c*c,y<A&&(A=y,a=E,s&&(s.x=d,s.y=_,s.z=m)));return a}getFacetDataParameters(){return this._internalAbstractMeshDataInfo._facetData.facetParameters}disableFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetDataEnabled&&(e.facetDataEnabled=!1,e.facetPositions=[],e.facetNormals=[],e.facetPartitioning=new Array,e.facetParameters={},e.depthSortedIndices=new Uint32Array(0)),this}updateIndices(e,t,i=!1){return this}createNormals(e){const t=this.getVerticesData(S.PositionKind),i=this.getIndices();let s;return this.isVerticesDataPresent(S.NormalKind)?s=this.getVerticesData(S.NormalKind):s=[],j.ComputeNormals(t,i,s,{useRightHandedSystem:this.getScene().useRightHandedSystem}),this.setVerticesData(S.NormalKind,s,e),this}async optimizeIndicesAsync(){const e=this.getIndices();if(!e)return this;const{OptimizeIndices:t}=await he(async()=>{const{OptimizeIndices:i}=await import("./mesh.vertexData.functions-BXkNVxNr.js").then(s=>s.m);return{OptimizeIndices:i}},[],import.meta.url);return t(e),this.setIndices(e,this.getTotalVertices()),this}alignWithNormal(e,t){t||(t=Vi.Y);const i=U.Vector3[0],s=U.Vector3[1];return p.CrossToRef(t,e,s),p.CrossToRef(e,s,i),this.rotationQuaternion?re.RotationQuaternionFromAxisToRef(i,e,s,this.rotationQuaternion):p.RotationFromAxisToRef(i,e,s,this.rotation),this}_checkOcclusionQuery(e=!1){return!1}disableEdgesRendering(){throw pe("EdgesRenderer")}enableEdgesRendering(e,t,i){throw pe("EdgesRenderer")}getConnectedParticleSystems(){return this._scene.particleSystems.filter(e=>e.emitter===this)}}At.OCCLUSION_TYPE_NONE=0;At.OCCLUSION_TYPE_OPTIMISTIC=1;At.OCCLUSION_TYPE_STRICT=2;At.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0;At.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1;At.CULLINGSTRATEGY_STANDARD=0;At.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;At.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;At.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;M([_i.filter((...[o,e,t,i,s])=>!Array.isArray(o)&&!Array.isArray(e)&&!Array.isArray(t)&&!Array.isArray(i)&&!Array.isArray(s))],At,"_ApplySkeleton",null);Ye("BABYLON.AbstractMesh",At);class Rs extends V{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...s)=>{const r=t.apply(e,s);return this._markAllSubMeshesAsTexturesDirty(),r};const i=e.splice;e.splice=(s,r)=>{const n=i.apply(e,[s,r]);return this._markAllSubMeshesAsTexturesDirty(),n}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map(e=>e?e.getActiveTextures():[]))}hasTexture(e){if(super.hasTexture(e))return!0;for(let t=0;t<this.subMaterials.length;t++)if(this.subMaterials[t]?.hasTexture(e))return!0;return!1}getClassName(){return"MultiMaterial"}isReadyForSubMesh(e,t,i){for(let s=0;s<this.subMaterials.length;s++){const r=this.subMaterials[s];if(r){if(r._storeEffectOnSubMeshes){if(!r.isReadyForSubMesh(e,t,i))return!1;continue}if(!r.isReady(e))return!1}}return!0}clone(e,t){const i=new Rs(e,this.getScene());for(let s=0;s<this.subMaterials.length;s++){let r;const n=this.subMaterials[s];t&&n?r=n.clone(e+"-"+n.name):r=this.subMaterials[s],i.subMaterials.push(r)}return i}serialize(){const e={};e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,Le&&(e.tags=Le.GetTags(this)),e.materialsUniqueIds=[],e.materials=[];for(let t=0;t<this.subMaterials.length;t++){const i=this.subMaterials[t];i?(e.materialsUniqueIds.push(i.uniqueId),e.materials.push(i.id)):(e.materialsUniqueIds.push(null),e.materials.push(null))}return e}dispose(e,t,i){const s=this.getScene();if(!s)return;if(i)for(let n=0;n<this.subMaterials.length;n++){const a=this.subMaterials[n];a&&a.dispose(e,t)}const r=s.multiMaterials.indexOf(this);r>=0&&s.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new Rs(e.name,t);if(i.id=e.id,i._loadedUniqueId=e.uniqueId,Le&&Le.AddTagsTo(i,e.tags),e.materialsUniqueIds)i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds;else for(const s of e.materials)i.subMaterials.push(t.getLastMaterialById(s));return i}}Ye("BABYLON.MultiMaterial",Rs);class Wg{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class Bc{}class Bh{constructor(){this.batchCache=new Nh(this),this.batchCacheReplacementModeInFrozenMode=new Nh(this),this.instancesBufferSize=32*16*4}}class Gg{constructor(){this.renderPasses={}}}class Nh{constructor(e){this.parent=e,this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class Hg{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=32*16,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class Xg{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}}const li={source:null,parent:null,doNotCloneChildren:!1,clonePhysicsImpostor:!0,cloneThinInstances:!1};class F extends At{static _GetDefaultSideOrientation(e){return e||F.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(S.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(S.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new z),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new z),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new z),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new z),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new z),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get sideOrientation(){return this._internalMeshDataInfo._sideOrientation}set sideOrientation(e){this._internalMeshDataInfo._sideOrientation=e,this._internalAbstractMeshDataInfo._sideOrientationHint=this._scene.useRightHandedSystem&&e===1||!this._scene.useRightHandedSystem&&e===0}get _effectiveSideOrientation(){return this._internalMeshDataInfo._effectiveSideOrientation}get overrideMaterialSideOrientation(){return this.sideOrientation}set overrideMaterialSideOrientation(e){this.sideOrientation=e,this.material&&(this.material.sideOrientation=null)}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){e&&(this.material&&this.material.sideOrientation===null||this._internalAbstractMeshDataInfo._sideOrientationHint)&&(e.sideOrientation=null),this._setMaterial(e)}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){const e=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._instanceDataStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId];return e?e.instancesData:void 0}get previousWorldMatrixInstancedBuffer(){const e=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._instanceDataStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId];return e?e.instancesPreviousData:void 0}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}_copySource(e,t,i=!0,s=!1){const r=this.getScene();if(e._geometry&&e._geometry.applyToMesh(this),Na.DeepCopy(e,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=e,r.useClonedMeshMap&&(e._internalMeshDataInfo.meshMap||(e._internalMeshDataInfo.meshMap={}),e._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=e._originalBuilderSideOrientation,this._creationDataStorage=e._creationDataStorage,e._ranges){const n=e._ranges;for(const a in n)Object.prototype.hasOwnProperty.call(n,a)&&n[a]&&this.createAnimationRange(a,n[a].from,n[a].to)}if(e.metadata&&e.metadata.clone?this.metadata=e.metadata.clone():this.metadata=e.metadata,this._internalMetadata=e._internalMetadata,Le&&Le.HasTags(e)&&Le.AddTagsTo(this,Le.GetTags(e,!0)),this.setEnabled(e.isEnabled(!1)),this.parent=e.parent,this.setPivotMatrix(e.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=this.name+"."+e.id,this.material=e.material,!t){const n=e.getDescendants(!0);for(let a=0;a<n.length;a++){const h=n[a];h._isMesh?(li.parent=this,li.doNotCloneChildren=t,li.clonePhysicsImpostor=i,li.cloneThinInstances=s,h.clone(this.name+"."+h.name,li)):h.clone&&h.clone(this.name+"."+h.name,this)}}if(e.morphTargetManager&&(this.morphTargetManager=e.morphTargetManager),r.getPhysicsEngine){const n=r.getPhysicsEngine();if(i&&n)if(n.getPluginVersion()===1){const a=n.getImpostorForPhysicsObject(e);a&&(this.physicsImpostor=a.clone(this))}else n.getPluginVersion()===2&&e.physicsBody&&e.physicsBody.clone(this)}for(let n=0;n<r.particleSystems.length;n++){const a=r.particleSystems[n];a.emitter===e&&a.clone(a.name,this)}if(this.skeleton=e.skeleton,s&&(e._thinInstanceDataStorage.matrixData?(this.thinInstanceSetBuffer("matrix",new Float32Array(e._thinInstanceDataStorage.matrixData),16,!e._thinInstanceDataStorage.matrixBuffer.isUpdatable()),this._thinInstanceDataStorage.matrixBufferSize=e._thinInstanceDataStorage.matrixBufferSize,this._thinInstanceDataStorage.instancesCount=e._thinInstanceDataStorage.instancesCount):this._thinInstanceDataStorage.matrixBufferSize=e._thinInstanceDataStorage.matrixBufferSize,e._userThinInstanceBuffersStorage)){const n=e._userThinInstanceBuffersStorage;for(const a in n.data)this.thinInstanceSetBuffer(a,new Float32Array(n.data[a]),n.strides[a],!n.vertexBuffers?.[a]?.isUpdatable()),this._userThinInstanceBuffersStorage.sizes[a]=n.sizes[a]}this.refreshBoundingInfo(!0,!0),this.computeWorldMatrix(!0)}constructor(e,t=null,i=null,s=null,r,n=!0){super(e,t),this._internalMeshDataInfo=new Xg,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._thinInstanceDataStorage=new Hg,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=F.DEFAULTSIDE,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._instanceDataStorage=new Gg,this._instanceDataStorage.engine=t.getEngine(),this._instanceDataStorage.useMonoDataStorageRenderPass=!this._instanceDataStorage.engine.isWebGPU,this._instanceDataStorage.useMonoDataStorageRenderPass&&(this._instanceDataStorage.dataStorageRenderPass=new Bh),this._scene.useRightHandedSystem?this.sideOrientation=0:this.sideOrientation=1,this._onBeforeDraw=(l,c,u)=>{l&&u&&(this._uniformBuffer?this.transferToEffect(c):u.bindOnlyWorldMatrix(c))};let a,h=!1;if(i&&i._addToSceneRootNodes===void 0){const l=i;a=l.parent??null,s=l.source??null,r=l.doNotCloneChildren??!1,n=l.clonePhysicsImpostor??!0,h=l.cloneThinInstances??!1}else a=i;s&&this._copySource(s,r,n,h),a!==null&&(this.parent=a),this._instanceDataStorage.hardwareInstancedRendering=this.getEngine().getCaps().instancedArrays,this._internalMeshDataInfo._onMeshReadyObserverAdded=l=>{l.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add(()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))}))},this.onMeshReadyObservable=new z(this._internalMeshDataInfo._onMeshReadyObserverAdded),s&&s.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const s=this.getTotalVertices()===0||t&&t.doNotInstantiate&&(t.doNotInstantiate===!0||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));s.parent=e||this.parent,s.position=this.position.clone(),s.scaling=this.scaling.clone(),this.rotationQuaternion?s.rotationQuaternion=this.rotationQuaternion.clone():s.rotation=this.rotation.clone(),i&&i(this,s);for(const r of this.getChildTransformNodes(!0))r.getClassName()==="InstancedMesh"&&s.getClassName()==="Mesh"&&r.sourceMesh===this?r.instantiateHierarchy(s,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:s},i):r.instantiateHierarchy(s,t,i);return s}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);if(e)if(this._geometry){const i=this.getIndices(),s=this.getVerticesData(S.PositionKind);s&&i&&(t+=", flat shading: "+(s.length/3===i.length?"YES":"NO"))}else t+=", flat shading: UNKNOWN";return t}_unBindEffect(){super._unBindEffect();for(const e of this.instances)e._unBindEffect()}get hasLODLevels(){return this._internalMeshDataInfo._LODLevels.length>0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,i)=>t.distanceOrScreenCoverage<i.distanceOrScreenCoverage?e:t.distanceOrScreenCoverage>i.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return W.Warn("You cannot use a mesh as LOD level twice"),this;const i=new Wg(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let i=0;i<t._LODLevels.length;i++){const s=t._LODLevels[i];if(s.distanceOrScreenCoverage===e)return s.mesh}return null}removeLODLevel(e){const t=this._internalMeshDataInfo;for(let i=0;i<t._LODLevels.length;i++)t._LODLevels[i].mesh===e&&(t._LODLevels.splice(i,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this}getLOD(e,t){const i=this._internalMeshDataInfo;if(!i._LODLevels||i._LODLevels.length===0)return this;const s=t||this.getBoundingInfo().boundingSphere,r=e.mode===be.ORTHOGRAPHIC_CAMERA?e.minZ:s.centerWorld.subtract(e.globalPosition).length();let n=r,a=1;if(i._useLODScreenCoverage){const h=e.screenArea;let l=s.radiusWorld*e.minZ/r;l=l*l*Math.PI,n=l/h,a=-1}if(a*i._LODLevels[i._LODLevels.length-1].distanceOrScreenCoverage>a*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let h=0;h<i._LODLevels.length;h++){const l=i._LODLevels[h];if(a*l.distanceOrScreenCoverage<a*n){if(l.mesh){if(l.mesh.delayLoadState===4)return l.mesh._checkDelayState(),this;if(l.mesh.delayLoadState===2)return this;l.mesh._preActivate(),l.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)}return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,l.mesh),l.mesh}}return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this}get geometry(){return this._geometry}getTotalVertices(){return this._geometry===null||this._geometry===void 0?0:this._geometry.getTotalVertices()}getVerticesData(e,t,i,s){if(!this._geometry)return null;let r=s?void 0:this._userInstancedBuffersStorage?.vertexBuffers[e]?.getFloatData(this.instances.length+1,i||t&&this._geometry.meshes.length!==1);return r||(r=this._geometry.getVerticesData(e,t,i)),r}copyVerticesData(e,t){this._geometry&&this._geometry.copyVerticesData(e,t)}getVertexBuffer(e,t){return this._geometry?(t?void 0:this._userInstancedBuffersStorage?.vertexBuffers[e])??this._geometry.getVertexBuffer(e):null}isVerticesDataPresent(e,t){return this._geometry?!t&&this._userInstancedBuffersStorage?.vertexBuffers[e]!==void 0||this._geometry.isVerticesDataPresent(e):this._delayInfo?this._delayInfo.indexOf(e)!==-1:!1}isVertexBufferUpdatable(e,t){if(!this._geometry)return this._delayInfo?this._delayInfo.indexOf(e)!==-1:!1;if(!t){const i=this._userInstancedBuffersStorage?.vertexBuffers[e];if(i)return i.isUpdatable()}return this._geometry.isVertexBufferUpdatable(e)}getVerticesDataKinds(e){if(!this._geometry){const i=[];if(this._delayInfo)for(const s of this._delayInfo)i.push(s);return i}const t=this._geometry.getVerticesDataKinds();if(!e&&this._userInstancedBuffersStorage)for(const i in this._userInstancedBuffersStorage.vertexBuffers)t.indexOf(i)===-1&&t.push(i);return t}getTotalIndices(){return this._geometry?this._geometry.getTotalIndices():0}getIndices(e,t){return this._geometry?this._geometry.getIndices(e,t):[]}get isBlocked(){return this._masterMesh!==null&&this._masterMesh!==void 0}isReady(e=!1,t=!1){if(this.delayLoadState===2||!super.isReady(e))return!1;if(!this.subMeshes||this.subMeshes.length===0||!e)return!0;const i=this.getEngine(),s=this.getScene(),r=t||i.getCaps().instancedArrays&&(this.instances.length>0||this.hasThinInstances);this.computeWorldMatrix();const n=this.material||s.defaultMaterial;if(n){if(n._storeEffectOnSubMeshes)for(const h of this.subMeshes){const l=h.getMaterial();if(l){if(l._storeEffectOnSubMeshes){if(!l.isReadyForSubMesh(this,h,r))return!1}else if(!l.isReady(this,r))return!1}}else if(!n.isReady(this,r))return!1}const a=i.currentRenderPassId;for(const h of this.lightSources){const l=h.getShadowGenerators();if(!l)continue;const c=l.values();for(let u=c.next();u.done!==!0;u=c.next()){const f=u.value;if(f&&(!f.getShadowMap()?.renderList||f.getShadowMap()?.renderList&&f.getShadowMap()?.renderList?.indexOf(this)!==-1)){const _=f.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let m=0;m<_.length;++m){i.currentRenderPassId=_[m];for(const g of this.subMeshes)if(!f.isReady(g,r,g.getMaterial()?.needAlphaBlendingForMesh(this)??!1))return i.currentRenderPassId=a,!1}i.currentRenderPassId=a}}}for(const h of this._internalMeshDataInfo._LODLevels)if(h.mesh&&!h.mesh.isReady(r))return!1;return!0}get areNormalsFrozen(){return this._internalMeshDataInfo._areNormalsFrozen}freezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!0,this}unfreezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!1,this}set overridenInstanceCount(e){this._instanceDataStorage.overridenInstanceCount=e}_getInstanceDataStorage(){if(this._instanceDataStorage.useMonoDataStorageRenderPass)return this._instanceDataStorage.dataStorageRenderPass;const e=this._instanceDataStorage.engine.currentRenderPassId;let t=this._instanceDataStorage.renderPasses[e];return t||(t=new Bh,this._instanceDataStorage.renderPasses[e]=t),t}_preActivate(){const e=this._internalMeshDataInfo,t=this.getScene().getRenderId();return e._preActivateId===t?this:(e._preActivateId=t,this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass.visibleInstances=null:this._getInstanceDataStorage().visibleInstances=null,this)}_preActivateForIntermediateRendering(e){const t=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._getInstanceDataStorage();return t.visibleInstances&&(t.visibleInstances.intermediateDefaultRenderId=e),this}_registerInstanceForRenderId(e,t){const i=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._getInstanceDataStorage();return i.visibleInstances||(i.visibleInstances={defaultRenderId:t,selfDefaultRenderId:this._renderId,intermediateDefaultRenderId:-1}),i.visibleInstances[t]||(i.previousRenderId!==void 0&&(!this._instanceDataStorage.useMonoDataStorageRenderPass||this._instanceDataStorage.isFrozen)&&delete i.visibleInstances[i.previousRenderId],i.previousRenderId=t,i.visibleInstances[t]=new Array),i.visibleInstances[t].push(e),this}_afterComputeWorldMatrix(){super._afterComputeWorldMatrix(),this.hasThinInstances&&(this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1))}_postActivate(){this.edgesShareWithInstances&&this.edgesRenderer&&this.edgesRenderer.isEnabled&&this._renderingGroup&&(this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer),this.edgesRenderer.customInstances.push(this.getWorldMatrix()))}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i;typeof e=="object"?i=e:i={applySkeleton:e,applyMorph:t};const s=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getData(i,null,S.PositionKind),s),this}_createGlobalSubMesh(e){const t=this.getTotalVertices();if(!t||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){const i=this.getIndices();if(!i)return null;const s=i.length;let r=!1;if(e)r=!0;else for(const n of this.subMeshes){if(n.indexStart+n.indexCount>s){r=!0;break}if(n.verticesStart+n.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new Kt(0,0,t,0,this.getTotalIndices()||(this.isUnIndexed?t:0),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,s=0;for(;i%3!==0;)i++;this.releaseSubMeshes();for(let r=0;r<e&&!(s>=t);r++)Kt.CreateFromIndices(0,s,s+i>=t?t-s:i,this,void 0,!1),s+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,s){if(this._geometry)this._geometry.setVerticesData(e,t,i,s);else{const r=new j;r.set(t,e);const n=this.getScene();new Rt(Rt.RandomId(),n,r,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const i=this.getVertexBuffer(e);!i||i.isUpdatable()===t||this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0,i=null){return this._geometry||(this._geometry=Rt.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,i,t),this}updateVerticesData(e,t,i,s){return this._geometry?(s?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(S.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(S.PositionKind,i,!1,!1),t){const s=this.getIndices(),r=this.getVerticesData(S.NormalKind);if(!r)return this;j.ComputeNormals(i,s,r),this.updateVerticesData(S.NormalKind,r,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(this._geometry.meshes.length===1)return this;const e=this._geometry,t=this._geometry.copy(Rt.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i,s=null){let r=this._geometry;r||(r=new Rt(Rt.RandomId(),this.getScene(),void 0,void 0,this)),r.setIndexBuffer(e,t,i,s)}setIndices(e,t=null,i=!1,s=!1){if(this._geometry)this._geometry.setIndices(e,t,i,s);else{const r=new j;r.indices=e;const n=this.getScene();new Rt(Rt.RandomId(),n,r,i,this,t)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,s=!0){if(!this._geometry)return this;const r=this.getScene().getEngine();let n;if(this._unIndexed)switch(this._getRenderingFillMode(i)){case V.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:n=null;break}else switch(this._getRenderingFillMode(i)){case V.PointFillMode:n=null;break;case V.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case V.TriangleFillMode:n=this._geometry.getIndexBuffer();break}return this._bindDirect(t,n,s)}_bindDirect(e,t,i=!0){if(!this._geometry)return this;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(e),!i||!this._userInstancedBuffersStorage||this.hasThinInstances)this._geometry._bind(e,t);else{if(!this._instanceDataStorage.useMonoDataStorageRenderPass&&this._userInstancedBuffersStorage.renderPasses&&this._userInstancedBuffersStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId]){const s=this._userInstancedBuffersStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId];for(const r in s)this._userInstancedBuffersStorage.vertexBuffers[r]=s[r]}this._geometry._bind(e,t,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const r=this.getScene().getEngine(),n=r._currentMaterialContext,a=n&&n.useVertexPulling;return this._unIndexed&&t!==V.WireFrameFillMode||t==V.PointFillMode?r.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==V.WireFrameFillMode?r.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):a?r.drawArraysType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i):r.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){const i=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._getInstanceDataStorage();if(this._instanceDataStorage.isFrozen){if(t)return i.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,i.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,i.batchCacheReplacementModeInFrozenMode;if(i.previousBatch)return i.previousBatch}const s=this.getScene(),r=s._isInIntermediateRendering(),n=r?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,a=i.batchCache;if(a.mustReturn=!1,a.renderSelf[e]=t||!n&&this.isEnabled()&&this.isVisible,a.visibleInstances[e]=null,i.visibleInstances&&!t){const h=i.visibleInstances,l=s.getRenderId(),c=r?h.intermediateDefaultRenderId:h.defaultRenderId;a.visibleInstances[e]=h[l],!a.visibleInstances[e]&&c&&(a.visibleInstances[e]=h[c])}return a.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&a.visibleInstances[e]!==null&&a.visibleInstances[e]!==void 0,i.previousBatch=a,a}_updateInstancedBuffers(e,t,i,s,r,n){const a=t.visibleInstances[e._id],h=a?a.length:0,l=t.parent,c=this._instanceDataStorage;let u=l.instancesBuffer,f=l.instancesPreviousBuffer,d=0,_=0;const m=t.renderSelf[e._id],g=this._scene.floatingOriginOffset,T=!u||i!==l.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!l.instancesPreviousBuffer;if(!this._instanceDataStorage.manualUpdate&&(!c.isFrozen||T)){const R=this.getWorldMatrix();if(m){this._scene.needsPreviousWorldMatrices&&(c.masterMeshPreviousWorldMatrix?(c.masterMeshPreviousWorldMatrix.copyToArray(l.instancesPreviousData,d),c.masterMeshPreviousWorldMatrix.copyFrom(R)):(c.masterMeshPreviousWorldMatrix=R.clone(),c.masterMeshPreviousWorldMatrix.copyToArray(l.instancesPreviousData,d))),R.copyToArray(l.instancesData,d);const A=R.asArray();l.instancesData[d+12]=A[12]-g.x,l.instancesData[d+13]=A[13]-g.y,l.instancesData[d+14]=A[14]-g.z,d+=16,_++}if(a){if(F.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&e.getMaterial()?.needAlphaBlendingForMesh(e.getRenderingMesh())){const A=this._scene.activeCamera.globalPosition;for(let y=0;y<a.length;y++){const E=a[y];E._distanceToCamera=p.Distance(E.getBoundingInfo().boundingSphere.centerWorld,A)}a.sort((y,E)=>y._distanceToCamera>E._distanceToCamera?-1:y._distanceToCamera<E._distanceToCamera?1:0)}for(let A=0;A<a.length;A++){const y=a[A],E=y.getWorldMatrix();E.copyToArray(l.instancesData,d),this._scene.needsPreviousWorldMatrices&&(y._previousWorldMatrix?(y._previousWorldMatrix.copyToArray(l.instancesPreviousData,d),y._previousWorldMatrix.copyFrom(E)):(y._previousWorldMatrix=E.clone(),y._previousWorldMatrix.copyToArray(l.instancesPreviousData,d)));const x=E.asArray();l.instancesData[d+12]=x[12]-g.x,l.instancesData[d+13]=x[13]-g.y,l.instancesData[d+14]=x[14]-g.z,d+=16,_++}}}else _=(m?1:0)+h;if(T){u&&u.dispose(),f&&f.dispose(),u=new Vr(s,l.instancesData,!0,16,!1,!0),l.instancesBuffer=u,this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0});let R;if(this._instanceDataStorage.useMonoDataStorageRenderPass)R=this._userInstancedBuffersStorage.vertexBuffers;else{this._userInstancedBuffersStorage.renderPasses||(this._userInstancedBuffersStorage.renderPasses={});const A=this._instanceDataStorage.engine.currentRenderPassId;R=this._userInstancedBuffersStorage.renderPasses[A],R||(this._userInstancedBuffersStorage.renderPasses[A]=R={})}R.world0=u.createVertexBuffer("world0",0,4),R.world1=u.createVertexBuffer("world1",4,4),R.world2=u.createVertexBuffer("world2",8,4),R.world3=u.createVertexBuffer("world3",12,4),this._scene.needsPreviousWorldMatrices&&(f=new Vr(s,l.instancesPreviousData,!0,16,!1,!0),l.instancesPreviousBuffer=f,R.previousWorld0=f.createVertexBuffer("previousWorld0",0,4),R.previousWorld1=f.createVertexBuffer("previousWorld1",4,4),R.previousWorld2=f.createVertexBuffer("previousWorld2",8,4),R.previousWorld3=f.createVertexBuffer("previousWorld3",12,4)),this._invalidateInstanceVertexArrayObject()}else(!this._instanceDataStorage.isFrozen||this._instanceDataStorage.forceMatrixUpdates)&&(u.updateDirectly(l.instancesData,0,_),this._scene.needsPreviousWorldMatrices&&(!this._instanceDataStorage.manualUpdate||this._instanceDataStorage.previousManualUpdate)&&f.updateDirectly(l.instancesPreviousData,0,_));this._processInstancedBuffers(a,m),n&&r!==void 0&&(this.getScene()._activeIndices.addCount(e.indexCount*_,!1),s._currentDrawContext&&(s._currentDrawContext.useInstancing=!0),this._bind(e,n,r),this._draw(e,r,_)),this._scene.needsPreviousWorldMatrices&&!T&&this._instanceDataStorage.manualUpdate&&(!this._instanceDataStorage.isFrozen||this._instanceDataStorage.forceMatrixUpdates)&&!this._instanceDataStorage.previousManualUpdate&&f.updateDirectly(l.instancesData,0,_)}_renderWithInstances(e,t,i,s,r){const n=i.visibleInstances[e._id],a=n?n.length:0,h=i.parent,l=h.instancesBufferSize,u=(a+1)*16*4;for(;h.instancesBufferSize<u;)h.instancesBufferSize*=2;return(!h.instancesData||l!=h.instancesBufferSize)&&(h.instancesData=new Float32Array(h.instancesBufferSize/4)),(this._scene.needsPreviousWorldMatrices&&!h.instancesPreviousData||l!=h.instancesBufferSize)&&(h.instancesPreviousData=new Float32Array(h.instancesBufferSize/4)),this._updateInstancedBuffers(e,i,l,r,t,s),r.unbindInstanceAttributes(),this}_renderWithThinInstances(e,t,i,s){const r=this._thinInstanceDataStorage?.instancesCount??0;this.getScene()._activeIndices.addCount(e.indexCount*r,!1),s._currentDrawContext&&(s._currentDrawContext.useInstancing=!0),this._bind(e,i,t),this._draw(e,t,r),this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&this._thinInstanceDataStorage.matrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData,0,r):this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.matrixData,!1)),s.unbindInstanceAttributes()}_processInstancedBuffers(e,t){}_processRendering(e,t,i,s,r,n,a,h){const l=this.getScene(),c=l.getEngine();if(s=this._getRenderingFillMode(s),n&&t.getRenderingMesh().hasThinInstances)return this._renderWithThinInstances(t,s,i,c),this;if(n)this._renderWithInstances(t,s,r,i,c);else{c._currentDrawContext&&(c._currentDrawContext.useInstancing=!1);let u=0;r.renderSelf[t._id]&&(a&&a(!1,e.getWorldMatrix(),h),u++,this._draw(t,s,this._instanceDataStorage.overridenInstanceCount));const f=r.visibleInstances[t._id];if(f){const d=f.length;u+=d;for(let _=0;_<d;_++){const g=f[_].getWorldMatrix();a&&a(!0,g,h),this._draw(t,s)}}l._activeIndices.addCount(t.indexCount*u,!1)}return this}_disposeInstanceDataStorageRenderPass(e,t=!1){e?.instancesBuffer&&(t&&e.instancesBuffer.dispose(),e.instancesBuffer=null),e?.instancesPreviousBuffer&&(t&&e.instancesPreviousBuffer.dispose(),e.instancesPreviousBuffer=null)}_rebuild(e=!1){for(const t in this._instanceDataStorage.renderPasses){const i=this._instanceDataStorage.renderPasses[t];this._disposeInstanceDataStorageRenderPass(i,e)}if(this._disposeInstanceDataStorageRenderPass(this._instanceDataStorage.dataStorageRenderPass,e),this._userInstancedBuffersStorage){for(const t in this._userInstancedBuffersStorage.vertexBuffers){const i=this._userInstancedBuffersStorage.vertexBuffers[t];i&&(e&&i.dispose(),this._userInstancedBuffersStorage.vertexBuffers[t]=null)}this._userInstancedBuffersStorage.vertexArrayObjects&&(this._userInstancedBuffersStorage.vertexArrayObjects={})}this._internalMeshDataInfo._effectiveMaterial=null,super._rebuild(e)}_releaseRenderPassId(e){const t=this._instanceDataStorage.renderPasses[e];if(t&&(this._disposeInstanceDataStorageRenderPass(t,!0),delete this._instanceDataStorage.renderPasses[e]),this._userInstancedBuffersStorage?.renderPasses){const i=this._userInstancedBuffersStorage.renderPasses[e];if(i)for(const s in i)i[s]?.dispose();delete this._userInstancedBuffersStorage.renderPasses[e]}}_freeze(){if(this.subMeshes){for(let e=0;e<this.subMeshes.length;e++)this._getInstancesRenderList(e);this._internalMeshDataInfo._effectiveMaterial=null,this._instanceDataStorage.isFrozen=!0}}_unFreeze(){this._instanceDataStorage.isFrozen=!1;for(const e in this._instanceDataStorage.renderPasses){const t=this._instanceDataStorage.renderPasses[e];t.previousBatch=null}this._instanceDataStorage.dataStorageRenderPass&&(this._instanceDataStorage.dataStorageRenderPass.previousBatch=null)}renderWithRenderPassId(e,t,i,s,r=!0){const n=this._scene.getEngine(),a=n.currentRenderPassId;if(e!==void 0&&(n.currentRenderPassId=e),s)(!r||r&&s.isInFrustum(this._scene._frustumPlanes))&&this.render(s,!!t,i);else for(let h=0;h<this.subMeshes.length;h++){const l=this.subMeshes[h];(!r||r&&l.isInFrustum(this._scene._frustumPlanes))&&this.render(l,!!t,i)}return e!==void 0&&(n.currentRenderPassId=a),this}directRender(){if(!this.subMeshes)return this;for(const e of this.subMeshes)this.render(e,!1);return this}render(e,t,i){const s=this.getScene(),r=s.getEngine();this._internalAbstractMeshDataInfo._isActiveIntermediate?this._internalAbstractMeshDataInfo._isActiveIntermediate=!1:this._internalAbstractMeshDataInfo._isActive=!1;const n=s.activeCameras?.length??0,a=n>1&&s.activeCamera===s.activeCameras[0]||n<=1,h=this._occlusionDataStorage&&this._occlusionDataStorage.occlusionForRenderPassId!==-1&&this._occlusionDataStorage.occlusionForRenderPassId!==r.currentRenderPassId;if(a&&this._checkOcclusionQuery(h)&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const l=this._getInstancesRenderList(e._id,!!i);if(l.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let c=0,u=null;this.ignoreCameraMaxZ&&s.activeCamera&&!s._isInIntermediateRendering()&&(c=s.activeCamera.maxZ,u=s.activeCamera,s.activeCamera.maxZ=0,s.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const f=e.getRenderingMesh(),d=l.hardwareInstancedRendering[e._id]||f.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,_=this._instanceDataStorage,m=e.getMaterial();if(!m)return u&&(u.maxZ=c,s.updateTransformMatrix(!0)),this;if(!_.isFrozen||!this._internalMeshDataInfo._effectiveMaterial||this._internalMeshDataInfo._effectiveMaterial!==m){if(m._storeEffectOnSubMeshes){if(!m.isReadyForSubMesh(this,e,d))return u&&(u.maxZ=c,s.updateTransformMatrix(!0)),this}else if(!m.isReady(this,d))return u&&(u.maxZ=c,s.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=m}else if(m._storeEffectOnSubMeshes&&!e._drawWrapper?._wasPreviouslyReady||!m._storeEffectOnSubMeshes&&!m._getDrawWrapper()._wasPreviouslyReady)return u&&(u.maxZ=c,s.updateTransformMatrix(!0)),this;if(t){const P=this._internalMeshDataInfo._effectiveMaterial;if(P.alphaModes.length===1)r.setAlphaMode(P.alphaMode);else for(let v=0;v<P.alphaModes.length;v++){const O=P.alphaModes[v];r.setAlphaMode(O!==void 0?O:2,!1,v)}}let g;this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?g=e._drawWrapper:g=this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const T=g?.effect??null;for(const P of s._beforeRenderingMeshStage)P.action(this,e,l,T);if(!g||!T)return u&&(u.maxZ=c,s.updateTransformMatrix(!0)),this;const R=i||this;let A;if(!_.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||this._internalMeshDataInfo._effectiveMaterial.sideOrientation!==null||this._internalMeshDataInfo._effectiveMaterial._twoSidedLighting)){const P=R._getWorldMatrixDeterminant();A=this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this),P<0&&(A=A===V.ClockWiseSideOrientation?V.CounterClockWiseSideOrientation:V.ClockWiseSideOrientation),this._internalMeshDataInfo._effectiveSideOrientation=A}const y=this._internalMeshDataInfo._effectiveMaterial._preBind(g,this._internalMeshDataInfo._effectiveSideOrientation);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&r.setDepthWrite(!0);const E=this._internalMeshDataInfo._effectiveMaterial,x=E.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),d||this._bind(e,T,x,!1);const b=R.getWorldMatrix();E._storeEffectOnSubMeshes?E.bindForSubMesh(b,this,e):E.bind(b,this),!E.backFaceCulling&&E.separateCullingPass&&(r.setState(!0,E.zOffset,!1,!y,E.cullBackFaces,E.stencil,E.zOffsetUnits),this._processRendering(this,e,T,x,l,d,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),r.setState(!0,E.zOffset,!1,y,E.cullBackFaces,E.stencil,E.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,T,x,l,d,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const P of s._afterRenderingMeshStage)P.action(this,e,l,T);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),u&&(u.maxZ=c,s.updateTransformMatrix(!0)),s.performancePriority===2&&!_.isFrozen&&this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(S.MatricesWeightsKind)&&(this.isVerticesDataPresent(S.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(S.MatricesWeightsKind),t=e.length;for(let i=0;i<t;i+=4){const s=e[i]+e[i+1]+e[i+2]+e[i+3];if(s===0)e[i]=1;else{const r=1/s;e[i]*=r,e[i+1]*=r,e[i+2]*=r,e[i+3]*=r}}this.setVerticesData(S.MatricesWeightsKind,e)}_normalizeSkinWeightsAndExtra(){const e=this.getVerticesData(S.MatricesWeightsExtraKind),t=this.getVerticesData(S.MatricesWeightsKind),i=t.length;for(let s=0;s<i;s+=4){let r=t[s]+t[s+1]+t[s+2]+t[s+3];if(r+=e[s]+e[s+1]+e[s+2]+e[s+3],r===0)t[s]=1;else{const n=1/r;t[s]*=n,t[s+1]*=n,t[s+2]*=n,t[s+3]*=n,e[s]*=n,e[s+1]*=n,e[s+2]*=n,e[s+3]*=n}}this.setVerticesData(S.MatricesWeightsKind,t),this.setVerticesData(S.MatricesWeightsKind,e)}validateSkinning(){const e=this.getVerticesData(S.MatricesWeightsExtraKind),t=this.getVerticesData(S.MatricesWeightsKind);if(t===null||this.skeleton==null)return{skinned:!1,valid:!0,report:"not skinned"};const i=t.length;let s=0,r=0,n=0,a=0;const h=e===null?4:8,l=[];for(let g=0;g<=h;g++)l[g]=0;const c=.001;for(let g=0;g<i;g+=4){let T=t[g],R=T,A=R===0?0:1;for(let y=1;y<h;y++){const E=y<4?t[g+y]:e[g+y-4];E>T&&s++,E!==0&&A++,R+=E,T=E}if(l[A]++,A>n&&(n=A),R===0)r++;else{const y=1/R;let E=0;for(let x=0;x<h;x++)x<4?E+=Math.abs(t[g+x]-t[g+x]*y):E+=Math.abs(e[g+x-4]-e[g+x-4]*y);E>c&&a++}}const u=this.skeleton.bones.length,f=this.getVerticesData(S.MatricesIndicesKind),d=this.getVerticesData(S.MatricesIndicesExtraKind);let _=0;for(let g=0;g<i;g+=4)for(let T=0;T<h;T++){const R=T<4?f[g+T]:d[g+T-4];(R>=u||R<0)&&_++}const m="Number of Weights = "+i/4+`
|
|
1250
|
+
Maximum influences = `+n+`
|
|
1251
|
+
Missing Weights = `+r+`
|
|
1252
|
+
Not Sorted = `+s+`
|
|
1253
|
+
Not Normalized = `+a+`
|
|
1254
|
+
WeightCounts = [`+l+`]
|
|
1255
|
+
Number of bones = `+u+`
|
|
1256
|
+
Bad Bone Indices = `+_;return{skinned:!0,valid:r===0&&a===0&&_===0,report:m}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===4&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=this.delayLoadingFile.indexOf(".babylonbinarymeshdata")!==-1;return fe.LoadFile(this.delayLoadingFile,i=>{i instanceof ArrayBuffer?this._delayLoadingFunction(i,this):this._delayLoadingFunction(JSON.parse(i),this);for(const s of this.instances)s.refreshBoundingInfo(),s._syncSubMeshes();this.delayLoadState=1,e.removePendingData(this)},()=>{},e.offlineProvider,t),this}isInFrustum(e){return this.delayLoadState===2||!super.isInFrustum(e)?!1:(this._checkDelayState(),!0)}setMaterialById(e){const t=this.getScene().materials;let i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;const s=this.getScene().multiMaterials;for(i=s.length-1;i>-1;i--)if(s[i].id===e)return this.material=s[i],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(S.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(S.PositionKind);const s=p.Zero();let r;for(r=0;r<i.length;r+=3)p.TransformCoordinatesFromFloatsToRef(i[r],i[r+1],i[r+2],e,s).toArray(i,r);if(this.setVerticesData(S.PositionKind,i,this.getVertexBuffer(S.PositionKind).isUpdatable()),this.isVerticesDataPresent(S.NormalKind)){for(i=this.getVerticesData(S.NormalKind),r=0;r<i.length;r+=3)p.TransformNormalFromFloatsToRef(i[r],i[r+1],i[r+2],e,s).normalize().toArray(i,r);this.setVerticesData(S.NormalKind,i,this.getVertexBuffer(S.NormalKind).isUpdatable())}if(this.isVerticesDataPresent(S.TangentKind)){for(i=this.getVerticesData(S.TangentKind),r=0;r<i.length;r+=4)p.TransformNormalFromFloatsToRef(i[r],i[r+1],i[r+2],e,s).normalize().toArray(i,r);this.setVerticesData(S.TangentKind,i,this.getVertexBuffer(S.TangentKind).isUpdatable())}return e.determinant()<0&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=t,this}bakeCurrentTransformIntoVertices(e=!0,t=!1){return t&&this.makeGeometryUnique(),this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this}get _positions(){return this._internalAbstractMeshDataInfo._positions||this._geometry&&this._geometry._positions||null}_resetPointsArrayCache(){return this._geometry&&this._geometry._resetPointsArrayCache(),this}_generatePointsArray(){return this._geometry?this._geometry._generatePointsArray():!1}clone(e="",t=null,i,s=!0){if(t&&t._addToSceneRootNodes===void 0){const r=t;return li.source=this,li.doNotCloneChildren=r.doNotCloneChildren,li.clonePhysicsImpostor=r.clonePhysicsImpostor,li.cloneThinInstances=r.cloneThinInstances,new F(e,this.getScene(),li)}return new F(e,this.getScene(),t,this,i,s)}dispose(e,t=!1){this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);const i=this._internalMeshDataInfo;if(i._onBeforeDrawObservable&&i._onBeforeDrawObservable.clear(),i._onBeforeBindObservable&&i._onBeforeBindObservable.clear(),i._onBeforeRenderObservable&&i._onBeforeRenderObservable.clear(),i._onAfterRenderObservable&&i._onAfterRenderObservable.clear(),i._onBetweenPassObservable&&i._onBetweenPassObservable.clear(),this._scene.useClonedMeshMap){if(i.meshMap)for(const s in i.meshMap){const r=i.meshMap[s];r&&(r._internalMeshDataInfo._source=null,i.meshMap[s]=void 0)}i._source&&i._source._internalMeshDataInfo.meshMap&&(i._source._internalMeshDataInfo.meshMap[this.uniqueId]=void 0)}else{const s=this.getScene().meshes;for(const r of s){const n=r;n._internalMeshDataInfo&&n._internalMeshDataInfo._source&&n._internalMeshDataInfo._source===this&&(n._internalMeshDataInfo._source=null)}}i._source=null,this._disposeInstanceSpecificData(),this._disposeThinInstanceSpecificData(),this._internalMeshDataInfo._checkReadinessObserver&&this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),super.dispose(e,t)}_disposeInstanceSpecificData(){}_disposeThinInstanceSpecificData(){}_invalidateInstanceVertexArrayObject(){}applyDisplacementMap(e,t,i,s,r,n,a=!1,h){const l=this.getScene(),c=u=>{const f=u.width,d=u.height,m=this.getEngine().createCanvas(f,d).getContext("2d");m.drawImage(u,0,0);const g=m.getImageData(0,0,f,d).data;this.applyDisplacementMapFromBuffer(g,f,d,t,i,r,n,a),s&&s(this)};return fe.LoadImage(e,c,h||(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,r,n,a,h=!1){if(!this.isVerticesDataPresent(S.PositionKind)||!this.isVerticesDataPresent(S.NormalKind)||!this.isVerticesDataPresent(S.UVKind))return W.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(S.PositionKind,!0,!0),c=this.getVerticesData(S.NormalKind),u=this.getVerticesData(S.UVKind);let f=p.Zero();const d=p.Zero(),_=ie.Zero();n=n||ie.Zero(),a=a||new ie(1,1);for(let m=0;m<l.length;m+=3){p.FromArrayToRef(l,m,f),p.FromArrayToRef(c,m,d),ie.FromArrayToRef(u,m/3*2,_);const g=Math.abs(_.x*a.x+n.x%1)*(t-1)%t|0,T=Math.abs(_.y*a.y+n.y%1)*(i-1)%i|0,R=(g+T*t)*4,A=e[R]/255,y=e[R+1]/255,E=e[R+2]/255,x=A*.3+y*.59+E*.11;d.normalize(),d.scaleInPlace(s+(r-s)*x),f=f.add(d),f.toArray(l,m)}return j.ComputeNormals(l,this.getIndices(),c),h?(this.setVerticesData(S.PositionKind,l),this.setVerticesData(S.NormalKind,c),this.setVerticesData(S.UVKind,u)):(this.updateVerticesData(S.PositionKind,l),this.updateVerticesData(S.NormalKind,c)),this}_getFlattenedNormals(e,t){const i=new Float32Array(e.length*3);let s=0;const r=this.sideOrientation===(this._scene.useRightHandedSystem?1:0);for(let n=0;n<e.length;n+=3){const a=p.FromArray(t,e[n]*3),h=p.FromArray(t,e[n+1]*3),l=p.FromArray(t,e[n+2]*3),c=a.subtract(h),u=l.subtract(h),f=p.Normalize(p.Cross(c,u));r&&f.scaleInPlace(-1);for(let d=0;d<3;d++)i[s++]=f.x,i[s++]=f.y,i[s++]=f.z}return i}_convertToUnIndexedMesh(e=!1){const t=this.getVerticesDataKinds().filter(h=>!this.getVertexBuffer(h)?.getIsInstanced()),i=this.getIndices(!1,!0),s={},r=(h,l)=>{const c=new Float32Array(i.length*l);let u=0;for(let f=0;f<i.length;f++)for(let d=0;d<l;d++)c[u++]=h[i[f]*l+d];return c},n=this.getBoundingInfo(),a=this.geometry?this.subMeshes.slice(0):[];for(const h of t)s[h]=this.getVerticesData(h);for(const h of t){const l=this.getVertexBuffer(h),c=l.getSize();if(e&&h===S.NormalKind){const u=this._getFlattenedNormals(i,s[S.PositionKind]);this.setVerticesData(S.NormalKind,u,l.isUpdatable(),c)}else this.setVerticesData(h,r(s[h],c),l.isUpdatable(),c)}if(this.morphTargetManager){for(let h=0;h<this.morphTargetManager.numTargets;h++){const l=this.morphTargetManager.getTarget(h),c=l.getPositions();l.setPositions(r(c,3));const u=l.getNormals();u&&l.setNormals(e?this._getFlattenedNormals(i,c):r(u,3));const f=l.getTangents();f&&l.setTangents(r(f,3));const d=l.getUVs();d&&l.setUVs(r(d,2));const _=l.getColors();_&&l.setColors(r(_,4))}this.morphTargetManager.synchronize()}for(let h=0;h<i.length;h++)i[h]=h;this.setIndices(i),this._unIndexed=!0,this.releaseSubMeshes();for(const h of a){const l=h.getBoundingInfo();Kt.AddToMesh(h.materialIndex,h.indexStart,h.indexCount,h.indexStart,h.indexCount,this).setBoundingInfo(l)}return this.setBoundingInfo(n),this.synchronizeInstances(),this}convertToFlatShadedMesh(){return this._convertToUnIndexedMesh(!0)}convertToUnIndexedMesh(){return this._convertToUnIndexedMesh()}flipFaces(e=!1){const t=j.ExtractFromMesh(this);let i;if(e&&this.isVerticesDataPresent(S.NormalKind)&&t.normals){for(i=0;i<t.normals.length;i++)t.normals[i]*=-1;this.setVerticesData(S.NormalKind,t.normals,this.isVertexBufferUpdatable(S.NormalKind))}if(t.indices){let s;for(i=0;i<t.indices.length;i+=3)s=t.indices[i+1],t.indices[i+1]=t.indices[i+2],t.indices[i+2]=s;this.setIndices(t.indices,null,this.isVertexBufferUpdatable(S.PositionKind),!0)}return this}increaseVertices(e=1){const t=j.ExtractFromMesh(this),i=t.indices&&!Array.isArray(t.indices)&&Array.from?Array.from(t.indices):t.indices,s=t.positions&&!Array.isArray(t.positions)&&Array.from?Array.from(t.positions):t.positions,r=t.uvs&&!Array.isArray(t.uvs)&&Array.from?Array.from(t.uvs):t.uvs,n=t.normals&&!Array.isArray(t.normals)&&Array.from?Array.from(t.normals):t.normals;if(!i||!s)W.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions");else{t.indices=i,t.positions=s,r&&(t.uvs=r),n&&(t.normals=n);const a=e+1,h=[];for(let E=0;E<a+1;E++)h[E]=[];let l,c;const u=new p(0,0,0),f=new p(0,0,0),d=new ie(0,0),_=[],m=[],g=[];let T,R=s.length,A;r&&(A=r.length);let y;n&&(y=n.length);for(let E=0;E<i.length;E+=3){m[0]=i[E],m[1]=i[E+1],m[2]=i[E+2];for(let x=0;x<3;x++)if(l=m[x],c=m[(x+1)%3],g[l]===void 0&&g[c]===void 0?(g[l]=[],g[c]=[]):(g[l]===void 0&&(g[l]=[]),g[c]===void 0&&(g[c]=[])),g[l][c]===void 0&&g[c][l]===void 0){g[l][c]=[],u.x=(s[3*c]-s[3*l])/a,u.y=(s[3*c+1]-s[3*l+1])/a,u.z=(s[3*c+2]-s[3*l+2])/a,n&&(f.x=(n[3*c]-n[3*l])/a,f.y=(n[3*c+1]-n[3*l+1])/a,f.z=(n[3*c+2]-n[3*l+2])/a),r&&(d.x=(r[2*c]-r[2*l])/a,d.y=(r[2*c+1]-r[2*l+1])/a),g[l][c].push(l);for(let b=1;b<a;b++)g[l][c].push(s.length/3),s[R++]=s[3*l]+b*u.x,s[R++]=s[3*l+1]+b*u.y,s[R++]=s[3*l+2]+b*u.z,n&&(n[y++]=n[3*l]+b*f.x,n[y++]=n[3*l+1]+b*f.y,n[y++]=n[3*l+2]+b*f.z),r&&(r[A++]=r[2*l]+b*d.x,r[A++]=r[2*l+1]+b*d.y);g[l][c].push(c),g[c][l]=[],T=g[l][c].length;for(let b=0;b<T;b++)g[c][l][b]=g[l][c][T-1-b]}h[0][0]=i[E],h[1][0]=g[i[E]][i[E+1]][1],h[1][1]=g[i[E]][i[E+2]][1];for(let x=2;x<a;x++){h[x][0]=g[i[E]][i[E+1]][x],h[x][x]=g[i[E]][i[E+2]][x],u.x=(s[3*h[x][x]]-s[3*h[x][0]])/x,u.y=(s[3*h[x][x]+1]-s[3*h[x][0]+1])/x,u.z=(s[3*h[x][x]+2]-s[3*h[x][0]+2])/x,n&&(f.x=(n[3*h[x][x]]-n[3*h[x][0]])/x,f.y=(n[3*h[x][x]+1]-n[3*h[x][0]+1])/x,f.z=(n[3*h[x][x]+2]-n[3*h[x][0]+2])/x),r&&(d.x=(r[2*h[x][x]]-r[2*h[x][0]])/x,d.y=(r[2*h[x][x]+1]-r[2*h[x][0]+1])/x);for(let b=1;b<x;b++)h[x][b]=s.length/3,s[R++]=s[3*h[x][0]]+b*u.x,s[R++]=s[3*h[x][0]+1]+b*u.y,s[R++]=s[3*h[x][0]+2]+b*u.z,n&&(n[y++]=n[3*h[x][0]]+b*f.x,n[y++]=n[3*h[x][0]+1]+b*f.y,n[y++]=n[3*h[x][0]+2]+b*f.z),r&&(r[A++]=r[2*h[x][0]]+b*d.x,r[A++]=r[2*h[x][0]+1]+b*d.y)}h[a]=g[i[E+1]][i[E+2]],_.push(h[0][0],h[1][0],h[1][1]);for(let x=1;x<a;x++){let b;for(b=0;b<x;b++)_.push(h[x][b],h[x+1][b],h[x+1][b+1]),_.push(h[x][b],h[x+1][b+1],h[x][b+1]);_.push(h[x][b],h[x+1][b],h[x+1][b+1])}}t.indices=_,t.applyToMesh(this,this.isVertexBufferUpdatable(S.PositionKind))}}forceSharedVertices(){const e=j.ExtractFromMesh(this),t=e.uvs,i=e.indices,s=e.positions,r=e.colors,n=e.matricesIndices,a=e.matricesWeights,h=e.matricesIndicesExtra,l=e.matricesWeightsExtra;if(i===void 0||s===void 0||i===null||s===null)W.Warn("VertexData contains empty entries");else{const c=[],u=[],f=[],d=[],_=[],m=[],g=[],T=[];let R,A=0;const y={};let E,x;for(let P=0;P<i.length;P+=3){x=[i[P],i[P+1],i[P+2]],R=[];for(let v=0;v<3;v++){R[v]="";for(let O=0;O<3;O++)Math.abs(s[3*x[v]+O])<1e-8&&(s[3*x[v]+O]=0),R[v]+=s[3*x[v]+O]+"|"}if(!(R[0]==R[1]||R[0]==R[2]||R[1]==R[2]))for(let v=0;v<3;v++){if(E=y[R[v]],E===void 0){y[R[v]]=A,E=A++;for(let O=0;O<3;O++)c.push(s[3*x[v]+O]);if(r!=null)for(let O=0;O<4;O++)d.push(r[4*x[v]+O]);if(t!=null)for(let O=0;O<2;O++)f.push(t[2*x[v]+O]);if(n!=null)for(let O=0;O<4;O++)_.push(n[4*x[v]+O]);if(a!=null)for(let O=0;O<4;O++)m.push(a[4*x[v]+O]);if(h!=null)for(let O=0;O<4;O++)g.push(h[4*x[v]+O]);if(l!=null)for(let O=0;O<4;O++)T.push(l[4*x[v]+O])}u.push(E)}}const b=[];j.ComputeNormals(c,u,b),e.positions=c,e.indices=u,e.normals=b,t!=null&&(e.uvs=f),r!=null&&(e.colors=d),n!=null&&(e.matricesIndices=_),a!=null&&(e.matricesWeights=m),h!=null&&(e.matricesIndicesExtra=g),a!=null&&(e.matricesWeightsExtra=T),e.applyToMesh(this,this.isVertexBufferUpdatable(S.PositionKind))}}static _instancedMeshFactory(e,t){throw pe("InstancedMesh")}static _PhysicsImpostorParser(e,t,i){throw pe("PhysicsImpostor")}createInstance(e){const t=F._instancedMeshFactory(e,this);return t.parent=this.parent,t}synchronizeInstances(){for(let e=0;e<this.instances.length;e++)this.instances[e]._syncSubMeshes();return this}optimizeIndices(e){const t=this.getIndices(),i=this.getVerticesData(S.PositionKind);if(!i||!t)return this;const s=[];for(let n=0;n<i.length;n=n+3)s.push(p.FromArray(i,n));const r=[];return Lr.SyncAsyncForLoop(s.length,40,n=>{const a=s.length-1-n,h=s[a];for(let l=0;l<a;++l){const c=s[l];if(h.equals(c)){r[a]=l;break}}},()=>{for(let a=0;a<t.length;++a)t[a]=r[t[a]]||t[a];const n=this.subMeshes.slice(0);this.setIndices(t),this.subMeshes=n,e&&e(this)}),this}serialize(e={}){e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,e.type=this.getClassName(),Le&&Le.HasTags(this)&&(e.tags=Le.GetTags(this)),e.position=this.position.asArray(),this.rotationQuaternion?e.rotationQuaternion=this.rotationQuaternion.asArray():this.rotation&&(e.rotation=this.rotation.asArray()),e.scaling=this.scaling.asArray(),this._postMultiplyPivotMatrix?e.pivotMatrix=this.getPivotMatrix().asArray():e.localMatrix=this.getPivotMatrix().asArray(),e.isEnabled=this.isEnabled(!1),e.isVisible=this.isVisible,e.infiniteDistance=this.infiniteDistance,e.pickable=this.isPickable,e.receiveShadows=this.receiveShadows,e.billboardMode=this.billboardMode,e.visibility=this.visibility,e.alwaysSelectAsActiveMesh=this.alwaysSelectAsActiveMesh,e.checkCollisions=this.checkCollisions,e.ellipsoid=this.ellipsoid.asArray(),e.ellipsoidOffset=this.ellipsoidOffset.asArray(),e.doNotSyncBoundingInfo=this.doNotSyncBoundingInfo,e.isBlocker=this.isBlocker,e.sideOrientation=this.sideOrientation,this.parent&&this.parent._serializeAsParent(e),e.isUnIndexed=this.isUnIndexed;const t=this._geometry;if(t&&this.subMeshes){e.geometryUniqueId=t.uniqueId,e.geometryId=t.id,e.subMeshes=[];for(let i=0;i<this.subMeshes.length;i++){const s=this.subMeshes[i];e.subMeshes.push({materialIndex:s.materialIndex,verticesStart:s.verticesStart,verticesCount:s.verticesCount,indexStart:s.indexStart,indexCount:s.indexCount})}}if(this.material?this.material.doNotSerialize||(e.materialUniqueId=this.material.uniqueId,e.materialId=this.material.id):(this.material=null,e.materialUniqueId=this._scene.defaultMaterial.uniqueId,e.materialId=this._scene.defaultMaterial.id),this.morphTargetManager&&(e.morphTargetManagerId=this.morphTargetManager.uniqueId),this.skeleton&&(e.skeletonId=this.skeleton.id,e.skeletonUniqueId=this.skeleton.uniqueId,e.numBoneInfluencers=this.numBoneInfluencers),this.getScene()._getComponent(ce.NAME_PHYSICSENGINE)){const i=this.getPhysicsImpostor();i&&(e.physicsMass=i.getParam("mass"),e.physicsFriction=i.getParam("friction"),e.physicsRestitution=i.getParam("mass"),e.physicsImpostor=i.type)}this.metadata&&(e.metadata=this.metadata),e.instances=[];for(let i=0;i<this.instances.length;i++){const s=this.instances[i];if(s.doNotSerialize)continue;const r={name:s.name,id:s.id,isEnabled:s.isEnabled(!1),isVisible:s.isVisible,isPickable:s.isPickable,checkCollisions:s.checkCollisions,position:s.position.asArray(),scaling:s.scaling.asArray()};if(s.parent&&s.parent._serializeAsParent(r),s.rotationQuaternion?r.rotationQuaternion=s.rotationQuaternion.asArray():s.rotation&&(r.rotation=s.rotation.asArray()),this.getScene()._getComponent(ce.NAME_PHYSICSENGINE)){const n=s.getPhysicsImpostor();n&&(r.physicsMass=n.getParam("mass"),r.physicsFriction=n.getParam("friction"),r.physicsRestitution=n.getParam("mass"),r.physicsImpostor=n.type)}s.metadata&&(r.metadata=s.metadata),s.actionManager&&(r.actions=s.actionManager.serialize(s.name)),e.instances.push(r),me.AppendSerializedAnimations(s,r),r.ranges=s.serializeAnimationRanges()}if(this._thinInstanceDataStorage.instancesCount&&this._thinInstanceDataStorage.matrixData&&(e.thinInstances={instancesCount:this._thinInstanceDataStorage.instancesCount,matrixData:Array.from(this._thinInstanceDataStorage.matrixData),matrixBufferSize:this._thinInstanceDataStorage.matrixBufferSize,enablePicking:this.thinInstanceEnablePicking},this._userThinInstanceBuffersStorage)){const i={data:{},sizes:{},strides:{}};for(const s in this._userThinInstanceBuffersStorage.data)i.data[s]=Array.from(this._userThinInstanceBuffersStorage.data[s]),i.sizes[s]=this._userThinInstanceBuffersStorage.sizes[s],i.strides[s]=this._userThinInstanceBuffersStorage.strides[s];e.thinInstances.userThinInstance=i}return me.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.layerMask=this.layerMask,e.alphaIndex=this.alphaIndex,e.hasVertexAlpha=this.hasVertexAlpha,e.overlayAlpha=this.overlayAlpha,e.overlayColor=this.overlayColor.asArray(),e.renderOverlay=this.renderOverlay,e.applyFog=this.applyFog,this.actionManager&&(e.actions=this.actionManager.serialize(this.name)),e}_syncGeometryWithMorphTargetManager(){if(!this.geometry)return;this._markSubMeshesAsAttributesDirty();const e=this._internalAbstractMeshDataInfo._morphTargetManager;if(e&&e.vertexCount){if(e.vertexCount!==this.getTotalVertices()){W.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."),this.morphTargetManager=null;return}if(e.isUsingTextureForTargets)return;for(let t=0;t<e.numInfluencers;t++){const i=e.getActiveTarget(t),s=i.getPositions();if(!s){W.Error("Invalid morph target. Target must have positions.");return}this.geometry.setVerticesData(S.PositionKind+t,s,!1,3);const r=i.getNormals();r&&this.geometry.setVerticesData(S.NormalKind+t,r,!1,3);const n=i.getTangents();n&&this.geometry.setVerticesData(S.TangentKind+t,n,!1,3);const a=i.getUVs();a&&this.geometry.setVerticesData(S.UVKind+"_"+t,a,!1,2);const h=i.getUV2s();h&&this.geometry.setVerticesData(S.UV2Kind+"_"+t,h,!1,2);const l=i.getColors();l&&this.geometry.setVerticesData(S.ColorKind+t,l,!1,4)}}else{let t=0;for(;this.geometry.isVerticesDataPresent(S.PositionKind+t);)this.geometry.removeVerticesData(S.PositionKind+t),this.geometry.isVerticesDataPresent(S.NormalKind+t)&&this.geometry.removeVerticesData(S.NormalKind+t),this.geometry.isVerticesDataPresent(S.TangentKind+t)&&this.geometry.removeVerticesData(S.TangentKind+t),this.geometry.isVerticesDataPresent(S.UVKind+t)&&this.geometry.removeVerticesData(S.UVKind+"_"+t),this.geometry.isVerticesDataPresent(S.UV2Kind+t)&&this.geometry.removeVerticesData(S.UV2Kind+"_"+t),this.geometry.isVerticesDataPresent(S.ColorKind+t)&&this.geometry.removeVerticesData(S.ColorKind+t),t++}}static Parse(e,t,i){let s;if(e.type&&e.type==="LinesMesh"?s=F._LinesMeshParser(e,t):e.type&&e.type==="GroundMesh"?s=F._GroundMeshParser(e,t):e.type&&e.type==="GoldbergMesh"?s=F._GoldbergMeshParser(e,t):e.type&&e.type==="GreasedLineMesh"?s=F._GreasedLineMeshParser(e,t):e.type&&e.type==="TrailMesh"?s=F._TrailMeshParser(e,t):s=new F(e.name,t),s.id=e.id,s._waitingParsedUniqueId=e.uniqueId,Le&&Le.AddTagsTo(s,e.tags),s.position=p.FromArray(e.position),e.metadata!==void 0&&(s.metadata=e.metadata),e.rotationQuaternion?s.rotationQuaternion=re.FromArray(e.rotationQuaternion):e.rotation&&(s.rotation=p.FromArray(e.rotation)),s.scaling=p.FromArray(e.scaling),e.localMatrix?s.setPreTransformMatrix(D.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(D.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s.isVisible=e.isVisible,s.infiniteDistance=e.infiniteDistance,s.alwaysSelectAsActiveMesh=!!e.alwaysSelectAsActiveMesh,s.showBoundingBox=e.showBoundingBox,s.showSubMeshesBoundingBox=e.showSubMeshesBoundingBox,e.applyFog!==void 0&&(s.applyFog=e.applyFog),e.pickable!==void 0&&(s.isPickable=e.pickable),e.alphaIndex!==void 0&&(s.alphaIndex=e.alphaIndex),s.receiveShadows=e.receiveShadows,e.billboardMode!==void 0&&(s.billboardMode=e.billboardMode),e.visibility!==void 0&&(s.visibility=e.visibility),s.checkCollisions=e.checkCollisions,s.doNotSyncBoundingInfo=!!e.doNotSyncBoundingInfo,e.ellipsoid&&(s.ellipsoid=p.FromArray(e.ellipsoid)),e.ellipsoidOffset&&(s.ellipsoidOffset=p.FromArray(e.ellipsoidOffset)),e.overrideMaterialSideOrientation!=null&&(s.sideOrientation=e.overrideMaterialSideOrientation),e.sideOrientation!==void 0&&(s.sideOrientation=e.sideOrientation),e.isBlocker!==void 0&&(s.isBlocker=e.isBlocker),s._shouldGenerateFlatShading=e.useFlatShading,e.freezeWorldMatrix&&(s._waitingData.freezeWorldMatrix=e.freezeWorldMatrix),e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.actions!==void 0&&(s._waitingData.actions=e.actions),e.overlayAlpha!==void 0&&(s.overlayAlpha=e.overlayAlpha),e.overlayColor!==void 0&&(s.overlayColor=Re.FromArray(e.overlayColor)),e.renderOverlay!==void 0&&(s.renderOverlay=e.renderOverlay),s.isUnIndexed=!!e.isUnIndexed,s.hasVertexAlpha=e.hasVertexAlpha,e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s.buildBoundingInfo(p.FromArray(e.boundingBoxMinimum),p.FromArray(e.boundingBoxMaximum)),e._binaryInfo&&(s._binaryInfo=e._binaryInfo),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(S.UVKind),e.hasUVs2&&s._delayInfo.push(S.UV2Kind),e.hasUVs3&&s._delayInfo.push(S.UV3Kind),e.hasUVs4&&s._delayInfo.push(S.UV4Kind),e.hasUVs5&&s._delayInfo.push(S.UV5Kind),e.hasUVs6&&s._delayInfo.push(S.UV6Kind),e.hasColors&&s._delayInfo.push(S.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(S.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(S.MatricesWeightsKind),s._delayLoadingFunction=Rt._ImportGeometry,Pt.ForceFullSceneLoadingForIncremental&&s._checkDelayState()):Rt._ImportGeometry(e,s),e.materialUniqueId?s._waitingMaterialId=e.materialUniqueId:e.materialId&&(s._waitingMaterialId=e.materialId),e.morphTargetManagerId>-1&&(s._waitingMorphTargetManagerId=e.morphTargetManagerId),e.skeletonId!==void 0&&e.skeletonId!==null&&(s.skeleton=t.getLastSkeletonById(e.skeletonId),s._waitingSkeletonId=e.skeletonId,e.numBoneInfluencers&&(s.numBoneInfluencers=e.numBoneInfluencers)),e.skeletonUniqueId!==void 0&&e.skeletonUniqueId!==null&&(s._waitingSkeletonUniqueId=e.skeletonUniqueId),e.animations){for(let r=0;r<e.animations.length;r++){const n=e.animations[r],a=Pi("BABYLON.Animation");a&&s.animations.push(a.Parse(n))}lt.ParseAnimationRanges(s,e,t)}if(e.autoAnimate&&t.beginAnimation(s,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.layerMask&&!isNaN(e.layerMask)?s.layerMask=Math.abs(parseInt(e.layerMask)):s.layerMask=268435455,e.physicsImpostor&&(s.physicsImpostor=F._PhysicsImpostorParser(t,s,e)),e.lodMeshIds&&(s._waitingData.lods={ids:e.lodMeshIds,distances:e.lodDistances?e.lodDistances:null,coverages:e.lodCoverages?e.lodCoverages:null}),e.instances)for(let r=0;r<e.instances.length;r++){const n=e.instances[r],a=s.createInstance(n.name);if(n.id&&(a.id=n.id),Le&&(n.tags?Le.AddTagsTo(a,n.tags):Le.AddTagsTo(a,e.tags)),a.position=p.FromArray(n.position),n.metadata!==void 0&&(a.metadata=n.metadata),n.parentId!==void 0&&(a._waitingParentId=n.parentId),n.parentInstanceIndex!==void 0&&(a._waitingParentInstanceIndex=n.parentInstanceIndex),n.isEnabled!==void 0&&n.isEnabled!==null&&a.setEnabled(n.isEnabled),n.isVisible!==void 0&&n.isVisible!==null&&(a.isVisible=n.isVisible),n.isPickable!==void 0&&n.isPickable!==null&&(a.isPickable=n.isPickable),n.rotationQuaternion?a.rotationQuaternion=re.FromArray(n.rotationQuaternion):n.rotation&&(a.rotation=p.FromArray(n.rotation)),a.scaling=p.FromArray(n.scaling),n.checkCollisions!=null&&n.checkCollisions!=null&&(a.checkCollisions=n.checkCollisions),n.pickable!=null&&n.pickable!=null&&(a.isPickable=n.pickable),n.showBoundingBox!=null&&n.showBoundingBox!=null&&(a.showBoundingBox=n.showBoundingBox),n.showSubMeshesBoundingBox!=null&&n.showSubMeshesBoundingBox!=null&&(a.showSubMeshesBoundingBox=n.showSubMeshesBoundingBox),n.alphaIndex!=null&&n.showSubMeshesBoundingBox!=null&&(a.alphaIndex=n.alphaIndex),n.physicsImpostor&&(a.physicsImpostor=F._PhysicsImpostorParser(t,a,n)),n.actions!==void 0&&(a._waitingData.actions=n.actions),n.animations){for(let h=0;h<n.animations.length;h++){const l=n.animations[h],c=Pi("BABYLON.Animation");c&&a.animations.push(c.Parse(l))}lt.ParseAnimationRanges(a,n,t),n.autoAnimate&&t.beginAnimation(a,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1)}}if(e.thinInstances){const r=e.thinInstances;if(s.thinInstanceEnablePicking=!!r.enablePicking,r.matrixData?(s.thinInstanceSetBuffer("matrix",new Float32Array(r.matrixData),16,!1),s._thinInstanceDataStorage.matrixBufferSize=r.matrixBufferSize,s._thinInstanceDataStorage.instancesCount=r.instancesCount):s._thinInstanceDataStorage.matrixBufferSize=r.matrixBufferSize,e.thinInstances.userThinInstance){const n=e.thinInstances.userThinInstance;for(const a in n.data)s.thinInstanceSetBuffer(a,new Float32Array(n.data[a]),n.strides[a],!1),s._userThinInstanceBuffersStorage.sizes[a]=n.sizes[a]}}return s}setPositionsForCPUSkinning(){const e=this._internalMeshDataInfo;if(!e._sourcePositions){const t=this.getVerticesData(S.PositionKind);if(!t)return e._sourcePositions;e._sourcePositions=new Float32Array(t),this.isVertexBufferUpdatable(S.PositionKind)||this.setVerticesData(S.PositionKind,t,!0)}return e._sourcePositions}setNormalsForCPUSkinning(){const e=this._internalMeshDataInfo;if(!e._sourceNormals){const t=this.getVerticesData(S.NormalKind);if(!t)return e._sourceNormals;e._sourceNormals=new Float32Array(t),this.isVertexBufferUpdatable(S.NormalKind)||this.setVerticesData(S.NormalKind,t,!0)}return e._sourceNormals}applySkeleton(e){if(!this.geometry)return this;if(this.geometry._softwareSkinningFrameId==this.getScene().getFrameId())return this;if(this.geometry._softwareSkinningFrameId=this.getScene().getFrameId(),!this.isVerticesDataPresent(S.PositionKind))return this;if(!this.isVerticesDataPresent(S.MatricesIndicesKind))return this;if(!this.isVerticesDataPresent(S.MatricesWeightsKind))return this;const t=this.isVerticesDataPresent(S.NormalKind),i=this._internalMeshDataInfo;if(!i._sourcePositions){const T=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=T}t&&!i._sourceNormals&&this.setNormalsForCPUSkinning();let s=this.getVerticesData(S.PositionKind);if(!s)return this;s instanceof Float32Array||(s=new Float32Array(s));let r=this.getVerticesData(S.NormalKind);if(t){if(!r)return this;r instanceof Float32Array||(r=new Float32Array(r))}const n=this.getVerticesData(S.MatricesIndicesKind),a=this.getVerticesData(S.MatricesWeightsKind);if(!a||!n)return this;const h=this.numBoneInfluencers>4,l=h?this.getVerticesData(S.MatricesIndicesExtraKind):null,c=h?this.getVerticesData(S.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),f=p.Zero(),d=new D,_=new D;let m=0,g;for(let T=0;T<s.length;T+=3,m+=4){let R;for(g=0;g<4;g++)R=a[m+g],R>0&&(D.FromFloat32ArrayToRefScaled(u,Math.floor(n[m+g]*16),R,_),d.addToSelf(_));if(h)for(g=0;g<4;g++)R=c[m+g],R>0&&(D.FromFloat32ArrayToRefScaled(u,Math.floor(l[m+g]*16),R,_),d.addToSelf(_));p.TransformCoordinatesFromFloatsToRef(i._sourcePositions[T],i._sourcePositions[T+1],i._sourcePositions[T+2],d,f),f.toArray(s,T),t&&(p.TransformNormalFromFloatsToRef(i._sourceNormals[T],i._sourceNormals[T+1],i._sourceNormals[T+2],d,f),f.toArray(r,T)),d.reset()}return this.updateVerticesData(S.PositionKind,s),t&&this.updateVerticesData(S.NormalKind,r),this}static MinMax(e){let t=null,i=null;for(const s of e){const n=s.getBoundingInfo().boundingBox;!t||!i?(t=n.minimumWorld.clone(),i=n.maximumWorld.clone()):(t.minimizeInPlace(n.minimumWorld),i.maximizeInPlace(n.maximumWorld))}return!t||!i?{min:p.Zero(),max:p.Zero()}:{min:t,max:i}}static Center(e){const t=e instanceof Array?F.MinMax(e):e;return p.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,r,n){return ao(F._MergeMeshesCoroutine(e,t,i,s,r,n,!1))}static async MergeMeshesAsync(e,t=!0,i,s,r,n){return await Lc(F._MergeMeshesCoroutine(e,t,i,s,r,n,!0),Lg())}static*_MergeMeshesCoroutine(e,t=!0,i,s,r,n,a){if(e=e.filter(Boolean),e.length===0)return null;let h;if(!i){let b=0;for(h=0;h<e.length;h++)if(b+=e[h].getTotalVertices(),b>=65536)return W.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(r=!1);const l=new Array,c=new Array,u=new Array,f=e[0].sideOrientation;for(h=0;h<e.length;h++){const b=e[h];if(b.isAnInstance)return W.Warn("Cannot merge instance meshes."),null;if(f!==b.sideOrientation)return W.Warn("Cannot merge meshes with different sideOrientation values."),null;if(r||n){const P=u.reduce((v,O)=>Math.max(v,O.start+O.count),0);if(n)if(b.material){const v=b.material;if(v instanceof Rs){for(let O=0;O<v.subMaterials.length;O++)l.indexOf(v.subMaterials[O])<0&&l.push(v.subMaterials[O]);for(let O=0;O<b.subMeshes.length;O++)c.push(l.indexOf(v.subMaterials[b.subMeshes[O].materialIndex])),u.push({start:P+b.subMeshes[O].indexStart,count:b.subMeshes[O].indexCount})}else{l.indexOf(v)<0&&l.push(v);for(let O=0;O<b.subMeshes.length;O++)c.push(l.indexOf(v)),u.push({start:P+b.subMeshes[O].indexStart,count:b.subMeshes[O].indexCount})}}else for(let v=0;v<b.subMeshes.length;v++)c.push(0),u.push({start:P+b.subMeshes[v].indexStart,count:b.subMeshes[v].indexCount});else u.push({start:P,count:b.getTotalIndices()})}}const d=e[0],_=b=>{const P=b.computeWorldMatrix(!0);return{vertexData:j.ExtractFromMesh(b,!1,!1),transform:P}},{vertexData:m,transform:g}=_(d);a&&(yield);const T=new Array(e.length-1);for(let b=1;b<e.length;b++)T[b-1]=_(e[b]),a&&(yield);const R=m._mergeCoroutine(g,T,i,a,!t);let A=R.next();for(;!A.done;)a&&(yield),A=R.next();const y=A.value;s||(s=new F(d.name+"_merged",d.getScene()));const E=y._applyToCoroutine(s,void 0,a);let x=E.next();for(;!x.done;)a&&(yield),x=E.next();if(s.checkCollisions=d.checkCollisions,s.sideOrientation=d.sideOrientation,t)for(h=0;h<e.length;h++)e[h].dispose();if(r||n){for(s.releaseSubMeshes(),h=0;h<u.length;)Kt.CreateFromIndices(0,u[h].start,u[h].count,s,void 0,!1),h++;for(const b of s.subMeshes)b.refreshBoundingInfo();s.computeWorldMatrix(!0)}if(n){const b=new Rs(d.name+"_merged",d.getScene());b.subMaterials=l;for(let P=0;P<s.subMeshes.length;P++)s.subMeshes[P].materialIndex=c[P];s.material=b}else s.material=d.material;return s}addInstance(e){e._indexInSourceMeshInstanceArray=this.instances.length,this.instances.push(e)}removeInstance(e){const t=e._indexInSourceMeshInstanceArray;if(t!=-1){if(t!==this.instances.length-1){const i=this.instances[this.instances.length-1];this.instances[t]=i,i._indexInSourceMeshInstanceArray=t}e._indexInSourceMeshInstanceArray=-1,this.instances.pop()}}_shouldConvertRHS(){return this._scene.useRightHandedSystem&&this.sideOrientation===V.CounterClockWiseSideOrientation}_getRenderingFillMode(e){const t=this.getScene();return t.forcePointsCloud?V.PointFillMode:t.forceWireframe?V.WireFrameFillMode:this.overrideRenderingFillMode??e}setMaterialByID(e){return this.setMaterialById(e)}static CreateRibbon(e,t,i,s,r,n,a,h,l){throw new Error("Import MeshBuilder to populate this function")}static CreateDisc(e,t,i,s,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateBox(e,t,i,s,r){throw new Error("Import MeshBuilder to populate this function")}static CreateSphere(e,t,i,s,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateHemisphere(e,t,i,s){throw new Error("Import MeshBuilder to populate this function")}static CreateCylinder(e,t,i,s,r,n,a,h,l){throw new Error("Import MeshBuilder to populate this function")}static CreateTorus(e,t,i,s,r,n,a){throw new Error("Import MeshBuilder to populate this function")}static CreateTorusKnot(e,t,i,s,r,n,a,h,l,c){throw new Error("Import MeshBuilder to populate this function")}static CreateLines(e,t,i,s,r){throw new Error("Import MeshBuilder to populate this function")}static CreateDashedLines(e,t,i,s,r,n,a,h){throw new Error("Import MeshBuilder to populate this function")}static CreatePolygon(e,t,i,s,r,n,a){throw new Error("Import MeshBuilder to populate this function")}static ExtrudePolygon(e,t,i,s,r,n,a,h){throw new Error("Import MeshBuilder to populate this function")}static ExtrudeShape(e,t,i,s,r,n,a,h,l,c){throw new Error("Import MeshBuilder to populate this function")}static ExtrudeShapeCustom(e,t,i,s,r,n,a,h,l,c,u,f){throw new Error("Import MeshBuilder to populate this function")}static CreateLathe(e,t,i,s,r,n,a){throw new Error("Import MeshBuilder to populate this function")}static CreatePlane(e,t,i,s,r){throw new Error("Import MeshBuilder to populate this function")}static CreateGround(e,t,i,s,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateTiledGround(e,t,i,s,r,n,a,h,l){throw new Error("Import MeshBuilder to populate this function")}static CreateGroundFromHeightMap(e,t,i,s,r,n,a,h,l,c,u){throw new Error("Import MeshBuilder to populate this function")}static CreateTube(e,t,i,s,r,n,a,h,l,c){throw new Error("Import MeshBuilder to populate this function")}static CreatePolyhedron(e,t,i){throw new Error("Import MeshBuilder to populate this function")}static CreateIcoSphere(e,t,i){throw new Error("Import MeshBuilder to populate this function")}static CreateDecal(e,t,i,s,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateCapsule(e,t,i){throw new Error("Import MeshBuilder to populate this function")}static ExtendToGoldberg(e){throw new Error("Import MeshBuilder to populate this function")}}F.FRONTSIDE=j.FRONTSIDE;F.BACKSIDE=j.BACKSIDE;F.DOUBLESIDE=j.DOUBLESIDE;F.DEFAULTSIDE=j.DEFAULTSIDE;F.NO_CAP=0;F.CAP_START=1;F.CAP_END=2;F.CAP_ALL=3;F.NO_FLIP=0;F.FLIP_TILE=1;F.ROTATE_TILE=2;F.FLIP_ROW=3;F.ROTATE_ROW=4;F.FLIP_N_ROTATE_TILE=5;F.FLIP_N_ROTATE_ROW=6;F.CENTER=0;F.LEFT=1;F.RIGHT=2;F.TOP=3;F.BOTTOM=4;F.INSTANCEDMESH_SORT_TRANSPARENT=!1;F._GroundMeshParser=(o,e)=>{throw pe("GroundMesh")};F._GoldbergMeshParser=(o,e)=>{throw pe("GoldbergMesh")};F._LinesMeshParser=(o,e)=>{throw pe("LinesMesh")};F._GreasedLineMeshParser=(o,e)=>{throw pe("GreasedLineMesh")};F._GreasedLineRibbonMeshParser=(o,e)=>{throw pe("GreasedLineRibbonMesh")};F._TrailMeshParser=(o,e)=>{throw pe("TrailMesh")};Ye("BABYLON.Mesh",F);function Nc(o){let e=o.pathArray;const t=o.closeArray||!1,i=o.closePath||!1,s=o.invertUV||!1,r=Math.floor(e[0].length/2);let n=o.offset||r;n=n>r?r:Math.floor(n);const a=o.sideOrientation===0?0:o.sideOrientation||j.DEFAULTSIDE,h=o.uvs,l=o.colors,c=[],u=[],f=[],d=[],_=[],m=[],g=[],T=[];let R;const A=[],y=[];let E,x,b;if(e.length<2){const _e=[],Fe=[];for(x=0;x<e[0].length-n;x++)_e.push(e[0][x]),Fe.push(e[0][x+n]);e=[_e,Fe]}let P=0;const v=i?1:0,O=t?1:0;let k,Y;R=e[0].length;let q,L;for(E=0;E<e.length+O;E++){for(g[E]=0,_[E]=[0],k=E===e.length?e[0]:e[E],Y=k.length,R=R<Y?R:Y,b=0;b<Y;)c.push(k[b].x,k[b].y,k[b].z),b>0&&(q=k[b].subtract(k[b-1]).length(),L=q+g[E],_[E].push(L),g[E]=L),b++;i&&(b--,c.push(k[0].x,k[0].y,k[0].z),q=k[b].subtract(k[0]).length(),L=q+g[E],_[E].push(L),g[E]=L),A[E]=Y+v,y[E]=P,P+=Y+v}let ee,Q,se,le;for(x=0;x<R+v;x++)for(T[x]=0,m[x]=[0],E=0;E<e.length-1+O;E++)ee=e[E],Q=E===e.length-1?e[0]:e[E+1],x===R?(se=ee[0],le=Q[0]):(se=ee[x],le=Q[x]),q=le.subtract(se).length(),L=q+T[x],m[x].push(L),T[x]=L;let H,K;if(h)for(E=0;E<h.length;E++)d.push(h[E].x,we?1-h[E].y:h[E].y);else for(E=0;E<e.length+O;E++)for(x=0;x<R+v;x++)H=g[E]!=0?_[E][x]/g[E]:0,K=T[x]!=0?m[x][E]/T[x]:0,s?d.push(K,H):d.push(H,we?1-K:K);E=0;let w=0,B=A[E]-1,N=A[E+1]-1,X=B<N?B:N,Ee=y[1]-y[0];const ae=A.length-1;for(;w<=X&&E<ae;)u.push(w,w+Ee,w+1),u.push(w+Ee+1,w+1,w+Ee),w+=1,w===X&&(E++,Ee=y[E+1]-y[E],B=A[E]-1,N=A[E+1]-1,w=y[E],X=B<N?B+w:N+w);if(j.ComputeNormals(c,u,f),i){let _e,Fe;for(E=0;E<e.length;E++){_e=y[E]*3,E+1<e.length?Fe=(y[E+1]-1)*3:Fe=f.length-3,f[_e]=(f[_e]+f[Fe])*.5,f[_e+1]=(f[_e+1]+f[Fe+1])*.5,f[_e+2]=(f[_e+2]+f[Fe+2])*.5;const Xe=Math.sqrt(f[_e]*f[_e]+f[_e+1]*f[_e+1]+f[_e+2]*f[_e+2]);f[_e]/=Xe,f[_e+1]/=Xe,f[_e+2]/=Xe,f[Fe]=f[_e],f[Fe+1]=f[_e+1],f[Fe+2]=f[_e+2]}}if(t){let _e=y[0]*3,Fe=y[e.length]*3;for(x=0;x<R+v;x++){f[_e]=(f[_e]+f[Fe])*.5,f[_e+1]=(f[_e+1]+f[Fe+1])*.5,f[_e+2]=(f[_e+2]+f[Fe+2])*.5;const Xe=Math.sqrt(f[_e]*f[_e]+f[_e+1]*f[_e+1]+f[_e+2]*f[_e+2]);f[_e]/=Xe,f[_e+1]/=Xe,f[_e+2]/=Xe,f[Fe]=f[_e],f[Fe+1]=f[_e+1],f[Fe+2]=f[_e+2],_e+=3,Fe+=3}}j._ComputeSides(a,c,u,f,d,o.frontUVs,o.backUVs);let Se=null;if(l){Se=new Float32Array(l.length*4);for(let _e=0;_e<l.length;_e++)Se[_e*4]=l[_e].r,Se[_e*4+1]=l[_e].g,Se[_e*4+2]=l[_e].b,Se[_e*4+3]=l[_e].a}const We=new j,nt=new Float32Array(c),ct=new Float32Array(f),Ge=new Float32Array(d);return We.indices=u,We.positions=nt,We.normals=ct,We.uvs=Ge,Se&&We.set(Se,S.ColorKind),i&&(We._idx=y),We}function Gi(o,e,t=null){const i=e.pathArray,s=e.closeArray,r=e.closePath,n=F._GetDefaultSideOrientation(e.sideOrientation),a=e.instance,h=e.updatable;if(a){const l=U.Vector3[0].setAll(Number.MAX_VALUE),c=U.Vector3[1].setAll(-Number.MAX_VALUE),u=d=>{let _=i[0].length;const m=a;let g=0;const T=m._originalBuilderSideOrientation===F.DOUBLESIDE?2:1;for(let R=1;R<=T;++R)for(let A=0;A<i.length;++A){const y=i[A],E=y.length;_=_<E?_:E;for(let x=0;x<_;++x){const b=y[x];d[g]=b.x,d[g+1]=b.y,d[g+2]=b.z,l.minimizeInPlaceFromFloats(b.x,b.y,b.z),c.maximizeInPlaceFromFloats(b.x,b.y,b.z),g+=3}if(m._creationDataStorage&&m._creationDataStorage.closePath){const x=y[0];d[g]=x.x,d[g+1]=x.y,d[g+2]=x.z,g+=3}}},f=a.getVerticesData(S.PositionKind);if(u(f),a.hasBoundingInfo?a.getBoundingInfo().reConstruct(l,c,a._worldMatrix):a.buildBoundingInfo(l,c,a._worldMatrix),a.updateVerticesData(S.PositionKind,f,!1,!1),e.colors){const d=a.getVerticesData(S.ColorKind);for(let _=0,m=0;_<e.colors.length;_++,m+=4){const g=e.colors[_];d[m]=g.r,d[m+1]=g.g,d[m+2]=g.b,d[m+3]=g.a}a.updateVerticesData(S.ColorKind,d,!1,!1)}if(e.uvs){const d=a.getVerticesData(S.UVKind);for(let _=0;_<e.uvs.length;_++)d[_*2]=e.uvs[_].x,d[_*2+1]=we?1-e.uvs[_].y:e.uvs[_].y;a.updateVerticesData(S.UVKind,d,!1,!1)}if(!a.areNormalsFrozen||a.isFacetDataEnabled){const d=a.getIndices(),_=a.getVerticesData(S.NormalKind),m=a.isFacetDataEnabled?a.getFacetDataParameters():null;if(j.ComputeNormals(f,d,_,m),a._creationDataStorage&&a._creationDataStorage.closePath){let g,T;for(let R=0;R<i.length;R++)g=a._creationDataStorage.idx[R]*3,R+1<i.length?T=(a._creationDataStorage.idx[R+1]-1)*3:T=_.length-3,_[g]=(_[g]+_[T])*.5,_[g+1]=(_[g+1]+_[T+1])*.5,_[g+2]=(_[g+2]+_[T+2])*.5,_[T]=_[g],_[T+1]=_[g+1],_[T+2]=_[g+2]}a.areNormalsFrozen||a.updateVerticesData(S.NormalKind,_,!1,!1)}return a}else{const l=new F(o,t);l._originalBuilderSideOrientation=n,l._creationDataStorage=new Bc;const c=Nc(e);return r&&(l._creationDataStorage.idx=c._idx),l._creationDataStorage.closePath=r,l._creationDataStorage.closeArray=s,c.applyToMesh(l,h),l}}const Dm={CreateRibbon:Gi};j.CreateRibbon=Nc;F.CreateRibbon=(o,e,t=!1,i,s,r,n=!1,a,h)=>Gi(o,{pathArray:e,closeArray:t,closePath:i,offset:s,updatable:n,sideOrientation:a,instance:h},r);function Uc(o){const e=[],t=[],i=[],s=[],r=o.radius||.5,n=o.tessellation||64,a=o.arc&&(o.arc<=0||o.arc>1)?1:o.arc||1,h=o.sideOrientation===0?0:o.sideOrientation||j.DEFAULTSIDE;e.push(0,0,0),s.push(.5,.5);const l=Math.PI*2*a,c=a===1?l/n:l/(n-1);let u=0;for(let _=0;_<n;_++){const m=Math.cos(u),g=Math.sin(u),T=(m+1)/2,R=(1-g)/2;e.push(r*m,r*g,0),s.push(T,we?1-R:R),u+=c}a===1&&(e.push(e[3],e[4],e[5]),s.push(s[2],we?1-s[3]:s[3]));const f=e.length/3;for(let _=1;_<f-1;_++)t.push(_+1,0,_);j.ComputeNormals(e,t,i),j._ComputeSides(h,e,t,i,s,o.frontUVs,o.backUVs);const d=new j;return d.indices=t,d.positions=e,d.normals=i,d.uvs=s,d}function oo(o,e={},t=null){const i=new F(o,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Uc(e).applyToMesh(i,e.updatable),i}const Om={CreateDisc:oo};j.CreateDisc=Uc;F.CreateDisc=(o,e,t,i=null,s,r)=>oo(o,{radius:e,tessellation:t,sideOrientation:r,updatable:s},i);F._GroundMeshParser=(o,e)=>mr.Parse(o,e);class mr extends F{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);const i=this;i.createOrUpdateSubmeshesOctree&&i.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),s=U.Matrix[5];i.invertToRef(s);const r=U.Vector3[8];if(p.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.z,e<this._minX||e>=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const n=this._getFacetAt(e,t),a=-(n.x*e+n.z*t+n.w)/n.y;return p.TransformCoordinatesFromFloatsToRef(0,a,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new p(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),r=U.Matrix[5];s.invertToRef(r);const n=U.Vector3[8];if(p.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)return this;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const a=this._getFacetAt(e,t);return p.TransformNormalFromFloatsToRef(a.x,a.y,a.z,s,i),this}updateCoordinateHeights(){return(!this._heightQuads||this._heightQuads.length==0)&&this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),s=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[s*this._subdivisionsX+i];let n;return t<r.slope.x*e+r.slope.y?n=r.facet1:n=r.facet2,n}_initHeightQuads(){const e=this._subdivisionsX,t=this._subdivisionsY;this._heightQuads=[];for(let i=0;i<t;i++)for(let s=0;s<e;s++){const r={slope:ie.Zero(),facet1:new Me(0,0,0,0),facet2:new Me(0,0,0,0)};this._heightQuads[i*e+s]=r}return this}_computeHeightQuads(){const e=this.getVerticesData(S.PositionKind);if(!e)return this;const t=U.Vector3[3],i=U.Vector3[2],s=U.Vector3[1],r=U.Vector3[0],n=U.Vector3[4],a=U.Vector3[5],h=U.Vector3[6],l=U.Vector3[7],c=U.Vector3[8];let u,f,d,_,m,g,T;const R=this._subdivisionsX,A=this._subdivisionsY;for(let y=0;y<A;y++)for(let E=0;E<R;E++){u=E*3,f=y*(R+1)*3,d=(y+1)*(R+1)*3,t.x=e[f+u],t.y=e[f+u+1],t.z=e[f+u+2],i.x=e[f+u+3],i.y=e[f+u+4],i.z=e[f+u+5],s.x=e[d+u],s.y=e[d+u+1],s.z=e[d+u+2],r.x=e[d+u+3],r.y=e[d+u+4],r.z=e[d+u+5],_=(r.z-t.z)/(r.x-t.x),m=t.z-_*t.x,i.subtractToRef(t,n),s.subtractToRef(t,a),r.subtractToRef(t,h),p.CrossToRef(h,a,l),p.CrossToRef(n,h,c),l.normalize(),c.normalize(),g=-(l.x*t.x+l.y*t.y+l.z*t.z),T=-(c.x*i.x+c.y*i.y+c.z*i.z);const x=this._heightQuads[y*R+E];x.slope.copyFromFloats(_,m),x.facet1.copyFromFloats(l.x,l.y,l.z,g),x.facet2.copyFromFloats(c.x,c.y,c.z,T)}return this}serialize(e){super.serialize(e),e.subdivisionsX=this._subdivisionsX,e.subdivisionsY=this._subdivisionsY,e.minX=this._minX,e.maxX=this._maxX,e.minZ=this._minZ,e.maxZ=this._maxZ,e.width=this._width,e.height=this._height}static Parse(e,t){const i=new mr(e.name,t);return i._subdivisionsX=e.subdivisionsX||1,i._subdivisionsY=e.subdivisionsY||1,i._minX=e.minX,i._maxX=e.maxX,i._minZ=e.minZ,i._maxZ=e.maxZ,i._width=e.width,i._height=e.height,i}}function Oi(o){const e=[],t=[],i=[],s=[];let r,n;const a=o.width||o.size||1,h=o.height||o.size||1,l=(o.subdivisionsX||o.subdivisions||1)|0,c=(o.subdivisionsY||o.subdivisions||1)|0;for(r=0;r<=c;r++)for(n=0;n<=l;n++){const f=new p(n*a/l-a/2,0,(c-r)*h/c-h/2),d=new p(0,1,0);t.push(f.x,f.y,f.z),i.push(d.x,d.y,d.z),s.push(n/l,we?r/c:1-r/c)}for(r=0;r<c;r++)for(n=0;n<l;n++)e.push(n+1+(r+1)*(l+1)),e.push(n+1+r*(l+1)),e.push(n+r*(l+1)),e.push(n+(r+1)*(l+1)),e.push(n+1+(r+1)*(l+1)),e.push(n+r*(l+1));const u=new j;return u.indices=e,u.positions=t,u.normals=i,u.uvs=s,u}function kc(o){const e=o.xmin!==void 0&&o.xmin!==null?o.xmin:-1,t=o.zmin!==void 0&&o.zmin!==null?o.zmin:-1,i=o.xmax!==void 0&&o.xmax!==null?o.xmax:1,s=o.zmax!==void 0&&o.zmax!==null?o.zmax:1,r=o.subdivisions||{w:1,h:1},n=o.precision||{w:1,h:1},a=[],h=[],l=[],c=[];let u,f,d,_;r.h=r.h<1?1:r.h,r.w=r.w<1?1:r.w,n.w=n.w<1?1:n.w,n.h=n.h<1?1:n.h;const m={w:(i-e)/r.w,h:(s-t)/r.h};function g(R,A,y,E){const x=h.length/3,b=n.w+1;for(u=0;u<n.h;u++)for(f=0;f<n.w;f++){const O=[x+f+u*b,x+(f+1)+u*b,x+(f+1)+(u+1)*b,x+f+(u+1)*b];a.push(O[1]),a.push(O[2]),a.push(O[3]),a.push(O[0]),a.push(O[1]),a.push(O[3])}const P=p.Zero(),v=new p(0,1,0);for(u=0;u<=n.h;u++)for(P.z=u*(E-A)/n.h+A,f=0;f<=n.w;f++)P.x=f*(y-R)/n.w+R,P.y=0,h.push(P.x,P.y,P.z),l.push(v.x,v.y,v.z),c.push(f/n.w,u/n.h)}for(d=0;d<r.h;d++)for(_=0;_<r.w;_++)g(e+_*m.w,t+d*m.h,e+(_+1)*m.w,t+(d+1)*m.h);const T=new j;return T.indices=a,T.positions=h,T.normals=l,T.uvs=c,T}function Vc(o){const e=[],t=[],i=[],s=[];let r,n;const a=o.colorFilter||new Re(.3,.59,.11),h=o.alphaFilter||0;let l=!1;if(o.minHeight>o.maxHeight){l=!0;const u=o.maxHeight;o.maxHeight=o.minHeight,o.minHeight=u}for(r=0;r<=o.subdivisions;r++)for(n=0;n<=o.subdivisions;n++){const u=new p(n*o.width/o.subdivisions-o.width/2,0,(o.subdivisions-r)*o.height/o.subdivisions-o.height/2),f=(u.x+o.width/2)/o.width*(o.bufferWidth-1)|0,d=(1-(u.z+o.height/2)/o.height)*(o.bufferHeight-1)|0,_=(f+d*o.bufferWidth)*4;let m=o.buffer[_]/255,g=o.buffer[_+1]/255,T=o.buffer[_+2]/255;const R=o.buffer[_+3]/255;l&&(m=1-m,g=1-g,T=1-T);const A=m*a.r+g*a.g+T*a.b;R>=h?u.y=o.minHeight+(o.maxHeight-o.minHeight)*A:u.y=o.minHeight-Ke,o.heightBuffer&&(o.heightBuffer[r*(o.subdivisions+1)+n]=u.y),t.push(u.x,u.y,u.z),i.push(0,0,0),s.push(n/o.subdivisions,1-r/o.subdivisions)}for(r=0;r<o.subdivisions;r++)for(n=0;n<o.subdivisions;n++){const u=n+1+(r+1)*(o.subdivisions+1),f=n+1+r*(o.subdivisions+1),d=n+r*(o.subdivisions+1),_=n+(r+1)*(o.subdivisions+1),m=t[u*3+1]>=o.minHeight,g=t[f*3+1]>=o.minHeight,T=t[d*3+1]>=o.minHeight;m&&g&&T&&(e.push(u),e.push(f),e.push(d)),t[_*3+1]>=o.minHeight&&m&&T&&(e.push(_),e.push(u),e.push(d))}j.ComputeNormals(t,e,i);const c=new j;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function ho(o,e={},t){const i=new mr(o,t);return i._setReady(!1),i._subdivisionsX=e.subdivisionsX||e.subdivisions||1,i._subdivisionsY=e.subdivisionsY||e.subdivisions||1,i._width=e.width||1,i._height=e.height||1,i._maxX=i._width/2,i._maxZ=i._height/2,i._minX=-i._maxX,i._minZ=-i._maxZ,Oi(e).applyToMesh(i,e.updatable),i._setReady(!0),i}function lo(o,e,t=null){const i=new F(o,t);return kc(e).applyToMesh(i,e.updatable),i}function co(o,e,t={},i=null){const s=t.width||10,r=t.height||10,n=t.subdivisions||1,a=t.minHeight||0,h=t.maxHeight||1,l=t.colorFilter||new Re(.3,.59,.11),c=t.alphaFilter||0,u=t.updatable,f=t.onReady;i=i||ye.LastCreatedScene;const d=new mr(o,i);d._subdivisionsX=n,d._subdivisionsY=n,d._width=s,d._height=r,d._maxX=d._width/2,d._maxZ=d._height/2,d._minX=-d._maxX,d._minZ=-d._maxZ,d._setReady(!1);let _;t.passHeightBufferInCallback&&(_=new Float32Array((n+1)*(n+1)));const m=(g,T,R)=>{Vc({width:s,height:r,subdivisions:n,minHeight:a,maxHeight:h,colorFilter:l,buffer:g,bufferWidth:T,bufferHeight:R,alphaFilter:c,heightBuffer:_}).applyToMesh(d,u),f&&f(d,_),d._setReady(!0)};if(typeof e=="string"){const g=T=>{const R=T.width,A=T.height;if(i.isDisposed)return;const y=i?.getEngine().resizeImageBitmap(T,R,A);m(y,R,A)};fe.LoadImage(e,g,t.onError?t.onError:()=>{},i.offlineProvider)}else m(e.data,e.width,e.height);return d}const Fm={CreateGround:ho,CreateGroundFromHeightMap:co,CreateTiledGround:lo};j.CreateGround=Oi;j.CreateTiledGround=kc;j.CreateGroundFromHeightMap=Vc;F.CreateGround=(o,e,t,i,s,r)=>ho(o,{width:e,height:t,subdivisions:i,updatable:r},s);F.CreateTiledGround=(o,e,t,i,s,r,n,a,h)=>lo(o,{xmin:e,zmin:t,xmax:i,zmax:s,subdivisions:r,precision:n,updatable:h},a);F.CreateGroundFromHeightMap=(o,e,t,i,s,r,n,a,h,l,c)=>co(o,e,{width:t,height:i,subdivisions:s,minHeight:r,maxHeight:n,updatable:h,onReady:l,alphaFilter:c},a);function zc(o){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],s=[],r=o.width||o.size||1,n=o.height||o.size||1,a=o.depth||o.size||1,h=o.wrap||!1;let l=o.topBaseAt===void 0?1:o.topBaseAt,c=o.bottomBaseAt===void 0?0:o.bottomBaseAt;l=(l+4)%4,c=(c+4)%4;const u=[2,0,3,1],f=[2,0,1,3];let d=u[l],_=f[c],m=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(h){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],m=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let b=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],P=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const v=[17,18,19,16],O=[22,23,20,21];for(;d>0;)b.unshift(b.pop()),v.unshift(v.pop()),d--;for(;_>0;)P.unshift(P.pop()),O.unshift(O.pop()),_--;b=b.flat(),P=P.flat(),m=m.concat(b).concat(P),t.push(v[0],v[2],v[3],v[0],v[1],v[2]),t.push(O[0],O[2],O[3],O[0],O[1],O[2])}const g=[r/2,n/2,a/2],T=m.reduce((b,P,v)=>b.concat(P*g[v%3]),[]),R=o.sideOrientation===0?0:o.sideOrientation||j.DEFAULTSIDE,A=o.faceUV||new Array(6),y=o.faceColors,E=[];for(let b=0;b<6;b++)A[b]===void 0&&(A[b]=new Me(0,0,1,1)),y&&y[b]===void 0&&(y[b]=new Ce(1,1,1,1));for(let b=0;b<6;b++)if(s.push(A[b].z,we?1-A[b].w:A[b].w),s.push(A[b].x,we?1-A[b].w:A[b].w),s.push(A[b].x,we?1-A[b].y:A[b].y),s.push(A[b].z,we?1-A[b].y:A[b].y),y)for(let P=0;P<4;P++)E.push(y[b].r,y[b].g,y[b].b,y[b].a);j._ComputeSides(R,T,t,i,s,o.frontUVs,o.backUVs);const x=new j;if(x.indices=t,x.positions=T,x.normals=i,x.uvs=s,y){const b=R===j.DOUBLESIDE?E.concat(E):E;x.colors=b}return x}function wm(o){const e=o.width||o.size||1,t=o.height||o.size||1,i=o.depth||o.size||1,s=(o.widthSegments||o.segments||1)|0,r=(o.heightSegments||o.segments||1)|0,n=(o.depthSegments||o.segments||1)|0,a=new D,h=new D,l=new D,c=Oi({width:e,height:i,subdivisionsX:s,subdivisionsY:n});D.TranslationToRef(0,-t/2,0,h),D.RotationZToRef(Math.PI,a),a.multiplyToRef(h,l),c.transform(l);const u=Oi({width:e,height:i,subdivisionsX:s,subdivisionsY:n});D.TranslationToRef(0,t/2,0,l),u.transform(l);const f=Oi({width:t,height:i,subdivisionsX:r,subdivisionsY:n});D.TranslationToRef(-e/2,0,0,h),D.RotationZToRef(Math.PI/2,a),a.multiplyToRef(h,l),f.transform(l);const d=Oi({width:t,height:i,subdivisionsX:r,subdivisionsY:n});D.TranslationToRef(e/2,0,0,h),D.RotationZToRef(-Math.PI/2,a),a.multiplyToRef(h,l),d.transform(l);const _=Oi({width:e,height:t,subdivisionsX:s,subdivisionsY:r});D.TranslationToRef(0,0,-i/2,h),D.RotationXToRef(-Math.PI/2,a),a.multiplyToRef(h,l),_.transform(l);const m=Oi({width:e,height:t,subdivisionsX:s,subdivisionsY:r});return D.TranslationToRef(0,0,i/2,h),D.RotationXToRef(Math.PI/2,a),a.multiplyToRef(h,l),m.transform(l),c.merge([u,d,f,_,m],!0),c}function uo(o,e={},t=null){const i=new F(o,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,zc(e).applyToMesh(i,e.updatable),i}const Lm={CreateBox:uo};j.CreateBox=zc;F.CreateBox=(o,e,t=null,i,s)=>uo(o,{size:e,sideOrientation:s,updatable:i},t);function zs(o){const e=o.pattern||F.NO_FLIP,t=o.tileWidth||o.tileSize||1,i=o.tileHeight||o.tileSize||1,s=o.alignHorizontal||0,r=o.alignVertical||0,n=o.width||o.size||1,a=Math.floor(n/t);let h=n-a*t;const l=o.height||o.size||1,c=Math.floor(l/i);let u=l-c*i;const f=t*a/2,d=i*c/2;let _=0,m=0,g=0,T=0,R=0,A=0;if(h>0||u>0){switch(g=-f,T=-d,R=f,A=d,s){case F.CENTER:h/=2,g-=h,R+=h;break;case F.LEFT:R+=h,_=-h/2;break;case F.RIGHT:g-=h,_=h/2;break}switch(r){case F.CENTER:u/=2,T-=u,A+=u;break;case F.BOTTOM:A+=u,m=-u/2;break;case F.TOP:T-=u,m=u/2;break}}const y=[],E=[],x=[];x[0]=[0,0,1,0,1,1,0,1],x[1]=[0,0,1,0,1,1,0,1],(e===F.ROTATE_TILE||e===F.ROTATE_ROW)&&(x[1]=[1,1,0,1,0,0,1,0]),(e===F.FLIP_TILE||e===F.FLIP_ROW)&&(x[1]=[1,0,0,0,0,1,1,1]),(e===F.FLIP_N_ROTATE_TILE||e===F.FLIP_N_ROTATE_ROW)&&(x[1]=[0,1,1,1,1,0,0,0]);let b=[];const P=[],v=[];let O=0;for(let L=0;L<c;L++)for(let ee=0;ee<a;ee++)y.push(-f+ee*t+_,-d+L*i+m,0),y.push(-f+(ee+1)*t+_,-d+L*i+m,0),y.push(-f+(ee+1)*t+_,-d+(L+1)*i+m,0),y.push(-f+ee*t+_,-d+(L+1)*i+m,0),v.push(O,O+1,O+3,O+1,O+2,O+3),e===F.FLIP_TILE||e===F.ROTATE_TILE||e===F.FLIP_N_ROTATE_TILE?b=b.concat(x[(ee%2+L%2)%2]):e===F.FLIP_ROW||e===F.ROTATE_ROW||e===F.FLIP_N_ROTATE_ROW?b=b.concat(x[L%2]):b=b.concat(x[0]),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1),O+=4;if(h>0||u>0){const L=u>0&&(r===F.CENTER||r===F.TOP),ee=u>0&&(r===F.CENTER||r===F.BOTTOM),Q=h>0&&(s===F.CENTER||s===F.RIGHT),se=h>0&&(s===F.CENTER||s===F.LEFT);let le,H,K,w,B;if(L&&Q&&(y.push(g+_,T+m,0),y.push(-f+_,T+m,0),y.push(-f+_,T+u+m,0),y.push(g+_,T+u+m,0),v.push(O,O+1,O+3,O+1,O+2,O+3),O+=4,H=1-h/t,K=1-u/i,w=1,B=1,le=[H,K,w,K,w,B,H,B],e===F.ROTATE_ROW&&(le=[1-H,1-K,1-w,1-K,1-w,1-B,1-H,1-B]),e===F.FLIP_ROW&&(le=[1-H,K,1-w,K,1-w,B,1-H,B]),e===F.FLIP_N_ROTATE_ROW&&(le=[H,1-K,w,1-K,w,1-B,H,1-B]),b=b.concat(le),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),L&&se&&(y.push(f+_,T+m,0),y.push(R+_,T+m,0),y.push(R+_,T+u+m,0),y.push(f+_,T+u+m,0),v.push(O,O+1,O+3,O+1,O+2,O+3),O+=4,H=0,K=1-u/i,w=h/t,B=1,le=[H,K,w,K,w,B,H,B],(e===F.ROTATE_ROW||e===F.ROTATE_TILE&&a%2===0)&&(le=[1-H,1-K,1-w,1-K,1-w,1-B,1-H,1-B]),(e===F.FLIP_ROW||e===F.FLIP_TILE&&a%2===0)&&(le=[1-H,K,1-w,K,1-w,B,1-H,B]),(e===F.FLIP_N_ROTATE_ROW||e===F.FLIP_N_ROTATE_TILE&&a%2===0)&&(le=[H,1-K,w,1-K,w,1-B,H,1-B]),b=b.concat(le),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),ee&&Q&&(y.push(g+_,d+m,0),y.push(-f+_,d+m,0),y.push(-f+_,A+m,0),y.push(g+_,A+m,0),v.push(O,O+1,O+3,O+1,O+2,O+3),O+=4,H=1-h/t,K=0,w=1,B=u/i,le=[H,K,w,K,w,B,H,B],(e===F.ROTATE_ROW&&c%2===1||e===F.ROTATE_TILE&&c%1===0)&&(le=[1-H,1-K,1-w,1-K,1-w,1-B,1-H,1-B]),(e===F.FLIP_ROW&&c%2===1||e===F.FLIP_TILE&&c%2===0)&&(le=[1-H,K,1-w,K,1-w,B,1-H,B]),(e===F.FLIP_N_ROTATE_ROW&&c%2===1||e===F.FLIP_N_ROTATE_TILE&&c%2===0)&&(le=[H,1-K,w,1-K,w,1-B,H,1-B]),b=b.concat(le),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),ee&&se&&(y.push(f+_,d+m,0),y.push(R+_,d+m,0),y.push(R+_,A+m,0),y.push(f+_,A+m,0),v.push(O,O+1,O+3,O+1,O+2,O+3),O+=4,H=0,K=0,w=h/t,B=u/i,le=[H,K,w,K,w,B,H,B],(e===F.ROTATE_ROW&&c%2===1||e===F.ROTATE_TILE&&(c+a)%2===1)&&(le=[1-H,1-K,1-w,1-K,1-w,1-B,1-H,1-B]),(e===F.FLIP_ROW&&c%2===1||e===F.FLIP_TILE&&(c+a)%2===1)&&(le=[1-H,K,1-w,K,1-w,B,1-H,B]),(e===F.FLIP_N_ROTATE_ROW&&c%2===1||e===F.FLIP_N_ROTATE_TILE&&(c+a)%2===1)&&(le=[H,1-K,w,1-K,w,1-B,H,1-B]),b=b.concat(le),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),L){const N=[];H=0,K=1-u/i,w=1,B=1,N[0]=[H,K,w,K,w,B,H,B],N[1]=[H,K,w,K,w,B,H,B],(e===F.ROTATE_TILE||e===F.ROTATE_ROW)&&(N[1]=[1-H,1-K,1-w,1-K,1-w,1-B,1-H,1-B]),(e===F.FLIP_TILE||e===F.FLIP_ROW)&&(N[1]=[1-H,K,1-w,K,1-w,B,1-H,B]),(e===F.FLIP_N_ROTATE_TILE||e===F.FLIP_N_ROTATE_ROW)&&(N[1]=[H,1-K,w,1-K,w,1-B,H,1-B]);for(let X=0;X<a;X++)y.push(-f+X*t+_,T+m,0),y.push(-f+(X+1)*t+_,T+m,0),y.push(-f+(X+1)*t+_,T+u+m,0),y.push(-f+X*t+_,T+u+m,0),v.push(O,O+1,O+3,O+1,O+2,O+3),O+=4,e===F.FLIP_TILE||e===F.ROTATE_TILE||e===F.FLIP_N_ROTATE_TILE?b=b.concat(N[(X+1)%2]):e===F.FLIP_ROW||e===F.ROTATE_ROW||e===F.FLIP_N_ROTATE_ROW?b=b.concat(N[1]):b=b.concat(N[0]),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(ee){const N=[];H=0,K=0,w=1,B=u/i,N[0]=[H,K,w,K,w,B,H,B],N[1]=[H,K,w,K,w,B,H,B],(e===F.ROTATE_TILE||e===F.ROTATE_ROW)&&(N[1]=[1-H,1-K,1-w,1-K,1-w,1-B,1-H,1-B]),(e===F.FLIP_TILE||e===F.FLIP_ROW)&&(N[1]=[1-H,K,1-w,K,1-w,B,1-H,B]),(e===F.FLIP_N_ROTATE_TILE||e===F.FLIP_N_ROTATE_ROW)&&(N[1]=[H,1-K,w,1-K,w,1-B,H,1-B]);for(let X=0;X<a;X++)y.push(-f+X*t+_,A-u+m,0),y.push(-f+(X+1)*t+_,A-u+m,0),y.push(-f+(X+1)*t+_,A+m,0),y.push(-f+X*t+_,A+m,0),v.push(O,O+1,O+3,O+1,O+2,O+3),O+=4,e===F.FLIP_TILE||e===F.ROTATE_TILE||e===F.FLIP_N_ROTATE_TILE?b=b.concat(N[(X+c)%2]):e===F.FLIP_ROW||e===F.ROTATE_ROW||e===F.FLIP_N_ROTATE_ROW?b=b.concat(N[c%2]):b=b.concat(N[0]),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(Q){const N=[];H=1-h/t,K=0,w=1,B=1,N[0]=[H,K,w,K,w,B,H,B],N[1]=[H,K,w,K,w,B,H,B],(e===F.ROTATE_TILE||e===F.ROTATE_ROW)&&(N[1]=[1-H,1-K,1-w,1-K,1-w,1-B,1-H,1-B]),(e===F.FLIP_TILE||e===F.FLIP_ROW)&&(N[1]=[1-H,K,1-w,K,1-w,B,1-H,B]),(e===F.FLIP_N_ROTATE_TILE||e===F.FLIP_N_ROTATE_ROW)&&(N[1]=[H,1-K,w,1-K,w,1-B,H,1-B]);for(let X=0;X<c;X++)y.push(g+_,-d+X*i+m,0),y.push(g+h+_,-d+X*i+m,0),y.push(g+h+_,-d+(X+1)*i+m,0),y.push(g+_,-d+(X+1)*i+m,0),v.push(O,O+1,O+3,O+1,O+2,O+3),O+=4,e===F.FLIP_TILE||e===F.ROTATE_TILE||e===F.FLIP_N_ROTATE_TILE?b=b.concat(N[(X+1)%2]):e===F.FLIP_ROW||e===F.ROTATE_ROW||e===F.FLIP_N_ROTATE_ROW?b=b.concat(N[X%2]):b=b.concat(N[0]),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(se){const N=[];H=0,K=0,w=h/i,B=1,N[0]=[H,K,w,K,w,B,H,B],N[1]=[H,K,w,K,w,B,H,B],(e===F.ROTATE_TILE||e===F.ROTATE_ROW)&&(N[1]=[1-H,1-K,1-w,1-K,1-w,1-B,1-H,1-B]),(e===F.FLIP_TILE||e===F.FLIP_ROW)&&(N[1]=[1-H,K,1-w,K,1-w,B,1-H,B]),(e===F.FLIP_N_ROTATE_TILE||e===F.FLIP_N_ROTATE_ROW)&&(N[1]=[H,1-K,w,1-K,w,1-B,H,1-B]);for(let X=0;X<c;X++)y.push(R-h+_,-d+X*i+m,0),y.push(R+_,-d+X*i+m,0),y.push(R+_,-d+(X+1)*i+m,0),y.push(R-h+_,-d+(X+1)*i+m,0),v.push(O,O+1,O+3,O+1,O+2,O+3),O+=4,e===F.FLIP_TILE||e===F.ROTATE_TILE||e===F.FLIP_N_ROTATE_TILE?b=b.concat(N[(X+a)%2]):e===F.FLIP_ROW||e===F.ROTATE_ROW||e===F.FLIP_N_ROTATE_ROW?b=b.concat(N[X%2]):b=b.concat(N[0]),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}}const k=o.sideOrientation===0?0:o.sideOrientation||j.DEFAULTSIDE;j._ComputeSides(k,y,v,E,b,o.frontUVs,o.backUVs);const Y=new j;Y.indices=v,Y.positions=y,Y.normals=E,Y.uvs=b;const q=k===j.DOUBLESIDE?P.concat(P):P;return Y.colors=q,Y}function Wc(o,e,t=null){const i=new F(o,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,zs(e).applyToMesh(i,e.updatable),i}const Bm={CreateTiledPlane:Wc};j.CreateTiledPlane=zs;const Ar=1,Mn=-1;function Gc(o){const t=o.faceUV||new Array(6),i=o.faceColors,s=o.pattern||F.NO_FLIP,r=o.width||o.size||1,n=o.height||o.size||1,a=o.depth||o.size||1,h=o.tileWidth||o.tileSize||1,l=o.tileHeight||o.tileSize||1,c=o.alignHorizontal||0,u=o.alignVertical||0,f=o.sideOrientation===0?0:o.sideOrientation||j.DEFAULTSIDE;for(let L=0;L<6;L++)t[L]===void 0&&(t[L]=new Me(0,0,1,1)),i&&i[L]===void 0&&(i[L]=new Ce(1,1,1,1));const d=r/2,_=n/2,m=a/2,g=[];for(let L=0;L<2;L++)g[L]=zs({pattern:s,tileWidth:h,tileHeight:l,width:r,height:n,alignVertical:u,alignHorizontal:c,sideOrientation:f});for(let L=2;L<4;L++)g[L]=zs({pattern:s,tileWidth:h,tileHeight:l,width:a,height:n,alignVertical:u,alignHorizontal:c,sideOrientation:f});let T=u;u===F.BOTTOM?T=F.TOP:u===F.TOP&&(T=F.BOTTOM);for(let L=4;L<6;L++)g[L]=zs({pattern:s,tileWidth:h,tileHeight:l,width:r,height:a,alignVertical:T,alignHorizontal:c,sideOrientation:f});const R=[],A=[];let y=[],E=[];const x=[],b=[],P=[],v=[];let O,k=0;for(let L=0;L<6;L++){const ee=g[L].positions.length;b[L]=[],P[L]=[];for(let Q=0;Q<ee/3;Q++)b[L].push(new p(g[L].positions[3*Q],g[L].positions[3*Q+1],g[L].positions[3*Q+2])),P[L].push(new p(g[L].normals[3*Q],g[L].normals[3*Q+1],g[L].normals[3*Q+2]));O=g[L].uvs.length,v[L]=[];for(let Q=0;Q<O;Q+=2)v[L][Q]=t[L].x+(t[L].z-t[L].x)*g[L].uvs[Q],v[L][Q+1]=t[L].y+(t[L].w-t[L].y)*g[L].uvs[Q+1],we&&(v[L][Q+1]=1-v[L][Q+1]);if(y=y.concat(v[L]),E=E.concat(g[L].indices.map(Q=>Q+k)),k+=b[L].length,i){const Q=i[L];for(let se=0;se<b[L].length;se++)x.push(Q.r,Q.g,Q.b,Q.a)}}const Y=[{m:D.RotationY(Math.PI),t:new p(0,0,m),op:Ar},{m:D.Identity(),t:new p(0,0,m),op:Mn},{m:D.RotationY(-Math.PI/2),t:new p(d,0,0),op:Ar},{m:D.RotationY(Math.PI/2),t:new p(d,0,0),op:Mn},{m:D.RotationX(Math.PI/2),t:new p(0,_,0),op:Ar},{m:D.RotationX(-Math.PI/2),t:new p(0,_,0),op:Mn}];for(let L=0;L<6;L++){const{m:ee,t:Q,op:se}=Y[L];for(const le of b[L]){const H=p.TransformCoordinates(le,ee),K=se===Ar?H.add(Q):H.subtract(Q);R.push(K.x,K.y,K.z)}for(const le of P[L]){const H=p.TransformNormal(le,ee);A.push(H.x,H.y,H.z)}}const q=new j;if(q.indices=E,q.positions=R,q.normals=A,q.uvs=y,i){const L=f===j.DOUBLESIDE?x.concat(x):x;q.colors=L}return q}function Hc(o,e,t=null){const i=new F(o,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Gc(e).applyToMesh(i,e.updatable),i}const Nm={CreateTiledBox:Hc};j.CreateTiledBox=Gc;function Xc(o){const e=(o.segments||32)|0,t=o.diameterX||o.diameter||1,i=o.diameterY||o.diameter||1,s=o.diameterZ||o.diameter||1,r=o.arc&&(o.arc<=0||o.arc>1)?1:o.arc||1,n=o.slice&&o.slice<=0?1:o.slice||1,a=o.sideOrientation===0?0:o.sideOrientation||j.DEFAULTSIDE,h=!!o.dedupTopBottomIndices,l=new p(t/2,i/2,s/2),c=2+e,u=2*c,f=[],d=[],_=[],m=[];for(let T=0;T<=c;T++){const R=T/c,A=R*Math.PI*n;for(let y=0;y<=u;y++){const E=y/u,x=E*Math.PI*2*r,b=D.RotationZ(-A),P=D.RotationY(x),v=p.TransformCoordinates(p.Up(),b),O=p.TransformCoordinates(v,P),k=O.multiply(l),Y=O.divide(l).normalize();d.push(k.x,k.y,k.z),_.push(Y.x,Y.y,Y.z),m.push(E,we?1-R:R)}if(T>0){const y=d.length/3;for(let E=y-2*(u+1);E+u+2<y;E++)h?(T>1&&(f.push(E),f.push(E+1),f.push(E+u+1)),(T<c||n<1)&&(f.push(E+u+1),f.push(E+1),f.push(E+u+2))):(f.push(E),f.push(E+1),f.push(E+u+1),f.push(E+u+1),f.push(E+1),f.push(E+u+2))}}j._ComputeSides(a,d,f,_,m,o.frontUVs,o.backUVs);const g=new j;return g.indices=f,g.positions=d,g.normals=_,g.uvs=m,g}function fo(o,e={},t=null){const i=new F(o,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Xc(e).applyToMesh(i,e.updatable),i}const Um={CreateSphere:fo};j.CreateSphere=Xc;F.CreateSphere=(o,e,t,i,s,r)=>fo(o,{segments:e,diameterX:t,diameterY:t,diameterZ:t,sideOrientation:r,updatable:s},i);function Kc(o){const e=o.height||2;let t=o.diameterTop===0?0:o.diameterTop||o.diameter||1,i=o.diameterBottom===0?0:o.diameterBottom||o.diameter||1;t=t||1e-5,i=i||1e-5;const s=(o.tessellation||24)|0,r=(o.subdivisions||1)|0,n=!!o.hasRings,a=!!o.enclose,h=o.cap===0?0:o.cap||F.CAP_ALL,l=o.arc&&(o.arc<=0||o.arc>1)?1:o.arc||1,c=o.sideOrientation===0?0:o.sideOrientation||j.DEFAULTSIDE,u=o.faceUV||new Array(3),f=o.faceColors,d=l!==1&&a?2:0,_=n?r:1,m=2+(1+d)*_;let g;for(g=0;g<m;g++)f&&f[g]===void 0&&(f[g]=new Ce(1,1,1,1));for(g=0;g<m;g++)u&&u[g]===void 0&&(u[g]=new Me(0,0,1,1));const T=[],R=[],A=[],y=[],E=[],x=Math.PI*2*l/s;let b,P,v;const O=(i-t)/2/e,k=p.Zero(),Y=p.Zero(),q=p.Zero(),L=p.Zero(),ee=p.Zero(),Q=Vi.Y;let se,le,H,K,w=1,B=0,N;for(se=0;se<=r;se++)for(P=se/r,v=(P*(t-i)+i)/2,K=n&&se!==0&&se!==r?2:1,H=0;H<K;H++){for(n&&(w+=H),a&&(w+=2*H),le=0;le<=s;le++)b=le*x,k.x=Math.cos(-b)*v,k.y=-e/2+P*e,k.z=Math.sin(-b)*v,t===0&&se===r?(Y.x=A[A.length-(s+1)*3],Y.y=A[A.length-(s+1)*3+1],Y.z=A[A.length-(s+1)*3+2]):(Y.x=k.x,Y.z=k.z,Y.y=Math.sqrt(Y.x*Y.x+Y.z*Y.z)*O,Y.normalize()),le===0&&(q.copyFrom(k),L.copyFrom(Y)),R.push(k.x,k.y,k.z),A.push(Y.x,Y.y,Y.z),n?N=B!==w?u[w].y:u[w].w:N=u[w].y+(u[w].w-u[w].y)*P,y.push(u[w].x+(u[w].z-u[w].x)*le/s,we?1-N:N),f&&E.push(f[w].r,f[w].g,f[w].b,f[w].a);l!==1&&a&&(R.push(k.x,k.y,k.z),R.push(0,k.y,0),R.push(0,k.y,0),R.push(q.x,q.y,q.z),p.CrossToRef(Q,Y,ee),ee.normalize(),A.push(ee.x,ee.y,ee.z,ee.x,ee.y,ee.z),p.CrossToRef(L,Q,ee),ee.normalize(),A.push(ee.x,ee.y,ee.z,ee.x,ee.y,ee.z),n?N=B!==w?u[w+1].y:u[w+1].w:N=u[w+1].y+(u[w+1].w-u[w+1].y)*P,y.push(u[w+1].x,we?1-N:N),y.push(u[w+1].z,we?1-N:N),n?N=B!==w?u[w+2].y:u[w+2].w:N=u[w+2].y+(u[w+2].w-u[w+2].y)*P,y.push(u[w+2].x,we?1-N:N),y.push(u[w+2].z,we?1-N:N),f&&(E.push(f[w+1].r,f[w+1].g,f[w+1].b,f[w+1].a),E.push(f[w+1].r,f[w+1].g,f[w+1].b,f[w+1].a),E.push(f[w+2].r,f[w+2].g,f[w+2].b,f[w+2].a),E.push(f[w+2].r,f[w+2].g,f[w+2].b,f[w+2].a))),B!==w&&(B=w)}const X=l!==1&&a?s+4:s;for(se=0,w=0;w<r;w++){let Se=0,We=0,nt=0,ct=0;for(le=0;le<s;le++)Se=se*(X+1)+le,We=(se+1)*(X+1)+le,nt=se*(X+1)+(le+1),ct=(se+1)*(X+1)+(le+1),T.push(Se,We,nt),T.push(ct,nt,We);l!==1&&a&&(T.push(Se+2,We+2,nt+2),T.push(ct+2,nt+2,We+2),T.push(Se+4,We+4,nt+4),T.push(ct+4,nt+4,We+4)),se=n?se+2:se+1}const Ee=Se=>{const We=Se?t/2:i/2;if(We===0)return;let nt,ct,Ge;const _e=Se?u[m-1]:u[0];let Fe=null;f&&(Fe=Se?f[m-1]:f[0]);const Xe=R.length/3,Ae=Se?e/2:-e/2,$e=new p(0,Ae,0);R.push($e.x,$e.y,$e.z),A.push(0,Se?1:-1,0);const zt=_e.y+(_e.w-_e.y)*.5;y.push(_e.x+(_e.z-_e.x)*.5,we?1-zt:zt),Fe&&E.push(Fe.r,Fe.g,Fe.b,Fe.a);const bt=new ie(.5,.5);for(Ge=0;Ge<=s;Ge++){nt=Math.PI*2*Ge*l/s;const $t=Math.cos(-nt),Ii=Math.sin(-nt);ct=new p($t*We,Ae,Ii*We);const hi=new ie($t*bt.x+.5,Ii*bt.y+.5);R.push(ct.x,ct.y,ct.z),A.push(0,Se?1:-1,0);const ns=_e.y+(_e.w-_e.y)*hi.y;y.push(_e.x+(_e.z-_e.x)*hi.x,we?1-ns:ns),Fe&&E.push(Fe.r,Fe.g,Fe.b,Fe.a)}for(Ge=0;Ge<s;Ge++)Se?(T.push(Xe),T.push(Xe+(Ge+2)),T.push(Xe+(Ge+1))):(T.push(Xe),T.push(Xe+(Ge+1)),T.push(Xe+(Ge+2)))};(h===F.CAP_START||h===F.CAP_ALL)&&Ee(!1),(h===F.CAP_END||h===F.CAP_ALL)&&Ee(!0),j._ComputeSides(c,R,T,A,y,o.frontUVs,o.backUVs);const ae=new j;return ae.indices=T,ae.positions=R,ae.normals=A,ae.uvs=y,f&&(ae.colors=E),ae}function _o(o,e={},t){const i=new F(o,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Kc(e).applyToMesh(i,e.updatable),i}const km={CreateCylinder:_o};j.CreateCylinder=Kc;F.CreateCylinder=(o,e,t,i,s,r,n,a,h)=>((n===void 0||!(n instanceof je))&&(n!==void 0&&(h=a||F.DEFAULTSIDE,a=n),n=r,r=1),_o(o,{height:e,diameterTop:t,diameterBottom:i,tessellation:s,subdivisions:r,sideOrientation:h,updatable:a},n));function Yc(o){const e=[],t=[],i=[],s=[],r=o.diameter||1,n=o.thickness||.5,a=(o.tessellation||16)|0,h=o.sideOrientation===0?0:o.sideOrientation||j.DEFAULTSIDE,l=a+1;for(let u=0;u<=a;u++){const f=u/a,d=u*Math.PI*2/a-Math.PI/2,_=D.Translation(r/2,0,0).multiply(D.RotationY(d));for(let m=0;m<=a;m++){const g=1-m/a,T=m*Math.PI*2/a+Math.PI,R=Math.cos(T),A=Math.sin(T);let y=new p(R,A,0),E=y.scale(n/2);const x=new ie(f,g);E=p.TransformCoordinates(E,_),y=p.TransformNormal(y,_),t.push(E.x,E.y,E.z),i.push(y.x,y.y,y.z),s.push(x.x,we?1-x.y:x.y);const b=(u+1)%l,P=(m+1)%l;e.push(u*l+m),e.push(u*l+P),e.push(b*l+m),e.push(u*l+P),e.push(b*l+P),e.push(b*l+m)}}j._ComputeSides(h,t,e,i,s,o.frontUVs,o.backUVs);const c=new j;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function go(o,e={},t){const i=new F(o,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Yc(e).applyToMesh(i,e.updatable),i}const Vm={CreateTorus:go};j.CreateTorus=Yc;F.CreateTorus=(o,e,t,i,s,r,n)=>go(o,{diameter:e,thickness:t,tessellation:i,sideOrientation:n,updatable:r},s);function jc(o){const e=[],t=[],i=[],s=[],r=o.radius||2,n=o.tube||.5,a=o.radialSegments||32,h=o.tubularSegments||32,l=o.p||2,c=o.q||3,u=o.sideOrientation===0?0:o.sideOrientation||j.DEFAULTSIDE,f=g=>{const T=Math.cos(g),R=Math.sin(g),A=c/l*g,y=Math.cos(A),E=r*(2+y)*.5*T,x=r*(2+y)*R*.5,b=r*Math.sin(A)*.5;return new p(E,x,b)};let d,_;for(d=0;d<=a;d++){const T=d%a/a*2*l*Math.PI,R=f(T),A=f(T+.01),y=A.subtract(R);let E=A.add(R);const x=p.Cross(y,E);for(E=p.Cross(x,y),x.normalize(),E.normalize(),_=0;_<h;_++){const P=_%h/h*2*Math.PI,v=-n*Math.cos(P),O=n*Math.sin(P);t.push(R.x+v*E.x+O*x.x),t.push(R.y+v*E.y+O*x.y),t.push(R.z+v*E.z+O*x.z),s.push(d/a),s.push(we?1-_/h:_/h)}}for(d=0;d<a;d++)for(_=0;_<h;_++){const g=(_+1)%h,T=d*h+_,R=(d+1)*h+_,A=(d+1)*h+g,y=d*h+g;e.push(y),e.push(R),e.push(T),e.push(y),e.push(A),e.push(R)}j.ComputeNormals(t,e,i),j._ComputeSides(u,t,e,i,s,o.frontUVs,o.backUVs);const m=new j;return m.indices=e,m.positions=t,m.normals=i,m.uvs=s,m}function po(o,e={},t){const i=new F(o,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,jc(e).applyToMesh(i,e.updatable),i}const zm={CreateTorusKnot:po};j.CreateTorusKnot=jc;F.CreateTorusKnot=(o,e,t,i,s,r,n,a,h,l)=>po(o,{radius:e,tube:t,radialSegments:i,tubularSegments:s,p:r,q:n,sideOrientation:l,updatable:h},a);F._instancedMeshFactory=(o,e)=>{const t=new mo(o,e);if(e.instancedBuffers){t.instancedBuffers={};for(const i in e.instancedBuffers)t.instancedBuffers[i]=e.instancedBuffers[i]}return t};class mo extends At{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const i of t.getAnimationRanges())i!=null&&this.createAnimationRange(i.name,i.from,i.to);if(this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),!t.skeleton&&!t.morphTargetManager&&t.hasBoundingInfo){const i=t.getBoundingInfo();this.buildBoundingInfo(i.minimum,i.maximum)}else this.refreshBoundingInfo(!0,!0);this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){this._sourceMesh?.receiveShadows!==e&&fe.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){this._sourceMesh?.material!==e&&fe.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){this._sourceMesh?.visibility!==e&&fe.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){this._sourceMesh?.skeleton!==e&&fe.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){!this._sourceMesh||e===this._sourceMesh.renderingGroupId||W.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}get geometry(){return this._sourceMesh._geometry}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}copyVerticesData(e,t){this._sourceMesh.copyVerticesData(e,t)}getVertexBuffer(e,t){return this._sourceMesh.getVertexBuffer(e,t)}setVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,s),this.sourceMesh}updateVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,s),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i;typeof e=="object"?i=e:i={applySkeleton:e,applyMorph:t};const s=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getData(i,null,S.PositionKind),s),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||W.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),t){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1}_postActivate(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)}getWorldMatrix(){if(this._currentLOD&&this._currentLOD!==this._sourceMesh&&this._currentLOD.billboardMode!==xe.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new D);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,U.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(U.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;const t=this.sourceMesh.getLODLevels();if(!t||t.length===0)this._currentLOD=this.sourceMesh;else{const i=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,i.boundingSphere)}return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh);return this}_generatePointsArray(){return this._sourceMesh._generatePointsArray()}_updateBoundingInfo(){return this.hasBoundingInfo?this.getBoundingInfo().update(this.worldMatrixFromCache):this.buildBoundingInfo(this.absolutePosition,this.absolutePosition,this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}clone(e,t=null,i,s){const r=(s||this._sourceMesh).createInstance(e);if(Na.DeepCopy(this,r,["name","subMeshes","uniqueId","parent","lightSources","receiveShadows","material","visibility","skeleton","sourceMesh","isAnInstance","facetNb","isFacetDataEnabled","isBlocked","useBones","hasInstances","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","hasBoundingInfo","geometry"],[]),t&&(r.parent=t),!i)for(let n=0;n<this.getScene().meshes.length;n++){const a=this.getScene().meshes[n];a.parent===this&&a.clone(a.name,r)}return r.computeWorldMatrix(!0),this.onClonedObservable.notifyObservers(r),r}dispose(e,t=!1){this._sourceMesh.removeInstance(this),super.dispose(e,t)}_serializeAsParent(e){super._serializeAsParent(e),e.parentId=this._sourceMesh.uniqueId,e.parentInstanceIndex=this._indexInSourceMeshInstanceArray}instantiateHierarchy(e=null,t,i){const s=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0,t&&t.newSourcedMesh);s&&i&&i(this,s);for(const r of this.getChildTransformNodes(!0))r.instantiateHierarchy(s,t,i);return s}}F.prototype.registerInstancedBuffer=function(o,e){if(this._userInstancedBuffersStorage?.vertexBuffers[o]?.dispose(),this._userInstancedBuffersStorage?.renderPasses)for(const t in this._userInstancedBuffersStorage.renderPasses){const i=this._userInstancedBuffersStorage.renderPasses[t];i[o]?.dispose(),delete i[o]}if(!this.instancedBuffers){this.instancedBuffers={};for(const t of this.instances)t.instancedBuffers={}}this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this.instancedBuffers[o]=null,this._userInstancedBuffersStorage.strides[o]=e,this._userInstancedBuffersStorage.sizes[o]=e*32,this._userInstancedBuffersStorage.data[o]=new Float32Array(this._userInstancedBuffersStorage.sizes[o]),this._userInstancedBuffersStorage.vertexBuffers[o]=this._instanceDataStorage.useMonoDataStorageRenderPass?new S(this.getEngine(),this._userInstancedBuffersStorage.data[o],o,!0,!1,e,!0):null;for(const t of this.instances)t.instancedBuffers[o]=null;this._invalidateInstanceVertexArrayObject(),this._markSubMeshesAsAttributesDirty()};F.prototype._processInstancedBuffers=function(o,e){const t=o?o.length:0,i=!this._instanceDataStorage.useMonoDataStorageRenderPass;let s;if(i){const r=this._instanceDataStorage.engine.currentRenderPassId;this._userInstancedBuffersStorage.renderPasses||(this._userInstancedBuffersStorage.renderPasses={}),this._userInstancedBuffersStorage.renderPasses[r]||(this._userInstancedBuffersStorage.renderPasses[r]={}),s=this._userInstancedBuffersStorage.renderPasses[r]}for(const r in this.instancedBuffers){let n=this._userInstancedBuffersStorage.sizes[r];const a=this._userInstancedBuffersStorage.strides[r],h=(t+1)*a;for(;n<h;)n*=2;this._userInstancedBuffersStorage.data[r].length!=n&&(this._userInstancedBuffersStorage.data[r]=new Float32Array(n),this._userInstancedBuffersStorage.sizes[r]=n,i?s[r]&&(s[r].dispose(),s[r]=null):this._userInstancedBuffersStorage.vertexBuffers[r]&&(this._userInstancedBuffersStorage.vertexBuffers[r].dispose(),this._userInstancedBuffersStorage.vertexBuffers[r]=null));const l=this._userInstancedBuffersStorage.data[r];let c=0;if(e){const u=this.instancedBuffers[r]??0;u.toArray?u.toArray(l,c):u.copyToArray?u.copyToArray(l,c):l[c]=u,c+=a}for(let u=0;u<t;u++){const d=o[u].instancedBuffers[r]??0;d.toArray?d.toArray(l,c):d.copyToArray?d.copyToArray(l,c):l[c]=d,c+=a}i?s[r]?s[r].updateDirectly(l,0):(s[r]=new S(this.getEngine(),this._userInstancedBuffersStorage.data[r],r,!0,!1,a,!0),this._invalidateInstanceVertexArrayObject()):this._userInstancedBuffersStorage.vertexBuffers[r]?this._userInstancedBuffersStorage.vertexBuffers[r].updateDirectly(l,0):(this._userInstancedBuffersStorage.vertexBuffers[r]=new S(this.getEngine(),this._userInstancedBuffersStorage.data[r],r,!0,!1,a,!0),this._invalidateInstanceVertexArrayObject())}};F.prototype._invalidateInstanceVertexArrayObject=function(){if(!(!this._userInstancedBuffersStorage||this._userInstancedBuffersStorage.vertexArrayObjects===void 0)){for(const o in this._userInstancedBuffersStorage.vertexArrayObjects)this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[o]);this._userInstancedBuffersStorage.vertexArrayObjects={}}};F.prototype._disposeInstanceSpecificData=function(){for(const o in this._instanceDataStorage.renderPasses)this._instanceDataStorage.renderPasses[o].instancesBuffer?.dispose();for(this._instanceDataStorage.renderPasses={},this._instanceDataStorage.dataStorageRenderPass?.instancesBuffer?.dispose();this.instances.length;)this.instances[0].dispose();for(const o in this.instancedBuffers)this._userInstancedBuffersStorage.vertexBuffers[o]&&this._userInstancedBuffersStorage.vertexBuffers[o].dispose();this._invalidateInstanceVertexArrayObject(),this.instancedBuffers={}};Ye("BABYLON.InstancedMesh",mo);class Zc extends V{constructor(e,t,i=!0,s=!1){super(e,t,void 0,s),this._normalMatrix=new D,this._storeEffectOnSubMeshes=i}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return e?!this._storeEffectOnSubMeshes||!e.subMeshes||e.subMeshes.length===0?!0:this.isReadyForSubMesh(e,e.subMeshes[0],t):!1}_isReadyForSubMesh(e){const t=e.materialDefines;return!!(!this.checkReadyOnEveryCall&&e.effect&&t&&t._renderId===this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,i){super._afterBind(e,t,i),this.getScene()._cachedEffect=t,i?i._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,i,s=1){return i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,s)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}const Uh=new WeakMap;function Kg(o){const e=o.getVertexBuffers();if(!e)return null;let t=Uh.get(o);if(!t)t=new Map,Uh.set(o,t);else{let i=!1;for(const s in e)if(!t.has(s)){i=!0;break}if(!i)return t}for(const i in e){const s=e[i];if(s){const r=s.byteOffset,n=s.byteStride,a=s.type,h=s.normalized;t.set(i,{offset:r,stride:n,type:a,normalized:h})}}return t}function Yg(o,e){e.forEach((t,i)=>{const s=`vp_${i}_info`;o.setFloat4(s,t.offset,t.stride,t.type,t.normalized?1:0)})}const Pn={effect:null,subMesh:null};class Hi extends Zc{constructor(e,t,i,s={},r=!0){super(e,t,r),this._textures={},this._internalTextures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new D,this._cachedWorldViewProjectionMatrix=new D,this._multiview=!1,this._vertexPullingMetadata=null,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...s}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){this._options.uniforms.indexOf(e)===-1&&this._options.uniforms.push(e)}setTexture(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._textures[e]=t,this}setInternalTexture(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._internalTextures[e]=t,this}removeTexture(e){delete this._textures[e]}setTextureArray(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return this._options.externalTextures.indexOf(e)===-1&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce((i,s)=>(i.push(s.r,s.g,s.b),i),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce((i,s)=>(i.push(s.r,s.g,s.b,s.a),i),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce((i,s)=>(s.toArray(i,i.length),i),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(t.length*16);for(let s=0;s<t.length;s++)t[s].copyToArray(i,s*16);return this._matrixArrays[e]=i,this}setMatrix3x3(e,t){return this._checkUniform(e),this._matrices3x3[e]=t,this}setMatrix2x2(e,t){return this._checkUniform(e),this._matrices2x2[e]=t,this}setArray2(e,t){return this._checkUniform(e),this._vectors2Arrays[e]=t,this}setArray3(e,t){return this._checkUniform(e),this._vectors3Arrays[e]=t,this}setArray4(e,t){return this._checkUniform(e),this._vectors4Arrays[e]=t,this}setUniformBuffer(e,t){return this._options.uniformBuffers.indexOf(e)===-1&&this._options.uniformBuffers.push(e),this._uniformBuffers[e]=t,this}setTextureSampler(e,t){return this._options.samplerObjects.indexOf(e)===-1&&this._options.samplerObjects.push(e),this._textureSamplers[e]=t,this}setStorageBuffer(e,t){return this._options.storageBuffers.indexOf(e)===-1&&this._options.storageBuffers.push(e),this._storageBuffers[e]=t,this}setDefine(e,t){const i=e.trimEnd()+" ",s=this.options.defines.findIndex(r=>r===e||r.startsWith(i));return s>=0&&this.options.defines.splice(s,1),(typeof t!="boolean"||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){const s=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const x=s?i._drawWrapper:this._drawWrapper;if(x.effect&&x._wasPreviouslyReady&&x._wasPreviouslyUsingInstances===t)return!0}const r=this.getScene(),n=r.getEngine(),a=[],h=[];let l=null,c=this._shaderPath,u=this._options.uniforms,f=this._options.uniformBuffers,d=this._options.samplers;n.getCaps().multiview&&r.activeCamera&&r.activeCamera.outputRenderTarget&&r.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,a.push("#define MULTIVIEW"),u.indexOf("viewProjection")!==-1&&u.indexOf("viewProjectionR")===-1&&u.push("viewProjectionR"));for(let x=0;x<this._options.defines.length;x++){const b=this._options.defines[x].indexOf("#define")===0?this._options.defines[x]:`#define ${this._options.defines[x]}`;a.push(b)}for(let x=0;x<this._options.attributes.length;x++)h.push(this._options.attributes[x]);if(e&&e.isVerticesDataPresent(S.ColorKind)&&(h.indexOf(S.ColorKind)===-1&&h.push(S.ColorKind),a.push("#define VERTEXCOLOR")),t&&(a.push("#define INSTANCES"),Ps(h,this._materialHelperNeedsPreviousMatrices),e?.hasThinInstances&&(a.push("#define THIN_INSTANCES"),e&&e.isVerticesDataPresent(S.ColorInstanceKind)&&(h.push(S.ColorInstanceKind),a.push("#define INSTANCESCOLOR")))),e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton){h.push(S.MatricesIndicesKind),h.push(S.MatricesWeightsKind),e.numBoneInfluencers>4&&(h.push(S.MatricesIndicesExtraKind),h.push(S.MatricesWeightsExtraKind));const x=e.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),l=new Cs,l.addCPUSkinningFallback(0,e),x.isUsingTextureForMatrices?(a.push("#define BONETEXTURE"),u.indexOf("boneTextureWidth")===-1&&u.push("boneTextureWidth"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(a.push("#define BonesPerMesh "+(x.bones.length+1)),u.indexOf("mBones")===-1&&u.push("mBones"))}else a.push("#define NUM_BONE_INFLUENCERS 0");let _=0;const m=e?e.morphTargetManager:null;if(m){const x=a.indexOf("#define UV1")!==-1,b=a.indexOf("#define UV2")!==-1,P=a.indexOf("#define TANGENT")!==-1,v=a.indexOf("#define NORMAL")!==-1,O=a.indexOf("#define VERTEXCOLOR")!==-1;_=_r(m,a,h,e,!0,v,P,x,b,O),m.isUsingTextureForTargets&&(u.indexOf("morphTargetTextureIndices")===-1&&u.push("morphTargetTextureIndices"),this._options.samplers.indexOf("morphTargets")===-1&&this._options.samplers.push("morphTargets")),_>0&&(u=u.slice(),u.push("morphTargetInfluences"),u.push("morphTargetCount"),u.push("morphTargetTextureInfo"),u.push("morphTargetTextureIndices"))}else a.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const x=e.bakedVertexAnimationManager;x&&x.isEnabled&&(a.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),u.indexOf("bakedVertexAnimationSettings")===-1&&u.push("bakedVertexAnimationSettings"),u.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&u.push("bakedVertexAnimationTextureSizeInverted"),u.indexOf("bakedVertexAnimationTime")===-1&&u.push("bakedVertexAnimationTime"),this._options.samplers.indexOf("bakedVertexAnimationTexture")===-1&&this._options.samplers.push("bakedVertexAnimationTexture"),t&&h.push("bakedVertexAnimationSettingsInstanced"))}for(const x in this._textures)if(!this._textures[x].isReady())return!1;for(const x in this._internalTextures)if(!this._internalTextures[x].isReady)return!1;e&&this.needAlphaTestingForMesh(e)&&a.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(As(u),dr(this,r,a)),r.fogEnabled&&e?.applyFog&&r.fogMode!==je.FOGMODE_NONE&&(a.push("#define FOG"),u.indexOf("view")===-1&&u.push("view"),u.indexOf("vFogInfos")===-1&&u.push("vFogInfos"),u.indexOf("vFogColor")===-1&&u.push("vFogColor")),this._useLogarithmicDepth&&(a.push("#define LOGARITHMICDEPTH"),u.indexOf("logarithmicDepthConstant")===-1&&u.push("logarithmicDepthConstant"));const g=i?i.getRenderingMesh():e;if(g&&this.useVertexPulling){const x=g.geometry;x&&(this._vertexPullingMetadata=Kg(x),this._vertexPullingMetadata&&this._vertexPullingMetadata.forEach((P,v)=>{u.push(`vp_${v}_info`)})),a.push("#define USE_VERTEX_PULLING");const b=g.geometry?.getIndexBuffer();b&&!g.isUnIndexed&&(a.push("#define VERTEX_PULLING_USE_INDEX_BUFFER"),b.is32Bits&&a.push("#define VERTEX_PULLING_INDEX_BUFFER_32BITS"))}this.customShaderNameResolve&&(u=u.slice(),f=f.slice(),d=d.slice(),c=this.customShaderNameResolve(this.name,u,f,d,a,h));const T=s?i._getDrawWrapper(void 0,!0):this._drawWrapper,R=T?.effect??null,A=T?.defines??null,y=a.join(`
|
|
1257
|
+
`);let E=R;return A!==y&&(E=n.createEffect(c,{attributes:h,uniformsNames:u,uniformBuffersNames:f,samplers:d,defines:y,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:_},shaderLanguage:this._options.shaderLanguage,extraInitializationsAsync:this._options.extraInitializationsAsync},n),s?i.setEffect(E,y,this._materialContext):T&&T.setEffect(E,y),this._onEffectCreatedObservable&&(Pn.effect=E,Pn.subMesh=i??e?.subMeshes[0]??null,this._onEffectCreatedObservable.notifyObservers(Pn))),T._wasPreviouslyUsingInstances=!!t,E?.isReady()?(R!==E&&r.resetCachedMaterial(),T._wasPreviouslyReady=!0,!0):!1}bindOnlyWorldMatrix(e,t){const i=t??this.getEffect();if(!i)return;const s=this._options.uniforms;s.indexOf("world")!==-1&&i.setMatrix("world",e);const r=this.getScene();s.indexOf("worldView")!==-1&&(e.multiplyToRef(r.getViewMatrix(),this._cachedWorldViewMatrix),i.setMatrix("worldView",this._cachedWorldViewMatrix)),s.indexOf("worldViewProjection")!==-1&&(e.multiplyToRef(r.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),i.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),s.indexOf("view")!==-1&&i.setMatrix("view",r.getViewMatrix())}bindForSubMesh(e,t,i){this.bind(e,t,i._drawWrapperOverride?.effect,i)}bind(e,t,i,s){const r=s&&this._storeEffectOnSubMeshes,n=i??(r?s.effect:this.getEffect());if(!n)return;const a=this.getScene();this._activeEffect=n,this.bindOnlyWorldMatrix(e,i);const h=this._options.uniformBuffers;let l=!1;if(n&&h&&h.length>0&&a.getEngine().supportsUniformBuffers)for(let u=0;u<h.length;++u)switch(h[u]){case"Mesh":t&&(t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e));break;case"Scene":so(n,a.getSceneUniformBuffer()),a.finalizeSceneUbo(),l=!0;break}const c=t&&r?this._mustRebind(a,n,s,t.visibility):a.getCachedMaterial()!==this;if(n&&c){!l&&this._options.uniforms.indexOf("view")!==-1&&n.setMatrix("view",a.getViewMatrix()),!l&&this._options.uniforms.indexOf("projection")!==-1&&n.setMatrix("projection",a.getProjectionMatrix()),!l&&this._options.uniforms.indexOf("viewProjection")!==-1&&(n.setMatrix("viewProjection",a.getTransformMatrix()),this._multiview&&n.setMatrix("viewProjectionR",a._transformMatrixR)),a.activeCamera&&this._options.uniforms.indexOf("cameraPosition")!==-1&&n.setVector3("cameraPosition",a.activeCamera.globalPosition),vs(t,n),Ms(n,this,a),this._vertexPullingMetadata&&Yg(n,this._vertexPullingMetadata),this._useLogarithmicDepth&&pc(r?s.materialDefines:n.defines,n,a),t&&mc(a,t,n);let u;for(u in this._textures)n.setTexture(u,this._textures[u]);for(u in this._internalTextures)n._bindTexture(u,this._internalTextures[u]);for(u in this._textureArrays)n.setTextureArray(u,this._textureArrays[u]);for(u in this._ints)n.setInt(u,this._ints[u]);for(u in this._uints)n.setUInt(u,this._uints[u]);for(u in this._floats)n.setFloat(u,this._floats[u]);for(u in this._floatsArrays)n.setArray(u,this._floatsArrays[u]);for(u in this._colors3)n.setColor3(u,this._colors3[u]);for(u in this._colors3Arrays)n.setArray3(u,this._colors3Arrays[u]);for(u in this._colors4){const g=this._colors4[u];n.setFloat4(u,g.r,g.g,g.b,g.a)}for(u in this._colors4Arrays)n.setArray4(u,this._colors4Arrays[u]);for(u in this._vectors2)n.setVector2(u,this._vectors2[u]);for(u in this._vectors3)n.setVector3(u,this._vectors3[u]);for(u in this._vectors4)n.setVector4(u,this._vectors4[u]);for(u in this._quaternions)n.setQuaternion(u,this._quaternions[u]);for(u in this._matrices)n.setMatrix(u,this._matrices[u]);for(u in this._matrixArrays)n.setMatrices(u,this._matrixArrays[u]);for(u in this._matrices3x3)n.setMatrix3x3(u,this._matrices3x3[u]);for(u in this._matrices2x2)n.setMatrix2x2(u,this._matrices2x2[u]);for(u in this._vectors2Arrays)n.setArray2(u,this._vectors2Arrays[u]);for(u in this._vectors3Arrays)n.setArray3(u,this._vectors3Arrays[u]);for(u in this._vectors4Arrays)n.setArray4(u,this._vectors4Arrays[u]);for(u in this._quaternionsArrays)n.setArray4(u,this._quaternionsArrays[u]);for(u in this._uniformBuffers){const g=this._uniformBuffers[u].getBuffer();g&&n.bindUniformBuffer(g,u)}const f=a.getEngine(),d=f.setExternalTexture;if(d)for(u in this._externalTextures)d.call(f,u,this._externalTextures[u]);const _=f.setTextureSampler;if(_)for(u in this._textureSamplers)_.call(f,u,this._textureSamplers[u]);const m=f.setStorageBuffer;if(m)for(u in this._storageBuffers)m.call(f,u,this._storageBuffers[u])}if(n&&t&&(c||!this.isFrozen)){Is(t,n),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(n);const u=t.bakedVertexAnimationManager;if(u&&u.isEnabled){const f=r?s._drawWrapper:this._drawWrapper;t.bakedVertexAnimationManager?.bind(n,!!f._wasPreviouslyUsingInstances)}}this._afterBind(t,n,s)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let s=0;s<i.length;s++)e.push(i[s])}return e}hasTexture(e){if(super.hasTexture(e))return!0;for(const i in this._textures)if(this._textures[i]===e)return!0;const t=e.getInternalTexture();for(const i in this._internalTextures)if(this._internalTextures[i]===t)return!0;for(const i in this._textureArrays){const s=this._textureArrays[i];for(let r=0;r<s.length;r++)if(s[r]===e)return!0}return!1}clone(e){const t=me.Clone(()=>new Hi(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);t.name=e,t.id=e,typeof t._shaderPath=="object"&&(t._shaderPath={...t._shaderPath}),this._options={...this._options};const i=Object.keys(this._options);for(const s of i){const r=this._options[s];Array.isArray(r)&&(this._options[s]=r.slice(0))}this.stencil.copyTo(t.stencil);for(const s in this._textures)t.setTexture(s,this._textures[s]);for(const s in this._internalTextures)t.setInternalTexture(s,this._internalTextures[s]);for(const s in this._textureArrays)t.setTextureArray(s,this._textureArrays[s]);for(const s in this._externalTextures)t.setExternalTexture(s,this._externalTextures[s]);for(const s in this._ints)t.setInt(s,this._ints[s]);for(const s in this._uints)t.setUInt(s,this._uints[s]);for(const s in this._floats)t.setFloat(s,this._floats[s]);for(const s in this._floatsArrays)t.setFloats(s,this._floatsArrays[s]);for(const s in this._colors3)t.setColor3(s,this._colors3[s]);for(const s in this._colors3Arrays)t._colors3Arrays[s]=this._colors3Arrays[s];for(const s in this._colors4)t.setColor4(s,this._colors4[s]);for(const s in this._colors4Arrays)t._colors4Arrays[s]=this._colors4Arrays[s];for(const s in this._vectors2)t.setVector2(s,this._vectors2[s]);for(const s in this._vectors3)t.setVector3(s,this._vectors3[s]);for(const s in this._vectors4)t.setVector4(s,this._vectors4[s]);for(const s in this._quaternions)t.setQuaternion(s,this._quaternions[s]);for(const s in this._quaternionsArrays)t._quaternionsArrays[s]=this._quaternionsArrays[s];for(const s in this._matrices)t.setMatrix(s,this._matrices[s]);for(const s in this._matrixArrays)t._matrixArrays[s]=this._matrixArrays[s].slice();for(const s in this._matrices3x3)t.setMatrix3x3(s,this._matrices3x3[s]);for(const s in this._matrices2x2)t.setMatrix2x2(s,this._matrices2x2[s]);for(const s in this._vectors2Arrays)t.setArray2(s,this._vectors2Arrays[s]);for(const s in this._vectors3Arrays)t.setArray3(s,this._vectors3Arrays[s]);for(const s in this._vectors4Arrays)t.setArray4(s,this._vectors4Arrays[s]);for(const s in this._uniformBuffers)t.setUniformBuffer(s,this._uniformBuffers[s]);for(const s in this._textureSamplers)t.setTextureSampler(s,this._textureSamplers[s]);for(const s in this._storageBuffers)t.setStorageBuffer(s,this._storageBuffers[s]);return t}dispose(e,t,i){if(t){let s;for(s in this._textures)this._textures[s].dispose();for(s in this._internalTextures)this._internalTextures[s].dispose();for(s in this._textureArrays){const r=this._textureArrays[s];for(let n=0;n<r.length;n++)r[n].dispose()}}this._textures={},this._internalTextures={},super.dispose(e,t,i)}serialize(){const e=me.Serialize(this);e.customType="BABYLON.ShaderMaterial",e.uniqueId=this.uniqueId,e.options=this._options,e.shaderPath=this._shaderPath,e.storeEffectOnSubMeshes=this._storeEffectOnSubMeshes;let t;e.stencil=this.stencil.serialize(),e.textures={};for(t in this._textures)e.textures[t]=this._textures[t].serialize();e.textureArrays={};for(t in this._textureArrays){e.textureArrays[t]=[];const i=this._textureArrays[t];for(let s=0;s<i.length;s++)e.textureArrays[t].push(i[s].serialize())}e.ints={};for(t in this._ints)e.ints[t]=this._ints[t];e.uints={};for(t in this._uints)e.uints[t]=this._uints[t];e.floats={};for(t in this._floats)e.floats[t]=this._floats[t];e.floatsArrays={};for(t in this._floatsArrays)e.floatsArrays[t]=this._floatsArrays[t];e.colors3={};for(t in this._colors3){const i=this._colors3[t];e.colors3[t]=[i.r,i.g,i.b]}e.colors3Arrays={};for(t in this._colors3Arrays)e.colors3Arrays[t]=this._colors3Arrays[t];e.colors4={};for(t in this._colors4){const i=this._colors4[t];e.colors4[t]=[i.r,i.g,i.b,i.a]}e.colors4Arrays={};for(t in this._colors4Arrays)e.colors4Arrays[t]=this._colors4Arrays[t];e.vectors2={};for(t in this._vectors2){const i=this._vectors2[t];e.vectors2[t]=[i.x,i.y]}e.vectors3={};for(t in this._vectors3){const i=this._vectors3[t];e.vectors3[t]=[i.x,i.y,i.z]}e.vectors4={};for(t in this._vectors4){const i=this._vectors4[t];e.vectors4[t]=[i.x,i.y,i.z,i.w]}e.quaternions={};for(t in this._quaternions)e.quaternions[t]=this._quaternions[t].asArray();e.matrices={};for(t in this._matrices)e.matrices[t]=this._matrices[t].asArray();e.matrixArray={};for(t in this._matrixArrays)e.matrixArray[t]=this._matrixArrays[t];e.matrices3x3={};for(t in this._matrices3x3)e.matrices3x3[t]=this._matrices3x3[t];e.matrices2x2={};for(t in this._matrices2x2)e.matrices2x2[t]=this._matrices2x2[t];e.vectors2Arrays={};for(t in this._vectors2Arrays)e.vectors2Arrays[t]=this._vectors2Arrays[t];e.vectors3Arrays={};for(t in this._vectors3Arrays)e.vectors3Arrays[t]=this._vectors3Arrays[t];e.vectors4Arrays={};for(t in this._vectors4Arrays)e.vectors4Arrays[t]=this._vectors4Arrays[t];e.quaternionsArrays={};for(t in this._quaternionsArrays)e.quaternionsArrays[t]=this._quaternionsArrays[t];return e}static Parse(e,t,i){const s=me.Parse(()=>new Hi(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);let r;e.stencil&&s.stencil.parse(e.stencil,t,i);for(r in e.textures)s.setTexture(r,G.Parse(e.textures[r],t,i));for(r in e.textureArrays){const n=e.textureArrays[r],a=[];for(let h=0;h<n.length;h++)a.push(G.Parse(n[h],t,i));s.setTextureArray(r,a)}for(r in e.ints)s.setInt(r,e.ints[r]);for(r in e.uints)s.setUInt(r,e.uints[r]);for(r in e.floats)s.setFloat(r,e.floats[r]);for(r in e.floatsArrays)s.setFloats(r,e.floatsArrays[r]);for(r in e.colors3){const n=e.colors3[r];s.setColor3(r,{r:n[0],g:n[1],b:n[2]})}for(r in e.colors3Arrays){const n=e.colors3Arrays[r].reduce((a,h,l)=>(l%3===0?a.push([h]):a[a.length-1].push(h),a),[]).map(a=>({r:a[0],g:a[1],b:a[2]}));s.setColor3Array(r,n)}for(r in e.colors4){const n=e.colors4[r];s.setColor4(r,{r:n[0],g:n[1],b:n[2],a:n[3]})}for(r in e.colors4Arrays){const n=e.colors4Arrays[r].reduce((a,h,l)=>(l%4===0?a.push([h]):a[a.length-1].push(h),a),[]).map(a=>({r:a[0],g:a[1],b:a[2],a:a[3]}));s.setColor4Array(r,n)}for(r in e.vectors2){const n=e.vectors2[r];s.setVector2(r,{x:n[0],y:n[1]})}for(r in e.vectors3){const n=e.vectors3[r];s.setVector3(r,{x:n[0],y:n[1],z:n[2]})}for(r in e.vectors4){const n=e.vectors4[r];s.setVector4(r,{x:n[0],y:n[1],z:n[2],w:n[3]})}for(r in e.quaternions)s.setQuaternion(r,re.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,D.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static async ParseFromFileAsync(e,t,i,s=""){return await new Promise((r,n)=>{const a=new at;a.addEventListener("readystatechange",()=>{if(a.readyState==4)if(a.status==200){const h=JSON.parse(a.responseText),l=this.Parse(h,i||ye.LastCreatedScene,s);e&&(l.name=e),r(l)}else n("Unable to load the ShaderMaterial")}),a.open("GET",t),a.send()})}static async ParseFromSnippetAsync(e,t,i=""){return await new Promise((s,r)=>{const n=new at;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const a=JSON.parse(JSON.parse(n.responseText).jsonPayload),h=JSON.parse(a.shaderMaterial),l=this.Parse(h,t||ye.LastCreatedScene,i);l.snippetId=e,s(l)}else r("Unable to load the snippet "+e)}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}Hi.SnippetUrl="https://snippet.babylonjs.com";Hi.CreateFromSnippetAsync=Hi.ParseFromSnippetAsync;Ye("BABYLON.ShaderMaterial",Hi);F._LinesMeshParser=(o,e)=>Ri.Parse(o,e);class Ri extends F{_isShaderMaterial(e){return e?e.getClassName()==="ShaderMaterial":!1}constructor(e,t=null,i=null,s=null,r,n,a,h){super(e,t,i,s,r),this.useVertexColor=n,this.useVertexAlpha=a,this.color=new Re(1,1,1),this.alpha=1,this._shaderLanguage=0,this._ownsMaterial=!1,s&&(this.color=s.color.clone(),this.alpha=s.alpha,this.useVertexColor=s.useVertexColor,this.useVertexAlpha=s.useVertexAlpha),this.intersectionThreshold=.1;const l=[],c={attributes:[S.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:l,useClipPlane:null,shaderLanguage:0};if(this.useVertexAlpha?c.defines.push("#define VERTEXALPHA"):c.needAlphaBlending=!1,this.useVertexColor?(c.defines.push("#define VERTEXCOLOR"),c.attributes.push(S.ColorKind)):(c.uniforms.push("color"),this._color4=new Ce),h)this.material=h;else{this.getScene().getEngine().isWebGPU&&!Ri.ForceGLSL&&(this._shaderLanguage=1),c.shaderLanguage=this._shaderLanguage,c.extraInitializationsAsync=async()=>{this._shaderLanguage===1?await Promise.all([he(()=>import("./color.vertex-dgbB6mhK.js"),__vite__mapDeps([17,5,18,7]),import.meta.url),he(()=>import("./color.fragment-CDn4ZgkT.js"),__vite__mapDeps([19,9,20]),import.meta.url)]):await Promise.all([he(()=>import("./color.vertex-CaMOSKlC.js"),__vite__mapDeps([21,22]),import.meta.url),he(()=>import("./color.fragment-BUdIBar6.js"),__vite__mapDeps([23,24]),import.meta.url)])};const f=new Hi("colorShader",this.getScene(),"color",c,!1);f.doNotSerialize=!0,this._ownsMaterial=!0,this._setInternalMaterial(f)}}getClassName(){return"LinesMesh"}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){const t=this.material;if(t===e)return;const i=t&&this._ownsMaterial;this._ownsMaterial=!1,this._setInternalMaterial(e),i&&t?.dispose()}_setInternalMaterial(e){this._setMaterial(e),this.material&&(this.material.fillMode=V.LineListDrawMode,this.material.disableLighting=!0)}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;const i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this.material)){const{r:s,g:r,b:n}=this.color;this._color4.set(s,r,n,this.alpha),this.material.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const s=this.getScene().getEngine();return this._unIndexed?s.drawArraysType(V.LineListDrawMode,e.verticesStart,e.verticesCount,i):s.drawElementsType(V.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||(this._ownsMaterial?this.material?.dispose(!1,!1,!0):t&&this.material?.dispose(!1,!1,!0)),super.dispose(e)}clone(e,t=null,i){if(t&&t._addToSceneRootNodes===void 0){const s=t;return s.source=this,new Ri(e,this.getScene(),s.parent,s.source,s.doNotCloneChildren)}return new Ri(e,this.getScene(),t,this,i)}createInstance(e){const t=new jg(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const i in this.instancedBuffers)t.instancedBuffers[i]=this.instancedBuffers[i]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new Ri(e.name,t);return i.color=Re.FromArray(e.color),i.alpha=e.alpha,i}}Ri.ForceGLSL=!1;class jg extends mo{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function qc(o){const e=[],t=[],i=o.lines,s=o.colors,r=[];let n=0;for(let h=0;h<i.length;h++){const l=i[h];for(let c=0;c<l.length;c++){const{x:u,y:f,z:d}=l[c];if(t.push(u,f,d),s){const _=s[h],{r:m,g,b:T,a:R}=_[c];r.push(m,g,T,R)}c>0&&(e.push(n-1),e.push(n)),n++}}const a=new j;return a.indices=e,a.positions=t,s&&(a.colors=r),a}function Qc(o){const e=o.dashSize||3,t=o.gapSize||1,i=o.dashNb||200,s=o.points,r=[],n=[],a=p.Zero();let h=0,l,c,u=0,f;for(f=0;f<s.length-1;f++)s[f+1].subtractToRef(s[f],a),h+=a.length();const d=h/i,_=e*d/(e+t);for(f=0;f<s.length-1;f++){s[f+1].subtractToRef(s[f],a),l=Math.floor(a.length()/d),a.normalize();for(let g=0;g<l;g++)c=d*g,r.push(s[f].x+c*a.x,s[f].y+c*a.y,s[f].z+c*a.z),r.push(s[f].x+(c+_)*a.x,s[f].y+(c+_)*a.y,s[f].z+(c+_)*a.z),n.push(u,u+1),u+=2}const m=new j;return m.positions=r,m.indices=n,m}function To(o,e,t=null){const i=e.instance,s=e.lines,r=e.colors;if(i){const l=i.getVerticesData(S.PositionKind);let c,u;r&&(c=i.getVerticesData(S.ColorKind));let f=0,d=0;for(let _=0;_<s.length;_++){const m=s[_];for(let g=0;g<m.length;g++)l[f]=m[g].x,l[f+1]=m[g].y,l[f+2]=m[g].z,r&&c&&(u=r[_],c[d]=u[g].r,c[d+1]=u[g].g,c[d+2]=u[g].b,c[d+3]=u[g].a,d+=4),f+=3}return i.updateVerticesData(S.PositionKind,l,!1,!1),r&&c&&i.updateVerticesData(S.ColorKind,c,!1,!1),i.refreshBoundingInfo(),i}const n=!!r,a=new Ri(o,t,null,void 0,void 0,n,e.useVertexAlpha,e.material);return qc(e).applyToMesh(a,e.updatable),a}function Eo(o,e,t=null){const i=e.colors?[e.colors]:null;return To(o,{lines:[e.points],updatable:e.updatable,instance:e.instance,colors:i,useVertexAlpha:e.useVertexAlpha,material:e.material},t)}function xo(o,e,t=null){const i=e.points,s=e.instance,r=e.gapSize||1,n=e.dashSize||3;if(s){const l=c=>{const u=p.Zero(),f=c.length/6;let d=0,_,m,g=0,T,R;for(T=0;T<i.length-1;T++)i[T+1].subtractToRef(i[T],u),d+=u.length();const A=d/f,y=s._creationDataStorage.dashSize,E=s._creationDataStorage.gapSize,x=y*A/(y+E);for(T=0;T<i.length-1;T++)for(i[T+1].subtractToRef(i[T],u),_=Math.floor(u.length()/A),u.normalize(),R=0;R<_&&g<c.length;)m=A*R,c[g]=i[T].x+m*u.x,c[g+1]=i[T].y+m*u.y,c[g+2]=i[T].z+m*u.z,c[g+3]=i[T].x+(m+x)*u.x,c[g+4]=i[T].y+(m+x)*u.y,c[g+5]=i[T].z+(m+x)*u.z,g+=6,R++;for(;g<c.length;)c[g]=i[T].x,c[g+1]=i[T].y,c[g+2]=i[T].z,g+=3};return(e.dashNb||e.dashSize||e.gapSize||e.useVertexAlpha||e.material)&&W.Warn("You have used an option other than points with the instance option. Please be aware that these other options will be ignored."),s.updateMeshPositions(l,!1),s}const a=new Ri(o,t,null,void 0,void 0,void 0,e.useVertexAlpha,e.material);return Qc(e).applyToMesh(a,e.updatable),a._creationDataStorage=new Bc,a._creationDataStorage.dashSize=n,a._creationDataStorage.gapSize=r,a}const Wm={CreateDashedLines:xo,CreateLineSystem:To,CreateLines:Eo};j.CreateLineSystem=qc;j.CreateDashedLines=Qc;F.CreateLines=(o,e,t=null,i=!1,s=null)=>Eo(o,{points:e,updatable:i,instance:s},t);F.CreateDashedLines=(o,e,t,i,s,r=null,n,a)=>xo(o,{points:e,dashSize:t,gapSize:i,dashNb:s,updatable:n,instance:a},r);class Zg extends ie{constructor(e,t){super(e.x,e.y),this.index=t}}class In{constructor(){this.elements=[]}add(e){const t=[];for(const i of e){const s=new Zg(i,this.elements.length);t.push(s),this.elements.push(s)}return t}computeBounds(){const e=new ie(this.elements[0].x,this.elements[0].y),t=new ie(this.elements[0].x,this.elements[0].y);for(const i of this.elements)i.x<e.x?e.x=i.x:i.x>t.x&&(t.x=i.x),i.y<e.y?e.y=i.y:i.y>t.y&&(t.y=i.y);return{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class Gm{static Rectangle(e,t,i,s){return[new ie(e,t),new ie(i,t),new ie(i,s),new ie(e,s)]}static Circle(e,t=0,i=0,s=32){const r=[];let n=0;const a=Math.PI*2/s;for(let h=0;h<s;h++)r.push(new ie(t+Math.cos(n)*e,i+Math.sin(n)*e)),n-=a;return r}static Parse(e){const t=e.split(/[^-+eE.\d]+/).map(parseFloat).filter(r=>!isNaN(r));let i;const s=[];for(i=0;i<(t.length&2147483646);i+=2)s.push(new ie(t[i],t[i+1]));return s}static StartingAt(e,t){return ar.StartingAt(e,t)}}class qg{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,s=earcut){this._points=new In,this._outlinepoints=new In,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=e,this._scene=i||ye.LastCreatedScene;let r;t instanceof ar?r=t.getPoints():r=t,this._addToepoint(r),this._points.add(r),this._outlinepoints.add(r),typeof this.bjsEarcut>"u"&&W.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new In;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){const s=new F(this._name,this._scene),r=this.buildVertexData(t,i);return s.setVerticesData(S.PositionKind,r.positions,e),s.setVerticesData(S.NormalKind,r.normals,e),s.setVerticesData(S.UVKind,r.uvs,e),s.setIndices(r.indices),s}buildVertexData(e=0,t=2){const i=new j,s=[],r=[],n=[],a=this._points.computeBounds();for(const c of this._points.elements)s.push(0,1,0),r.push(c.x,0,c.y),n.push((c.x-a.min.x)/a.width,(c.y-a.min.y)/a.height);const h=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let c=0;c<l.length;c++)h.push(l[c]);if(e>0){const c=r.length/3;for(const f of this._points.elements)s.push(0,-1,0),r.push(f.x,-e,f.y),n.push(1-(f.x-a.min.x)/a.width,1-(f.y-a.min.y)/a.height);const u=h.length;for(let f=0;f<u;f+=3){const d=h[f+0],_=h[f+1],m=h[f+2];h.push(m+c),h.push(_+c),h.push(d+c)}this._addSide(r,s,n,h,a,this._outlinepoints,e,!1,t);for(const f of this._holes)this._addSide(r,s,n,h,a,f,e,!0,t)}return i.indices=h,i.positions=r,i.normals=s,i.uvs=n,i}_addSide(e,t,i,s,r,n,a,h,l){let c=e.length/3,u=0;for(let f=0;f<n.elements.length;f++){const d=n.elements[f],_=n.elements[(f+1)%n.elements.length];e.push(d.x,0,d.y),e.push(d.x,-a,d.y),e.push(_.x,0,_.y),e.push(_.x,-a,_.y);const m=n.elements[(f+n.elements.length-1)%n.elements.length],g=n.elements[(f+2)%n.elements.length];let T=new p(-(_.y-d.y),0,_.x-d.x),R=new p(-(d.y-m.y),0,d.x-m.x),A=new p(-(g.y-_.y),0,g.x-_.x);h||(T=T.scale(-1),R=R.scale(-1),A=A.scale(-1));const y=T.normalizeToNew();let E=R.normalizeToNew(),x;const b=p.Dot(E,y);b>l?b<Ke-1?E=new p(d.x,0,d.y).subtract(new p(_.x,0,_.y)).normalize():E=R.add(T).normalize():E=y;const P=p.Dot(A,T);P>l?P<Ke-1?x=new p(_.x,0,_.y).subtract(new p(d.x,0,d.y)).normalize():x=A.add(T).normalize():x=y,i.push(u/r.width,0),i.push(u/r.width,1),u+=T.length(),i.push(u/r.width,0),i.push(u/r.width,1),t.push(E.x,E.y,E.z),t.push(E.x,E.y,E.z),t.push(x.x,x.y,x.z),t.push(x.x,x.y,x.z),h?(s.push(c),s.push(c+2),s.push(c+1),s.push(c+1),s.push(c+2),s.push(c+3)):(s.push(c),s.push(c+1),s.push(c+2),s.push(c+1),s.push(c+3),s.push(c+2)),c+=4}}}function $c(o,e,t,i,s,r,n){const a=t||new Array(3),h=i,l=[],c=n||!1;for(let v=0;v<3;v++)a[v]===void 0&&(a[v]=new Me(0,0,1,1)),h&&h[v]===void 0&&(h[v]=new Ce(1,1,1,1));const u=o.getVerticesData(S.PositionKind),f=o.getVerticesData(S.NormalKind),d=o.getVerticesData(S.UVKind),_=o.getIndices(),m=u.length/9;let g,T,R,A,y=0;const E=[0];if(c)for(let v=m;v<u.length/3;v+=4)T=u[3*(v+2)]-u[3*v],R=u[3*(v+2)+2]-u[3*v+2],A=Math.sqrt(T*T+R*R),y+=A,E.push(y);let x,b=0;for(let v=0;v<f.length;v+=3)Math.abs(f[v+1])<.001&&(b=1),Math.abs(f[v+1]-1)<.001&&(b=0),Math.abs(f[v+1]+1)<.001&&(b=2),x=v/3,b===1?(g=x-m,g%4<1.5?c?d[2*x]=a[b].x+(a[b].z-a[b].x)*E[Math.floor(g/4)]/y:d[2*x]=a[b].x:c?d[2*x]=a[b].x+(a[b].z-a[b].x)*E[Math.floor(g/4)+1]/y:d[2*x]=a[b].z,g%2===0?d[2*x+1]=we?1-a[b].w:a[b].w:d[2*x+1]=we?1-a[b].y:a[b].y):(d[2*x]=(1-d[2*x])*a[b].x+d[2*x]*a[b].z,d[2*x+1]=(1-d[2*x+1])*a[b].y+d[2*x+1]*a[b].w,we&&(d[2*x+1]=1-d[2*x+1])),h&&l.push(h[b].r,h[b].g,h[b].b,h[b].a);j._ComputeSides(e,u,_,f,d,s,r);const P=new j;if(P.indices=_,P.positions=u,P.normals=f,P.uvs=d,h){const v=e===j.DOUBLESIDE?l.concat(l):l;P.colors=v}return P}function hn(o,e,t=null,i=earcut){e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation);const s=e.shape,r=e.holes||[],n=e.depth||0,a=e.smoothingThreshold||2,h=[];let l;for(let _=0;_<s.length;_++)h[_]=new ie(s[_].x,s[_].z);h[0].equalsWithEpsilon(h[h.length-1],1e-8)&&h.pop();const u=new qg(o,h,t||ye.LastCreatedScene,i);for(let _=0;_<r.length;_++){l=[];for(let m=0;m<r[_].length;m++)l.push(new ie(r[_][m].x,r[_][m].z));u.addHole(l)}const f=u.build(!1,n,a);return f._originalBuilderSideOrientation=e.sideOrientation,$c(f,e.sideOrientation,e.faceUV,e.faceColors,e.frontUVs,e.backUVs,e.wrap).applyToMesh(f,e.updatable),f}function ln(o,e,t=null,i=earcut){return hn(o,e,t,i)}const Hm={ExtrudePolygon:ln,CreatePolygon:hn};j.CreatePolygon=$c;F.CreatePolygon=(o,e,t,i,s,r,n=earcut)=>hn(o,{shape:e,holes:i,updatable:s,sideOrientation:r},t,n);F.ExtrudePolygon=(o,e,t,i,s,r,n,a=earcut)=>ln(o,{shape:e,holes:s,depth:t,updatable:r,sideOrientation:n},i,a);function bo(o,e,t=null){const i=e.path,s=e.shape,r=e.scale||1,n=e.rotation||0,a=e.cap===0?0:e.cap||F.NO_CAP,h=e.updatable,l=F._GetDefaultSideOrientation(e.sideOrientation),c=e.instance||null,u=e.invertUV||!1,f=e.closeShape||!1,d=e.closePath||!1,_=e.capFunction||null;return Jc(o,s,i,r,n,null,null,d,f,a,!1,t,!!h,l,c,u,e.frontUVs||null,e.backUVs||null,e.firstNormal||null,!!e.adjustFrame,_)}function Ro(o,e,t=null){const i=e.path,s=e.shape,r=p.Zero(),n=(R,A)=>{const y=e.scaleFunction?.(R,A)??1;return r.copyFromFloats(y,y,y)},a=e.rotationFunction||(()=>0),h=e.closePath||e.ribbonCloseArray||!1,l=e.closeShape||e.ribbonClosePath||!1,c=e.cap===0?0:e.cap||F.NO_CAP,u=e.updatable,f=e.firstNormal||null,d=e.adjustFrame||!1,_=F._GetDefaultSideOrientation(e.sideOrientation),m=e.instance,g=e.invertUV||!1,T=e.capFunction||null;return Jc(o,s,i,null,null,e.scaleVectorFunction??n,a,h,l,c,!0,t,!!u,_,m||null,g,e.frontUVs||null,e.backUVs||null,f,d,T||null)}function Jc(o,e,t,i,s,r,n,a,h,l,c,u,f,d,_,m,g,T,R,A,y){const E=(k,Y,q,L,ee,Q,se,le,H,K,w)=>{const B=q.getTangents(),N=q.getNormals(),X=q.getBinormals(),Ee=q.getDistances();if(w){for(let Ae=0;Ae<B.length;Ae++)if(B[Ae].x==0&&B[Ae].y==0&&B[Ae].z==0&&B[Ae].copyFrom(B[Ae-1]),N[Ae].x==0&&N[Ae].y==0&&N[Ae].z==0&&N[Ae].copyFrom(N[Ae-1]),X[Ae].x==0&&X[Ae].y==0&&X[Ae].z==0&&X[Ae].copyFrom(X[Ae-1]),Ae>0){let $e=B[Ae-1];p.Dot($e,B[Ae])<0&&B[Ae].scaleInPlace(-1),$e=N[Ae-1],p.Dot($e,N[Ae])<0&&N[Ae].scaleInPlace(-1),$e=X[Ae-1],p.Dot($e,X[Ae])<0&&X[Ae].scaleInPlace(-1)}}let ae=0;const Se=()=>ee!==null?ee:p.OneReadOnly,nt=K&&le?le:()=>Q!==null?Q:0,ct=K&&se?se:Se;let Ge=H===F.NO_CAP||H===F.CAP_END?0:2;const _e=U.Matrix[0];for(let Ae=0;Ae<Y.length;Ae++){const $e=[],zt=nt(Ae,Ee[Ae]),bt=ct(Ae,Ee[Ae]);D.RotationAxisToRef(B[Ae],ae,_e);for(let $t=0;$t<k.length;$t++){const Ii=B[Ae].scale(k[$t].z).add(N[Ae].scale(k[$t].x)).add(X[Ae].scale(k[$t].y)),hi=p.Zero();p.TransformCoordinatesToRef(Ii,_e,hi),hi.multiplyInPlace(bt).addInPlace(Y[Ae]),$e[$t]=hi}L[Ge]=$e,ae+=zt,Ge++}const Xe=y||(Ae=>{const $e=Array(),zt=p.Zero();let bt;for(bt=0;bt<Ae.length;bt++)zt.addInPlace(Ae[bt]);for(zt.scaleInPlace(1/Ae.length),bt=0;bt<Ae.length;bt++)$e.push(zt);return $e});switch(H){case F.NO_CAP:break;case F.CAP_START:L[0]=Xe(L[2]),L[1]=L[2];break;case F.CAP_END:L[Ge]=L[Ge-1],L[Ge+1]=Xe(L[Ge-1]);break;case F.CAP_ALL:L[0]=Xe(L[2]),L[1]=L[2],L[Ge]=L[Ge-1],L[Ge+1]=Xe(L[Ge-1]);break}return L},x=i!==null?new p(i,i,i):null;let b;if(_){const k=_._creationDataStorage;return R?k.path3D.update(t,R):k.path3D.update(t),b=E(e,t,k.path3D,k.pathArray,x,s,r,n,k.cap,c,A),_=Gi("",{pathArray:b,closeArray:!1,closePath:!1,offset:0,updatable:!1,sideOrientation:0,instance:_},u||void 0),_}const P=R?new Ks(t,R):new Ks(t),v=new Array;l=l<0||l>3?0:l,b=E(e,t,P,v,x,s,r,n,l,c,A);const O=Gi(o,{pathArray:b,closeArray:a,closePath:h,updatable:f,sideOrientation:d,invertUV:m,frontUVs:g||void 0,backUVs:T||void 0},u);return O._creationDataStorage.pathArray=b,O._creationDataStorage.path3D=P,O._creationDataStorage.cap=l,O}const Xm={ExtrudeShape:bo,ExtrudeShapeCustom:Ro};F.ExtrudeShape=(o,e,t,i,s,r,n=null,a,h,l)=>{const c={shape:e,path:t,scale:i,rotation:s,cap:r===0?0:r||F.NO_CAP,sideOrientation:h,instance:l,updatable:a};return bo(o,c,n)};F.ExtrudeShapeCustom=(o,e,t,i,s,r,n,a,h,l,c,u)=>{const f={shape:e,path:t,scaleFunction:i,rotationFunction:s,ribbonCloseArray:r,ribbonClosePath:n,cap:a===0?0:a||F.NO_CAP,sideOrientation:c,instance:u,updatable:l};return Ro(o,f,h)};function So(o,e,t=null){const i=e.arc?e.arc<=0||e.arc>1?1:e.arc:1,s=e.closed===void 0?!0:e.closed,r=e.shape,n=e.radius||1,a=e.tessellation||64,h=e.clip||0,l=e.updatable,c=F._GetDefaultSideOrientation(e.sideOrientation),u=e.cap||F.NO_CAP,f=Math.PI*2,d=[],_=e.invertUV||!1;let m,g;const T=f/a*i;let R,A;for(m=0;m<=a-h;m++){for(A=[],(u==F.CAP_START||u==F.CAP_ALL)&&(A.push(new p(0,r[0].y,0)),A.push(new p(Math.cos(m*T)*r[0].x*n,r[0].y,Math.sin(m*T)*r[0].x*n))),g=0;g<r.length;g++)R=new p(Math.cos(m*T)*r[g].x*n,r[g].y,Math.sin(m*T)*r[g].x*n),A.push(R);(u==F.CAP_END||u==F.CAP_ALL)&&(A.push(new p(Math.cos(m*T)*r[r.length-1].x*n,r[r.length-1].y,Math.sin(m*T)*r[r.length-1].x*n)),A.push(new p(0,r[r.length-1].y,0))),d.push(A)}return Gi(o,{pathArray:d,closeArray:s,sideOrientation:c,updatable:l,invertUV:_,frontUVs:e.frontUVs,backUVs:e.backUVs},t)}const Km={CreateLathe:So};F.CreateLathe=(o,e,t,i,s,r,n)=>So(o,{shape:e,radius:t,tessellation:i,sideOrientation:n,updatable:r},s);function eu(o){const e=[],t=[],i=[],s=[],r=o.width!==void 0?o.width:o.size!==void 0?o.size:1,n=o.height!==void 0?o.height:o.size!==void 0?o.size:1,a=o.sideOrientation===0?0:o.sideOrientation||j.DEFAULTSIDE,h=r/2,l=n/2;t.push(-h,-l,0),i.push(0,0,-1),s.push(0,we?1:0),t.push(h,-l,0),i.push(0,0,-1),s.push(1,we?1:0),t.push(h,l,0),i.push(0,0,-1),s.push(1,we?0:1),t.push(-h,l,0),i.push(0,0,-1),s.push(0,we?0:1),e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),j._ComputeSides(a,t,e,i,s,o.frontUVs,o.backUVs);const c=new j;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function yo(o,e={},t=null){const i=new F(o,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,eu(e).applyToMesh(i,e.updatable),e.sourcePlane&&(i.translate(e.sourcePlane.normal,-e.sourcePlane.d),i.setDirection(e.sourcePlane.normal.scale(-1))),i}const Ym={CreatePlane:yo};j.CreatePlane=eu;F.CreatePlane=(o,e,t,i,s)=>yo(o,{size:e,width:e,height:e,sideOrientation:s,updatable:i},t);function Ao(o,e,t=null){const i=e.path;let s=e.instance,r=1;e.radius!==void 0?r=e.radius:s&&(r=s._creationDataStorage.radius);const n=e.tessellation||64,a=e.radiusFunction||null;let h=e.cap||F.NO_CAP;const l=e.invertUV||!1,c=e.updatable,u=F._GetDefaultSideOrientation(e.sideOrientation);e.arc=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1;const f=(T,R,A,y,E,x,b,P)=>{const v=R.getTangents(),O=R.getNormals(),k=R.getDistances(),q=Math.PI*2/E*P,ee=x||(()=>y);let Q,se,le,H;const K=U.Matrix[0];let w=b===F.NO_CAP||b===F.CAP_END?0:2;for(let N=0;N<T.length;N++){se=ee(N,k[N]),Q=Array(),le=O[N];for(let X=0;X<E;X++)D.RotationAxisToRef(v[N],q*X,K),H=Q[X]?Q[X]:p.Zero(),p.TransformCoordinatesToRef(le,K,H),H.scaleInPlace(se).addInPlace(T[N]),Q[X]=H;A[w]=Q,w++}const B=(N,X)=>{const Ee=Array();for(let ae=0;ae<N;ae++)Ee.push(T[X]);return Ee};switch(b){case F.NO_CAP:break;case F.CAP_START:A[0]=B(E,0),A[1]=A[2].slice(0);break;case F.CAP_END:A[w]=A[w-1].slice(0),A[w+1]=B(E,T.length-1);break;case F.CAP_ALL:A[0]=B(E,0),A[1]=A[2].slice(0),A[w]=A[w-1].slice(0),A[w+1]=B(E,T.length-1);break}return A};let d,_;if(s){const T=s._creationDataStorage,R=e.arc||T.arc;return d=T.path3D.update(i),_=f(i,d,T.pathArray,r,T.tessellation,a,T.cap,R),s=Gi("",{pathArray:_,instance:s}),T.path3D=d,T.pathArray=_,T.arc=R,T.radius=r,s}d=new Ks(i);const m=new Array;h=h<0||h>3?0:h,_=f(i,d,m,r,n,a,h,e.arc);const g=Gi(o,{pathArray:_,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:l,frontUVs:e.frontUVs,backUVs:e.backUVs},t);return g._creationDataStorage.pathArray=_,g._creationDataStorage.path3D=d,g._creationDataStorage.tessellation=n,g._creationDataStorage.cap=h,g._creationDataStorage.arc=e.arc,g._creationDataStorage.radius=r,g}const jm={CreateTube:Ao};F.CreateTube=(o,e,t,i,s,r,n,a,h,l)=>Ao(o,{path:e,radius:t,tessellation:i,radiusFunction:s,arc:1,cap:r,updatable:a,sideOrientation:h,instance:l},n);function tu(o){const e=[];e[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},e[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},e[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},e[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},e[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},e[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},e[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},e[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},e[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},e[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},e[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},e[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},e[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},e[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},e[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};const t=o.type&&(o.type<0||o.type>=e.length)?0:o.type||0,i=o.size,s=o.sizeX||i||1,r=o.sizeY||i||1,n=o.sizeZ||i||1,a=o.custom||e[t],h=a.face.length,l=o.faceUV||new Array(h),c=o.faceColors,u=o.flat===void 0?!0:o.flat,f=o.sideOrientation===0?0:o.sideOrientation||j.DEFAULTSIDE,d=[],_=[],m=[],g=[],T=[];let R=0,A=0;const y=[];let E,x,b,P,v,O,k,Y;if(u)for(x=0;x<h;x++)c&&c[x]===void 0&&(c[x]=new Ce(1,1,1,1)),l&&l[x]===void 0&&(l[x]=new Me(0,0,1,1));if(u)for(x=0;x<h;x++){const L=a.face[x].length;for(v=2*Math.PI/L,O=.5*Math.tan(v/2),k=.5,E=0;E<L;E++)d.push(a.vertex[a.face[x][E]][0]*s,a.vertex[a.face[x][E]][1]*r,a.vertex[a.face[x][E]][2]*n),y.push(R),R++,b=l[x].x+(l[x].z-l[x].x)*(.5+O),P=l[x].y+(l[x].w-l[x].y)*(k-.5),g.push(b,we?1-P:P),Y=O*Math.cos(v)-k*Math.sin(v),k=O*Math.sin(v)+k*Math.cos(v),O=Y,c&&T.push(c[x].r,c[x].g,c[x].b,c[x].a);for(E=0;E<L-2;E++)_.push(y[0+A],y[E+2+A],y[E+1+A]);A+=L}else{for(E=0;E<a.vertex.length;E++)d.push(a.vertex[E][0]*s,a.vertex[E][1]*r,a.vertex[E][2]*n),g.push(0,we?1:0);for(x=0;x<h;x++)for(E=0;E<a.face[x].length-2;E++)_.push(a.face[x][0],a.face[x][E+2],a.face[x][E+1])}j.ComputeNormals(d,_,m),j._ComputeSides(f,d,_,m,g,o.frontUVs,o.backUVs);const q=new j;return q.positions=d,q.indices=_,q.normals=m,q.uvs=g,c&&u&&(q.colors=T),q}function cn(o,e={},t=null){const i=new F(o,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,tu(e).applyToMesh(i,e.updatable),i}const Zm={CreatePolyhedron:cn};j.CreatePolyhedron=tu;F.CreatePolyhedron=(o,e,t)=>cn(o,e,t);function iu(o){const e=o.sideOrientation||j.DEFAULTSIDE,t=o.radius||1,i=o.flat===void 0?!0:o.flat,s=(o.subdivisions||4)|0,r=o.radiusX||t,n=o.radiusY||t,a=o.radiusZ||t,h=(1+Math.sqrt(5))/2,l=[-1,h,-0,1,h,0,-1,-h,0,1,-h,0,0,-1,-h,0,1,-h,0,-1,h,0,1,h,h,0,1,h,0,-1,-h,0,1,-h,0,-1],c=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],u=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],f=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],d=138/1024,_=239/1024,m=60/1024,g=26/1024,T=-40/1024,R=20/1024,A=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],y=[],E=[],x=[],b=[];let P=0;const v=new Array(3),O=new Array(3);let k;for(k=0;k<3;k++)v[k]=p.Zero(),O[k]=ie.Zero();for(let q=0;q<20;q++){for(k=0;k<3;k++){const ee=c[3*q+k];v[k].copyFromFloats(l[3*u[ee]],l[3*u[ee]+1],l[3*u[ee]+2]),v[k].normalize(),O[k].copyFromFloats(f[2*ee]*d+m+A[q]*T,f[2*ee+1]*_+g+A[q]*R)}const L=(ee,Q,se,le)=>{const H=p.Lerp(v[0],v[2],Q/s),K=p.Lerp(v[1],v[2],Q/s),w=s===Q?v[2]:p.Lerp(H,K,ee/(s-Q));w.normalize();let B;if(i){const ae=p.Lerp(v[0],v[2],le/s),Se=p.Lerp(v[1],v[2],le/s);B=p.Lerp(ae,Se,se/(s-le))}else B=new p(w.x,w.y,w.z);B.x/=r,B.y/=n,B.z/=a,B.normalize();const N=ie.Lerp(O[0],O[2],Q/s),X=ie.Lerp(O[1],O[2],Q/s),Ee=s===Q?O[2]:ie.Lerp(N,X,ee/(s-Q));E.push(w.x*r,w.y*n,w.z*a),x.push(B.x,B.y,B.z),b.push(Ee.x,we?1-Ee.y:Ee.y),y.push(P),P++};for(let ee=0;ee<s;ee++)for(let Q=0;Q+ee<s;Q++)L(Q,ee,Q+1/3,ee+1/3),L(Q+1,ee,Q+1/3,ee+1/3),L(Q,ee+1,Q+1/3,ee+1/3),Q+ee+1<s&&(L(Q+1,ee,Q+2/3,ee+2/3),L(Q+1,ee+1,Q+2/3,ee+2/3),L(Q,ee+1,Q+2/3,ee+2/3))}j._ComputeSides(e,E,y,x,b,o.frontUVs,o.backUVs);const Y=new j;return Y.indices=y,Y.positions=E,Y.normals=x,Y.uvs=b,Y}function Mo(o,e={},t=null){const i=new F(o,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,iu(e).applyToMesh(i,e.updatable),i}const qm={CreateIcoSphere:Mo};j.CreateIcoSphere=iu;F.CreateIcoSphere=(o,e,t)=>Mo(o,e,t);const Qg=new p(1,0,0),$g=new p(-1,0,0),Jg=new p(0,1,0),ep=new p(0,-1,0),tp=new p(0,0,1),ip=new p(0,0,-1);class Hr{constructor(e=p.Zero(),t=p.Up(),i=ie.Zero(),s=0,r=0,n=null,a=null,h=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=s,this.vertexIdxForBones=r,this.localPositionOverride=n,this.localNormalOverride=a,this.matrixIndicesOverride=h,this.matrixWeightsOverride=l}clone(){return new Hr(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,this.localPositionOverride?.slice(),this.localNormalOverride?.slice(),this.matrixIndicesOverride?.slice(),this.matrixWeightsOverride?.slice())}}function Po(o,e,t){const i=!!e.skeleton,s=!!e.morphTargetManager?.numTargets,r=t.localMode||i,n=e.getIndices(),a=i||s?e.getPositionData(!0,!0):e.getVerticesData(S.PositionKind),h=i||s?e.getNormalsData(!0,!0):e.getVerticesData(S.NormalKind),l=r?i?e.getVerticesData(S.PositionKind):a:null,c=r?i?e.getVerticesData(S.NormalKind):h:null,u=e.getVerticesData(S.UVKind),f=i?e.getVerticesData(S.MatricesIndicesKind):null,d=i?e.getVerticesData(S.MatricesWeightsKind):null,_=i?e.getVerticesData(S.MatricesIndicesExtraKind):null,m=i?e.getVerticesData(S.MatricesWeightsExtraKind):null,g=t.position||p.Zero();let T=t.normal||p.Up();const R=t.size||p.One(),A=t.angle||0;if(!T){const se=new p(0,0,1),le=e.getScene().activeCamera,H=p.TransformCoordinates(se,le.getWorldMatrix());T=le.globalPosition.subtract(H)}const y=-Math.atan2(T.z,T.x)-Math.PI/2,E=Math.sqrt(T.x*T.x+T.z*T.z),x=Math.atan2(T.y,E),b=new j;b.indices=[],b.positions=[],b.normals=[],b.uvs=[],b.matricesIndices=i?[]:null,b.matricesWeights=i?[]:null,b.matricesIndicesExtra=_?[]:null,b.matricesWeightsExtra=m?[]:null;let P=0;const v=(se,le)=>{const H=new Hr;if(!n||!a||!h)return H;const K=n[se];if(H.vertexIdx=K*3,H.vertexIdxForBones=K*4,H.position=new p(a[K*3],a[K*3+1],a[K*3+2]),p.TransformCoordinatesToRef(H.position,le,H.position),H.normal=new p(h[K*3],h[K*3+1],h[K*3+2]),p.TransformNormalToRef(H.normal,le,H.normal),t.captureUVS&&u){const w=u[K*2+1];H.uv=new ie(u[K*2],we?1-w:w)}return H},O=[0,0,0,0],k=(se,le)=>{if(se.length===0)return se;const H=.5*Math.abs(p.Dot(R,le)),K=(N,X,Ee,ae)=>{for(let Se=0;Se<ae;++Se)if(N[Ee+Se]===X)return Ee+Se;return-1},w=(N,X)=>{const Ee=p.GetClipFactor(N.position,X.position,le,H);let ae=O,Se=O;if(f&&d){const Ls=N.matrixIndicesOverride?0:N.vertexIdxForBones,_n=N.matrixIndicesOverride??f,Co=N.matrixWeightsOverride??d,gn=X.matrixIndicesOverride?0:X.vertexIdxForBones,Do=X.matrixIndicesOverride??f,Oo=X.matrixWeightsOverride??d;ae=[0,0,0,0],Se=[0,0,0,0];let Yi=0;for(let Jt=0;Jt<4;++Jt)if(Co[Ls+Jt]>0){const Bs=K(Do,_n[Ls+Jt],gn,4);ae[Yi]=_n[Ls+Jt],Se[Yi]=Br(Co[Ls+Jt],Bs>=0?Oo[Bs]:0,Ee),Yi++}for(let Jt=0;Jt<4&&Yi<4;++Jt){const Bs=Do[gn+Jt];K(_n,Bs,Ls,4)===-1&&(ae[Yi]=Bs,Se[Yi]=Br(0,Oo[gn+Jt],Ee),Yi++)}const Er=Se[0]+Se[1]+Se[2]+Se[3];Se[0]/=Er,Se[1]/=Er,Se[2]/=Er,Se[3]/=Er}const We=N.localPositionOverride?N.localPositionOverride[0]:l?.[N.vertexIdx]??0,nt=N.localPositionOverride?N.localPositionOverride[1]:l?.[N.vertexIdx+1]??0,ct=N.localPositionOverride?N.localPositionOverride[2]:l?.[N.vertexIdx+2]??0,Ge=X.localPositionOverride?X.localPositionOverride[0]:l?.[X.vertexIdx]??0,_e=X.localPositionOverride?X.localPositionOverride[1]:l?.[X.vertexIdx+1]??0,Fe=X.localPositionOverride?X.localPositionOverride[2]:l?.[X.vertexIdx+2]??0,Xe=N.localNormalOverride?N.localNormalOverride[0]:c?.[N.vertexIdx]??0,Ae=N.localNormalOverride?N.localNormalOverride[1]:c?.[N.vertexIdx+1]??0,$e=N.localNormalOverride?N.localNormalOverride[2]:c?.[N.vertexIdx+2]??0,zt=X.localNormalOverride?X.localNormalOverride[0]:c?.[X.vertexIdx]??0,bt=X.localNormalOverride?X.localNormalOverride[1]:c?.[X.vertexIdx+1]??0,$t=X.localNormalOverride?X.localNormalOverride[2]:c?.[X.vertexIdx+2]??0,Ii=Xe+(zt-Xe)*Ee,hi=Ae+(bt-Ae)*Ee,ns=$e+($t-$e)*Ee,dn=Math.sqrt(Ii*Ii+hi*hi+ns*ns);return new Hr(p.Lerp(N.position,X.position,Ee),p.Lerp(N.normal,X.normal,Ee).normalize(),ie.Lerp(N.uv,X.uv,Ee),-1,-1,l?[We+(Ge-We)*Ee,nt+(_e-nt)*Ee,ct+(Fe-ct)*Ee]:null,c?[Ii/dn,hi/dn,ns/dn]:null,ae,Se)};let B=null;se.length>3&&(B=[]);for(let N=0;N<se.length;N+=3){let X=null,Ee=null,ae=null,Se=null;const We=p.Dot(se[N].position,le)-H,nt=p.Dot(se[N+1].position,le)-H,ct=p.Dot(se[N+2].position,le)-H,Ge=We>0,_e=nt>0,Fe=ct>0;switch((Ge?1:0)+(_e?1:0)+(Fe?1:0)){case 0:se.length>3?(B.push(se[N]),B.push(se[N+1]),B.push(se[N+2])):B=se;break;case 1:if(B=B??new Array,Ge&&(X=se[N+1],Ee=se[N+2],ae=w(se[N],X),Se=w(se[N],Ee)),_e){X=se[N],Ee=se[N+2],ae=w(se[N+1],X),Se=w(se[N+1],Ee),B.push(ae),B.push(Ee.clone()),B.push(X.clone()),B.push(Ee.clone()),B.push(ae.clone()),B.push(Se);break}Fe&&(X=se[N],Ee=se[N+1],ae=w(se[N+2],X),Se=w(se[N+2],Ee)),X&&Ee&&ae&&Se&&(B.push(X.clone()),B.push(Ee.clone()),B.push(ae),B.push(Se),B.push(ae.clone()),B.push(Ee.clone()));break;case 2:B=B??new Array,Ge||(X=se[N].clone(),Ee=w(X,se[N+1]),ae=w(X,se[N+2]),B.push(X),B.push(Ee),B.push(ae)),_e||(X=se[N+1].clone(),Ee=w(X,se[N+2]),ae=w(X,se[N]),B.push(X),B.push(Ee),B.push(ae)),Fe||(X=se[N+2].clone(),Ee=w(X,se[N]),ae=w(X,se[N+1]),B.push(X),B.push(Ee),B.push(ae));break}}return B},Y=e instanceof F?e:null,q=Y?._thinInstanceDataStorage.matrixData,L=Y?.thinInstanceCount||1,ee=U.Matrix[0];ee.copyFrom(D.IdentityReadOnly);for(let se=0;se<L;++se){if(Y?.hasThinInstances&&q){const N=se*16;ee.setRowFromFloats(0,q[N+0],q[N+1],q[N+2],q[N+3]),ee.setRowFromFloats(1,q[N+4],q[N+5],q[N+6],q[N+7]),ee.setRowFromFloats(2,q[N+8],q[N+9],q[N+10],q[N+11]),ee.setRowFromFloats(3,q[N+12],q[N+13],q[N+14],q[N+15])}const le=D.RotationYawPitchRoll(y,x,A).multiply(D.Translation(g.x,g.y,g.z)),H=D.Invert(le),K=e.getWorldMatrix(),w=ee.multiply(K).multiply(H),B=new Array(3);for(let N=0;N<n.length;N+=3){let X=B;if(X[0]=v(N,w),X[1]=v(N+1,w),X[2]=v(N+2,w),!(t.cullBackFaces&&-X[0].normal.z<=0&&-X[1].normal.z<=0&&-X[2].normal.z<=0)&&(X=k(X,Qg),!!X&&(X=k(X,$g),!!X&&(X=k(X,Jg),!!X&&(X=k(X,ep),!!X&&(X=k(X,tp),!!X&&(X=k(X,ip),!!X)))))))for(let Ee=0;Ee<X.length;Ee++){const ae=X[Ee];if(b.indices.push(P),r?(ae.localPositionOverride?(b.positions[P*3]=ae.localPositionOverride[0],b.positions[P*3+1]=ae.localPositionOverride[1],b.positions[P*3+2]=ae.localPositionOverride[2]):l&&(b.positions[P*3]=l[ae.vertexIdx],b.positions[P*3+1]=l[ae.vertexIdx+1],b.positions[P*3+2]=l[ae.vertexIdx+2]),ae.localNormalOverride?(b.normals[P*3]=ae.localNormalOverride[0],b.normals[P*3+1]=ae.localNormalOverride[1],b.normals[P*3+2]=ae.localNormalOverride[2]):c&&(b.normals[P*3]=c[ae.vertexIdx],b.normals[P*3+1]=c[ae.vertexIdx+1],b.normals[P*3+2]=c[ae.vertexIdx+2])):(ae.position.toArray(b.positions,P*3),ae.normal.toArray(b.normals,P*3)),b.matricesIndices&&b.matricesWeights&&(ae.matrixIndicesOverride?(b.matricesIndices[P*4]=ae.matrixIndicesOverride[0],b.matricesIndices[P*4+1]=ae.matrixIndicesOverride[1],b.matricesIndices[P*4+2]=ae.matrixIndicesOverride[2],b.matricesIndices[P*4+3]=ae.matrixIndicesOverride[3]):(f&&(b.matricesIndices[P*4]=f[ae.vertexIdxForBones],b.matricesIndices[P*4+1]=f[ae.vertexIdxForBones+1],b.matricesIndices[P*4+2]=f[ae.vertexIdxForBones+2],b.matricesIndices[P*4+3]=f[ae.vertexIdxForBones+3]),_&&b.matricesIndicesExtra&&(b.matricesIndicesExtra[P*4]=_[ae.vertexIdxForBones],b.matricesIndicesExtra[P*4+1]=_[ae.vertexIdxForBones+1],b.matricesIndicesExtra[P*4+2]=_[ae.vertexIdxForBones+2],b.matricesIndicesExtra[P*4+3]=_[ae.vertexIdxForBones+3])),ae.matrixWeightsOverride?(b.matricesWeights[P*4]=ae.matrixWeightsOverride[0],b.matricesWeights[P*4+1]=ae.matrixWeightsOverride[1],b.matricesWeights[P*4+2]=ae.matrixWeightsOverride[2],b.matricesWeights[P*4+3]=ae.matrixWeightsOverride[3]):(d&&(b.matricesWeights[P*4]=d[ae.vertexIdxForBones],b.matricesWeights[P*4+1]=d[ae.vertexIdxForBones+1],b.matricesWeights[P*4+2]=d[ae.vertexIdxForBones+2],b.matricesWeights[P*4+3]=d[ae.vertexIdxForBones+3]),m&&b.matricesWeightsExtra&&(b.matricesWeightsExtra[P*4]=m[ae.vertexIdxForBones],b.matricesWeightsExtra[P*4+1]=m[ae.vertexIdxForBones+1],b.matricesWeightsExtra[P*4+2]=m[ae.vertexIdxForBones+2],b.matricesWeightsExtra[P*4+3]=m[ae.vertexIdxForBones+3]))),t.captureUVS)ae.uv.toArray(b.uvs,P*2);else{b.uvs.push(.5+ae.position.x/R.x);const Se=.5+ae.position.y/R.y;b.uvs.push(we?1-Se:Se)}P++}}}b.indices.length===0&&(b.indices=null),b.positions.length===0&&(b.positions=null),b.normals.length===0&&(b.normals=null),b.uvs.length===0&&(b.uvs=null),b.matricesIndices?.length===0&&(b.matricesIndices=null),b.matricesWeights?.length===0&&(b.matricesWeights=null),b.matricesIndicesExtra?.length===0&&(b.matricesIndicesExtra=null),b.matricesWeightsExtra?.length===0&&(b.matricesWeightsExtra=null);const Q=new F(o,e.getScene());return b.applyToMesh(Q),r?(Q.skeleton=e.skeleton,Q.parent=e):(Q.position=g.clone(),Q.rotation=new p(x,y,A)),Q.computeWorldMatrix(!0),Q.refreshBoundingInfo(!0,!0),Q}const Qm={CreateDecal:Po};F.CreateDecal=(o,e,t,i,s,r)=>Po(o,e,{position:t,normal:i,size:s,angle:r});function su(o={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const e=Math.max(o.subdivisions?o.subdivisions:2,1)|0,t=Math.max(o.tessellation?o.tessellation:16,3)|0,i=Math.max(o.height?o.height:1,0),s=Math.max(o.radius?o.radius:.25,0),r=Math.max(o.capSubdivisions?o.capSubdivisions:6,1)|0,n=t,a=e,h=Math.max(o.radiusTop?o.radiusTop:s,0),l=Math.max(o.radiusBottom?o.radiusBottom:s,0),c=i-(h+l),u=0,f=2*Math.PI,d=Math.max(o.topCapSubdivisions?o.topCapSubdivisions:r,1),_=Math.max(o.bottomCapSubdivisions?o.bottomCapSubdivisions:r,1),m=Math.acos((l-h)/i);let g=[];const T=[],R=[],A=[];let y=0;const E=[],x=c*.5,b=Math.PI*.5;let P,v;const O=p.Zero(),k=p.Zero(),Y=Math.cos(m),q=Math.sin(m),L=new ie(h*q,x+h*Y).subtract(new ie(l*q,-x+l*Y)).length(),ee=h*m+L+l*(b-m);let Q=0;for(v=0;v<=d;v++){const K=[],w=b-m*(v/d);Q+=h*m/d;const B=Math.cos(w),N=Math.sin(w),X=B*h;for(P=0;P<=n;P++){const Ee=P/n,ae=Ee*f+u,Se=Math.sin(ae),We=Math.cos(ae);k.x=X*Se,k.y=x+N*h,k.z=X*We,T.push(k.x,k.y,k.z),O.set(B*Se,N,B*We),R.push(O.x,O.y,O.z),A.push(Ee,we?Q/ee:1-Q/ee),K.push(y),y++}E.push(K)}const se=i-h-l+Y*h-Y*l,le=q*(l-h)/se;for(v=1;v<=a;v++){const K=[];Q+=L/a;const w=q*(v*(l-h)/a+h);for(P=0;P<=n;P++){const B=P/n,N=B*f+u,X=Math.sin(N),Ee=Math.cos(N);k.x=w*X,k.y=x+Y*h-v*se/a,k.z=w*Ee,T.push(k.x,k.y,k.z),O.set(X,le,Ee).normalize(),R.push(O.x,O.y,O.z),A.push(B,we?Q/ee:1-Q/ee),K.push(y),y++}E.push(K)}for(v=1;v<=_;v++){const K=[],w=b-m-(Math.PI-m)*(v/_);Q+=l*m/_;const B=Math.cos(w),N=Math.sin(w),X=B*l;for(P=0;P<=n;P++){const Ee=P/n,ae=Ee*f+u,Se=Math.sin(ae),We=Math.cos(ae);k.x=X*Se,k.y=-x+N*l,k.z=X*We,T.push(k.x,k.y,k.z),O.set(B*Se,N,B*We),R.push(O.x,O.y,O.z),A.push(Ee,we?Q/ee:1-Q/ee),K.push(y),y++}E.push(K)}for(P=0;P<n;P++)for(v=0;v<d+a+_;v++){const K=E[v][P],w=E[v+1][P],B=E[v+1][P+1],N=E[v][P+1];g.push(K),g.push(w),g.push(N),g.push(w),g.push(B),g.push(N)}if(g=g.reverse(),o.orientation&&!o.orientation.equals(p.Up())){const K=new D;o.orientation.clone().scale(Math.PI*.5).cross(p.Up()).toQuaternion().toRotationMatrix(K);const w=p.Zero();for(let B=0;B<T.length;B+=3)w.set(T[B],T[B+1],T[B+2]),p.TransformCoordinatesToRef(w.clone(),K,w),T[B]=w.x,T[B+1]=w.y,T[B+2]=w.z}const H=new j;return H.positions=T,H.normals=R,H.uvs=A,H.indices=g,H}function Io(o,e={orientation:p.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6,updatable:!1},t=null){const i=new F(o,t);return su(e).applyToMesh(i,e.updatable),i}const $m={CreateCapsule:Io};F.CreateCapsule=(o,e,t)=>Io(o,e,t);j.CreateCapsule=su;class Ze{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(e=Math.floor(e),W.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(t=Math.floor(t),W.Warn("y is not an integer, floor(y) used"))}clone(){return new Ze(this.x,this.y)}rotate60About(e){const t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){const t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&(e=Math.floor(e),W.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),W.Warn("n not an integer only floor(n) used"));const i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&(e=Math.floor(e),W.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),W.Warn("n is not an integer, floor(n) used"));const i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){const i=p.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new Ze(0,0)}}class ru{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new va("icosahedron","Regular",[[0,ot,-1],[-ot,1,0],[-1,0,-ot],[1,0,-ot],[ot,1,0],[0,ot,1],[-1,0,ot],[-ot,-1,0],[0,-ot,-1],[ot,-1,0],[1,0,ot],[0,-ot,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12;const t={},i=this.m,s=this.n;let r=i;s!==0&&(r=Nr(i,s));const n=i/r,a=s/r;let h,l,c,u,f;const d=Ze.Zero(),_=new Ze(i,s),m=new Ze(-s,i+s),g=Ze.Zero(),T=Ze.Zero(),R=Ze.Zero();let A=[],y,E,x,b;const P=[],v=this.vertByDist,O=(k,Y,q,L)=>{y=k+"|"+q,E=Y+"|"+L,y in t||E in t?y in t&&!(E in t)?t[E]=t[y]:E in t&&!(y in t)&&(t[y]=t[E]):(t[y]=e,t[E]=e,e++),v[q][0]>2?P[t[y]]=[-v[q][0],v[q][1],t[y]]:P[t[y]]=[A[v[q][0]],v[q][1],t[y]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let k=0;k<20;k++){if(A=this.IDATA.face[k],c=A[2],u=A[1],f=A[0],x=d.x+"|"+d.y,y=k+"|"+x,y in t||(t[y]=c,P[c]=[A[v[x][0]],v[x][1]]),x=_.x+"|"+_.y,y=k+"|"+x,y in t||(t[y]=u,P[u]=[A[v[x][0]],v[x][1]]),x=m.x+"|"+m.y,y=k+"|"+x,y in t||(t[y]=f,P[f]=[A[v[x][0]],v[x][1]]),h=this.IDATA.edgematch[k][0],l=this.IDATA.edgematch[k][1],l==="B")for(let Y=1;Y<r;Y++)T.x=i-Y*(n+a),T.y=s+Y*n,R.x=-Y*a,R.y=Y*(n+a),x=T.x+"|"+T.y,b=R.x+"|"+R.y,O(k,h,x,b);if(l==="O")for(let Y=1;Y<r;Y++)R.x=-Y*a,R.y=Y*(n+a),g.x=Y*n,g.y=Y*a,x=R.x+"|"+R.y,b=g.x+"|"+g.y,O(k,h,x,b);if(h=this.IDATA.edgematch[k][2],l=this.IDATA.edgematch[k][3],l&&l==="A")for(let Y=1;Y<r;Y++)g.x=Y*n,g.y=Y*a,T.x=i-(r-Y)*(n+a),T.y=s+(r-Y)*n,x=g.x+"|"+g.y,b=T.x+"|"+T.y,O(k,h,x,b);for(let Y=0;Y<this.vertices.length;Y++)x=this.vertices[Y].x+"|"+this.vertices[Y].y,y=k+"|"+x,y in t||(t[y]=e++,v[x][0]>2?P[t[y]]=[-v[x][0],v[x][1],t[y]]:P[t[y]]=[A[v[x][0]],v[x][1],t[y]])}this.closestTo=P,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,s=e*e+t*t+e*t;this.coau=(e+t)/s,this.cobu=-t/s,this.coav=-i*(e-t)/s,this.cobv=i*(2*e+t)/s}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i<t+e+1;i++)for(let s=this.min[i];s<this.max[i]+1;s++)s<this.max[i]&&s<this.max[i+1]+1&&this.innerFacets.push(["|"+s+"|"+i,"|"+s+"|"+(i+1),"|"+(s+1)+"|"+i]),i>0&&s<this.max[i-1]&&s+1<this.max[i]+1&&this.innerFacets.push(["|"+s+"|"+i,"|"+(s+1)+"|"+i,"|"+(s+1)+"|"+(i-1)])}edgeVecsABOB(){const e=this.m,t=this.n,i=new Ze(-t,e+t);for(let s=1;s<e+t;s++){const r=new Ze(this.min[s],s),n=new Ze(this.min[s-1],s-1),a=new Ze(this.min[s+1],s+1),h=r.clone(),l=n.clone(),c=a.clone();h.rotate60About(i),l.rotate60About(i),c.rotate60About(i);const u=new Ze(this.max[h.y],h.y),f=new Ze(this.max[h.y-1],h.y-1),d=new Ze(this.max[h.y-1]-1,h.y-1);(h.x!==u.x||h.y!==u.y)&&(h.x!==f.x?(this.vertexTypes.push([1,0,0]),this.isoVecsABOB.push([r,f,d]),this.vertexTypes.push([1,0,0]),this.isoVecsABOB.push([r,d,u])):h.y===c.y?(this.vertexTypes.push([1,1,0]),this.isoVecsABOB.push([r,n,f]),this.vertexTypes.push([1,0,1]),this.isoVecsABOB.push([r,f,a])):(this.vertexTypes.push([1,1,0]),this.isoVecsABOB.push([r,n,f]),this.vertexTypes.push([1,0,0]),this.isoVecsABOB.push([r,f,u])))}}mapABOBtoOBOA(){const e=new Ze(0,0);for(let t=0;t<this.isoVecsABOB.length;t++){const i=[];for(let s=0;s<3;s++)e.x=this.isoVecsABOB[t][s].x,e.y=this.isoVecsABOB[t][s].y,this.vertexTypes[t][s]===0&&e.rotateNeg120(this.m,this.n),i.push(e.clone());this.isoVecsOBOA.push(i)}}mapABOBtoBAOA(){const e=new Ze(0,0);for(let t=0;t<this.isoVecsABOB.length;t++){const i=[];for(let s=0;s<3;s++)e.x=this.isoVecsABOB[t][s].x,e.y=this.isoVecsABOB[t][s].y,this.vertexTypes[t][s]===1&&e.rotate120(this.m,this.n),i.push(e.clone());this.isoVecsBAOA.push(i)}}MapToFace(e,t){const i=this.IDATA.face[e],s=i[2],r=i[1],n=i[0],a=p.FromArray(this.IDATA.vertex[s]),h=p.FromArray(this.IDATA.vertex[r]),l=p.FromArray(this.IDATA.vertex[n]),c=h.subtract(a),u=l.subtract(a),f=c.scale(this.coau).add(u.scale(this.cobu)),d=c.scale(this.coav).add(u.scale(this.cobv));let _,m;for(let g=0;g<this.cartesian.length;g++)m=f.scale(this.cartesian[g].x).add(d.scale(this.cartesian[g].y)).add(a),m.x,m.y,m.z,_=e+"|"+this.vertices[g].x+"|"+this.vertices[g].y,t.vertex[this.vecToidx[_]]=[m.x,m.y,m.z]}build(e,t){const i=[],s=Ze.Zero(),r=new Ze(e,t),n=new Ze(-t,e+t);i.push(s,r,n);for(let E=t;E<e+1;E++)for(let x=0;x<e+1-E;x++)i.push(new Ze(x,E));if(t>0){const E=Nr(e,t),x=e/E,b=t/E;for(let v=1;v<E;v++)i.push(new Ze(v*x,v*b)),i.push(new Ze(-v*b,v*(x+b))),i.push(new Ze(e-v*(x+b),t+v*x));const P=e/t;for(let v=1;v<t;v++)for(let O=0;O<v*P;O++)i.push(new Ze(O,v)),i.push(new Ze(O,v).rotate120(e,t)),i.push(new Ze(O,v).rotateNeg120(e,t))}i.sort((E,x)=>E.x-x.x),i.sort((E,x)=>E.y-x.y);const a=new Array(e+t+1),h=new Array(e+t+1);for(let E=0;E<a.length;E++)a[E]=1/0,h[E]=-1/0;let l,c;const u=i.length;for(let E=0;E<u;E++)c=i[E].x,l=i[E].y,a[l]=Math.min(c,a[l]),h[l]=Math.max(c,h[l]);const f=(E,x)=>{const b=E.clone();return x==="A"&&b.rotateNeg120(e,t),x==="B"&&b.rotate120(e,t),b.x<0?b.y:b.x+b.y},d=[],_=[],m=[],g=[],T={},R=[];let A=-1,y=-1;for(let E=0;E<u;E++)d[E]=i[E].toCartesianOrigin(new Ze(0,0),.5),_[E]=f(i[E],"O"),m[E]=f(i[E],"A"),g[E]=f(i[E],"B"),_[E]===m[E]&&m[E]===g[E]?(A=3,y=_[E]):_[E]===m[E]?(A=4,y=_[E]):m[E]===g[E]?(A=5,y=m[E]):g[E]===_[E]&&(A=6,y=_[E]),_[E]<m[E]&&_[E]<g[E]&&(A=2,y=_[E]),m[E]<_[E]&&m[E]<g[E]&&(A=1,y=m[E]),g[E]<m[E]&&g[E]<_[E]&&(A=0,y=g[E]),R.push([A,y,i[E].x,i[E].y]);R.sort((E,x)=>E[2]-x[2]),R.sort((E,x)=>E[3]-x[3]),R.sort((E,x)=>E[1]-x[1]),R.sort((E,x)=>E[0]-x[0]);for(let E=0;E<R.length;E++)T[R[E][2]+"|"+R[E][3]]=[R[E][0],R[E][1],E];return this.m=e,this.n=t,this.vertices=i,this.vertByDist=T,this.cartesian=d,this.min=a,this.max=h,this}}class va{constructor(e,t,i,s){this.name=e,this.category=t,this.vertex=i,this.face=s}}class un extends va{innerToData(e,t){for(let i=0;i<t.innerFacets.length;i++)this.face.push(t.innerFacets[i].map(s=>t.vecToidx[e+s]))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let s=0;s<t.isoVecsABOB.length;s++){const r=[];for(let n=0;n<3;n++)t.vertexTypes[s][n]===0?r.push(e+"|"+t.isoVecsABOB[s][n].x+"|"+t.isoVecsABOB[s][n].y):r.push(i+"|"+t.isoVecsABOB[s][n].x+"|"+t.isoVecsABOB[s][n].y);this.face.push([t.vecToidx[r[0]],t.vecToidx[r[1]],t.vecToidx[r[2]]])}}mapOBOAtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let s=0;s<t.isoVecsOBOA.length;s++){const r=[];for(let n=0;n<3;n++)t.vertexTypes[s][n]===1?r.push(e+"|"+t.isoVecsOBOA[s][n].x+"|"+t.isoVecsOBOA[s][n].y):r.push(i+"|"+t.isoVecsOBOA[s][n].x+"|"+t.isoVecsOBOA[s][n].y);this.face.push([t.vecToidx[r[0]],t.vecToidx[r[1]],t.vecToidx[r[2]]])}}mapBAOAtoDATA(e,t){const i=t.IDATA.edgematch[e][2];for(let s=0;s<t.isoVecsBAOA.length;s++){const r=[];for(let n=0;n<3;n++)t.vertexTypes[s][n]===1?r.push(e+"|"+t.isoVecsBAOA[s][n].x+"|"+t.isoVecsBAOA[s][n].y):r.push(i+"|"+t.isoVecsBAOA[s][n].x+"|"+t.isoVecsBAOA[s][n].y);this.face.push([t.vecToidx[r[0]],t.vecToidx[r[1]],t.vecToidx[r[2]]])}}orderData(e){const t=[];for(let n=0;n<13;n++)t[n]=[];const i=e.closestTo;for(let n=0;n<i.length;n++)i[n][0]>-1?i[n][1]>0&&t[i[n][0]].push([n,i[n][1]]):t[12].push([n,i[n][0]]);const s=[];for(let n=0;n<12;n++)s[n]=n;let r=12;for(let n=0;n<12;n++){t[n].sort((a,h)=>a[1]-h[1]);for(let a=0;a<t[n].length;a++)s[t[n][a][0]]=r++}for(let n=0;n<t[12].length;n++)s[t[12][n][0]]=r++;for(let n=0;n<this.vertex.length;n++)this.vertex[n].push(s[n]);this.vertex.sort((n,a)=>n[3]-a[3]);for(let n=0;n<this.vertex.length;n++)this.vertex[n].pop();for(let n=0;n<this.face.length;n++)for(let a=0;a<this.face[n].length;a++)this.face[n][a]=s[this.face[n][a]];this.sharedNodes=t[12].length,this.poleNodes=this.vertex.length-this.sharedNodes}setOrder(e,t){const i=[],s=[];let r=t.pop();s.push(r);let n=this.face[r].indexOf(e);n=(n+2)%3;let a=this.face[r][n];i.push(a);let h=0;for(;t.length>0;)r=t[h],this.face[r].indexOf(a)>-1?(n=(this.face[r].indexOf(a)+1)%3,a=this.face[r][n],i.push(a),s.push(r),t.splice(h,1),h=0):h++;return this.adjacentFaces.push(i),s}toGoldbergPolyhedronData(){const e=new va("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let l=0;l<t;l++)i[l]=[];for(let l=0;l<this.face.length;l++)for(let c=0;c<3;c++)i[this.face[l][c]].push(l);let s,r,n,a,h;this.adjacentFaces=[];for(let l=0;l<i.length;l++){e.face[l]=this.setOrder(l,i[l].concat([]));for(const c of i[l]){s=0,r=0,n=0,a=this.face[c];for(let u=0;u<3;u++)h=this.vertex[a[u]],s+=h[0],r+=h[1],n+=h[2];e.vertex[c]=[s/3,r/3,n/3]}}return e}static BuildGeodesicData(e){const t=new un("Geodesic-m-n","Geodesic",[[0,ot,-1],[-ot,1,0],[-1,0,-ot],[1,0,-ot],[ot,1,0],[0,ot,1],[-1,0,ot],[-ot,-1,0],[0,-ot,-1],[ot,-1,0],[1,0,ot],[0,-ot,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let s=0;s<e.IDATA.face.length;s++)e.MapToFace(s,t),t.innerToData(s,e),e.IDATA.edgematch[s][1]==="B"&&t.mapABOBtoDATA(s,e),e.IDATA.edgematch[s][1]==="O"&&t.mapOBOAtoDATA(s,e),e.IDATA.edgematch[s][3]==="A"&&t.mapBAOAtoDATA(s,e);t.orderData(e);const i=1;return t.vertex=t.vertex.map(function(s){const r=s[0],n=s[1],a=s[2],h=Math.sqrt(r*r+n*n+a*a);return s[0]*=i/h,s[1]*=i/h,s[2]*=i/h,s}),t}}function sp(o,e,t=null){let i=e.m||1;i!==Math.floor(i)&&(i=Math.floor(i),W.Warn("m not an integer only floor(m) used"));let s=e.n||0;if(s!==Math.floor(s)&&(s=Math.floor(s),W.Warn("n not an integer only floor(n) used")),s>i){const l=s;s=i,i=l,W.Warn("n > m therefore m and n swapped")}const r=new ru;r.build(i,s);const a={custom:un.BuildGeodesicData(r),size:e.size,sizeX:e.sizeX,sizeY:e.sizeY,sizeZ:e.sizeZ,faceUV:e.faceUV,faceColors:e.faceColors,flat:e.flat,updatable:e.updatable,sideOrientation:e.sideOrientation,frontUVs:e.frontUVs,backUVs:e.backUVs};return cn(o,a,t)}F._GoldbergMeshParser=(o,e)=>fn.Parse(o,e);class fn extends F{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return t===void 0?(e>this.goldbergData.nbUnsharedFaces-1&&(W.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(W.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(W.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let i=0;i<e.length;i++){const s=e[i][0],r=e[i][1],n=e[i][2];for(let a=s;a<r+1;a++)this.goldbergData.faceColors[a]=n}const t=[];for(let i=0;i<12;i++)for(let s=0;s<5;s++)t.push(this.goldbergData.faceColors[i].r,this.goldbergData.faceColors[i].g,this.goldbergData.faceColors[i].b,this.goldbergData.faceColors[i].a);for(let i=12;i<this.goldbergData.faceColors.length;i++)for(let s=0;s<6;s++)t.push(this.goldbergData.faceColors[i].r,this.goldbergData.faceColors[i].g,this.goldbergData.faceColors[i].b,this.goldbergData.faceColors[i].a);return t}setGoldbergFaceColors(e){const t=this._changeGoldbergFaceColors(e);this.setVerticesData(S.ColorKind,t)}updateGoldbergFaceColors(e){const t=this._changeGoldbergFaceColors(e);this.updateVerticesData(S.ColorKind,t)}_changeGoldbergFaceUVs(e){const t=this.getVerticesData(S.UVKind);for(let i=0;i<e.length;i++){const s=e[i][0],r=e[i][1],n=e[i][2],a=e[i][3],h=e[i][4],l=[],c=[];let u,f;for(let d=0;d<5;d++)u=n.x+a*Math.cos(h+d*Math.PI/2.5),f=n.y+a*Math.sin(h+d*Math.PI/2.5),u<0&&(u=0),u>1&&(u=1),l.push(u,f);for(let d=0;d<6;d++)u=n.x+a*Math.cos(h+d*Math.PI/3),f=n.y+a*Math.sin(h+d*Math.PI/3),u<0&&(u=0),u>1&&(u=1),c.push(u,f);for(let d=s;d<Math.min(12,r+1);d++)for(let _=0;_<5;_++)t[10*d+2*_]=l[2*_],t[10*d+2*_+1]=l[2*_+1];for(let d=Math.max(12,s);d<r+1;d++)for(let _=0;_<6;_++)t[12*d-24+2*_]=c[2*_],t[12*d-23+2*_]=c[2*_+1]}return t}setGoldbergFaceUVs(e){const t=this._changeGoldbergFaceUVs(e);this.setVerticesData(S.UVKind,t)}updateGoldbergFaceUVs(e){const t=this._changeGoldbergFaceUVs(e);this.updateVerticesData(S.UVKind,t)}placeOnGoldbergFaceAt(e,t,i){const s=p.RotationFromAxis(this.goldbergData.faceXaxis[t],this.goldbergData.faceYaxis[t],this.goldbergData.faceZaxis[t]);e.rotation=s,e.position=this.goldbergData.faceCenters[t].add(this.goldbergData.faceXaxis[t].scale(i.x)).add(this.goldbergData.faceYaxis[t].scale(i.y)).add(this.goldbergData.faceZaxis[t].scale(i.z))}serialize(e){super.serialize(e),e.type="GoldbergMesh";const t={};if(t.adjacentFaces=this.goldbergData.adjacentFaces,t.nbSharedFaces=this.goldbergData.nbSharedFaces,t.nbUnsharedFaces=this.goldbergData.nbUnsharedFaces,t.nbFaces=this.goldbergData.nbFaces,t.nbFacesAtPole=this.goldbergData.nbFacesAtPole,this.goldbergData.faceColors){t.faceColors=[];for(const i of this.goldbergData.faceColors)t.faceColors.push(i.asArray())}if(this.goldbergData.faceCenters){t.faceCenters=[];for(const i of this.goldbergData.faceCenters)t.faceCenters.push(i.asArray())}if(this.goldbergData.faceZaxis){t.faceZaxis=[];for(const i of this.goldbergData.faceZaxis)t.faceZaxis.push(i.asArray())}if(this.goldbergData.faceYaxis){t.faceYaxis=[];for(const i of this.goldbergData.faceYaxis)t.faceYaxis.push(i.asArray())}if(this.goldbergData.faceXaxis){t.faceXaxis=[];for(const i of this.goldbergData.faceXaxis)t.faceXaxis.push(i.asArray())}e.goldbergData=t}static Parse(e,t){const i=e.goldbergData;i.faceColors=i.faceColors.map(r=>Ce.FromArray(r)),i.faceCenters=i.faceCenters.map(r=>p.FromArray(r)),i.faceZaxis=i.faceZaxis.map(r=>p.FromArray(r)),i.faceXaxis=i.faceXaxis.map(r=>p.FromArray(r)),i.faceYaxis=i.faceYaxis.map(r=>p.FromArray(r));const s=new fn(e.name,t);return s.goldbergData=i,s}}function rp(o,e){const t=o.size,i=o.sizeX||t||1,s=o.sizeY||t||1,r=o.sizeZ||t||1,n=o.sideOrientation===0?0:o.sideOrientation||j.DEFAULTSIDE,a=[],h=[],l=[],c=[];let u=1/0,f=-1/0,d=1/0,_=-1/0;for(let T=0;T<e.vertex.length;T++)u=Math.min(u,e.vertex[T][0]*i),f=Math.max(f,e.vertex[T][0]*i),d=Math.min(d,e.vertex[T][1]*s),_=Math.max(_,e.vertex[T][1]*s);let m=0;for(let T=0;T<e.face.length;T++){const R=e.face[T],A=p.FromArray(e.vertex[R[0]]),y=p.FromArray(e.vertex[R[2]]),E=p.FromArray(e.vertex[R[1]]),x=y.subtract(A),b=E.subtract(A),P=p.Cross(b,x).normalize();for(let v=0;v<R.length;v++){l.push(P.x,P.y,P.z);const O=e.vertex[R[v]];a.push(O[0]*i,O[1]*s,O[2]*r);const k=(O[1]*s-d)/(_-d);c.push((O[0]*i-u)/(f-u),we?1-k:k)}for(let v=0;v<R.length-2;v++)h.push(m,m+v+2,m+v+1);m+=R.length}j._ComputeSides(n,a,h,l,c);const g=new j;return g.positions=a,g.indices=h,g.normals=l,g.uvs=c,g}function np(o,e,t=null){const i=e.size,s=e.sizeX||i||1,r=e.sizeY||i||1,n=e.sizeZ||i||1;let a=e.m||1;a!==Math.floor(a)&&(a=Math.floor(a),W.Warn("m not an integer only floor(m) used"));let h=e.n||0;if(h!==Math.floor(h)&&(h=Math.floor(h),W.Warn("n not an integer only floor(n) used")),h>a){const _=h;h=a,a=_,W.Warn("n > m therefore m and n swapped")}const l=new ru;l.build(a,h);const c=un.BuildGeodesicData(l),u=c.toGoldbergPolyhedronData(),f=new fn(o,t);e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),f._originalBuilderSideOrientation=e.sideOrientation,rp(e,u).applyToMesh(f,e.updatable),f.goldbergData.nbSharedFaces=c.sharedNodes,f.goldbergData.nbUnsharedFaces=c.poleNodes,f.goldbergData.adjacentFaces=c.adjacentFaces,f.goldbergData.nbFaces=f.goldbergData.nbSharedFaces+f.goldbergData.nbUnsharedFaces,f.goldbergData.nbFacesAtPole=(f.goldbergData.nbUnsharedFaces-12)/12;for(let _=0;_<c.vertex.length;_++)f.goldbergData.faceCenters.push(p.FromArray(c.vertex[_])),f.goldbergData.faceCenters[_].x*=s,f.goldbergData.faceCenters[_].y*=r,f.goldbergData.faceCenters[_].z*=n,f.goldbergData.faceColors.push(new Ce(1,1,1,1));for(let _=0;_<u.face.length;_++){const m=u.face[_],g=p.FromArray(u.vertex[m[0]]),T=p.FromArray(u.vertex[m[2]]),R=p.FromArray(u.vertex[m[1]]),A=T.subtract(g),y=R.subtract(g),E=p.Cross(y,A).normalize(),x=p.Cross(y,E).normalize();f.goldbergData.faceXaxis.push(y.normalize()),f.goldbergData.faceYaxis.push(E),f.goldbergData.faceZaxis.push(x)}return f}class ap{constructor(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}moveTo(e,t){this._currentPath=new ar(e,t),this._tempPaths.push(this._currentPath)}lineTo(e,t){this._currentPath.addLineTo(e,t)}quadraticCurveTo(e,t,i,s){this._currentPath.addQuadraticCurveTo(e,t,i,s,this._resolution)}bezierCurveTo(e,t,i,s,r,n){this._currentPath.addBezierCurveTo(e,t,i,s,r,n,this._resolution)}extractHoles(){for(const e of this._tempPaths)e.area()>0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function op(o,e,t,i,s,r){const n=r.glyphs[o]||r.glyphs["?"];if(!n)return null;const a=new ap(s);if(n.o){const h=n.o.split(" ");for(let l=0,c=h.length;l<c;)switch(h[l++]){case"m":{const f=parseInt(h[l++])*e+t,d=parseInt(h[l++])*e+i;a.moveTo(f,d);break}case"l":{const f=parseInt(h[l++])*e+t,d=parseInt(h[l++])*e+i;a.lineTo(f,d);break}case"q":{const f=parseInt(h[l++])*e+t,d=parseInt(h[l++])*e+i,_=parseInt(h[l++])*e+t,m=parseInt(h[l++])*e+i;a.quadraticCurveTo(_,m,f,d);break}case"b":{const f=parseInt(h[l++])*e+t,d=parseInt(h[l++])*e+i,_=parseInt(h[l++])*e+t,m=parseInt(h[l++])*e+i,g=parseInt(h[l++])*e+t,T=parseInt(h[l++])*e+i;a.bezierCurveTo(_,m,g,T,f,d);break}}}return a.extractHoles(),{offsetX:n.ha*e,shapePath:a}}function hp(o,e,t,i){const s=Array.from(o),r=e/i.resolution,n=(i.boundingBox.yMax-i.boundingBox.yMin+i.underlineThickness)*r,a=[];let h=0,l=0;for(let c=0;c<s.length;c++){const u=s[c];if(u===`
|
|
1258
|
+
`)h=0,l-=n;else{const f=op(u,r,h,l,t,i);f&&(h+=f.offsetX,a.push(f.shapePath))}}return a}function lp(o,e,t,i={size:50,resolution:8,depth:1},s=null,r=earcut){const n=hp(e,i.size||50,i.resolution||8,t),a=[];let h=0;for(const c of n){if(!c.paths.length)continue;const u=c.holes.slice();for(const f of c.paths){const d=[],_=[],m=f.getPoints();for(const R of m)_.push(new p(R.x,0,R.y));const g=u.slice();for(const R of g){const A=R.getPoints();let y=!1;for(const x of A)if(f.isPointInside(x)){y=!0;break}if(!y)continue;const E=[];for(const x of A)E.push(new p(x.x,0,x.y));d.push(E),u.splice(u.indexOf(R),1)}if(!d.length&&u.length)for(const R of u){const A=R.getPoints(),y=[];for(const E of A)y.push(new p(E.x,0,E.y));d.push(y)}const T=ln(o,{shape:_,holes:d.length?d:void 0,depth:i.depth||1,faceUV:i.faceUV||i.perLetterFaceUV?.(h),faceColors:i.faceColors||i.perLetterFaceColors?.(h),sideOrientation:F._GetDefaultSideOrientation(i.sideOrientation||F.DOUBLESIDE)},s,r);a.push(T),h++}}const l=F.MergeMeshes(a,!0,!0);if(l){const c=l.getBoundingInfo().boundingBox;l.position.x+=-(c.minimumWorld.x+c.maximumWorld.x)/2,l.position.y+=-(c.minimumWorld.y+c.maximumWorld.y)/2,l.position.z+=-(c.minimumWorld.z+c.maximumWorld.z)/2+c.extendSize.z,l.name=o;const u=new xe("pivot",s);u.rotation.x=-Math.PI/2,l.parent=u,l.bakeCurrentTransformIntoVertices(),l.parent=null,u.dispose()}return l}const cp={CreateBox:uo,CreateTiledBox:Hc,CreateSphere:fo,CreateDisc:oo,CreateIcoSphere:Mo,CreateRibbon:Gi,CreateCylinder:_o,CreateTorus:go,CreateTorusKnot:po,CreateLineSystem:To,CreateLines:Eo,CreateDashedLines:xo,ExtrudeShape:bo,ExtrudeShapeCustom:Ro,CreateLathe:So,CreateTiledPlane:Wc,CreatePlane:yo,CreateGround:ho,CreateTiledGround:lo,CreateGroundFromHeightMap:co,CreatePolygon:hn,ExtrudePolygon:ln,CreateTube:Ao,CreatePolyhedron:cn,CreateGeodesic:sp,CreateGoldberg:np,CreateDecal:Po,CreateCapsule:Io,CreateText:lp},Jm=Object.freeze(Object.defineProperty({__proto__:null,MeshBuilder:cp},Symbol.toStringTag,{value:"Module"}));var kh;(function(o){o[o.NormalizedViewDepth=0]="NormalizedViewDepth",o[o.ViewDepth=1]="ViewDepth",o[o.ScreenDepth=2]="ScreenDepth"})(kh||(kh={}));class Xi extends Qe{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(he(()=>Promise.resolve().then(()=>mp),void 0,import.meta.url))):t.push(he(()=>Promise.resolve().then(()=>gp),void 0,import.meta.url))}constructor(e,t=null,i="",s){super({...s,name:e,engine:t||$.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:Xi.FragmentUrl,uniforms:Xi.Uniforms,defines:i}),this.textureWidth=0,this.textureHeight=0}bind(e=!1){super.bind(e);const t=this.drawWrapper.effect;this.textureWidth===1||this.textureHeight===1?t.setInt2("texSize",this.textureWidth,this.textureHeight):t.setFloat2("texSize",this.textureWidth,this.textureHeight)}}Xi.FragmentUrl="minmaxRedux";Xi.Uniforms=["texSize"];const up=new Float32Array(4*1*1),fp=new Uint8Array(4*1*1),ei={min:0,max:0};class dp{get depthRedux(){return this._depthRedux}set depthRedux(e){this._depthRedux!==e&&(this._depthRedux=e,this._recreatePostProcesses())}get textureWidth(){return this._textureWidth}get textureHeight(){return this._textureHeight}constructor(e,t=!0){this.onAfterReductionPerformed=new z,this._textureWidth=0,this._textureHeight=0,this._scene=e,this._depthRedux=t,this.reductionSteps=[]}setTextureDimensions(e,t,i=0){return e===this._textureWidth&&t===this._textureHeight&&i===this._depthTextureType?!1:(this._textureWidth=e,this._textureHeight=t,this._depthTextureType=i,this._recreatePostProcesses(),!0)}readMinMax(e){const t=e.type===$.TEXTURETYPE_FLOAT||e.type===$.TEXTURETYPE_HALF_FLOAT,i=t?up:fp;this._scene.getEngine()._readTexturePixels(e,1,1,-1,0,i,!1),ei.min=i[0],ei.max=i[1],t||(ei.min=ei.min/255,ei.max=ei.max/255),ei.min>=ei.max&&(ei.min=0,ei.max=1),this.onAfterReductionPerformed.notifyObservers(ei)}dispose(e=!0){e&&(this.onAfterReductionPerformed.clear(),this._textureWidth=0,this._textureHeight=0);for(let t=0;t<this.reductionSteps.length;++t)this.reductionSteps[t].dispose();this.reductionSteps.length=0}_recreatePostProcesses(){this.dispose(!1);const e=this._scene;let t=this.textureWidth,i=this.textureHeight;const s=new Xi("Initial reduction phase",e.getEngine(),"#define INITIAL"+(this._depthRedux?`
|
|
1259
|
+
#define DEPTH_REDUX`:"")+(this._depthTextureType===1?`
|
|
1260
|
+
#define VIEW_DEPTH`:""));s.textureWidth=t,s.textureHeight=i,this.reductionSteps.push(s);let r=1;for(;t>1||i>1;){t=Math.max(Math.round(t/2),1),i=Math.max(Math.round(i/2),1);const n=new Xi("Reduction phase "+r,e.getEngine(),"#define "+(t==1&&i==1?"LAST":t==1||i==1?"ONEBEFORELAST":"MAIN"));n.textureWidth=t,n.textureHeight=i,this.reductionSteps.push(n),r++}}}const Ca="minmaxReduxPixelShader",nu=`varying vec2 vUV;uniform sampler2D textureSampler;
|
|
1261
|
+
#if defined(INITIAL)
|
|
1262
|
+
uniform vec2 texSize;void main(void)
|
|
1263
|
+
{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(textureSampler,coord,0).r;float f2=texelFetch(textureSampler,coord+ivec2(1,0),0).r;float f3=texelFetch(textureSampler,coord+ivec2(1,1),0).r;float f4=texelFetch(textureSampler,coord+ivec2(0,1),0).r;
|
|
1264
|
+
#ifdef DEPTH_REDUX
|
|
1265
|
+
#ifdef VIEW_DEPTH
|
|
1266
|
+
float minz=3.4e38;if (f1 != 0.0) { minz=f1; }
|
|
1267
|
+
if (f2 != 0.0) { minz=min(minz,f2); }
|
|
1268
|
+
if (f3 != 0.0) { minz=min(minz,f3); }
|
|
1269
|
+
if (f4 != 0.0) { minz=min(minz,f4); }
|
|
1270
|
+
float maxz=max(max(max(f1,f2),f3),f4);
|
|
1271
|
+
#else
|
|
1272
|
+
float minz=min(min(min(f1,f2),f3),f4);float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);
|
|
1273
|
+
#endif
|
|
1274
|
+
#else
|
|
1275
|
+
float minz=min(min(min(f1,f2),f3),f4);float maxz=max(max(max(f1,f2),f3),f4);
|
|
1276
|
+
#endif
|
|
1277
|
+
glFragColor=vec4(minz,maxz,0.,0.);}
|
|
1278
|
+
#elif defined(MAIN)
|
|
1279
|
+
uniform vec2 texSize;void main(void)
|
|
1280
|
+
{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}
|
|
1281
|
+
#elif defined(ONEBEFORELAST)
|
|
1282
|
+
uniform ivec2 texSize;void main(void)
|
|
1283
|
+
{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}
|
|
1284
|
+
#elif defined(LAST)
|
|
1285
|
+
void main(void)
|
|
1286
|
+
{glFragColor=vec4(0.);if (true) {
|
|
1287
|
+
discard;}}
|
|
1288
|
+
#endif
|
|
1289
|
+
`;Z.ShadersStore[Ca]||(Z.ShadersStore[Ca]=nu);const _p={name:Ca,shader:nu},gp=Object.freeze(Object.defineProperty({__proto__:null,minmaxReduxPixelShader:_p},Symbol.toStringTag,{value:"Module"})),Da="minmaxReduxPixelShader",au=`varying vUV: vec2f;var textureSampler: texture_2d<f32>;
|
|
1290
|
+
#if defined(INITIAL)
|
|
1291
|
+
uniform texSize: vec2f;@fragment
|
|
1292
|
+
fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*(uniforms.texSize-1.0));let f1=textureLoad(textureSampler,coord,0).r;let f2=textureLoad(textureSampler,coord+vec2i(1,0),0).r;let f3=textureLoad(textureSampler,coord+vec2i(1,1),0).r;let f4=textureLoad(textureSampler,coord+vec2i(0,1),0).r;
|
|
1293
|
+
#ifdef DEPTH_REDUX
|
|
1294
|
+
#ifdef VIEW_DEPTH
|
|
1295
|
+
var minz=3.4e38;if (f1 != 0.0) { minz=f1; }
|
|
1296
|
+
if (f2 != 0.0) { minz=min(minz,f2); }
|
|
1297
|
+
if (f3 != 0.0) { minz=min(minz,f3); }
|
|
1298
|
+
if (f4 != 0.0) { minz=min(minz,f4); }
|
|
1299
|
+
let maxz=max(max(max(f1,f2),f3),f4);
|
|
1300
|
+
#else
|
|
1301
|
+
let minz=min(min(min(f1,f2),f3),f4);let maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);
|
|
1302
|
+
#endif
|
|
1303
|
+
#else
|
|
1304
|
+
let minz=min(min(min(f1,f2),f3),f4);let maxz=max(max(max(f1,f2),f3),f4);
|
|
1305
|
+
#endif
|
|
1306
|
+
fragmentOutputs.color=vec4f(minz,maxz,0.,0.);}
|
|
1307
|
+
#elif defined(MAIN)
|
|
1308
|
+
uniform texSize: vec2f;@fragment
|
|
1309
|
+
fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*(uniforms.texSize-1.0));let f1=textureLoad(textureSampler,coord,0).rg;let f2=textureLoad(textureSampler,coord+vec2i(1,0),0).rg;let f3=textureLoad(textureSampler,coord+vec2i(1,1),0).rg;let f4=textureLoad(textureSampler,coord+vec2i(0,1),0).rg;let minz=min(min(min(f1.x,f2.x),f3.x),f4.x);let maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);fragmentOutputs.color=vec4(minz,maxz,0.,0.);}
|
|
1310
|
+
#elif defined(ONEBEFORELAST)
|
|
1311
|
+
uniform texSize: vec2i;@fragment
|
|
1312
|
+
fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*vec2f(uniforms.texSize-1));let f1=textureLoad(textureSampler,coord % uniforms.texSize,0).rg;let f2=textureLoad(textureSampler,(coord+vec2i(1,0)) % uniforms.texSize,0).rg;let f3=textureLoad(textureSampler,(coord+vec2i(1,1)) % uniforms.texSize,0).rg;let f4=textureLoad(textureSampler,(coord+vec2i(0,1)) % uniforms.texSize,0).rg;let minz=min(min(min(f1.x,f2.x),f3.x),f4.x);let maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);fragmentOutputs.color=vec4(minz,maxz,0.,0.);}
|
|
1313
|
+
#elif defined(LAST)
|
|
1314
|
+
@fragment
|
|
1315
|
+
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(0.);if (true) {
|
|
1316
|
+
discard;}}
|
|
1317
|
+
#endif
|
|
1318
|
+
`;Z.ShadersStoreWGSL[Da]||(Z.ShadersStoreWGSL[Da]=au);const pp={name:Da,shader:au},mp=Object.freeze(Object.defineProperty({__proto__:null,minmaxReduxPixelShaderWGSL:pp},Symbol.toStringTag,{value:"Module"}));class Tp{get onAfterReductionPerformed(){return this._thinMinMaxReducer.onAfterReductionPerformed}constructor(e){this._onAfterUnbindObserver=null,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new zr(e.getScene()),this._thinMinMaxReducer=new dp(e.getScene()),this._reductionSteps=[],this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,s=!0){if(e!==this._sourceTexture&&(this._thinMinMaxReducer.depthRedux=t,this.deactivate(),this._sourceTexture=e,this._forceFullscreenViewport=s,this._thinMinMaxReducer.setTextureDimensions(e.getRenderWidth(),e.getRenderHeight()))){this._disposePostProcesses();const r=this._thinMinMaxReducer.reductionSteps;for(let n=0;n<r.length;++n){const a=r[n],h=new Ne(a.name,Xi.FragmentUrl,{effectWrapper:a,samplingMode:1,engine:this._camera.getScene().getEngine(),textureType:i,textureFormat:7,size:{width:a.textureWidth,height:a.textureHeight}});this._reductionSteps.push(h),h.autoClear=!1,h.forceFullscreenViewport=s,n===0&&(h.externalTextureSamplerBinding=!0,h.onApplyObservable.add(l=>{l.setTexture("textureSampler",this._sourceTexture)})),n===r.length-1&&this._reductionSteps[n-1].onAfterRenderObservable.add(()=>{this._thinMinMaxReducer.readMinMax(h.inputTexture.texture)})}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){this._onAfterUnbindObserver||!this._sourceTexture||(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add(()=>{const e=this._camera.getScene().getEngine();e._debugPushGroup?.("min max reduction"),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport,0,0,!0,this._reductionSteps.length-1),e.unBindFramebuffer(this._reductionSteps[this._reductionSteps.length-1].inputTexture,!1),e._debugPopGroup?.()}),this._activated=!0)}deactivate(){!this._onAfterUnbindObserver||!this._sourceTexture||(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){e&&(this.onAfterReductionPerformed.clear(),this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=void 0,this._disposePostProcesses(),this._postProcessManager.dispose(),this._postProcessManager=void 0,this._thinMinMaxReducer.dispose(),this._thinMinMaxReducer=void 0,this._sourceTexture=null)}_disposePostProcesses(){for(let e=0;e<this._reductionSteps.length;++e)this._reductionSteps[e].dispose();this._reductionSteps.length=0}}class Ep extends Tp{get depthRenderer(){return this._depthRenderer}constructor(e){super(e)}setDepthRenderer(e=null,t=2,i=!0){const s=this._camera.getScene();this._depthRenderer&&(delete s._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null),e===null&&(s._depthRenderer||(s._depthRenderer={}),this._depthRendererId="minmax_"+this._camera.id,e=this._depthRenderer=new Wi(s,t,this._camera,!1,1,!1,`DepthRenderer ${this._depthRendererId}`),e.enabled=!1,s._depthRenderer[this._depthRendererId]=e),super.setSourceTexture(e.getDepthMap(),!0,t,i)}setSourceTexture(e,t,i=2,s=!0){super.setSourceTexture(e,t,i,s)}activate(){this._depthRenderer&&(this._depthRenderer.enabled=!0),super.activate()}deactivate(){super.deactivate(),this._depthRenderer&&(this._depthRenderer.enabled=!1)}dispose(e=!0){super.dispose(e),this._depthRenderer&&e&&(this._depthRenderer.dispose(),this._depthRenderer=null)}}const Vh=p.Up(),xp=p.Zero(),ht=new p,hs=new p,Mr=new D;class ft extends de{_validateFilter(e){return e===de.FILTER_NONE||e===de.FILTER_PCF||e===de.FILTER_PCSS?e:(W.Error('Unsupported filter "'+e+'"!'),de.FILTER_NONE)}get numCascades(){return this._numCascades}set numCascades(e){e=Math.min(Math.max(e,ft.MIN_CASCADES_COUNT),ft.MAX_CASCADES_COUNT),e!==this._numCascades&&(this._numCascades=e,this.recreateShadowMap(),this._recreateSceneUBOs())}get freezeShadowCastersBoundingInfo(){return this._freezeShadowCastersBoundingInfo}set freezeShadowCastersBoundingInfo(e){this._freezeShadowCastersBoundingInfoObservable&&e&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),!this._freezeShadowCastersBoundingInfoObservable&&!e&&(this._freezeShadowCastersBoundingInfoObservable=this._scene.onBeforeRenderObservable.add(()=>this._computeShadowCastersBoundingInfo())),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){const e=this._shadowMap.renderList;for(let t=0;t<e.length;t++){const i=e[t];if(!i)continue;const s=i.getBoundingInfo(),r=s.boundingBox;this._scbiMin.minimizeInPlace(r.minimumWorld),this._scbiMax.maximizeInPlace(r.maximumWorld)}}this._shadowCastersBoundingInfo.reConstruct(this._scbiMin,this._scbiMax)}get shadowCastersBoundingInfo(){return this._shadowCastersBoundingInfo}set shadowCastersBoundingInfo(e){this._shadowCastersBoundingInfo=e}setMinMaxDistance(e,t){this._minDistance===e&&this._maxDistance===t||(e>t&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return ft.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e<this._numCascades?this._cascadeMinExtents[e]:null}getCascadeMaxExtents(e){return e>=0&&e<this._numCascades?this._cascadeMaxExtents[e]:null}get shadowMaxZ(){return this._getCamera()?this._shadowMaxZ:0}set shadowMaxZ(e){const t=this._getCamera();if(!t){this._shadowMaxZ=e;return}this._shadowMaxZ===e||e<t.minZ||e>t.maxZ&&t.maxZ!==0||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e<this._numCascades?this._viewMatrices[e]:null}getCascadeProjectionMatrix(e){return e>=0&&e<this._numCascades?this._projectionMatrices[e]:null}getCascadeTransformMatrix(e){return e>=0&&e<this._numCascades?this._transformMatrices[e]:null}setDepthRenderer(e){this._depthRenderer=e,this._depthReducer&&this._depthReducer.setDepthRenderer(this._depthRenderer)}get autoCalcDepthBounds(){return this._autoCalcDepthBounds}set autoCalcDepthBounds(e){const t=this._getCamera();if(t){if(this._autoCalcDepthBounds=e,!e){this._depthReducer&&this._depthReducer.deactivate(),this.setMinMaxDistance(0,1);return}this._depthReducer||(this._depthReducer=new Ep(t),this._depthReducer.onAfterReductionPerformed.add(i=>{let s=i.min,r=i.max;s>=r&&(s=0,r=1),(s!=this._minDistance||r!=this._maxDistance)&&this.setMinMaxDistance(s,r)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate??-1}set autoCalcDepthBoundsRefreshRate(e){this._depthReducer?.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,s=i-t,r=this._minDistance,n=this._shadowMaxZ<i&&this._shadowMaxZ>=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,a=t+r*s,h=t+n*s,l=h-a,c=h/a;for(let u=0;u<this._cascades.length;++u){const f=(u+1)/this._numCascades,d=a*c**f,_=a+l*f,m=this._lambda*(d-_)+_;this._cascades[u].prevBreakDistance=u===0?r:this._cascades[u-1].breakDistance,this._cascades[u].breakDistance=(m-t)/s,this._viewSpaceFrustumsZ[u]=m,this._frustumLengths[u]=(this._cascades[u].breakDistance-this._cascades[u].prevBreakDistance)*s}this._breaksAreDirty=!1}_computeMatrices(){const e=this._scene;if(!this._getCamera())return;p.NormalizeToRef(this._light.getShadowDirection(0),this._lightDirection),Math.abs(p.Dot(this._lightDirection,p.Up()))===1&&(this._lightDirection.z=1e-13),this._cachedDirection.copyFrom(this._lightDirection);const i=e.getEngine().useReverseDepthBuffer;for(let s=0;s<this._numCascades;++s){this._computeFrustumInWorldSpace(s),this._computeCascadeFrustum(s),this._cascadeMaxExtents[s].subtractToRef(this._cascadeMinExtents[s],ht),this._frustumCenter[s].addToRef(this._lightDirection.scale(this._cascadeMinExtents[s].z),this._shadowCameraPos[s]),D.LookAtLHToRef(this._shadowCameraPos[s],this._frustumCenter[s],Vh,this._viewMatrices[s]);let r=0,n=ht.z;const a=this._shadowCastersBoundingInfo;a.update(this._viewMatrices[s]);const h=a.boundingBox.minimumWorld.z,l=a.boundingBox.maximumWorld.z;h>n||(!this._depthClamp||this.filter===de.FILTER_PCSS?(r=Math.min(r,h),this.filter!==de.FILTER_PCSS&&(n=Math.min(n,l))):(n=Math.min(n,l),r=Math.max(r,h),n=Math.max(r+1,n))),D.OrthoOffCenterLHToRef(this._cascadeMinExtents[s].x,this._cascadeMaxExtents[s].x,this._cascadeMinExtents[s].y,this._cascadeMaxExtents[s].y,i?n:r,i?r:n,this._projectionMatrices[s],e.getEngine().isNDCHalfZRange),this._cascadeMinExtents[s].z=r,this._cascadeMaxExtents[s].z=n,this._viewMatrices[s].multiplyToRef(this._projectionMatrices[s],this._transformMatrices[s]),p.TransformCoordinatesToRef(xp,this._transformMatrices[s],ht),ht.scaleInPlace(this._mapSize/2),hs.copyFromFloats(Math.round(ht.x),Math.round(ht.y),Math.round(ht.z)),hs.subtractInPlace(ht).scaleInPlace(2/this._mapSize),D.TranslationToRef(hs.x,hs.y,0,Mr),this._projectionMatrices[s].multiplyToRef(Mr,this._projectionMatrices[s]),this._viewMatrices[s].multiplyToRef(this._projectionMatrices[s],this._transformMatrices[s]),this._transformMatrices[s].copyToArray(this._transformMatricesAsArray,s*16)}}_computeFrustumInWorldSpace(e){const t=this._getCamera();if(!t)return;const i=this._cascades[e].prevBreakDistance,s=this._cascades[e].breakDistance,r=this._scene.getEngine().isNDCHalfZRange;t.getViewMatrix();const n=t.maxZ===0,a=t.maxZ;n&&(t.maxZ=this._shadowMaxZ,t.getProjectionMatrix(!0));const h=D.Invert(t.getTransformationMatrix());n&&(t.maxZ=a,t.getProjectionMatrix(!0));const l=this._scene.getEngine().useReverseDepthBuffer?4:0;for(let c=0;c<ft._FrustumCornersNdcSpace.length;++c)ht.copyFrom(ft._FrustumCornersNdcSpace[(c+l)%ft._FrustumCornersNdcSpace.length]),r&&ht.z===-1&&(ht.z=0),p.TransformCoordinatesToRef(ht,h,this._frustumCornersWorldSpace[e][c]);for(let c=0;c<ft._FrustumCornersNdcSpace.length/2;++c)ht.copyFrom(this._frustumCornersWorldSpace[e][c+4]).subtractInPlace(this._frustumCornersWorldSpace[e][c]),hs.copyFrom(ht).scaleInPlace(i),ht.scaleInPlace(s),ht.addInPlace(this._frustumCornersWorldSpace[e][c]),this._frustumCornersWorldSpace[e][c+4].copyFrom(ht),this._frustumCornersWorldSpace[e][c].addInPlace(hs)}_computeCascadeFrustum(e){if(this._cascadeMinExtents[e].copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cascadeMaxExtents[e].copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._frustumCenter[e].copyFromFloats(0,0,0),!!this._getCamera()){for(let i=0;i<this._frustumCornersWorldSpace[e].length;++i)this._frustumCenter[e].addInPlace(this._frustumCornersWorldSpace[e][i]);if(this._frustumCenter[e].scaleInPlace(1/this._frustumCornersWorldSpace[e].length),this.stabilizeCascades){let i=0;for(let s=0;s<this._frustumCornersWorldSpace[e].length;++s){const r=this._frustumCornersWorldSpace[e][s].subtractToRef(this._frustumCenter[e],ht).length();i=Math.max(i,r)}i=Math.ceil(i*16)/16,this._cascadeMaxExtents[e].copyFromFloats(i,i,i),this._cascadeMinExtents[e].copyFromFloats(-i,-i,-i)}else{const i=this._frustumCenter[e];this._frustumCenter[e].addToRef(this._lightDirection,ht),D.LookAtLHToRef(i,ht,Vh,Mr);for(let s=0;s<this._frustumCornersWorldSpace[e].length;++s)p.TransformCoordinatesToRef(this._frustumCornersWorldSpace[e][s],Mr,ht),this._cascadeMinExtents[e].minimizeInPlace(ht),this._cascadeMaxExtents[e].maximizeInPlace(ht)}}}_recreateSceneUBOs(){if(this._disposeSceneUBOs(),this._sceneUBOs)for(let e=0;e<this._numCascades;++e)this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for CSM Shadow Generator (light "${this._light.name}" cascade #${e})`,{forceMono:!0}))}static get IsSupported(){const e=ye.LastCreatedEngine;return e?e._features.supportCSM:!1}constructor(e,t,i,s,r=!0){if(!ft.IsSupported){W.Error("CascadedShadowMap is not supported by the current engine.");return}super(e,t,i,s,r),this.usePercentageCloserFiltering=!0}_initializeGenerator(){this.penumbraDarkness=this.penumbraDarkness??1,this._numCascades=this._numCascades??ft.DEFAULT_CASCADES_COUNT,this.stabilizeCascades=this.stabilizeCascades??!1,this._freezeShadowCastersBoundingInfoObservable=this._freezeShadowCastersBoundingInfoObservable??null,this.freezeShadowCastersBoundingInfo=this.freezeShadowCastersBoundingInfo??!1,this._scbiMin=this._scbiMin??new p(0,0,0),this._scbiMax=this._scbiMax??new p(0,0,0),this._shadowCastersBoundingInfo=this._shadowCastersBoundingInfo??new wt(new p(0,0,0),new p(0,0,0)),this._breaksAreDirty=this._breaksAreDirty??!0,this._minDistance=this._minDistance??0,this._maxDistance=this._maxDistance??1,this._currentLayer=this._currentLayer??0,this._shadowMaxZ=this._shadowMaxZ??this._getCamera()?.maxZ??1e4,this._debug=this._debug??!1,this._depthClamp=this._depthClamp??!0,this._cascadeBlendPercentage=this._cascadeBlendPercentage??.1,this._lambda=this._lambda??.5,this._autoCalcDepthBounds=this._autoCalcDepthBounds??!1,this._recreateSceneUBOs(),super._initializeGenerator()}_createTargetRenderTexture(){const e=this._scene.getEngine();this._shadowMap?.dispose();const t={width:this._mapSize,height:this._mapSize,layers:this.numCascades};this._shadowMap=new yt(this._light.name+"_CSMShadowMap",t,this._scene,!1,!0,this._textureType,!1,void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForCSMShadowGenerator-${this._light.name}`),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(super._initializeShadowMap(),this._shadowMap===null)return;this._transformMatricesAsArray=new Float32Array(this._numCascades*16),this._tempTransformMatricesAsArray=new Float32Array(this._numCascades*16),this._viewSpaceFrustumsZ=new Array(this._numCascades),this._frustumLengths=new Array(this._numCascades),this._lightSizeUVCorrection=new Array(this._numCascades*2),this._depthCorrection=new Array(this._numCascades),this._cascades=[],this._viewMatrices=[],this._projectionMatrices=[],this._transformMatrices=[],this._cascadeMinExtents=[],this._cascadeMaxExtents=[],this._frustumCenter=[],this._shadowCameraPos=[],this._frustumCornersWorldSpace=[];for(let t=0;t<this._numCascades;++t){this._cascades[t]={prevBreakDistance:0,breakDistance:0},this._viewMatrices[t]=D.Zero(),this._projectionMatrices[t]=D.Zero(),this._transformMatrices[t]=D.Zero(),this._cascadeMinExtents[t]=new p,this._cascadeMaxExtents[t]=new p,this._frustumCenter[t]=new p,this._shadowCameraPos[t]=new p,this._frustumCornersWorldSpace[t]=new Array(ft._FrustumCornersNdcSpace.length);for(let i=0;i<ft._FrustumCornersNdcSpace.length;++i)this._frustumCornersWorldSpace[t][i]=new p}const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.clear(),this._shadowMap.onBeforeRenderObservable.clear(),this._shadowMap.onBeforeRenderObservable.add(t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===de.FILTER_PCF&&e.setColorWrite(!1),zi.eyeAtCamera=!1,this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onBeforeBindObservable.add(()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._enableGPUDebugMarkers&&e._debugPushGroup?.(`Cascaded shadow map generation for pass id ${e.currentRenderPassId}`),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()}),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==de.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,s=this._light;if(!i.shadowsEnabled||!s.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const r=this._getCamera();r&&this._shadowMaxZ<=(r.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),this.cascadeBlendPercentage===0&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light,s=this._scene;if(!s.shadowsEnabled||!i.shadowEnabled)return;const r=this._getCamera();if(!r)return;const n=this.getShadowMap();if(!n)return;const a=n.getSize().width,h=this._transformMatricesAsArray,l=s.floatingOriginMode?Nf(this._scene.floatingOriginOffset,this._viewMatrices,this._projectionMatrices,this._numCascades,this._tempTransformMatricesAsArray):h;if(t.setMatrices("lightMatrix"+e,l),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,this.cascadeBlendPercentage===0?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===de.FILTER_PCF)t.setDepthStencilTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a,1/a,this.frustumEdgeFalloff,e);else if(this._filter===de.FILTER_PCSS){for(let c=0;c<this._numCascades;++c)this._lightSizeUVCorrection[c*2+0]=c===0?1:(this._cascadeMaxExtents[0].x-this._cascadeMinExtents[0].x)/(this._cascadeMaxExtents[c].x-this._cascadeMinExtents[c].x),this._lightSizeUVCorrection[c*2+1]=c===0?1:(this._cascadeMaxExtents[0].y-this._cascadeMinExtents[0].y)/(this._cascadeMaxExtents[c].y-this._cascadeMinExtents[c].y),this._depthCorrection[c]=c===0?1:(this._cascadeMaxExtents[c].z-this._cascadeMinExtents[c].z)/(this._cascadeMaxExtents[0].z-this._cascadeMinExtents[0].z);t.setDepthStencilTexture("shadowTexture"+e,n),t.setTexture("depthTexture"+e,n),t.setArray2("lightSizeUVCorrection"+e,this._lightSizeUVCorrection),t.setArray("depthCorrection"+e,this._depthCorrection),t.setFloat("penumbraDarkness"+e,this.penumbraDarkness),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/a,this._contactHardeningLightSizeUVRatio*a,this.frustumEdgeFalloff,e)}else t.setTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a,1/a,this.frustumEdgeFalloff,e);i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(r),this.getLight().getDepthMinZ(r)+this.getLight().getDepthMaxZ(r),e)}getTransformMatrix(){return this.getCascadeTransformMatrix(0)}dispose(){super.dispose(),this._freezeShadowCastersBoundingInfoObservable&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._depthReducer&&(this._depthReducer.dispose(),this._depthReducer=null)}serialize(){const e=super.serialize(),t=this.getShadowMap();if(!t)return e;if(e.numCascades=this._numCascades,e.debug=this._debug,e.stabilizeCascades=this.stabilizeCascades,e.lambda=this._lambda,e.cascadeBlendPercentage=this.cascadeBlendPercentage,e.depthClamp=this._depthClamp,e.autoCalcDepthBounds=this.autoCalcDepthBounds,e.shadowMaxZ=this._shadowMaxZ,e.penumbraDarkness=this.penumbraDarkness,e.freezeShadowCastersBoundingInfo=this._freezeShadowCastersBoundingInfo,e.minDistance=this.minDistance,e.maxDistance=this.maxDistance,e.renderList=[],t.renderList)for(let i=0;i<t.renderList.length;i++){const s=t.renderList[i];e.renderList.push(s.id)}return e}static Parse(e,t){const i=de.Parse(e,t,(s,r,n)=>new ft(s,r,void 0,n));return e.numCascades!==void 0&&(i.numCascades=e.numCascades),e.debug!==void 0&&(i.debug=e.debug),e.stabilizeCascades!==void 0&&(i.stabilizeCascades=e.stabilizeCascades),e.lambda!==void 0&&(i.lambda=e.lambda),e.cascadeBlendPercentage!==void 0&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),e.depthClamp!==void 0&&(i.depthClamp=e.depthClamp),e.autoCalcDepthBounds!==void 0&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),e.shadowMaxZ!==void 0&&(i.shadowMaxZ=e.shadowMaxZ),e.penumbraDarkness!==void 0&&(i.penumbraDarkness=e.penumbraDarkness),e.freezeShadowCastersBoundingInfo!==void 0&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),e.minDistance!==void 0&&e.maxDistance!==void 0&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}ft._FrustumCornersNdcSpace=[new p(-1,1,-1),new p(1,1,-1),new p(1,-1,-1),new p(-1,-1,-1),new p(-1,1,1),new p(1,1,1),new p(1,-1,1),new p(-1,-1,1)];ft.CLASSNAME="CascadedShadowGenerator";ft.DEFAULT_CASCADES_COUNT=4;ft.MIN_CASCADES_COUNT=2;ft.MAX_CASCADES_COUNT=4;ft._SceneComponentInitialization=o=>{throw pe("ShadowGeneratorSceneComponent")};Tc(ce.NAME_SHADOWGENERATOR,(o,e)=>{if(o.shadowGenerators!==void 0&&o.shadowGenerators!==null)for(let t=0,i=o.shadowGenerators.length;t<i;t++){const s=o.shadowGenerators[t];s.className===ft.CLASSNAME?ft.Parse(s,e):de.Parse(s,e)}});class bp{constructor(e){this.name=ce.NAME_SHADOWGENERATOR,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ce.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR,this,this._gatherRenderTargets)}rebuild(){}serialize(e){e.shadowGenerators=[];const t=this.scene.lights;for(const i of t){if(i.doNotSerialize)continue;const s=i.getShadowGenerators();if(s){const r=s.values();for(let n=r.next();n.done!==!0;n=r.next()){const a=n.value;a.doNotSerialize||e.shadowGenerators.push(a.serialize())}}}}addFromContainer(e){}removeFromContainer(e,t){}dispose(){}_gatherRenderTargets(e){const t=this.scene;if(this.scene.shadowsEnabled)for(let i=0;i<t.lights.length;i++){const s=t.lights[i],r=s.getShadowGenerators();if(s.isEnabled()&&s.shadowEnabled&&r){const n=r.values();for(let a=n.next();a.done!==!0;a=n.next()){const l=a.value.getShadowMap();t.textures.indexOf(l)!==-1&&e.push(l)}}}}}de._SceneComponentInitialization=o=>{let e=o._getComponent(ce.NAME_SHADOWGENERATOR);e||(e=new bp(o),o._addComponent(e))};const Rp=new RegExp("^([gimus]+)!");class Fi{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let s=0;s<this._plugins.length;++s)if(this._plugins[s].name===e.name)return!1;if(this._material._uniformBufferLayoutBuilt&&(this._material.resetDrawCache(),this._material._createUniformBuffer()),!e.isCompatible(this._material.shaderLanguage))throw`The plugin "${e.name}" can't be added to the material "${this._material.name}" because the plugin is not compatible with the shader language of the material.`;const t=e.getClassName();Fi._MaterialPluginClassToMainDefine[t]||(Fi._MaterialPluginClassToMainDefine[t]="MATERIALPLUGIN_"+ ++Fi._MaterialPluginCounter),this._material._callbackPluginEventGeneric=(s,r)=>this._handlePluginEvent(s,r),this._plugins.push(e),this._plugins.sort((s,r)=>s.priority-r.priority),this._codeInjectionPoints={};const i={};i[Fi._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const s of this._plugins)s.collectDefines(i),this._collectPointNames("vertex",s.getCustomCode("vertex",this._material.shaderLanguage)),this._collectPointNames("fragment",s.getCustomCode("fragment",this._material.shaderLanguage));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){this._activePlugins.indexOf(e)===-1&&(this._activePlugins.push(e),this._activePlugins.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t<this._plugins.length;++t)if(this._plugins[t].name===e)return this._plugins[t];return null}_handlePluginEventIsReadyForSubMesh(e){let t=!0;for(const i of this._activePlugins)t=t&&i.isReadyForSubMesh(e.defines,this._scene,this._engine,e.subMesh);e.isReadyForSubMesh=t}_handlePluginEventPrepareDefinesBeforeAttributes(e){for(const t of this._activePlugins)t.prepareDefinesBeforeAttributes(e.defines,this._scene,e.mesh)}_handlePluginEventPrepareDefines(e){for(const t of this._activePlugins)t.prepareDefines(e.defines,this._scene,e.mesh)}_handlePluginEventHardBindForSubMesh(e){for(const t of this._activePluginsForExtraEvents)t.hardBindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventBindForSubMesh(e){for(const t of this._activePlugins)t.bindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventHasRenderTargetTextures(e){let t=!1;for(const i of this._activePluginsForExtraEvents)if(t=i.hasRenderTargetTextures(),t)break;e.hasRenderTargetTextures=t}_handlePluginEventFillRenderTargetTextures(e){for(const t of this._activePluginsForExtraEvents)t.fillRenderTargetTextures(e.renderTargets)}_handlePluginEvent(e,t){switch(e){case 512:{const i=t;for(const s of this._activePlugins)s.getActiveTextures(i.activeTextures);break}case 256:{const i=t;for(const s of this._activePlugins)s.getAnimatables(i.animatables);break}case 1024:{const i=t;let s=!1;for(const r of this._activePlugins)if(s=r.hasTexture(i.texture),s)break;i.hasTexture=s;break}case 2:{const i=t;for(const s of this._plugins)s.dispose(i.forceDisposeTextures);break}case 4:{const i=t;i.defineNames=this._defineNamesFromPlugins;break}case 128:{const i=t;for(const s of this._activePlugins)i.fallbackRank=s.addFallbacks(i.defines,i.fallbacks,i.fallbackRank),s.getAttributes(i.attributes,this._scene,i.mesh);this._uniformList.length>0&&i.uniforms.push(...this._uniformList),this._samplerList.length>0&&i.samplers.push(...this._samplerList),this._uboList.length>0&&i.uniformBuffersNames.push(...this._uboList),i.customCode=this._injectCustomCode(i,i.customCode);break}case 8:{const i=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];const s=this._material.shaderLanguage===1;for(const r of this._plugins){const n=r.getUniforms(this._material.shaderLanguage);if(n){if(n.ubo)for(const a of n.ubo){if(a.size&&a.type){const h=a.arraySize??0;if(i.ubo.addUniform(a.name,a.size,h),s){let l;switch(a.type){case"mat4":l="mat4x4f";break;case"float":l="f32";break;default:l=`${a.type}f`;break}h>0?this._uboDeclaration+=`uniform ${a.name}: array<${l}, ${h}>;
|
|
1319
|
+
`:this._uboDeclaration+=`uniform ${a.name}: ${l};
|
|
1320
|
+
`}else this._uboDeclaration+=`${a.type} ${a.name}${h>0?`[${h}]`:""};
|
|
1321
|
+
`}this._uniformList.push(a.name)}n.vertex&&(this._vertexDeclaration+=n.vertex+`
|
|
1322
|
+
`),n.fragment&&(this._fragmentDeclaration+=n.fragment+`
|
|
1323
|
+
`),n.externalUniforms&&this._uniformList.push(...n.externalUniforms)}r.getSamplers(this._samplerList),r.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,s)=>{t&&(s=t(i,s)),this._uboDeclaration&&(s=s.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(s=s.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(s=s.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const r=this._codeInjectionPoints?.[i];if(!r)return s;let n=null;for(let a in r){let h="";for(const l of this._activePlugins){const c=this._material.shaderLanguage;let u=l.getCustomCode(i,c)?.[a];u&&(l.resolveIncludes&&(n===null&&(n={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Z.GetShadersRepository(c),includesShadersStore:Z.GetIncludesShadersStore(c),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}),n.isFragment=i==="fragment",Ws(u,n,f=>u=f)),h+=u+`
|
|
1324
|
+
`)}if(h.length>0)if(a.charAt(0)==="!"){a=a.substring(1);let l="g";if(a.charAt(0)==="!")l="",a=a.substring(1);else{const d=Rp.exec(a);d&&d.length>=2&&(l=d[1],a=a.substring(l.length+1))}l.indexOf("g")<0&&(l+="g");const c=s,u=new RegExp(a,l);let f=u.exec(c);for(;f!==null;){let d=h;for(let _=0;_<f.length;++_)d=d.replace("$"+_,f[_]);s=s.replace(f[0],d),f=u.exec(c)}}else{const l="#define "+a;s=s.replace(l,`
|
|
1325
|
+
`+h+`
|
|
1326
|
+
`+l)}}return s}}}Fi._MaterialPluginClassToMainDefine={};Fi._MaterialPluginCounter=0;ye.OnEnginesDisposedObservable.add(()=>{ou()});const wi=[];let Oa=!1,Fa=null;function eT(o,e){Oa||(Fa=V.OnEventObservable.add(i=>{for(const[,s]of wi)s(i)},1),Oa=!0);const t=wi.filter(([i,s])=>i===o);t.length>0?t[0][1]=e:wi.push([o,e])}function tT(o){for(let e=0;e<wi.length;++e)if(wi[e][0]===o)return wi.splice(e,1),wi.length===0&&ou(),!0;return!1}function ou(){wi.length=0,Oa=!1,V.OnEventObservable.remove(Fa),Fa=null}class ws{isCompatible(e){switch(e){case 0:return!0;default:return!1}}_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,s,r=!0,n=!1,a=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this.doNotSerialize=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=a,e.pluginManager||(e.pluginManager=new Fi(e),e.onDisposeObservable.add(()=>{e.pluginManager=void 0})),this._pluginDefineNames=s,this._pluginManager=e.pluginManager,r&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[127]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,s){return!0}hardBindForSubMesh(e,t,i,s){}bindForSubMesh(e,t,i,s){}dispose(e){}getCustomCode(e,t=0){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if(t[0]==="_")continue;const i=typeof this._pluginDefineNames[t];e[t]={type:i==="number"?"number":i==="string"?"string":i==="boolean"?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(e=0){return{}}copyTo(e){me.Clone(()=>e,this)}serialize(){return me.Serialize(this)}parse(e,t,i){me.Parse(()=>this,e,t,i)}}M([C()],ws.prototype,"name",void 0);M([C()],ws.prototype,"priority",void 0);M([C()],ws.prototype,"resolveIncludes",void 0);M([C()],ws.prototype,"registerForExtraEvents",void 0);Ye("BABYLON.MaterialPluginBase",ws);je.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new sr(this)),this._outlineRenderer};Object.defineProperty(F.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(o){o&&this.getScene().getOutlineRenderer(),this._renderOutline=o},enumerable:!0,configurable:!0});Object.defineProperty(F.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(o){o&&this.getScene().getOutlineRenderer(),this._renderOverlay=o},enumerable:!0,configurable:!0});class sr{get shaderLanguage(){return this._shaderLanguage}constructor(e){this.name=ce.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.enabled=!0,this._shaderLanguage=0,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let i=0;i<4;++i)this._passIdForDrawWrapper[i]=this._engine.createRenderPassId(`Outline Renderer (${i})`);this._engine.isWebGPU&&(this._shaderLanguage=1)}register(){this.scene._beforeRenderingMeshStage.registerStep(ce.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(ce.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e<this._passIdForDrawWrapper.length;++e)this._engine.releaseRenderPassId(this._passIdForDrawWrapper[e])}render(e,t,i=!1,s){s=s??this._passIdForDrawWrapper[0];const r=this.scene,n=r.getEngine(),a=n.getCaps().instancedArrays&&(t.visibleInstances[e._id]!==null&&t.visibleInstances[e._id]!==void 0||e.getRenderingMesh().hasThinInstances);if(!this.isReady(e,a,s))return;const h=e.getMesh(),l=h._internalAbstractMeshDataInfo._actAsRegularMesh?h:null,c=e.getRenderingMesh(),u=l||c,f=e.getMaterial();if(!f||!r.activeCamera)return;const d=e._getDrawWrapper(s),_=ys.GetEffect(d);n.enableEffect(d),f.useLogarithmicDepth&&_.setFloat("logarithmicDepthConstant",2/(Math.log(r.activeCamera.maxZ+1)/Math.LN2)),_.setFloat("offset",i?0:c.outlineWidth),_.setColor4("color",i?c.overlayColor:c.outlineColor,i?c.overlayAlpha:f.alpha),_.setMatrix("viewProjection",r.getTransformMatrix()),_.setMatrix("world",u.getWorldMatrix()),vs(c,_),Is(c,_),c.morphTargetManager&&c.morphTargetManager.isUsingTextureForTargets&&c.morphTargetManager._bind(_),a||c._bind(e,_,f.fillMode);const m=e.getMesh().bakedVertexAnimationManager;if(m&&m.isEnabled&&m.bind(_,a),f&&f.needAlphaTestingForMesh(u)){const g=f.getAlphaTestTexture();g&&(_.setTexture("diffuseSampler",g),_.setMatrix("diffuseMatrix",g.getTextureMatrix()))}Ms(_,f,r),n.setZOffset(-this.zOffset),n.setZOffsetUnits(-this.zOffsetUnits),c._processRendering(u,e,_,f.fillMode,t,a,(g,T)=>{_.setMatrix("world",T)}),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=i??this._passIdForDrawWrapper[0];const s=[],r=[S.PositionKind,S.NormalKind],n=e.getMesh(),a=e.getMaterial();if(!a)return!1;const h=n.getScene();let l=!1,c=!1;const u=!1;a.needAlphaTestingForMesh(n)&&(s.push("#define ALPHATEST"),n.isVerticesDataPresent(S.UVKind)&&(r.push(S.UVKind),s.push("#define UV1"),l=!0),n.isVerticesDataPresent(S.UV2Kind)&&(r.push(S.UV2Kind),s.push("#define UV2"),c=!0)),a.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),dr(a,h,s);const f=new Cs;if(n.useBones&&n.computeBonesUsingShaders&&n.skeleton){r.push(S.MatricesIndicesKind),r.push(S.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(S.MatricesIndicesExtraKind),r.push(S.MatricesWeightsExtraKind));const R=n.skeleton;s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),n.numBoneInfluencers>0&&f.addCPUSkinningFallback(0,n),R.isUsingTextureForMatrices?s.push("#define BONETEXTURE"):s.push("#define BonesPerMesh "+(R.bones.length+1))}else s.push("#define NUM_BONE_INFLUENCERS 0");const d=n.morphTargetManager?_r(n.morphTargetManager,s,r,n,!0,!0,!1,l,c,u):0;t&&(s.push("#define INSTANCES"),Ps(r),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const _=n.bakedVertexAnimationManager;_&&_.isEnabled&&(s.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&r.push("bakedVertexAnimationSettingsInstanced"));const m=e._getDrawWrapper(i,!0),g=m.defines,T=s.join(`
|
|
1327
|
+
`);if(g!==T){const R=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","boneTextureWidth","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],A=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"];As(R),m.setEffect(this.scene.getEngine().createEffect("outline",{attributes:r,uniformsNames:R,uniformBuffersNames:[],samplers:A,defines:T,fallbacks:f,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:d},shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{this._shaderLanguage===1?await Promise.all([he(()=>import("./outline.fragment-DQK2JikO.js"),__vite__mapDeps([25,9,26,27]),import.meta.url),he(()=>import("./outline.vertex-CKcILDiL.js"),__vite__mapDeps([28,5,6,7,26,29]),import.meta.url)]):await Promise.all([he(()=>import("./outline.fragment-BK0vgcx7.js"),__vite__mapDeps([30,31,32]),import.meta.url),he(()=>import("./outline.vertex-CHR7GZYH.js"),__vite__mapDeps([33,31,34]),import.meta.url)])}},this.scene.getEngine()),T)}return m.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this.enabled&&(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline)){const s=t.getMaterial();s&&s.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(sr._StencilReference),this._engine.setStencilFunctionReference(sr._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),s&&s.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(this.enabled){if(e.renderOverlay){const s=this._engine.getAlphaMode(),r=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(s),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.setAlphaBlend(r)}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}}sr._StencilReference=4;class I{}I.AUTOSAMPLERSUFFIX="Sampler";I.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS";I.ALPHA_DISABLE=0;I.ALPHA_ADD=1;I.ALPHA_COMBINE=2;I.ALPHA_SUBTRACT=3;I.ALPHA_MULTIPLY=4;I.ALPHA_MAXIMIZED=5;I.ALPHA_ONEONE=6;I.ALPHA_PREMULTIPLIED=7;I.ALPHA_PREMULTIPLIED_PORTERDUFF=8;I.ALPHA_INTERPOLATE=9;I.ALPHA_SCREENMODE=10;I.ALPHA_ONEONE_ONEONE=11;I.ALPHA_ALPHATOCOLOR=12;I.ALPHA_REVERSEONEMINUS=13;I.ALPHA_SRC_DSTONEMINUSSRCALPHA=14;I.ALPHA_ONEONE_ONEZERO=15;I.ALPHA_EXCLUSION=16;I.ALPHA_LAYER_ACCUMULATE=17;I.ALPHA_MIN=18;I.ALPHA_MAX=19;I.ALPHA_DUAL_SRC0_ADD_SRC1xDST=20;I.ALPHA_EQUATION_ADD=0;I.ALPHA_EQUATION_SUBSTRACT=1;I.ALPHA_EQUATION_REVERSE_SUBTRACT=2;I.ALPHA_EQUATION_MAX=3;I.ALPHA_EQUATION_MIN=4;I.ALPHA_EQUATION_DARKEN=5;I.DELAYLOADSTATE_NONE=0;I.DELAYLOADSTATE_LOADED=1;I.DELAYLOADSTATE_LOADING=2;I.DELAYLOADSTATE_NOTLOADED=4;I.NEVER=512;I.ALWAYS=519;I.LESS=513;I.EQUAL=514;I.LEQUAL=515;I.GREATER=516;I.GEQUAL=518;I.NOTEQUAL=517;I.KEEP=7680;I.ZERO=0;I.REPLACE=7681;I.INCR=7682;I.DECR=7683;I.INVERT=5386;I.INCR_WRAP=34055;I.DECR_WRAP=34056;I.TEXTURE_CLAMP_ADDRESSMODE=0;I.TEXTURE_WRAP_ADDRESSMODE=1;I.TEXTURE_MIRROR_ADDRESSMODE=2;I.TEXTURE_CREATIONFLAG_STORAGE=1;I.TEXTUREFORMAT_ALPHA=0;I.TEXTUREFORMAT_LUMINANCE=1;I.TEXTUREFORMAT_LUMINANCE_ALPHA=2;I.TEXTUREFORMAT_RGB=4;I.TEXTUREFORMAT_RGBA=5;I.TEXTUREFORMAT_RED=6;I.TEXTUREFORMAT_R=6;I.TEXTUREFORMAT_R16_UNORM=33322;I.TEXTUREFORMAT_RG16_UNORM=33324;I.TEXTUREFORMAT_RGB16_UNORM=32852;I.TEXTUREFORMAT_RGBA16_UNORM=32859;I.TEXTUREFORMAT_R16_SNORM=36760;I.TEXTUREFORMAT_RG16_SNORM=36761;I.TEXTUREFORMAT_RGB16_SNORM=36762;I.TEXTUREFORMAT_RGBA16_SNORM=36763;I.TEXTUREFORMAT_RG=7;I.TEXTUREFORMAT_RED_INTEGER=8;I.TEXTUREFORMAT_R_INTEGER=8;I.TEXTUREFORMAT_RG_INTEGER=9;I.TEXTUREFORMAT_RGB_INTEGER=10;I.TEXTUREFORMAT_RGBA_INTEGER=11;I.TEXTUREFORMAT_BGRA=12;I.TEXTUREFORMAT_DEPTH24_STENCIL8=13;I.TEXTUREFORMAT_DEPTH32_FLOAT=14;I.TEXTUREFORMAT_DEPTH16=15;I.TEXTUREFORMAT_DEPTH24=16;I.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17;I.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18;I.TEXTUREFORMAT_STENCIL8=19;I.TEXTUREFORMAT_UNDEFINED=4294967295;I.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492;I.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493;I.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495;I.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494;I.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779;I.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919;I.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778;I.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918;I.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777;I.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776;I.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917;I.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916;I.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808;I.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840;I.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196;I.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492;I.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493;I.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494;I.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495;I.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496;I.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497;I.TEXTURETYPE_UNSIGNED_BYTE=0;I.TEXTURETYPE_UNSIGNED_INT=0;I.TEXTURETYPE_FLOAT=1;I.TEXTURETYPE_HALF_FLOAT=2;I.TEXTURETYPE_BYTE=3;I.TEXTURETYPE_SHORT=4;I.TEXTURETYPE_UNSIGNED_SHORT=5;I.TEXTURETYPE_INT=6;I.TEXTURETYPE_UNSIGNED_INTEGER=7;I.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;I.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;I.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;I.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;I.TEXTURETYPE_UNSIGNED_INT_24_8=12;I.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;I.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;I.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;I.TEXTURETYPE_UNDEFINED=16;I.TEXTURE_2D=3553;I.TEXTURE_2D_ARRAY=35866;I.TEXTURE_CUBE_MAP=34067;I.TEXTURE_CUBE_MAP_ARRAY=3735928559;I.TEXTURE_3D=32879;I.TEXTURE_NEAREST_SAMPLINGMODE=1;I.TEXTURE_NEAREST_NEAREST=1;I.TEXTURE_BILINEAR_SAMPLINGMODE=2;I.TEXTURE_LINEAR_LINEAR=2;I.TEXTURE_TRILINEAR_SAMPLINGMODE=3;I.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;I.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;I.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;I.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;I.TEXTURE_NEAREST_LINEAR=7;I.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;I.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;I.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;I.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;I.TEXTURE_LINEAR_NEAREST=12;I.TEXTURE_EXPLICIT_MODE=0;I.TEXTURE_SPHERICAL_MODE=1;I.TEXTURE_PLANAR_MODE=2;I.TEXTURE_CUBIC_MODE=3;I.TEXTURE_PROJECTION_MODE=4;I.TEXTURE_SKYBOX_MODE=5;I.TEXTURE_INVCUBIC_MODE=6;I.TEXTURE_EQUIRECTANGULAR_MODE=7;I.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;I.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;I.TEXTURE_FILTERING_QUALITY_OFFLINE=4096;I.TEXTURE_FILTERING_QUALITY_HIGH=64;I.TEXTURE_FILTERING_QUALITY_MEDIUM=16;I.TEXTURE_FILTERING_QUALITY_LOW=8;I.SCALEMODE_FLOOR=1;I.SCALEMODE_NEAREST=2;I.SCALEMODE_CEILING=3;I.MATERIAL_TextureDirtyFlag=1;I.MATERIAL_LightDirtyFlag=2;I.MATERIAL_FresnelDirtyFlag=4;I.MATERIAL_AttributesDirtyFlag=8;I.MATERIAL_MiscDirtyFlag=16;I.MATERIAL_PrePassDirtyFlag=32;I.MATERIAL_ImageProcessingDirtyFlag=64;I.MATERIAL_AllDirtyFlag=127;I.MATERIAL_TriangleFillMode=0;I.MATERIAL_WireFrameFillMode=1;I.MATERIAL_PointFillMode=2;I.MATERIAL_PointListDrawMode=3;I.MATERIAL_LineListDrawMode=4;I.MATERIAL_LineLoopDrawMode=5;I.MATERIAL_LineStripDrawMode=6;I.MATERIAL_TriangleStripDrawMode=7;I.MATERIAL_TriangleFanDrawMode=8;I.MATERIAL_ClockWiseSideOrientation=0;I.MATERIAL_CounterClockWiseSideOrientation=1;I.MATERIAL_DIFFUSE_MODEL_E_OREN_NAYAR=0;I.MATERIAL_DIFFUSE_MODEL_BURLEY=1;I.MATERIAL_DIFFUSE_MODEL_LAMBERT=2;I.MATERIAL_DIFFUSE_MODEL_LEGACY=3;I.MATERIAL_DIELECTRIC_SPECULAR_MODEL_GLTF=0;I.MATERIAL_DIELECTRIC_SPECULAR_MODEL_OPENPBR=1;I.MATERIAL_CONDUCTOR_SPECULAR_MODEL_GLTF=0;I.MATERIAL_CONDUCTOR_SPECULAR_MODEL_OPENPBR=1;I.ACTION_NothingTrigger=0;I.ACTION_OnPickTrigger=1;I.ACTION_OnLeftPickTrigger=2;I.ACTION_OnRightPickTrigger=3;I.ACTION_OnCenterPickTrigger=4;I.ACTION_OnPickDownTrigger=5;I.ACTION_OnDoublePickTrigger=6;I.ACTION_OnPickUpTrigger=7;I.ACTION_OnPickOutTrigger=16;I.ACTION_OnLongPressTrigger=8;I.ACTION_OnPointerOverTrigger=9;I.ACTION_OnPointerOutTrigger=10;I.ACTION_OnEveryFrameTrigger=11;I.ACTION_OnIntersectionEnterTrigger=12;I.ACTION_OnIntersectionExitTrigger=13;I.ACTION_OnKeyDownTrigger=14;I.ACTION_OnKeyUpTrigger=15;I.PARTICLES_BILLBOARDMODE_Y=2;I.PARTICLES_BILLBOARDMODE_ALL=7;I.PARTICLES_BILLBOARDMODE_STRETCHED=8;I.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9;I.MESHES_CULLINGSTRATEGY_STANDARD=0;I.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;I.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;I.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;I.SCENELOADER_NO_LOGGING=0;I.SCENELOADER_MINIMAL_LOGGING=1;I.SCENELOADER_SUMMARY_LOGGING=2;I.SCENELOADER_DETAILED_LOGGING=3;I.PREPASS_IRRADIANCE_TEXTURE_TYPE=0;I.PREPASS_POSITION_TEXTURE_TYPE=1;I.PREPASS_VELOCITY_TEXTURE_TYPE=2;I.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3;I.PREPASS_COLOR_TEXTURE_TYPE=4;I.PREPASS_DEPTH_TEXTURE_TYPE=5;I.PREPASS_NORMAL_TEXTURE_TYPE=6;I.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7;I.PREPASS_WORLD_NORMAL_TEXTURE_TYPE=8;I.PREPASS_LOCAL_POSITION_TEXTURE_TYPE=9;I.PREPASS_SCREENSPACE_DEPTH_TEXTURE_TYPE=10;I.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE=11;I.PREPASS_ALBEDO_TEXTURE_TYPE=12;I.PREPASS_NORMALIZED_VIEW_DEPTH_TEXTURE_TYPE=13;I.BUFFER_CREATIONFLAG_READ=1;I.BUFFER_CREATIONFLAG_WRITE=2;I.BUFFER_CREATIONFLAG_READWRITE=3;I.BUFFER_CREATIONFLAG_UNIFORM=4;I.BUFFER_CREATIONFLAG_VERTEX=8;I.BUFFER_CREATIONFLAG_INDEX=16;I.BUFFER_CREATIONFLAG_STORAGE=32;I.BUFFER_CREATIONFLAG_INDIRECT=64;I.RENDERPASS_MAIN=0;I.INPUT_ALT_KEY=18;I.INPUT_CTRL_KEY=17;I.INPUT_META_KEY1=91;I.INPUT_META_KEY2=92;I.INPUT_META_KEY3=93;I.INPUT_SHIFT_KEY=16;I.SNAPSHOTRENDERING_STANDARD=0;I.SNAPSHOTRENDERING_FAST=1;I.PERSPECTIVE_CAMERA=0;I.ORTHOGRAPHIC_CAMERA=1;I.FOVMODE_VERTICAL_FIXED=0;I.FOVMODE_HORIZONTAL_FIXED=1;I.RIG_MODE_NONE=0;I.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;I.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;I.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;I.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;I.RIG_MODE_STEREOSCOPIC_INTERLACED=14;I.RIG_MODE_VR=20;I.RIG_MODE_CUSTOM=22;I.MAX_SUPPORTED_UV_SETS=6;I.GL_ALPHA_EQUATION_ADD=32774;I.GL_ALPHA_EQUATION_MIN=32775;I.GL_ALPHA_EQUATION_MAX=32776;I.GL_ALPHA_EQUATION_SUBTRACT=32778;I.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779;I.GL_ALPHA_FUNCTION_SRC=768;I.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769;I.GL_ALPHA_FUNCTION_SRC_ALPHA=770;I.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771;I.GL_ALPHA_FUNCTION_DST_ALPHA=772;I.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773;I.GL_ALPHA_FUNCTION_DST_COLOR=774;I.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775;I.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776;I.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769;I.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770;I.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771;I.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772;I.GL_ALPHA_FUNCTION_SRC1_COLOR=35065;I.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_COLOR=35066;I.GL_ALPHA_FUNCTION_SRC1_ALPHA=34185;I.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_ALPHA=35067;I.SnippetUrl="https://snippet.babylonjs.com";I.FOGMODE_NONE=0;I.FOGMODE_EXP=1;I.FOGMODE_EXP2=2;I.FOGMODE_LINEAR=3;I.BYTE=5120;I.UNSIGNED_BYTE=5121;I.SHORT=5122;I.UNSIGNED_SHORT=5123;I.INT=5124;I.UNSIGNED_INT=5125;I.FLOAT=5126;I.PositionKind="position";I.NormalKind="normal";I.TangentKind="tangent";I.UVKind="uv";I.UV2Kind="uv2";I.UV3Kind="uv3";I.UV4Kind="uv4";I.UV5Kind="uv5";I.UV6Kind="uv6";I.ColorKind="color";I.ColorInstanceKind="instanceColor";I.MatricesIndicesKind="matricesIndices";I.MatricesWeightsKind="matricesWeights";I.MatricesIndicesExtraKind="matricesIndicesExtra";I.MatricesWeightsExtraKind="matricesWeightsExtra";I.ANIMATIONTYPE_FLOAT=0;I.ANIMATIONTYPE_VECTOR3=1;I.ANIMATIONTYPE_QUATERNION=2;I.ANIMATIONTYPE_MATRIX=3;I.ANIMATIONTYPE_COLOR3=4;I.ANIMATIONTYPE_COLOR4=7;I.ANIMATIONTYPE_VECTOR2=5;I.ANIMATIONTYPE_SIZE=6;I.ShadowMinZ=0;I.ShadowMaxZ=1e4;I.OUTLINELAYER_SAMPLING_TRIDIRECTIONAL=0;I.OUTLINELAYER_SAMPLING_OCTADIRECTIONAL=1;class zh{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,s,r){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&(t.prePassRenderer.getIndex(2)!==-1||t.prePassRenderer.getIndex(11)!==-1)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=s.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const n=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=n.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==n.frameId&&(this._lastUpdateFrameId=n.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=s.clone()}}}class vo{constructor(e){if(this.VERTEXOUTPUT_INVARIANT=!1,this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))e[0]!=="_"&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)this._keys.indexOf(e)===-1&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;t<this._keys.length;t++){const i=this._keys[t];if(this[i]!==e[i])return!1}return!0}cloneTo(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(let t=0;t<this._keys.length;t++){const i=this._keys[t];e[i]=this[i]}}reset(){for(const e of this._keys)this._setDefaultValue(e)}_setDefaultValue(e){const t=this._externalProperties?.[e]?.type??typeof this[e],i=this._externalProperties?.[e]?.default;switch(t){case"number":this[e]=i??0;break;case"string":this[e]=i??"";break;default:this[e]=i??!1;break}}toString(){let e="";for(let t=0;t<this._keys.length;t++){const i=this._keys[t],s=this[i];switch(typeof s){case"number":case"string":e+="#define "+i+" "+s+`
|
|
1328
|
+
`;break;default:s&&(e+="#define "+i+`
|
|
1329
|
+
`);break}}return e}}function Sp(o){return class extends o{constructor(){super(...arguments),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1}}}class iT extends vo{constructor(){super(),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class yp extends vo{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class rs extends ws{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"DetailMap",140,new yp,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=V.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&Pe.DetailTextureEnabled&&!this._texture.isReady()):!0}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&Pe.DetailTextureEnabled&&this._isEnabled?(Ci(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&this._texture&&Pe.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),Di(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&Pe.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture?.dispose()}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}M([qt("detailTexture"),ze("_markAllSubMeshesAsTexturesDirty")],rs.prototype,"texture",void 0);M([C()],rs.prototype,"diffuseBlendLevel",void 0);M([C()],rs.prototype,"roughnessBlendLevel",void 0);M([C()],rs.prototype,"bumpLevel",void 0);M([C(),ze("_markAllSubMeshesAsTexturesDirty")],rs.prototype,"normalBlendMethod",void 0);M([C(),ze("_markAllSubMeshesAsTexturesDirty")],rs.prototype,"isEnabled",void 0);var Wh;(function(o){o[o.Zero=0]="Zero",o[o.One=1]="One",o[o.MaxViewZ=2]="MaxViewZ",o[o.NoClear=3]="NoClear"})(Wh||(Wh={}));class Dt{static CreateConfiguration(e){return Dt._Configurations[e]={defines:{},previousWorldMatrices:{},previousViewProjection:D.Zero(),currentViewProjection:D.Zero(),previousBones:{},lastUpdateFrameId:-1,excludedSkinnedMesh:[],reverseCulling:!1},Dt._Configurations[e]}static DeleteConfiguration(e){delete Dt._Configurations[e]}static GetConfiguration(e){return Dt._Configurations[e]}static AddUniformsAndSamplers(e,t){e.push("previousWorld","previousViewProjection","mPreviousBones")}static MarkAsDirty(e,t){for(const i of t)if(i.subMeshes)for(const s of i.subMeshes)s._removeDrawWrapper(e)}static PrepareDefines(e,t,i){if(!i._arePrePassDirty)return;const s=Dt._Configurations[e];if(!s)return;i.PREPASS=!0;let r=0;for(let n=0;n<Dt.GeometryTextureDescriptions.length;n++){const a=Dt.GeometryTextureDescriptions[n],h=a.define,l=a.defineIndex,c=s.defines[l];c!==void 0?(i[h]=!0,i[l]=c,r++):(i[h]=!1,delete i[l])}i.SCENE_MRT_COUNT=r,i.BONES_VELOCITY_ENABLED=t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&!t.skeleton.isUsingTextureForMatrices&&s.excludedSkinnedMesh.indexOf(t)===-1}static Bind(e,t,i,s,r){const n=Dt._Configurations[e];if(!n)return;const a=i.getScene(),h=a.getEngine();if(n.reverseCulling&&h.setStateCullFaceType(a._mirroredCameraPosition?r.cullBackFaces:!r.cullBackFaces),(n.defines.PREPASS_VELOCITY_INDEX!==void 0||n.defines.PREPASS_VELOCITY_LINEAR_INDEX!==void 0)&&(n.previousWorldMatrices[i.uniqueId]||(n.previousWorldMatrices[i.uniqueId]=s.clone()),n.previousViewProjection||(n.previousViewProjection=a.getTransformMatrix().clone(),n.currentViewProjection=a.getTransformMatrix().clone()),n.currentViewProjection.updateFlag!==a.getTransformMatrix().updateFlag?(n.lastUpdateFrameId=h.frameId,n.previousViewProjection.copyFrom(n.currentViewProjection),n.currentViewProjection.copyFrom(a.getTransformMatrix())):n.lastUpdateFrameId!==h.frameId&&(n.lastUpdateFrameId=h.frameId,n.previousViewProjection.copyFrom(n.currentViewProjection)),t.setMatrix("previousWorld",n.previousWorldMatrices[i.uniqueId]),t.setMatrix("previousViewProjection",n.previousViewProjection),n.previousWorldMatrices[i.uniqueId]=s.clone(),i.useBones&&i.computeBonesUsingShaders&&i.skeleton)){const l=i.skeleton;if(!l.isUsingTextureForMatrices||t.getUniformIndex("boneTextureWidth")===-1){const c=l.getTransformMatrices(i);c&&(n.previousBones[i.uniqueId]||(n.previousBones[i.uniqueId]=c.slice()),t.setMatrices("mPreviousBones",n.previousBones[i.uniqueId]),n.previousBones[i.uniqueId].set(c))}}}}Dt.GeometryTextureDescriptions=[{type:0,name:"Irradiance",clearType:0,define:"PREPASS_IRRADIANCE",defineIndex:"PREPASS_IRRADIANCE_INDEX"},{type:1,name:"WorldPosition",clearType:0,define:"PREPASS_POSITION",defineIndex:"PREPASS_POSITION_INDEX"},{type:2,name:"Velocity",clearType:0,define:"PREPASS_VELOCITY",defineIndex:"PREPASS_VELOCITY_INDEX"},{type:3,name:"Reflectivity",clearType:0,define:"PREPASS_REFLECTIVITY",defineIndex:"PREPASS_REFLECTIVITY_INDEX"},{type:5,name:"ViewDepth",clearType:2,define:"PREPASS_DEPTH",defineIndex:"PREPASS_DEPTH_INDEX"},{type:6,name:"ViewNormal",clearType:0,define:"PREPASS_NORMAL",defineIndex:"PREPASS_NORMAL_INDEX"},{type:7,name:"AlbedoSqrt",clearType:0,define:"PREPASS_ALBEDO_SQRT",defineIndex:"PREPASS_ALBEDO_SQRT_INDEX"},{type:8,name:"WorldNormal",clearType:0,define:"PREPASS_WORLD_NORMAL",defineIndex:"PREPASS_WORLD_NORMAL_INDEX"},{type:9,name:"LocalPosition",clearType:0,define:"PREPASS_LOCAL_POSITION",defineIndex:"PREPASS_LOCAL_POSITION_INDEX"},{type:10,name:"ScreenDepth",clearType:1,define:"PREPASS_SCREENSPACE_DEPTH",defineIndex:"PREPASS_SCREENSPACE_DEPTH_INDEX"},{type:11,name:"LinearVelocity",clearType:0,define:"PREPASS_VELOCITY_LINEAR",defineIndex:"PREPASS_VELOCITY_LINEAR_INDEX"},{type:12,name:"Albedo",clearType:0,define:"PREPASS_ALBEDO",defineIndex:"PREPASS_ALBEDO_INDEX"},{type:13,name:"NormalizedViewDepth",clearType:1,define:"PREPASS_NORMALIZED_VIEW_DEPTH",defineIndex:"PREPASS_NORMALIZED_VIEW_DEPTH_INDEX"},{type:4,name:"Color",clearType:3,define:"PREPASS_COLOR",defineIndex:"PREPASS_COLOR_INDEX"}];Dt._Configurations={};function Ap(o){return class extends o{constructor(){super(...arguments),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1}}}function Mp(o){return class extends o{constructor(...e){super(...e),_u()(this,"_imageProcessingConfiguration")}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsImageProcessingDirty&&this._markAllSubMeshesAsImageProcessingDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),!e&&this.getScene?this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration:e&&(this._imageProcessingConfiguration=e),this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty&&this._markAllSubMeshesAsImageProcessingDirty()})))}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}}}const vn={effect:null,subMesh:null};class Pp extends Ap(vo){}class hu extends Sp(Pp){constructor(e){super(e),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_POSITION=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.MORPHTARGETS_UV2=!1,this.MORPHTARGETS_COLOR=!1,this.MORPHTARGETTEXTURE_HASPOSITIONS=!1,this.MORPHTARGETTEXTURE_HASNORMALS=!1,this.MORPHTARGETTEXTURE_HASTANGENTS=!1,this.MORPHTARGETTEXTURE_HASUVS=!1,this.MORPHTARGETTEXTURE_HASUV2S=!1,this.MORPHTARGETTEXTURE_HASCOLORS=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_COLOR=!1,this.PREPASS_COLOR_INDEX=-1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO=!1,this.PREPASS_ALBEDO_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_SCREENSPACE_DEPTH=!1,this.PREPASS_SCREENSPACE_DEPTH_INDEX=-1,this.PREPASS_NORMALIZED_VIEW_DEPTH=!1,this.PREPASS_NORMALIZED_VIEW_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_WORLD_NORMAL=!1,this.PREPASS_WORLD_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_LOCAL_POSITION=!1,this.PREPASS_LOCAL_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_VELOCITY_LINEAR=!1,this.PREPASS_VELOCITY_LINEAR_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.AREALIGHTSUPPORTED=!0,this.USE_VERTEX_PULLING=!1,this.RIGHT_HANDED=!1,this.CLUSTLIGHT_SLICES=0,this.CLUSTLIGHT_BATCH=0,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}}class Ip extends Mp(Zc){}class te extends Ip{get isPrePassCapable(){return!this.disableDepthWrite}get canRenderToMRT(){return!0}constructor(e,t,i=!1){super(e,t,void 0,i||te.ForceGLSL),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new Re(0,0,0),this.diffuseColor=new Re(1,1,1),this.specularColor=new Re(1,1,1),this.emissiveColor=new Re(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._shadersLoaded=!1,this._renderTargets=new Et(16),this._globalAmbientColor=new Re(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new rs(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new zh,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),te.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),te.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return te.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||te.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return this._hasTransparencyMode?this._transparencyModeIsBlend:this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled}needAlphaTesting(){return this._hasTransparencyMode?this._transparencyModeIsTest:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===V.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==V.MATERIAL_OPAQUE}_hasAlphaChannel(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new hu(this._eventInfo.defineNames));const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const a=r.getEngine();n._needNormals=z_(r,e,n,!0,this._maxSimultaneousLights,this._disableLighting),Z_(r,n);const h=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Q_(r,n,this.canRenderToMRT&&!h),q_(r,n,h),Dt.PrepareDefines(a.currentRenderPassId,e,n),n._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n._needUVs=!1;for(let c=1;c<=6;++c)n["MAINUV"+c]=!1;if(r.texturesEnabled){if(n.DIFFUSEDIRECTUV=0,n.BUMPDIRECTUV=0,n.AMBIENTDIRECTUV=0,n.OPACITYDIRECTUV=0,n.EMISSIVEDIRECTUV=0,n.SPECULARDIRECTUV=0,n.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&te.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())Ci(this._diffuseTexture,n,"DIFFUSE");else return!1;else n.DIFFUSE=!1;if(this._ambientTexture&&te.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())Ci(this._ambientTexture,n,"AMBIENT");else return!1;else n.AMBIENT=!1;if(this._opacityTexture&&te.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())Ci(this._opacityTexture,n,"OPACITY"),n.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else n.OPACITY=!1;if(this._reflectionTexture&&te.ReflectionTextureEnabled?(n.ROUGHNESS=this._roughness>0,n.REFLECTIONOVERALPHA=this._useReflectionOverAlpha):(n.ROUGHNESS=!1,n.REFLECTIONOVERALPHA=!1),!W_(r,this._reflectionTexture,n))return!1;if(this._emissiveTexture&&te.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())Ci(this._emissiveTexture,n,"EMISSIVE");else return!1;else n.EMISSIVE=!1;if(this._lightmapTexture&&te.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())Ci(this._lightmapTexture,n,"LIGHTMAP"),n.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,n.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else n.LIGHTMAP=!1;if(this._specularTexture&&te.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())Ci(this._specularTexture,n,"SPECULAR"),n.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else n.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&te.BumpTextureEnabled){if(this._bumpTexture.isReady())Ci(this._bumpTexture,n,"BUMP"),n.PARALLAX=this._useParallax,n.PARALLAX_RHS=r.useRightHandedSystem,n.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;n.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else n.BUMP=!1,n.PARALLAX=!1,n.PARALLAX_RHS=!1,n.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&te.RefractionTextureEnabled)if(this._refractionTexture.isReadyOrNotBlocking())n._needUVs=!0,n.REFRACTION=!0,n.REFRACTIONMAP_3D=this._refractionTexture.isCube,n.RGBDREFRACTION=this._refractionTexture.isRGBD,n.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize;else return!1;else n.REFRACTION=!1;n.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else n.DIFFUSE=!1,n.AMBIENT=!1,n.OPACITY=!1,n.REFLECTION=!1,n.EMISSIVE=!1,n.LIGHTMAP=!1,n.BUMP=!1,n.REFRACTION=!1;n.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),n.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,n.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,n.SPECULAROVERALPHA=this._useSpecularOverAlpha,n.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,n.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,n.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n),n.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,n.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}if(n._areFresnelDirty&&(te.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(n.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,n.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,n.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,n.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,n.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,n.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,n._needNormals=!0,n.FRESNEL=!0):n.FRESNEL=!1),n.AREALIGHTUSED||n.CLUSTLIGHT_BATCH){for(let c=0;c<e.lightSources.length;c++)if(!e.lightSources[c]._isReady())return!1}V_(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this.needAlphaTestingForMesh(e),n,this._applyDecalMapAfterDetailMap,this._useVertexPulling,t.getRenderingMesh(),this._isVertexOutputInvariant),H_(r,a,this,n,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=n,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),j_(e,n,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let l=!1;if(n.isDirty){const c=n._areLightsDisposed;n.markAsProcessed();const u=new Cs;n.REFLECTION&&u.addFallback(0,"REFLECTION"),n.SPECULAR&&u.addFallback(0,"SPECULAR"),n.BUMP&&u.addFallback(0,"BUMP"),n.PARALLAX&&u.addFallback(1,"PARALLAX"),n.PARALLAX_RHS&&u.addFallback(1,"PARALLAX_RHS"),n.PARALLAXOCCLUSION&&u.addFallback(0,"PARALLAXOCCLUSION"),n.SPECULAROVERALPHA&&u.addFallback(0,"SPECULAROVERALPHA"),n.FOG&&u.addFallback(1,"FOG"),n.POINTSIZE&&u.addFallback(0,"POINTSIZE"),n.LOGARITHMICDEPTH&&u.addFallback(0,"LOGARITHMICDEPTH"),U_(n,u,this._maxSimultaneousLights),n.SPECULARTERM&&u.addFallback(0,"SPECULARTERM"),n.DIFFUSEFRESNEL&&u.addFallback(1,"DIFFUSEFRESNEL"),n.OPACITYFRESNEL&&u.addFallback(2,"OPACITYFRESNEL"),n.REFLECTIONFRESNEL&&u.addFallback(3,"REFLECTIONFRESNEL"),n.EMISSIVEFRESNEL&&u.addFallback(4,"EMISSIVEFRESNEL"),n.FRESNEL&&u.addFallback(4,"FRESNEL"),n.MULTIVIEW&&u.addFallback(0,"MULTIVIEW");const f=[S.PositionKind];n.NORMAL&&f.push(S.NormalKind),n.TANGENT&&f.push(S.TangentKind);for(let x=1;x<=6;++x)n["UV"+x]&&f.push(`uv${x===1?"":x}`);n.VERTEXCOLOR&&f.push(S.ColorKind),B_(f,e,n,u),N_(f,n),io(f,e,n),O_(f,e,n);let d="default";const _=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices","cameraInfo"],m=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler","areaLightsLTC1Sampler","areaLightsLTC2Sampler"];eg(_,m,!1);const g=["Material","Scene","Mesh"],T={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=u,this._eventInfo.fallbackRank=0,this._eventInfo.defines=n,this._eventInfo.uniforms=_,this._eventInfo.attributes=f,this._eventInfo.samplers=m,this._eventInfo.uniformBuffersNames=g,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=T,this._callbackPluginEventGeneric(128,this._eventInfo),Dt.AddUniformsAndSamplers(_,m),zh.AddUniforms(_),Oe&&(Oe.PrepareUniforms(_,n),Oe.PrepareSamplers(m,n)),tg({uniformsNames:_,uniformBuffersNames:g,samplers:m,defines:n,maxSimultaneousLights:this._maxSimultaneousLights}),As(_);const R={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,_,g,m,n,f,R));const A=n.toString(),y=t.effect,E=r.getEngine().createEffect(d,{attributes:f,uniformsNames:_,uniformBuffersNames:g,samplers:m,defines:A,fallbacks:u,onCompiled:this.onCompiled,onError:this.onError,indexParameters:T,processFinalCode:R.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:n.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{this._shaderLanguage===1?await Promise.all([he(()=>import("./default.vertex-YrvIUn4x.js"),__vite__mapDeps([35,36,14,37,5,7,38,18,6,26,29]),import.meta.url),he(()=>import("./default.fragment-C4zjkcFb.js").then(x=>x.a),__vite__mapDeps([39,36,14,40,38,9,26,20,27]),import.meta.url)]):await Promise.all([he(()=>import("./default.vertex-A8wQopNr.js"),__vite__mapDeps([41,42,43,16,44,22,31,34]),import.meta.url),he(()=>import("./default.fragment-C4xg7O-P.js").then(x=>x.a),__vite__mapDeps([45,46,43,16,44,31,24,32]),import.meta.url)]),this._shadersLoaded=!0}},a);if(this._eventInfo.customCode=void 0,E)if(this._onEffectCreatedObservable&&(vn.effect=E,vn.subMesh=t,this._onEffectCreatedObservable.notifyObservers(vn)),this.allowShaderHotSwapping&&y&&!E.isReady()){if(n.markAsUnprocessed(),l=this.isFrozen,c)return n._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(E,n,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!l,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),e.addUniform("cameraInfo",4),ig(e,!1,!0),super.buildUniformLayout()}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),Dt.Bind(s.getEngine().currentRenderPassId,this._activeEffect,t,e,this);const a=s.activeCamera;a?this._uniformBuffer.updateFloat4("cameraInfo",a.minZ,a.maxZ,0,0):this._uniformBuffer.updateFloat4("cameraInfo",0,0,0,0),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const h=this._mustRebind(s,n,i,t.visibility);vs(t,n);const l=this._uniformBuffer;if(h){if(this.bindViewProjection(n),!l.useUbo||!this.isFrozen||!l.isSync||i._drawWrapper._forceRebindOnNextCall){if(te.FresnelEnabled&&r.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(l.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),l.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&l.updateColor4("opacityParts",new Re(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(l.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),l.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(l.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),l.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(l.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),l.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled&&(this._diffuseTexture&&te.DiffuseTextureEnabled&&(l.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Di(this._diffuseTexture,l,"diffuse")),this._ambientTexture&&te.AmbientTextureEnabled&&(l.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),Di(this._ambientTexture,l,"ambient")),this._opacityTexture&&te.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Di(this._opacityTexture,l,"opacity")),this._hasAlphaChannel()&&l.updateFloat("alphaCutOff",this.alphaCutOff),D_(s,r,l,Re.White(),this._reflectionTexture,!1,!1,!0,!1,!1,!1,this.roughness),(!this._reflectionTexture||!te.ReflectionTextureEnabled)&&l.updateFloat2("vReflectionInfos",0,this.roughness),this._emissiveTexture&&te.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Di(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&te.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Di(this._lightmapTexture,l,"lightmap")),this._specularTexture&&te.SpecularTextureEnabled&&(l.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),Di(this._specularTexture,l,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&te.BumpTextureEnabled&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),Di(this._bumpTexture,l,"bump"),s._mirroredCameraPosition?l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&te.RefractionTextureEnabled)){let c=1;if(this._refractionTexture.isCube||(l.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(c=this._refractionTexture.depth)),l.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,c,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const u=this._refractionTexture;l.updateVector3("vRefractionPosition",u.boundingBoxPosition),l.updateVector3("vRefractionSize",u.boundingBoxSize)}}this.pointsCloud&&l.updateFloat("pointSize",this.pointSize),l.updateColor4("vSpecularColor",this.specularColor,this.specularPower),l.updateColor3("vEmissiveColor",te.EmissiveTextureEnabled?this.emissiveColor:Re.BlackReadOnly),l.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&te.DiffuseTextureEnabled&&n.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&te.AmbientTextureEnabled&&n.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&te.OpacityTextureEnabled&&n.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&te.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?n.setTexture("reflectionCubeSampler",this._reflectionTexture):n.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&te.EmissiveTextureEnabled&&n.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&te.LightmapTextureEnabled&&n.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&te.SpecularTextureEnabled&&n.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&te.BumpTextureEnabled&&n.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&te.RefractionTextureEnabled&&(this._refractionTexture.isCube?n.setTexture("refractionCubeSampler",this._refractionTexture):n.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Ms(n,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(h||!this.isFrozen)&&(s.lightsEnabled&&!this._disableLighting&&L_(s,t,n,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==je.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||r.PREPASS||r.CLUSTLIGHT_BATCH)&&this.bindView(n),mc(s,t,n),r.NUM_MORPH_INFLUENCERS&&Is(t,n),r.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,r.INSTANCES),this.useLogarithmicDepth&&pc(r,n,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),l.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e)}dispose(e,t){t&&(this._diffuseTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._specularTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._refractionTexture?.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=me.Clone(()=>new te(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return s.name=e,s.id=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}static Parse(e,t,i){const s=me.Parse(()=>new te(e.name,t),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),V._ParsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return Pe.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){Pe.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return Pe.DetailTextureEnabled}static set DetailTextureEnabled(e){Pe.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return Pe.AmbientTextureEnabled}static set AmbientTextureEnabled(e){Pe.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return Pe.OpacityTextureEnabled}static set OpacityTextureEnabled(e){Pe.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return Pe.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){Pe.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return Pe.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){Pe.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return Pe.SpecularTextureEnabled}static set SpecularTextureEnabled(e){Pe.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return Pe.BumpTextureEnabled}static set BumpTextureEnabled(e){Pe.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return Pe.LightmapTextureEnabled}static set LightmapTextureEnabled(e){Pe.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return Pe.RefractionTextureEnabled}static set RefractionTextureEnabled(e){Pe.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return Pe.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){Pe.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return Pe.FresnelEnabled}static set FresnelEnabled(e){Pe.FresnelEnabled=e}}te.ForceGLSL=!1;M([qt("diffuseTexture")],te.prototype,"_diffuseTexture",void 0);M([ze("_markAllSubMeshesAsTexturesAndMiscDirty")],te.prototype,"diffuseTexture",void 0);M([qt("ambientTexture")],te.prototype,"_ambientTexture",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"ambientTexture",void 0);M([qt("opacityTexture")],te.prototype,"_opacityTexture",void 0);M([ze("_markAllSubMeshesAsTexturesAndMiscDirty")],te.prototype,"opacityTexture",void 0);M([qt("reflectionTexture")],te.prototype,"_reflectionTexture",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"reflectionTexture",void 0);M([qt("emissiveTexture")],te.prototype,"_emissiveTexture",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"emissiveTexture",void 0);M([qt("specularTexture")],te.prototype,"_specularTexture",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"specularTexture",void 0);M([qt("bumpTexture")],te.prototype,"_bumpTexture",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"bumpTexture",void 0);M([qt("lightmapTexture")],te.prototype,"_lightmapTexture",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"lightmapTexture",void 0);M([qt("refractionTexture")],te.prototype,"_refractionTexture",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"refractionTexture",void 0);M([ss("ambient")],te.prototype,"ambientColor",void 0);M([ss("diffuse")],te.prototype,"diffuseColor",void 0);M([ss("specular")],te.prototype,"specularColor",void 0);M([ss("emissive")],te.prototype,"emissiveColor",void 0);M([C()],te.prototype,"specularPower",void 0);M([C("useAlphaFromDiffuseTexture")],te.prototype,"_useAlphaFromDiffuseTexture",void 0);M([ze("_markAllSubMeshesAsTexturesAndMiscDirty")],te.prototype,"useAlphaFromDiffuseTexture",void 0);M([C("useEmissiveAsIllumination")],te.prototype,"_useEmissiveAsIllumination",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useEmissiveAsIllumination",void 0);M([C("linkEmissiveWithDiffuse")],te.prototype,"_linkEmissiveWithDiffuse",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"linkEmissiveWithDiffuse",void 0);M([C("useSpecularOverAlpha")],te.prototype,"_useSpecularOverAlpha",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useSpecularOverAlpha",void 0);M([C("useReflectionOverAlpha")],te.prototype,"_useReflectionOverAlpha",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useReflectionOverAlpha",void 0);M([C("disableLighting")],te.prototype,"_disableLighting",void 0);M([ze("_markAllSubMeshesAsLightsDirty")],te.prototype,"disableLighting",void 0);M([C("useObjectSpaceNormalMap")],te.prototype,"_useObjectSpaceNormalMap",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useObjectSpaceNormalMap",void 0);M([C("useParallax")],te.prototype,"_useParallax",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useParallax",void 0);M([C("useParallaxOcclusion")],te.prototype,"_useParallaxOcclusion",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useParallaxOcclusion",void 0);M([C()],te.prototype,"parallaxScaleBias",void 0);M([C("roughness")],te.prototype,"_roughness",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"roughness",void 0);M([C()],te.prototype,"indexOfRefraction",void 0);M([C()],te.prototype,"invertRefractionY",void 0);M([C()],te.prototype,"alphaCutOff",void 0);M([C("useLightmapAsShadowmap")],te.prototype,"_useLightmapAsShadowmap",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useLightmapAsShadowmap",void 0);M([rr("diffuseFresnelParameters")],te.prototype,"_diffuseFresnelParameters",void 0);M([ze("_markAllSubMeshesAsFresnelDirty")],te.prototype,"diffuseFresnelParameters",void 0);M([rr("opacityFresnelParameters")],te.prototype,"_opacityFresnelParameters",void 0);M([ze("_markAllSubMeshesAsFresnelAndMiscDirty")],te.prototype,"opacityFresnelParameters",void 0);M([rr("reflectionFresnelParameters")],te.prototype,"_reflectionFresnelParameters",void 0);M([ze("_markAllSubMeshesAsFresnelDirty")],te.prototype,"reflectionFresnelParameters",void 0);M([rr("refractionFresnelParameters")],te.prototype,"_refractionFresnelParameters",void 0);M([ze("_markAllSubMeshesAsFresnelDirty")],te.prototype,"refractionFresnelParameters",void 0);M([rr("emissiveFresnelParameters")],te.prototype,"_emissiveFresnelParameters",void 0);M([ze("_markAllSubMeshesAsFresnelDirty")],te.prototype,"emissiveFresnelParameters",void 0);M([C("useReflectionFresnelFromSpecular")],te.prototype,"_useReflectionFresnelFromSpecular",void 0);M([ze("_markAllSubMeshesAsFresnelDirty")],te.prototype,"useReflectionFresnelFromSpecular",void 0);M([C("useGlossinessFromSpecularMapAlpha")],te.prototype,"_useGlossinessFromSpecularMapAlpha",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useGlossinessFromSpecularMapAlpha",void 0);M([C("maxSimultaneousLights")],te.prototype,"_maxSimultaneousLights",void 0);M([ze("_markAllSubMeshesAsLightsDirty")],te.prototype,"maxSimultaneousLights",void 0);M([C("invertNormalMapX")],te.prototype,"_invertNormalMapX",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"invertNormalMapX",void 0);M([C("invertNormalMapY")],te.prototype,"_invertNormalMapY",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"invertNormalMapY",void 0);M([C("twoSidedLighting")],te.prototype,"_twoSidedLighting",void 0);M([ze("_markAllSubMeshesAsTexturesDirty")],te.prototype,"twoSidedLighting",void 0);M([C("applyDecalMapAfterDetailMap")],te.prototype,"_applyDecalMapAfterDetailMap",void 0);M([ze("_markAllSubMeshesAsMiscDirty")],te.prototype,"applyDecalMapAfterDetailMap",void 0);Ye("BABYLON.StandardMaterial",te);je.DefaultMaterialFactory=o=>new te("default material",o);const sT=Object.freeze(Object.defineProperty({__proto__:null,StandardMaterial:te,StandardMaterialDefines:hu},Symbol.toStringTag,{value:"Module"}));lt.AddNodeConstructor("Light_Type_3",(o,e)=>()=>new Tr(o,p.Zero(),e));class Tr extends De{constructor(e,t,i,s){super(e,i,s),this.groundColor=new Re(0,0,0),this.direction=t||p.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=p.Normalize(e.subtract(p.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=p.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){const i=p.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=D.Identity()),this._worldMatrix}getTypeID(){return De.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}M([ss()],Tr.prototype,"groundColor",void 0);M([Ut()],Tr.prototype,"direction",void 0);Ye("BABYLON.HemisphericLight",Tr);const rT=Object.freeze(Object.defineProperty({__proto__:null,HemisphericLight:Tr},Symbol.toStringTag,{value:"Module"}));Ie.prototype.createDynamicTexture=function(o,e,t,i){const s=new xt(this,4);return s.baseWidth=o,s.baseHeight=e,t&&(o=this.needPOTTextures?ni(o,this._caps.maxTextureSize):o,e=this.needPOTTextures?ni(e,this._caps.maxTextureSize):e),s.width=o,s.height=e,s.isReady=!1,s.generateMipMaps=t,s.samplingMode=i,this.updateTextureSamplingMode(i,s),this._internalTexturesCache.push(s),s};Ie.prototype.updateDynamicTexture=function(o,e,t,i=!1,s,r=!1,n=!1){if(!o)return;const a=this._gl,h=a.TEXTURE_2D,l=this._bindTextureDirectly(h,o,!0,r);this._unpackFlipY(t===void 0?o.invertY:t),i&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(o.type),u=this._getInternalFormat(s||o.format),f=this._getRGBABufferInternalSizedFormat(o.type,u);a.texImage2D(h,0,f,u,c,e),o.generateMipMaps&&a.generateMipmap(h),l||this._bindTextureDirectly(h,null),i&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),s&&(o.format=s),o._dynamicTextureSource=e,o._premulAlpha=i,o.invertY=t||!1,o.isReady=!0};class wa extends G{constructor(e,t,i,s=!1,r=3,n=5,a){const h=!i||i._isScene,l=h?i:i?.scene,c=h?!s:i;super(null,l,c,a,r,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=G.CLAMP_ADDRESSMODE,this.wrapV=G.CLAMP_ADDRESSMODE,this._generateMipMaps=s;const u=this._getEngine();if(!u)return;if(t.getContext)this._canvas=t,this._ownCanvas=!1,this._texture=u.createDynamicTexture(this._canvas.width,this._canvas.height,s,r);else{this._canvas=u.createCanvas(1,1),this._ownCanvas=!0;const d=t;d.width||d.width===0?this._texture=u.createDynamicTexture(d.width,d.height,s,r):this._texture=u.createDynamicTexture(t,t,s,r)}const f=this.getSize();this._canvas.width!==f.width&&(this._canvas.width=f.width),this._canvas.height!==f.height&&(this._canvas.height=f.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){const t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){const i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){const t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._texture&&this._getEngine().updateDynamicTexture(this._texture,this._canvas,e===void 0?!0:e,t,this._format||void 0,void 0,i)}drawText(e,t,i,s,r,n,a,h=!0){const l=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,l.width,l.height)),this._context.font=s,t==null){const c=this._context.measureText(e);t=(l.width-c.width)/2}if(i==null){const c=parseInt(s.replace(/\D/g,""));i=l.height/2+c/3.65}this._context.fillStyle=r||"",this._context.fillText(e,t,i),h&&this.update(a)}dispose(){super.dispose(),this._ownCanvas&&this._canvas?.remove?.(),this._canvas=null,this._context=null}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new wa(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){const e=this.getScene();e&&!e.isReady()&&W.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return wa._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return e.toDataURL!==void 0}_rebuild(){this.update()}}export{jp as $,Hh as A,an as B,pc as C,Is as D,so as E,Di as F,Yg as G,vh as H,no as I,Ct as J,bi as K,wt as L,ts as M,Lm as N,Vr as O,yi as P,be as Q,bs as R,Fg as S,$m as T,ft as U,gi as V,Fs as W,ke as X,Re as Y,Ce as Z,qe as _,Bt as a,km as a$,I as a0,jo as a1,cf as a2,ml as a3,Gp as a4,Kp as a5,wp as a6,uo as a7,zc as a8,Io as a9,hn as aA,$c as aB,cn as aC,tu as aD,kl as aE,Td as aF,Gi as aG,Nc as aH,wm as aI,fo as aJ,Xc as aK,lp as aL,hp as aM,Hc as aN,Gc as aO,lo as aP,kc as aQ,Wc as aR,zs as aS,go as aT,po as aU,jc as aV,Yc as aW,Ao as aX,tn as aY,St as aZ,vi as a_,su as aa,_o as ab,Kc as ac,xo as ad,Qc as ae,Po as af,oo as ag,Uc as ah,Od as ai,sp as aj,np as ak,rp as al,ho as am,co as an,Vc as ao,Oi as ap,Mo as aq,iu as ar,dd as as,Vl as at,So as au,To as av,qc as aw,Eo as ax,yo as ay,eu as az,J as b,pr as b$,or as b0,Qm as b1,Au as b2,Xh as b3,Ua as b4,Ha as b5,hl as b6,Na as b7,Tt as b8,_l as b9,rg as bA,Jf as bB,Qe as bC,Kr as bD,Id as bE,Su as bF,$ as bG,ye as bH,ps as bI,im as bJ,Ke as bK,Xr as bL,hr as bM,Tu as bN,pd as bO,md as bP,pf as bQ,ro as bR,ln as bS,bo as bT,Ro as bU,Ns as bV,et as bW,Us as bX,Vu as bY,um as bZ,zi as b_,Sf as ba,sf as bb,ga as bc,Ih as bd,Ph as be,og as bf,Ep as bg,Wi as bh,Og as bi,rs as bj,ah as bk,lh as bl,Xf as bm,ue as bn,ai as bo,Om as bp,Cp as bq,ys as br,sh as bs,ih as bt,en as bu,vd as bv,wa as bw,it as bx,Cs as by,Qt as bz,At as c,al as c$,wg as c0,Vt as c1,nn as c2,oi as c3,on as c4,xd as c5,Gt as c6,rn as c7,Np as c8,qa as c9,fn as cA,Os as cB,Fm as cC,mr as cD,U_ as cE,er as cF,Tr as cG,xf as cH,bf as cI,Nr as cJ,Ka as cK,qm as cL,Vp as cM,Oe as cN,iT as cO,Sp as cP,Mp as cQ,xc as cR,ku as cS,jg as cT,mo as cU,xt as cV,zo as cW,Sh as cX,Ef as cY,Tl as cZ,Ur as c_,El as ca,xl as cb,un as cc,Rt as cd,Wh as ce,sl as cf,Pi as cg,Bp as ch,Ba as ci,Ul as cj,ni as ck,Of as cl,Wo as cm,k_ as cn,fd as co,yl as cp,mm as cq,Lp as cr,Nf as cs,gm as ct,yd as cu,xi as cv,$p as cw,hf as cx,lf as cy,Zt as cz,gt as d,di as d$,uh as d0,ls as d1,nl as d2,Ji as d3,mt as d4,Dl as d5,$s as d6,Nn as d7,eh as d8,Km as d9,Tp as dA,gl as dB,Mf as dC,Rs as dD,pl as dE,ms as dF,th as dG,lt as dH,Rf as dI,dl as dJ,jt as dK,z as dL,Eu as dM,qp as dN,Wr as dO,Zo as dP,sr as dQ,mf as dR,kf as dS,ot as dT,Mu as dU,Tm as dV,Qa as dW,lr as dX,ar as dY,Ks as dZ,If as d_,Br as da,Tf as db,De as dc,Be as dd,Wm as de,Ri as df,ki as dg,Or as dh,jr as di,Go as dj,W as dk,Qr as dl,V as dm,vo as dn,yp as dp,Pe as dq,Dt as dr,ws as ds,Fi as dt,kt as du,D as dv,Ya as dw,F as dx,cp as dy,Wg as dz,As as e,Hs as e$,dt as e0,nd as e1,Zs as e2,yf as e3,si as e4,Ym as e5,ve as e6,Ei as e7,Pl as e8,zf as e9,H_ as eA,W_ as eB,G_ as eC,z_ as eD,Ci as eE,V_ as eF,K_ as eG,Z_ as eH,q_ as eI,Q_ as eJ,Bf as eK,dr as eL,ig as eM,eg as eN,J_ as eO,tg as eP,Lf as eQ,Kg as eR,No as eS,Ps as eT,Zc as eU,re as eV,il as eW,Ad as eX,Zr as eY,tt as eZ,Pf as e_,Te as ea,Gm as eb,Hm as ec,qg as ed,Zm as ee,va as ef,Ne as eg,zr as eh,$i as ei,bc as ej,cg as ek,ug as el,zh as em,Op as en,Si as eo,O_ as ep,B_ as eq,N_ as er,io as es,fm as et,_r as eu,j_ as ev,Y_ as ew,X_ as ex,$_ as ey,C_ as ez,pm as f,hg as f$,za as f0,Ye as f1,eT as f2,yt as f3,od as f4,ti as f5,Vf as f6,pt as f7,qr as f8,Ga as f9,Af as fA,Yo as fB,Um as fC,js as fD,Ts as fE,st as fF,te as fG,hu as fH,yu as fI,Lt as fJ,rf as fK,qo as fL,Dp as fM,Kt as fN,nh as fO,Le as fP,ut as fQ,ol as fR,G as fS,nf as fT,em as fU,lg as fV,Yt as fW,_t as fX,Bi as fY,It as fZ,_a as f_,Fr as fa,gd as fb,Bl as fc,Uf as fd,_d as fe,Ru as ff,Dm as fg,ad as fh,Ss as fi,Wp as fj,je as fk,ce as fl,Pt as fm,Un as fn,me as fo,Wa as fp,Hi as fq,Z as fr,de as fs,bp as ft,gr as fu,Xm as fv,Ds as fw,ui as fx,Et as fy,Zi as fz,Tc as g,ru as g$,Mh as g0,Ai as g1,is as g2,Ie as g3,Mi as g4,ri as g5,tr as g6,xs as g7,Ni as g8,ir as g9,Hl as gA,Wl as gB,Gr as gC,ie as gD,p as gE,Me as gF,S as gG,j as gH,An as gI,Ys as gJ,id as gK,Js as gL,Ol as gM,Xu as gN,ed as gO,at as gP,Rd as gQ,Ue as gR,rh as gS,ud as gT,cd as gU,Bc as gV,wd as gW,bl as gX,Il as gY,Nh as gZ,Ng as g_,dp as ga,Jr as gb,Es as gc,Li as gd,Za as ge,Nm as gf,Bm as gg,Gs as gh,es as gi,U as gj,ul as gk,Ed as gl,ii as gm,vr as gn,fe as go,Vm as gp,zm as gq,xe as gr,zp as gs,jm as gt,Ap as gu,oe as gv,$r as gw,ou as gx,tT as gy,zl as gz,tl as h,yg as h$,Yr as h0,tm as h1,pe as h2,M as h3,he as h4,df as h5,vp as h6,wu as h7,$d as h8,b_ as h9,i_ as hA,A_ as hB,Nd as hC,rm as hD,hm as hE,a_ as hF,rT as hG,Bd as hH,sm as hI,om as hJ,n_ as hK,Ud as hL,nm as hM,lm as hN,o_ as hO,kd as hP,h_ as hQ,Ia as hR,Yd as hS,p_ as hT,qd as hU,E_ as hV,Cm as hW,Bg as hX,Xp as hY,Hp as hZ,Jm as h_,pg as ha,bm as hb,Mg as hc,Pm as hd,Up as he,dg as hf,xm as hg,fg as hh,Em as hi,Ig as hj,Im as hk,xg as hl,ym as hm,Lg as hn,_g as ho,Cg as hp,vm as hq,Jp as hr,ze as hs,zd as ht,c_ as hu,to as hv,v_ as hw,kp as hx,e_ as hy,S_ as hz,Qi as i,Mm as i0,Eg as i1,Sm as i2,Sg as i3,Am as i4,Tg as i5,Rm as i6,_i as i7,fr as i8,Hd as i9,gu as iA,qt as iB,uu as iC,Ut as iD,Yp as iE,ng as iF,sT as iG,Df as iH,we as iI,am as ia,cm as ib,d_ as ic,r_ as id,P_ as ie,sc as ig,I_ as ih,Zf as ii,Qf as ij,pi as ik,el as il,wc as im,Lc as io,ao as ip,Qp as iq,C as ir,pu as is,ss as it,La as iu,du as iv,rr as iw,_u as ix,Gh as iy,fu as iz,fi as j,Nl as k,Ff as l,Fp as m,Lr as n,Vi as o,Ui as p,Ve as q,Zp as r,vs as s,Ms as t,mc as u,D_ as v,dm as w,w_ as x,_m as y,L_ as z};
|