/*:
@plugindesc
3D rendering for RPG Maker MV, 
version 0.6.5 
@author Cutievirus

@help
Requires RPG Maker MV
	
This is the full version of MV3D. Please do not use it unless you are a
patron or have purchased a perpetual license from itch.io.

https://cutievirus.itch.io/mv3d
https://www.patreon.com/cutievirus


For assistance with the plugin, please join the discord:

Discord: http://cutievirus.com/discord  


For full documentation, please see the wiki:

https://mv3d.cutievirus.com/documentation



## Patron Heroes:

- AMemoryofEternity 
- Fyoha 
- 冬空 橙
- AmalgamAsh
- Goatse Man
- Kaine Lowe
- Anthony Xue
- Kaibris
- Galatic Acid
- Ricky Smith
- james gray
- Bird Man
- Matthias Herrmann
- OneDrive

## Patron Knights:

- CattleDog
- hsumi1 .
- Whitely
- L
- Nemo Ma
- Clumsydemonwithfire 
- Matteo Calbi
- RetroChaos
- Collin
- Trick
- Christian Cano
- MageisHero
- Rareica
- Jimmy McCarney
- Jesse 
- sef 
- Man Meat
- Jovon Hampton
- Joseph Reyes
- Brendan Lundy
- moxri 
- ManaBomb
- + 1 hidden




@command command
@text Legacy Command
@desc Use the old command syntax

@arg command
@text Command
@desc Enter the command without the mv3d/mz3d prefix.


@command camera
@text Camera
@desc Change the camera settings.

@arg pitch
@text Pitch
@desc Aims the camera up and down
@type number
@decimals 0
@min 0
@max 180

@arg yaw
@text Yaw
@desc Rotates the camera around the target
@type number
@decimals 0
@min 0
@max 360

@arg roll
@text Roll
@desc Tilts the camera side to side
@type number
@decimals 0
@min -360
@max 360

@arg dist
@text Distance
@desc The distance of the camera to the target (0=first person)
@type number
@decimals 3
@min 0

@arg zoom
@text Zoom
@desc Modifies the FOV to zoom the camera.
@type number
@decimals 4
@min -9999
@max 9999

@arg height
@text Height
@desc The height of the camera.
@type number
@decimals 3

@arg mode
@text Mode
@desc Switch between perspective mode and orthographic mode.
@type select
@option perspective
@option orthographic

@arg follow
@text Follow Target
@desc Which character should the camera follow?
(enter the event id, or the word "player")

@arg pan
@text Pan
@desc Pan the camera away from the target
@type struct<XY>

@arg time
@text Time
@desc Time in seconds to complete transition
@type number
@decimals 3
@min 0
@default 1


@command cameraTrack
@text Camera Tracking
@desc Automatically rotate the camera to face the tracking target.

@arg target
@text Target
@desc Enter the event id or "player". Leave blank to disable.

@arg trackYaw
@text Track Yaw
@type boolean
@default true

@arg trackPitch
@text Track Pitch
@type boolean
@default true

@arg time
@text Smoothness
@desc How smoothly the target will be tracked. Higher number = slower.
@type number
@decimals 3
@default 0


@command fog
@text Fog
@desc Change fog settings.

@arg color
@text Fog Color

@arg near
@text Start Distance
@type number
@decimals 3

@arg far
@text End Distance
@type number
@decimals 3

@arg time
@text Time
@type number
@decimals 3
@default 1


@command light
@text Lighting
@desc Change light settings.

@arg color
@text Ambient Color
@desc The ambient light lights everything in the scene.

@arg time
@text Time
@type number
@decimals 0
@default 1


@command lamp
@text Lamp
@desc Add a lamp lightsource to a character.

@arg target
@text Target
@desc Enter the event id or "player". Blank for current event.

@arg color
@text Color

@arg intensity
@text Intensity
@type number
@decimals 3
@min 0

@arg dist
@text Distance
@desc How far the light will travel.
@type number
@decimals 3
@min 0

@arg time
@text Time
@type number
@decimals 3
@default 1


@command flashlight
@text Flashlight
@desc Add a flashlight lightsource to a character.

@arg target
@text Target
@desc Enter the event id or "player". Blank for current event.

@arg color
@text Color

@arg intensity
@text Intensity
@type number
@decimals 3
@min 0

@arg dist
@text Distance
@desc How far the light will travel.
@type number
@decimals 3
@min 0

@arg angle
@text Beam Width
@desc An angle that describes the width of the beam.
@type number
@min 0 @max 360

@arg yaw
@text Yaw
@desc The horizontal angle of the flashlight beam.
@type number
@decimals 0
@min 0
@max 360

@arg pitch
@text Pitch
@desc The vertical angle of the flashlight beam.
@type number
@decimals 0
@min 0
@max 180

@arg time
@text Time
@type number
@decimals 3
@default 1


@command resolution
@text Resolution Scale
@desc Scale the resolution for a pixellated effect.

@arg scale
@text Scale
@desc Should be between 0 and 1.
@type number
@decimals 4
@min 0 @max 1
@default 1.0000

@arg time
@text Time
@type number
@decimals 3
@default 1


@command configure
@text Configure
@desc Change the target event's configuration

@arg target
@text Target
@desc Enter the event id or "player". Blank for current event.

@arg config
@text Configuration
@type note


@command set
@text Set Property
@desc Change the value of one of these properties

@arg property
@text Property
@type select
@option lockCamera
@option allowRotation
@option allowPitch
@option diagonalMovement
@option turnIncrement
@option inputCameraMouse
@option inputCameraGamepad
@option cameraCollision
@option airshipHeight

@arg value
@text Value

@command light
@text Lighting
@desc Change light settings.

@arg color
@text Ambient Color
@desc The ambient light lights everything in the scene. When sunlight is enabled, this is the color of the shadows.

@arg sunColor
@text Sunlight Color
@desc The color of the sunlight. Set to black to disable sunlight.

@arg sunYaw
@text Sunlight Yaw
@desc The horizontal angle of the sunlight and shadows.
@type number
@decimals 3
@min 0
@max 360

@arg sunPitch
@text Sunlight Pitch
@desc The vertical angle of the sunlight. Closer to 90 = longer shadows.
@type number
@decimals 0
@min -180
@max 180

@arg time
@text Time
@type number
@decimals 0
@default 1

@param options
@text Option Settings

@param 3dMenu
@text 3D Options Menu
@desc Whether 3D options will be in a submenu, regular options menu, or disabled.
@parent options
@type select
@option SUBMENU
@option ENABLE
@option DISABLE
@default ENABLE


@param renderDistOptionName
@text Render Distance Option Name
@desc symbol name: mv3d-renderDist
@parent options
@type text
@default Render Distance

@param renderDist
@text Render Distance Default
@desc The maximum distance that can be rendered by the camera.
@parent renderDistOptionName
@type number
@default 25
@min 0

@param renderDistOption
@text Render Distance Option
@desc Should Render Distance appear on options menu?
@parent renderDistOptionName
@type boolean
@default true

@param renderDistMin
@text Render Distance Min
@parent renderDistOptionName
@type number
@default 10
@min 0

@param renderDistMax
@text Render Distance Max
@parent renderDistOptionName
@type number
@default 100
@min 0


#param mipmapOptionName
#text Mipmapping Option Name
#desc symbol name: mv3d-mipmap
#parent options
#type text
#default Mipmapping

#param mipmap
#text Mipmapping Default
#parent mipmapOptionName
#type boolean
#default false

#param mipmapOption
#text Mipmapping Option
#desc Should Mipmapping appear on options menu?
#parent mipmapOptionName
#type boolean
#default true


@param fovOptionName
@text FOV Option Name
@desc symbol name: mv3d-fov
@parent options
@type text
@default FOV

@param fov
@text FOV Default
@parent fovOptionName
@type number
@default 70
@min 0 @max 180

@param fovOption
@text FOV Option
@desc Should FOV appear on options menu?
@parent fovOptionName
@type boolean
@default false

@param fovMin
@text FOV Min
@parent fovOptionName
@type number
@default 50
@min 0 @max 180

@param fovMax
@text FOV Max
@parent fovOptionName
@type number
@default 100
@min 0 @max 180

@param invertYOptionName
@text Invert Y Axis Option Name
@desc symbol name: mv3d-inverty
@parent options
@type text
@default Invert Y Axis

@param invertYOption
@text Invert Y Axis Option
@desc Should invert Y axis appear on options menu?
@parent invertYOptionName
@type boolean
@default true

@param lookSensitivityOptionName
@text Look Sensitivity Option Name
@desc symbol name: mv3d-looksensitivity
@parent options
@type text
@default Look Sensitivity

@param lookSensitivityOption
@text Look Sensitivity Option
@desc Should look sensitivity appear in options menu
@parent lookSensitivityOptionName
@type boolean
@default true

@param spacer|graphics @text‏‏‎ ‎@desc ===============================================

@param graphics
@text Graphics

@param antialiasing
@text Antialiasing
@parent graphics
@type boolean
@default true

@param edgefix
@text Edge Fix
@desc Fixes rendering issues at the edges of tiles.
@parent graphics
@type number
@decimals 1
@default 0.5

@param alphatest
@text Alpha Cutoff
@desc Pixels with alpha below this value will not be rendered.
@parent graphics
@type number
@decimals 2
@min 0.01 @max 1
@default 0.51

@param lightLimit
@text Lights Per Mesh
@parent graphics
@type number
@min 4
@default 8

@param backfaceCulling
@text Backface Culling
@parent graphics
@type boolean
@default true

@param cameraCollision
@text Camera Collision
@parent graphics
@type combo
@option Off
@option Type1
@option Type2
@option Type1 Smoothed
@option Type2 Smoothed
@default Type2 Smoothed

@param resScale
@text Resolution Scale
@desc Scale the resolution
@parent graphics
@type number
@decimals 2
@min 0 @max 1
@default 1

@param spacer|map @text‏‏‎ ‎@desc ===============================================

@param map
@text Map Settings

@param cellSize
@text Cell Size
@desc The size of the chunks the map is divided into.
@parent map
@type number
@default 10

@param unloadCells
@text Unload Far Cells
@desc Unload cells outside the render distance.
@parent map
@type boolean
@default false

@param eventsUpdateNear
@text Update All Events in Render Distance
@parent map
@type boolean
@default true

@param mapDefaults
@text Map Defaults
@parent map
@type note
@default
"enable(true)\nsun(white)\nambient(default)\nfog(black|20,100)\nceiling(backface:true)"


@param spacer|input @text‏‏‎ ‎@desc ===============================================

@param input
@text Input & Gameplay

@param inputCameraMouse
@text Mouse Camera Control
@parent input
@type boolean
@default false

@param inputCameraGamepad
@text Gamepad Camera Control
@parent input
@type boolean
@default true

@param inputGamepadTurnButton
@text Gamepad Turn Button
@parent input
@type select
@option Bumpers
@option Triggers
@option Unchanged
@default Bumpers

@param WASD
@text WASD
@parent input
@type boolean
@default true

@param dir8Movement
@text Diagonal Movement
@desc In smart mode, when diagonal movement fails, try moving straight.
@parent input
@type combo
@option Off
@option Diagonal Basic
@option Diagonal Basic 3D Only
@option Diagonal Smart
@option Diagonal Smart 3D Only
@default Diagonal Smart

@param keyboardPitch
@text Control Pitch
@parent input
@desc Allow player to change pitch with pageup & pagedown.
@type boolean
@default true

@param keyboardTurn
@text Allow Turning
@parent input
@desc Allows rotating camera with keyboard in 3rd person. Rotating is always allowed in 1st person.
@type select
@option Turn with Q+E (requires WASD) @value QE
@option Turn with A+D and left+right @value AD
@option disabled
@default QE

@param keyboardStrafe
@text Allow Strafing
@parent input
@desc Allows strafing in 1st person mode.
@type select
@option Strafe with Q+E (requires WASD) @value QE
@option Strafe with A+D and left+right @value AD
@option disabled
@default QE

@param turnIncrement
@text Turn Increment
@parent input
@desc How many degrees the camera will turn when you press the turn button. Other numbers may also be entered.
@type combo
@option 90
@option 45
@option SMOOTH
@default 90

@param yawSpeed
@text Turn Speed
@parent input
@desc Speed when turning with keyboard (in degrees per second).
@type number
@default 180

@param pitchSpeed
@text Pitch Speed
@parent input
@desc Speed when changing pitch with keyboard (in degrees per second).
@type number
@default 90


@param stairThresh
@text Stair Threshold
@desc If the distance in height between two tiles is less than this, they will be passable.
@parent input
@type number
@decimals 2
@default 0.1

@param walkOffEdge
@text Walk off Edge
@parent input
@type boolean
@default false

@param walkOnEvents
@text Walk on Events
@parent input
@type boolean
@default true

@param gravity
@text Gravity
@desc The speed characters will fall, in tiles per second.
@parent input
@type number
@decimals 2
@default 8

@param spacer|tileconfig @text‏‏‎ ‎@desc ===============================================

@param tileconfig
@text Tile Config

@param wallTileSettings
@text Wall Tile Settings
@desc The default tile settings for wall tiles.
@parent tileconfig
@type note
@default "height(2)"

@param tableTileSettings
@text Table Tile Settings
@desc The default tile settings for table tiles.
@parent tileconfig
@type note
@default "height(0.33)"

@param starTileSettings
@text Star Tile Settings
@desc The default tile settings for star tiles.
@parent tileconfig
@type note
@default "fringe(2)\npass(*)"

@param ceilingHeight
@text Ceiling Height
@desc Default height of ceiling for maps with ceiling enabled.
@parent tileconfig
@type number
@min -9999 @max 9999
@decimals 3
@default 2.0

@param baseHeight
@text Base Height
@desc Extra height added to every tile on the map.
@parent tileconfig
@type number
@min 0 @max 1
@decimals 3
@default 0.25

@param layerDist
@text Layering Distance
@desc The distance between tile layers. If this is too small
there may be z-fighting issues. (default: 0.0100)
@parent tileconfig
@type number
@decimals 4
@default 0.0100

@param animDelay
@text Animation Speed
@desc The number of milliseconds between each frame in tile animations.
@parent tileconfig
@type number
@default 333

@param regions
@text Regions
@desc use regions to determine tile height.
@parent tileconfig
@type struct<RegionHeight>[]
@default ["{\"regionId\":\"1\",\"conf\":\"height(1)\"}","{\"regionId\":\"2\",\"conf\":\"height(2)\"}","{\"regionId\":\"3\",\"conf\":\"height(3)\"}","{\"regionId\":\"4\",\"conf\":\"height(4)\"}","{\"regionId\":\"5\",\"conf\":\"height(5)\"}","{\"regionId\":\"6\",\"conf\":\"height(6)\"}","{\"regionId\":\"7\",\"conf\":\"height(7)\"}"]

@param ttags
@text Terrain Tags
@desc use terrain tags to determine tile height.
@parent tileconfig
@type struct<TTagHeight>[]
@default ["{\"terrainTag\":\"1\",\"conf\":\"shape(xcross),height(1),fringe(0)\"}","{\"terrainTag\":\"2\",\"conf\":\"shape(fence),height(1)\"}"]

@param spacer|characters @text‏‏‎ ‎@desc ===============================================

@param characters
@text Characters

@param heightTrigger
@text Event Trigger Height
@desc If true, events will need to be at the same elevation as the player to be triggered.
@parent characters
@type boolean
@default true

@param eventCharDefaults
@text Character Event Settings
@parent characters
@type note
@default "shadow(0.8,4)\nshape(sprite)\nscale(1)"

@param eventObjDefaults
@text Object Event Settings
@parent characters
@type note
@default "shadow(0)\nshape(sprite)\nscale(1)"

@param eventTileDefaults
@text Tile Event Settings
@parent characters
@type note
@default "shadow(0)\nshape(flat)\nscale(1)"

@param eventHeight
@text Event "Above Characters" Default Height
@parent characters
@type number
@decimals 1
@default 2.0

@param boatSettings
@text Boat Settings
@parent characters
@type struct<BoatStruct>
@default {"conf":"shadow(0.8,4),shape(sprite),scale(1),bush(false)"}

@param shipSettings
@text Ship Settings
@parent characters
@type struct<BoatStruct>
@default {"conf":"shadow(0.8,4),shape(sprite),scale(1),bush(false)"}

@param airshipSettings
@text Airship Settings
@parent characters
@type struct<AirshipStruct>
@default {"conf":"shadow(1,6),shape(sprite),scale(1),bush(false)","height":"2.0","bushLanding":"false"}

@param allowGlide
@text Allow Glide
@desc If true, collision detection for flying characters will use only current elevation and not target elevation.
@parent characters
@type boolean
@default true

@param spriteOffset
@text Sprite Offset
@parent characters
@type number
@min 0 @max 1
@decimals 2
@default 0.9

@param spacer|assets @text‏‏‎ ‎@desc ===============================================

@param assets
@text Assets

@param diagSymbol
@text Diagonal Sprite Symbol
@desc Character sheets with this symbol contain diagonal sprites. Leave blank to use diagonal sprites with all images.
@parent assets
@type text
@default {d}

@param shadowTexture
@text Shadow Texture
@parent assets
@type file
@dir img/MZ3D
@require 1
@default shadow

@param alphaMask
@text Bush Alpha Texture
@parent assets
@type file
@dir img/MZ3D
@require 1
@default bushAlpha

@param errorTexture
@text Error Texture
@parent assets
@type file
@dir img/MZ3D
@require 1
@default errorTexture

@param requiredImages
@text Other Required Images
@desc Specify additional images here to prevent them from being excluded during deployment.
@parent assets
@type file[]
@dir img/MZ3D
@require 1


@param spacer|shadow @text‏‏‎ ‎@desc ===============================================

@param shadow
@text Light & Shadow

@param dynShadowEnabled
@text Use Dynamic Shadows
@parent shadow
@type boolean
@default true

@param defShadowQuality
@text Default Shadow Quality
@parent shadow
@type combo
@option OFF
@option LOW
@option MEDIUM
@option HIGH
@default MEDIUM

@param shadowQualityOptionName
@text Shadow Quality Option Name
@desc symbol name: mv3d-dynShadow
@parent shadow
@type text
@default Shadow Quality

@param softShadows
@text Soft Shadows
@parent shadow
@type boolean
@default true

@param abnormal
@text Cross Normals Face Up
@desc Removes the darkness on fence and cross back faces.
@parent shadow
@type boolean
@default true

@param dynamicNormals
@text Dynamic Normals
@desc Characters won't be shaded when facing away from the sun.
@parent shadow
@type boolean
@default true

@param spacer|postProcessing @text‏‏‎ ‎@desc ===============================================

@param postProcessing
@text Post-Processing and Effects

@param alphaFog
@text Alpha Fog
@parent postProcessing
@desc How far the alpha fog will reach. 0=off, 1=full
@type number
@decimals 4
@min 0 @max 1
@default 0.1

@param glow
@text Glow Effect
@parent postProcessing
@desc The intensity of the glow effect.
@type combo
@option Off
@option 0.5
@option 1.0
@option 2.0
@default Off

@param glowRadius
@text Glow Radius
@parent postProcessing
@desc The size of the glow effect.
@type number
@decimals 0
@min 0
@default 48
*/
/*~struct~RegionHeight:
@param regionId
@text Region Id
@type number
@min 1 @max 255
@default 1

@param conf
@text Configuration Functions
@desc See tileset configuration for list of functions
@type text
@default height(2)
*/

/*~struct~TTagHeight:
@param terrainTag
@text Terrain Tag
@type number
@min 1 @max 7
@default 1

@param conf
@text Configuration Functions
@desc See tileset configuration for list of functions
@type text
@default shape(flat),height(0)
*/

/*~struct~BoatStruct:
@param conf
@text Settings
@type text
@default shadow(0.8,4),shape(sprite),scale(1),bush(false)

*/

/*~struct~AirshipStruct:
@param conf
@text Settings
@type text
@default shadow(1,6),shape(sprite),scale(1),bush(false)

@param height
@text Elevation
@type number
@decimals 1
@default 2.0

@param bushLanding
@text Land on Bush Tiles
@desc Whether the airship can land on bush tiles.
@type boolean
@default false

*/

/*~struct~XY:
@param x
@text X
@type number
@decimals 3
@default 0

@param y
@text Y
@type number
@decimals 3
@default 0

*/


/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 4);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeColor", function() { return makeColor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hexNumber", function() { return hexNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "relativeNumber", function() { return relativeNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "relativeBlend", function() { return relativeBlend; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "booleanNumber", function() { return booleanNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "booleanString", function() { return booleanString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "falseString", function() { return falseString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sleep", function() { return sleep; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "degtorad", function() { return degtorad; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "radtodeg", function() { return radtodeg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pointtorad", function() { return pointtorad; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pointtodeg", function() { return pointtodeg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sin", function() { return sin; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cos", function() { return cos; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unround", function() { return unround; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "minmax", function() { return minmax; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tileSize", function() { return tileSize; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tileWidth", function() { return tileWidth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tileHeight", function() { return tileHeight; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "optimalFrustrumWidth", function() { return optimalFrustrumWidth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "optimalFrustrumHeight", function() { return optimalFrustrumHeight; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "file", function() { return file; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filename", function() { return filename; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "foldername", function() { return foldername; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deprecated", function() { return deprecated; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throttle", function() { return throttle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dirtoh", function() { return dirtoh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dirtov", function() { return dirtov; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hvtodir", function() { return hvtodir; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "overload", function() { return overload; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "override", function() { return override; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "assign", function() { return assign; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "XAxis", function() { return XAxis; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "YAxis", function() { return YAxis; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ZAxis", function() { return ZAxis; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "v2origin", function() { return v2origin; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "v3origin", function() { return v3origin; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PI", function() { return PI; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PI2", function() { return PI2; });
/* harmony import */ var _main_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);


const {Vector2,Vector3,Color3,Color4} = window.BABYLON;

const makeColor = color=>{
	if (typeof color === 'number'){
		return {
			r: (color>>16)/255,
			g: (color>>8&255)/255,
			b: (color&255)/255,
			a: 1,
		};
	}else if(color instanceof Color3){
		return color.toColor4();
	}else if(color instanceof Color4){
		return color;
	}else{
		const canvas = document.createElement('canvas');
		canvas.width=1; canvas.height=1;
		const context = canvas.getContext('2d');
		context.fillStyle = color; context.fillRect(0,0,1,1);
		const bytes = context.getImageData(0,0,1,1).data;
		return new Color4(bytes[0]/255,bytes[1]/255,bytes[2]/255,bytes[3]/255);
	}
}


const hexNumber=n=>{
	n=String(n);
	if(n.startsWith('#')){
		n=n.substr(1);
	}
	return Number.parseInt(n,16);
};

const relativeNumber=(current,n)=>{
	if(n===''){ return +current; }
	const relative = /^[+]/.test(n);
	if(relative){n=n.substr(1);}
	n=Number(n);
	if(Number.isNaN(n)){ return +current; }
	if(relative){
		return +current+n;
	}else{
		return +n;
	}
};

const relativeBlend=(blender,n,time)=>{
	const relative = String(n).startsWith('+');
	blender.setValue(relativeNumber(blender.targetValue(),n),Number(time),!relative);
};

const booleanNumber=s=>{
	if(!isNaN(s)){return Number(s);}
	return booleanString(s);
};
const booleanString=s=>{
	return Boolean(falseString(s));
};
const falseString=s=>{
	if(!s){ return false; }
	if(typeof s !=='string'){ s=String(s); }
	const S=s.toUpperCase();
	if(falseString.values.includes(S)){
		return false;
	}
	return s;
};
falseString.values=['OFF','FALSE','UNDEFINED','NULL','DISABLE','DISABLED'];

const sleep=(ms=0)=>new Promise(resolve=>setTimeout(resolve,ms));
const degtorad=deg=>deg*Math.PI/180;
const radtodeg=rad=>rad*180/Math.PI;

const pointtorad=(x,y)=>Math.atan2(-y,x)-Math.PI/2;
const pointtodeg=(x,y)=>radtodeg(pointtorad(x,y));

const sin=r=>unround(Math.sin(r),1e15);
const cos=r=>unround(Math.cos(r),1e15);

const unround=(n,m=1e15)=>Math.round(n*m)/m;

const minmax=(min,max,v)=>Math.min(max,Math.max(min,v));

const tileSize=()=>tileWidth();
const tileWidth=()=>Game_Map.prototype.tileWidth();
const tileHeight=()=>Game_Map.prototype.tileHeight();
const optimalFrustrumWidth=()=>Graphics.width/48;
const optimalFrustrumHeight=()=>Graphics.height/48;

const file=(folder=_main_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].MV3D_FOLDER,name)=>{
	if(name.startsWith('/')){ return '.'+name; }
	else if(name.startsWith('./')){ return name; }
	if(folder.startsWith('/')){ folder='.'+folder; }
	else if(!folder.startsWith('./')&&folder!=='.'){ folder='./'+folder; }
	return `${folder}${folder.endsWith('/')?'':'/'}${name}`;
};

const filename=path=>{path=path.split('/');return path[path.length-1];}
const foldername=path=>{path=path.split('/');path.pop();return path.join('/')+'/';}

const issuedWarnings={};
const deprecated=message=>{
	if(message in issuedWarnings){ return; }
	issuedWarnings[message]=true;
	console.warn(message);
};

const throttle=(func,interval=100)=>{
	let last_call = 0;
	return function(){
		if(Date.now()-last_call>interval){
			func.apply(this,arguments);
			last_call = Date.now();
		}
	};
}

// directions

const dirtoh=d=>5 + ((d-1)%3-1);
const dirtov=d=>5 + (Math.floor((d-1)/3)-1)*3;
const hvtodir=(h,v)=>5 + (Math.floor((v-1)/3)-1)*3 + ((h-1)%3-1);

// overloading

const overload=funcs=>{
	const overloaded = function(){
		const l=arguments.length;
		if(typeof funcs[l] === 'function'){
			return funcs[l].apply(this,arguments);
		}else if(typeof funcs.default === 'function'){
			return funcs.default.apply(this,arguments);
		}else{ console.warn("Unsupported number of arguments."); }
	}
	for(const key in funcs){
		overloaded[key]=funcs[key].bind
	}
	return overloaded;
};

// override
const _override_default_condition=()=>!_main_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isDisabled();
const override=(obj,methodName,getNewMethod,condition=_override_default_condition)=>{
	const oldMethod = obj[methodName];
	const newMethod = getNewMethod(oldMethod);
	const overrider = function(){
		if(!(typeof condition==='function'?condition():condition)){ return oldMethod.apply(this,arguments); }
		return newMethod.apply(this,arguments);
	};
	Object.defineProperty(overrider,'name',{value:`${methodName}<mv3d_override>`});
	Object.defineProperty(newMethod,'name',{value:`${methodName}<mv3d>`});
	overrider.oldMethod=oldMethod; overrider.newMethod=newMethod;
	return obj[methodName] = overrider;
};

// assign
const assign=(obj,methods)=>{
	for (const key in methods){
		const descriptor = Object.getOwnPropertyDescriptor(methods,key);
		if (descriptor.get||descriptor.set){
			Object.defineProperty(obj,key,descriptor);
		}else if(methods[key] instanceof _main_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Attribute){
			const attribute = methods[key];
			Object.defineProperty(obj,key,attribute.descriptor);
		}else{
			obj[key]=methods[key];
		}
	}
};


// useful consts
const XAxis = new Vector3(1,0,0);
const YAxis = new Vector3(0,1,0);
const ZAxis = new Vector3(0,0,1);
const v2origin = new Vector2(0,0);
const v3origin = new Vector3(0,0,0);

const PI = Math.PI;
const PI2 = Math.PI*2;


/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var babylonjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var babylonjs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _mod_babylon_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(0);






const mz3d = {
	util:_util_js__WEBPACK_IMPORTED_MODULE_2__,

	setup(){
		this.setupParameters();
		Object(_mod_babylon_js__WEBPACK_IMPORTED_MODULE_1__[/* setupBabylonMods */ "i"])();

		this.canvas = document.createElement('canvas');
		this.texture = PIXI.Texture.from(this.canvas);
		this.texture.destroy = function(){};
		this.texture.baseTexture.scaleMode=PIXI.SCALE_MODES.NEAREST;
		this.engine = new babylonjs__WEBPACK_IMPORTED_MODULE_0__["Engine"](this.canvas,this.ANTIALIASING);
		this.scene = new babylonjs__WEBPACK_IMPORTED_MODULE_0__["Scene"](this.engine);
		//this.scene.clearColor.a=0;
		this.scene.clearColor.set(0,0,0,0);

		//this.engine.forcePOTTextures=true;

		this.cameraStick = new babylonjs__WEBPACK_IMPORTED_MODULE_0__["TransformNode"]("cameraStick",this.scene);
		this.cameraNode = new babylonjs__WEBPACK_IMPORTED_MODULE_0__["TransformNode"]("cameraNode",this.scene);
		this.cameraNode.parent=this.cameraStick;
		this.camera = new babylonjs__WEBPACK_IMPORTED_MODULE_0__["FreeCamera"]("camera",new babylonjs__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0,0,0),this.scene);
		this.camera.parent=this.cameraNode;
		this.camera.fov=Object(_util_js__WEBPACK_IMPORTED_MODULE_2__["degtorad"])(mz3d.FOV);
		/*
		this.camera.orthoLeft=-Graphics.width/2/tileSize();
		this.camera.orthoRight=Graphics.width/2/tileSize();
		this.camera.orthoTop=Graphics.height/2/tileSize();
		this.camera.orthoBottom=-Graphics.height/2/tileSize();
		*/
		this.camera.minZ=0.1;
		this.camera.maxZ=this.RENDER_DIST;

		//this.scene.activeCameras.push(this.camera);

		this.scene.ambientColor = new babylonjs__WEBPACK_IMPORTED_MODULE_0__["Color3"](1,1,1);
		this.scene.fogMode=_mod_babylon_js__WEBPACK_IMPORTED_MODULE_1__[/* FOGMODE_LINEAR */ "c"];

		this.map = new babylonjs__WEBPACK_IMPORTED_MODULE_0__["Node"]("map",this.scene);
		this.cells={};
		this.characters=[];

		this.setupBlenders();
		//this.updateBlenders(true);
		this.setupInput();

		this.setupSpriteMeshes();

		this.callFeatures('setup');

	},

	updateCanvas(){
		this.canvas.width = Graphics._width*mz3d.RES_SCALE;
		this.canvas.height = Graphics._height*mz3d.RES_SCALE;
	},

	render(){
		if(!this.texture.baseTexture){ return; }
		this.scene.render();
		this.texture.update();
		//this.callFeatures('render');
	},

	lastMapUpdate:0,
	update(){
		if( performance.now()-this.lastMapUpdate > 1000 && !this.mapUpdating ){
			this.updateMap();
			this.lastMapUpdate=performance.now();
		}

		this.updateAnimations();

		this.updateCharacters();

		this.intensiveUpdate();

		this.updateBlenders();

		// input
		this.updateInput();

		for (const key in this.cells){
			this.cells[key].update();
		}

		this.callFeatures('update');

		//this.updateData();
	},

	loadData(key,dfault){
		if(!$gameVariables || !$gameVariables.mv3d || !(key in $gameVariables.mv3d)){ return dfault; }
		return $gameVariables.mv3d[key];
	},
	saveData(key,value){
		if(!$gameVariables){ return console.warn(`MV3D: Couldn't save data ${key}:${value}`); }
		if(!$gameVariables.mv3d){ $gameVariables.mv3d={}; }
		$gameVariables.mv3d[key]=value;
	},
	clearData(key){
		if(!$gameVariables){ return console.warn(`MV3D: Couldn't clear data ${key}`); }
		if(!$gameVariables.mv3d){ return; }
		delete $gameVariables.mv3d[key];
	},

	updateCameraMode(){
		const mode = this.cameraMode;
		let updated=false;
		if(mode.startsWith('O')){
			if(this.camera.mode!==_mod_babylon_js__WEBPACK_IMPORTED_MODULE_1__[/* ORTHOGRAPHIC_CAMERA */ "f"]){ this.camera.mode=_mod_babylon_js__WEBPACK_IMPORTED_MODULE_1__[/* ORTHOGRAPHIC_CAMERA */ "f"]; updated=true; }
		}else{
			if(this.camera.mode!==_mod_babylon_js__WEBPACK_IMPORTED_MODULE_1__[/* PERSPECTIVE_CAMERA */ "g"]){ this.camera.mode=_mod_babylon_js__WEBPACK_IMPORTED_MODULE_1__[/* PERSPECTIVE_CAMERA */ "g"]; updated=true; }
		}
		if(updated){
			this.updateBlenders(true);
			this.callFeatures('updateCameraMode');
			this.updateParameters();
		}
	},
	get cameraMode(){
		return this.loadData('cameraMode',this.CAMERA_MODE).toUpperCase();
	},
	set cameraMode(v){
		v = String(v).toUpperCase().startsWith('O') ? 'ORTHOGRAPHIC' : 'PERSPECTIVE' ;
		this.saveData('cameraMode',v);
		this.updateBlenders(true);
	},

	is1stPerson(useCurrent){
		const k = useCurrent?'currentValue':'targetValue';
		return this.getCameraTarget()===$gamePlayer && this.blendCameraTransition[k]()<=0
		&& this.blendCameraDist[k]()<=0 && this.blendPanX[k]()===0 && this.blendPanY[k]()===0;
	},

	isDisabled(){
		return this.loadData('disabled', this.getMapConfig('disabled', false ));
	},
	disable(fadeType=2){
		mz3d.saveData('disabled',true);
		//SceneManager.goto(Scene_Map);
		$gamePlayer.reserveTransfer($gameMap.mapId(),$gamePlayer.x,$gamePlayer.y,$gamePlayer.direction(),fadeType);
	},
	enable(fadeType=2){
		mz3d.saveData('disabled',false);
		//SceneManager.goto(Scene_Map);
		$gamePlayer.reserveTransfer($gameMap.mapId(),$gamePlayer.x,$gamePlayer.y,$gamePlayer.direction(),fadeType);
		mz3d.createCharacters();
	},

	loopCoords(x,y){
		if(this.loopHorizontal()){
			const mapWidth=mz3d.mapWidth();
			const ox = this.cameraStick.x - mapWidth/2;
			x=(x-ox).mod(mapWidth)+ox;
		}
		if(this.loopVertical()){
			const mapHeight=mz3d.mapHeight();
			const oy = this.cameraStick.y - mapHeight/2;
			y=(y-oy).mod(mapHeight)+oy;
		}
		return new babylonjs__WEBPACK_IMPORTED_MODULE_0__["Vector2"](x,y);
	},

	getFieldSize(dist=mz3d.blendCameraDist.currentValue()){
		const size = Math.tan(mz3d.camera.fov/2)*dist*2;
		return {
			width:size*mz3d.engine.getAspectRatio(mz3d.camera),
			height:size,
		};
	},
	getScaleForDist(dist=mz3d.blendCameraDist.currentValue()){
		return Graphics.height/this.getFieldSize(dist).height/48;
	},
	getFovForDist(dist=mz3d.blendCameraDist.currentValue(),height=Object(_util_js__WEBPACK_IMPORTED_MODULE_2__["optimalFrustrumHeight"])()){
		return 2*Math.atan(height/2/dist);
	},
	getDistForFov(fov=mz3d.camera.fov,height=Object(_util_js__WEBPACK_IMPORTED_MODULE_2__["optimalFrustrumHeight"])()){
		return height/2/Math.tan(fov/2);
	},
	getFrustrumHeight(dist=mz3d.blendCameraDist.currentValue(),fov=mz3d.camera.fov){
		return 2*dist*Math.tan(fov/2);
	},


	getScreenPosition(node,offset=babylonjs__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero()){
		const matrix = node.parent ? node.parent.getWorldMatrix() : babylonjs__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Identity();
		const pos = node instanceof babylonjs__WEBPACK_IMPORTED_MODULE_0__["Vector3"] ? node.add(offset) : node.position.add(offset);
		const projected = babylonjs__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Project(pos,matrix,mz3d.scene.getTransformMatrix(),mz3d.camera.viewport);
		return {x:projected.x*Graphics.width, y:projected.y*Graphics.height, behindCamera:projected.z>1};
	},
	
	getUnscaledMatrix(mesh){
		const matrix = mesh.getWorldMatrix();
		const qrot=new babylonjs__WEBPACK_IMPORTED_MODULE_0__["Quaternion"](), vtrans=new babylonjs__WEBPACK_IMPORTED_MODULE_0__["Vector3"]();
		matrix.decompose(null,qrot,vtrans);
		return babylonjs__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Compose(babylonjs__WEBPACK_IMPORTED_MODULE_0__["Vector3"].One(),qrot,vtrans);
	},
	getTranslationMatrix(mesh){
		const matrix = mesh.getWorldMatrix();
		const vrot=babylonjs__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), vtrans=new babylonjs__WEBPACK_IMPORTED_MODULE_0__["Vector3"]();
		vrot.y=-Object(_util_js__WEBPACK_IMPORTED_MODULE_2__["degtorad"])(mz3d.blendCameraYaw.currentValue());
		vrot.x=-Object(_util_js__WEBPACK_IMPORTED_MODULE_2__["degtorad"])(mz3d.blendCameraPitch.currentValue()-90);
		matrix.decompose(null,null,vtrans);
		return babylonjs__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Compose(babylonjs__WEBPACK_IMPORTED_MODULE_0__["Vector3"].One(),vrot.toQuaternion(),vtrans);
	},
	getRotationMatrix(mesh){
		const matrix = mesh.getWorldMatrix();
		const qrot=new babylonjs__WEBPACK_IMPORTED_MODULE_0__["Quaternion"]();
		matrix.decompose(null,qrot,null);
		return babylonjs__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Compose(babylonjs__WEBPACK_IMPORTED_MODULE_0__["Vector3"].One(),qrot,babylonjs__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero());
	},

	globalPosition(node){
		const matrix = node.parent ? node.parent.getWorldMatrix() : babylonjs__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Identity();
		return babylonjs__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformCoordinates(node.position,matrix);
	},

}
window.mv3d=window.mz3d=mz3d;
/* harmony default export */ __webpack_exports__["a"] = (mz3d);

/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {

!function(e,t){ true?module.exports=t():undefined}("undefined"!=typeof self?self:"undefined"!=typeof global?global:this,function(){return function(e){var t={};function i(n){if(t[n])return t[n].exports;var r=t[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,i),r.l=!0,r.exports}return i.m=e,i.c=t,i.d=function(e,t,n){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)i.d(n,r,function(t){return e[t]}.bind(null,r));return n},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=151)}([function(e,t,i){"use strict";i.d(t,"d",function(){return s}),i.d(t,"e",function(){return c}),i.d(t,"f",function(){return l}),i.d(t,"b",function(){return u}),i.d(t,"a",function(){return h}),i.d(t,"c",function(){return f});var n=i(14),r=i(28),o=i(42),a=i(12),s=function(){function e(e,t){void 0===e&&(e=0),void 0===t&&(t=0),this.x=e,this.y=t}return e.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+"}"},e.prototype.getClassName=function(){return"Vector2"},e.prototype.getHashCode=function(){var e=0|this.x;return e=397*e^(0|this.y)},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,this},e.prototype.asArray=function(){var e=new Array;return this.toArray(e,0),e},e.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this},e.prototype.copyFromFloats=function(e,t){return this.x=e,this.y=t,this},e.prototype.set=function(e,t){return this.copyFromFloats(e,t)},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y)},e.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,this},e.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this},e.prototype.addVector3=function(t){return new e(this.x+t.x,this.y+t.y)},e.prototype.subtract=function(t){return new e(this.x-t.x,this.y-t.y)},e.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,this},e.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this},e.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this},e.prototype.multiply=function(t){return new e(this.x*t.x,this.y*t.y)},e.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,this},e.prototype.multiplyByFloats=function(t,i){return new e(this.x*t,this.y*i)},e.prototype.divide=function(t){return new e(this.x/t.x,this.y/t.y)},e.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,this},e.prototype.divideInPlace=function(e){return this.divideToRef(e,this)},e.prototype.negate=function(){return new e(-this.x,-this.y)},e.prototype.negateInPlace=function(){return this.x*=-1,this.y*=-1,this},e.prototype.negateToRef=function(e){return e.copyFromFloats(-1*this.x,-1*this.y)},e.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this},e.prototype.scale=function(t){var i=new e(0,0);return this.scaleToRef(t,i),i},e.prototype.scaleToRef=function(e,t){return t.x=this.x*e,t.y=this.y*e,this},e.prototype.scaleAndAddToRef=function(e,t){return t.x+=this.x*e,t.y+=this.y*e,this},e.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y},e.prototype.equalsWithEpsilon=function(e,t){return void 0===t&&(t=r.a),e&&n.a.WithinEpsilon(this.x,e.x,t)&&n.a.WithinEpsilon(this.y,e.y,t)},e.prototype.floor=function(){return new e(Math.floor(this.x),Math.floor(this.y))},e.prototype.fract=function(){return new e(this.x-Math.floor(this.x),this.y-Math.floor(this.y))},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},e.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},e.prototype.normalize=function(){var e=this.length();return 0===e?this:(this.x/=e,this.y/=e,this)},e.prototype.clone=function(){return new e(this.x,this.y)},e.Zero=function(){return new e(0,0)},e.One=function(){return new e(1,1)},e.FromArray=function(t,i){return void 0===i&&(i=0),new e(t[i],t[i+1])},e.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1]},e.CatmullRom=function(t,i,n,r,o){var a=o*o,s=o*a;return new e(.5*(2*i.x+(-t.x+n.x)*o+(2*t.x-5*i.x+4*n.x-r.x)*a+(-t.x+3*i.x-3*n.x+r.x)*s),.5*(2*i.y+(-t.y+n.y)*o+(2*t.y-5*i.y+4*n.y-r.y)*a+(-t.y+3*i.y-3*n.y+r.y)*s))},e.Clamp=function(t,i,n){var r=t.x;r=(r=r>n.x?n.x:r)<i.x?i.x:r;var o=t.y;return new e(r,o=(o=o>n.y?n.y:o)<i.y?i.y:o)},e.Hermite=function(t,i,n,r,o){var a=o*o,s=o*a,c=2*s-3*a+1,l=-2*s+3*a,u=s-2*a+o,h=s-a;return new e(t.x*c+n.x*l+i.x*u+r.x*h,t.y*c+n.y*l+i.y*u+r.y*h)},e.Lerp=function(t,i,n){return new e(t.x+(i.x-t.x)*n,t.y+(i.y-t.y)*n)},e.Dot=function(e,t){return e.x*t.x+e.y*t.y},e.Normalize=function(e){var t=e.clone();return t.normalize(),t},e.Minimize=function(t,i){return new e(t.x<i.x?t.x:i.x,t.y<i.y?t.y:i.y)},e.Maximize=function(t,i){return new e(t.x>i.x?t.x:i.x,t.y>i.y?t.y:i.y)},e.Transform=function(t,i){var n=e.Zero();return e.TransformToRef(t,i,n),n},e.TransformToRef=function(e,t,i){var n=t.m,r=e.x*n[0]+e.y*n[4]+n[12],o=e.x*n[1]+e.y*n[5]+n[13];i.x=r,i.y=o},e.PointInTriangle=function(e,t,i,n){var r=.5*(-i.y*n.x+t.y*(-i.x+n.x)+t.x*(i.y-n.y)+i.x*n.y),o=r<0?-1:1,a=(t.y*n.x-t.x*n.y+(n.y-t.y)*e.x+(t.x-n.x)*e.y)*o,s=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*o;return a>0&&s>0&&a+s<2*r*o},e.Distance=function(t,i){return Math.sqrt(e.DistanceSquared(t,i))},e.DistanceSquared=function(e,t){var i=e.x-t.x,n=e.y-t.y;return i*i+n*n},e.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},e.DistanceOfPointFromSegment=function(t,i,n){var r=e.DistanceSquared(i,n);if(0===r)return e.Distance(t,i);var o=n.subtract(i),a=Math.max(0,Math.min(1,e.Dot(t.subtract(i),o)/r)),s=i.add(o.multiplyByFloats(a,a));return e.Distance(t,s)},e}(),c=function(){function e(e,t,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),this.x=e,this.y=t,this.z=i}return e.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+"}"},e.prototype.getClassName=function(){return"Vector3"},e.prototype.getHashCode=function(){var e=0|this.x;return e=397*(e=397*e^(0|this.y))^(0|this.z)},e.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,this},e.prototype.toQuaternion=function(){return u.RotationYawPitchRoll(this.y,this.x,this.z)},e.prototype.addInPlace=function(e){return this.addInPlaceFromFloats(e.x,e.y,e.z)},e.prototype.addInPlaceFromFloats=function(e,t,i){return this.x+=e,this.y+=t,this.z+=i,this},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y,this.z+t.z)},e.prototype.addToRef=function(e,t){return t.copyFromFloats(this.x+e.x,this.y+e.y,this.z+e.z)},e.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this},e.prototype.subtract=function(t){return new e(this.x-t.x,this.y-t.y,this.z-t.z)},e.prototype.subtractToRef=function(e,t){return this.subtractFromFloatsToRef(e.x,e.y,e.z,t)},e.prototype.subtractFromFloats=function(t,i,n){return new e(this.x-t,this.y-i,this.z-n)},e.prototype.subtractFromFloatsToRef=function(e,t,i,n){return n.copyFromFloats(this.x-e,this.y-t,this.z-i)},e.prototype.negate=function(){return new e(-this.x,-this.y,-this.z)},e.prototype.negateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},e.prototype.negateToRef=function(e){return e.copyFromFloats(-1*this.x,-1*this.y,-1*this.z)},e.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this},e.prototype.scale=function(t){return new e(this.x*t,this.y*t,this.z*t)},e.prototype.scaleToRef=function(e,t){return t.copyFromFloats(this.x*e,this.y*e,this.z*e)},e.prototype.scaleAndAddToRef=function(e,t){return t.addInPlaceFromFloats(this.x*e,this.y*e,this.z*e)},e.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z},e.prototype.equalsWithEpsilon=function(e,t){return void 0===t&&(t=r.a),e&&n.a.WithinEpsilon(this.x,e.x,t)&&n.a.WithinEpsilon(this.y,e.y,t)&&n.a.WithinEpsilon(this.z,e.z,t)},e.prototype.equalsToFloats=function(e,t,i){return this.x===e&&this.y===t&&this.z===i},e.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this},e.prototype.multiply=function(e){return this.multiplyByFloats(e.x,e.y,e.z)},e.prototype.multiplyToRef=function(e,t){return t.copyFromFloats(this.x*e.x,this.y*e.y,this.z*e.z)},e.prototype.multiplyByFloats=function(t,i,n){return new e(this.x*t,this.y*i,this.z*n)},e.prototype.divide=function(t){return new e(this.x/t.x,this.y/t.y,this.z/t.z)},e.prototype.divideToRef=function(e,t){return t.copyFromFloats(this.x/e.x,this.y/e.y,this.z/e.z)},e.prototype.divideInPlace=function(e){return this.divideToRef(e,this)},e.prototype.minimizeInPlace=function(e){return this.minimizeInPlaceFromFloats(e.x,e.y,e.z)},e.prototype.maximizeInPlace=function(e){return this.maximizeInPlaceFromFloats(e.x,e.y,e.z)},e.prototype.minimizeInPlaceFromFloats=function(e,t,i){return e<this.x&&(this.x=e),t<this.y&&(this.y=t),i<this.z&&(this.z=i),this},e.prototype.maximizeInPlaceFromFloats=function(e,t,i){return e>this.x&&(this.x=e),t>this.y&&(this.y=t),i>this.z&&(this.z=i),this},e.prototype.isNonUniformWithinEpsilon=function(e){var t=Math.abs(this.x),i=Math.abs(this.y);if(!n.a.WithinEpsilon(t,i,e))return!0;var r=Math.abs(this.z);return!n.a.WithinEpsilon(t,r,e)||!n.a.WithinEpsilon(i,r,e)},Object.defineProperty(e.prototype,"isNonUniform",{get:function(){var e=Math.abs(this.x),t=Math.abs(this.y);if(e!==t)return!0;var i=Math.abs(this.z);return e!==i||t!==i},enumerable:!0,configurable:!0}),e.prototype.floor=function(){return new e(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))},e.prototype.fract=function(){return new e(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z))},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},e.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},e.prototype.normalize=function(){return this.normalizeFromLength(this.length())},e.prototype.reorderInPlace=function(e){var t=this;return"xyz"===(e=e.toLowerCase())?this:(d.Vector3[0].copyFrom(this),["x","y","z"].forEach(function(i,n){t[i]=d.Vector3[0][e[n]]}),this)},e.prototype.rotateByQuaternionToRef=function(t,i){return t.toRotationMatrix(d.Matrix[0]),e.TransformCoordinatesToRef(this,d.Matrix[0],i),i},e.prototype.rotateByQuaternionAroundPointToRef=function(e,t,i){return this.subtractToRef(t,d.Vector3[0]),d.Vector3[0].rotateByQuaternionToRef(e,d.Vector3[0]),t.addToRef(d.Vector3[0],i),i},e.prototype.cross=function(t){return e.Cross(this,t)},e.prototype.normalizeFromLength=function(e){return 0===e||1===e?this:this.scaleInPlace(1/e)},e.prototype.normalizeToNew=function(){var t=new e(0,0,0);return this.normalizeToRef(t),t},e.prototype.normalizeToRef=function(e){var t=this.length();return 0===t||1===t?e.copyFromFloats(this.x,this.y,this.z):this.scaleToRef(1/t,e)},e.prototype.clone=function(){return new e(this.x,this.y,this.z)},e.prototype.copyFrom=function(e){return this.copyFromFloats(e.x,e.y,e.z)},e.prototype.copyFromFloats=function(e,t,i){return this.x=e,this.y=t,this.z=i,this},e.prototype.set=function(e,t,i){return this.copyFromFloats(e,t,i)},e.prototype.setAll=function(e){return this.x=this.y=this.z=e,this},e.GetClipFactor=function(t,i,n,r){var o=e.Dot(t,n)-r;return o/(o-(e.Dot(i,n)-r))},e.GetAngleBetweenVectors=function(t,i,n){var r=t.normalizeToRef(d.Vector3[1]),o=i.normalizeToRef(d.Vector3[2]),a=e.Dot(r,o),s=d.Vector3[3];return e.CrossToRef(r,o,s),e.Dot(s,n)>0?Math.acos(a):-Math.acos(a)},e.FromArray=function(t,i){return void 0===i&&(i=0),new e(t[i],t[i+1],t[i+2])},e.FromFloatArray=function(t,i){return e.FromArray(t,i)},e.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2]},e.FromFloatArrayToRef=function(t,i,n){return e.FromArrayToRef(t,i,n)},e.FromFloatsToRef=function(e,t,i,n){n.copyFromFloats(e,t,i)},e.Zero=function(){return new e(0,0,0)},e.One=function(){return new e(1,1,1)},e.Up=function(){return new e(0,1,0)},Object.defineProperty(e,"UpReadOnly",{get:function(){return e._UpReadOnly},enumerable:!0,configurable:!0}),Object.defineProperty(e,"ZeroReadOnly",{get:function(){return e._ZeroReadOnly},enumerable:!0,configurable:!0}),e.Down=function(){return new e(0,-1,0)},e.Forward=function(){return new e(0,0,1)},e.Backward=function(){return new e(0,0,-1)},e.Right=function(){return new e(1,0,0)},e.Left=function(){return new e(-1,0,0)},e.TransformCoordinates=function(t,i){var n=e.Zero();return e.TransformCoordinatesToRef(t,i,n),n},e.TransformCoordinatesToRef=function(t,i,n){e.TransformCoordinatesFromFloatsToRef(t.x,t.y,t.z,i,n)},e.TransformCoordinatesFromFloatsToRef=function(e,t,i,n,r){var o=n.m,a=e*o[0]+t*o[4]+i*o[8]+o[12],s=e*o[1]+t*o[5]+i*o[9]+o[13],c=e*o[2]+t*o[6]+i*o[10]+o[14],l=1/(e*o[3]+t*o[7]+i*o[11]+o[15]);r.x=a*l,r.y=s*l,r.z=c*l},e.TransformNormal=function(t,i){var n=e.Zero();return e.TransformNormalToRef(t,i,n),n},e.TransformNormalToRef=function(e,t,i){this.TransformNormalFromFloatsToRef(e.x,e.y,e.z,t,i)},e.TransformNormalFromFloatsToRef=function(e,t,i,n,r){var o=n.m;r.x=e*o[0]+t*o[4]+i*o[8],r.y=e*o[1]+t*o[5]+i*o[9],r.z=e*o[2]+t*o[6]+i*o[10]},e.CatmullRom=function(t,i,n,r,o){var a=o*o,s=o*a;return new e(.5*(2*i.x+(-t.x+n.x)*o+(2*t.x-5*i.x+4*n.x-r.x)*a+(-t.x+3*i.x-3*n.x+r.x)*s),.5*(2*i.y+(-t.y+n.y)*o+(2*t.y-5*i.y+4*n.y-r.y)*a+(-t.y+3*i.y-3*n.y+r.y)*s),.5*(2*i.z+(-t.z+n.z)*o+(2*t.z-5*i.z+4*n.z-r.z)*a+(-t.z+3*i.z-3*n.z+r.z)*s))},e.Clamp=function(t,i,n){var r=new e;return e.ClampToRef(t,i,n,r),r},e.ClampToRef=function(e,t,i,n){var r=e.x;r=(r=r>i.x?i.x:r)<t.x?t.x:r;var o=e.y;o=(o=o>i.y?i.y:o)<t.y?t.y:o;var a=e.z;a=(a=a>i.z?i.z:a)<t.z?t.z:a,n.copyFromFloats(r,o,a)},e.CheckExtends=function(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)},e.Hermite=function(t,i,n,r,o){var a=o*o,s=o*a,c=2*s-3*a+1,l=-2*s+3*a,u=s-2*a+o,h=s-a;return new e(t.x*c+n.x*l+i.x*u+r.x*h,t.y*c+n.y*l+i.y*u+r.y*h,t.z*c+n.z*l+i.z*u+r.z*h)},e.Lerp=function(t,i,n){var r=new e(0,0,0);return e.LerpToRef(t,i,n,r),r},e.LerpToRef=function(e,t,i,n){n.x=e.x+(t.x-e.x)*i,n.y=e.y+(t.y-e.y)*i,n.z=e.z+(t.z-e.z)*i},e.Dot=function(e,t){return e.x*t.x+e.y*t.y+e.z*t.z},e.Cross=function(t,i){var n=e.Zero();return e.CrossToRef(t,i,n),n},e.CrossToRef=function(e,t,i){var n=e.y*t.z-e.z*t.y,r=e.z*t.x-e.x*t.z,o=e.x*t.y-e.y*t.x;i.copyFromFloats(n,r,o)},e.Normalize=function(t){var i=e.Zero();return e.NormalizeToRef(t,i),i},e.NormalizeToRef=function(e,t){e.normalizeToRef(t)},e.Project=function(t,i,n,r){var o=r.width,a=r.height,s=r.x,c=r.y,l=d.Matrix[1];h.FromValuesToRef(o/2,0,0,0,0,-a/2,0,0,0,0,.5,0,s+o/2,a/2+c,.5,1,l);var u=d.Matrix[0];return i.multiplyToRef(n,u),u.multiplyToRef(l,u),e.TransformCoordinates(t,u)},e._UnprojectFromInvertedMatrixToRef=function(t,i,r){e.TransformCoordinatesToRef(t,i,r);var o=i.m,a=t.x*o[3]+t.y*o[7]+t.z*o[11]+o[15];n.a.WithinEpsilon(a,1)&&r.scaleInPlace(1/a)},e.UnprojectFromTransform=function(t,i,n,r,o){var a=d.Matrix[0];r.multiplyToRef(o,a),a.invert(),t.x=t.x/i*2-1,t.y=-(t.y/n*2-1);var s=new e;return e._UnprojectFromInvertedMatrixToRef(t,a,s),s},e.Unproject=function(t,i,n,r,o,a){var s=e.Zero();return e.UnprojectToRef(t,i,n,r,o,a,s),s},e.UnprojectToRef=function(t,i,n,r,o,a,s){e.UnprojectFloatsToRef(t.x,t.y,t.z,i,n,r,o,a,s)},e.UnprojectFloatsToRef=function(t,i,n,r,o,a,s,c,l){var u=d.Matrix[0];a.multiplyToRef(s,u),u.multiplyToRef(c,u),u.invert();var h=d.Vector3[0];h.x=t/r*2-1,h.y=-(i/o*2-1),h.z=2*n-1,e._UnprojectFromInvertedMatrixToRef(h,u,l)},e.Minimize=function(e,t){var i=e.clone();return i.minimizeInPlace(t),i},e.Maximize=function(e,t){var i=e.clone();return i.maximizeInPlace(t),i},e.Distance=function(t,i){return Math.sqrt(e.DistanceSquared(t,i))},e.DistanceSquared=function(e,t){var i=e.x-t.x,n=e.y-t.y,r=e.z-t.z;return i*i+n*n+r*r},e.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},e.RotationFromAxis=function(t,i,n){var r=e.Zero();return e.RotationFromAxisToRef(t,i,n,r),r},e.RotationFromAxisToRef=function(e,t,i,n){var r=d.Quaternion[0];u.RotationQuaternionFromAxisToRef(e,t,i,r),r.toEulerAnglesToRef(n)},e._UpReadOnly=e.Up(),e._ZeroReadOnly=e.Zero(),e}(),l=function(){function e(e,t,i,n){this.x=e,this.y=t,this.z=i,this.w=n}return e.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+" W:"+this.w+"}"},e.prototype.getClassName=function(){return"Vector4"},e.prototype.getHashCode=function(){var e=0|this.x;return e=397*(e=397*(e=397*e^(0|this.y))^(0|this.z))^(0|this.w)},e.prototype.asArray=function(){var e=new Array;return this.toArray(e,0),e},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,this},e.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},e.prototype.addToRef=function(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,this},e.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this},e.prototype.subtract=function(t){return new e(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},e.prototype.subtractToRef=function(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,this},e.prototype.subtractFromFloats=function(t,i,n,r){return new e(this.x-t,this.y-i,this.z-n,this.w-r)},e.prototype.subtractFromFloatsToRef=function(e,t,i,n,r){return r.x=this.x-e,r.y=this.y-t,r.z=this.z-i,r.w=this.w-n,this},e.prototype.negate=function(){return new e(-this.x,-this.y,-this.z,-this.w)},e.prototype.negateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this.w*=-1,this},e.prototype.negateToRef=function(e){return e.copyFromFloats(-1*this.x,-1*this.y,-1*this.z,-1*this.w)},e.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},e.prototype.scale=function(t){return new e(this.x*t,this.y*t,this.z*t,this.w*t)},e.prototype.scaleToRef=function(e,t){return t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,t.w=this.w*e,this},e.prototype.scaleAndAddToRef=function(e,t){return t.x+=this.x*e,t.y+=this.y*e,t.z+=this.z*e,t.w+=this.w*e,this},e.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},e.prototype.equalsWithEpsilon=function(e,t){return void 0===t&&(t=r.a),e&&n.a.WithinEpsilon(this.x,e.x,t)&&n.a.WithinEpsilon(this.y,e.y,t)&&n.a.WithinEpsilon(this.z,e.z,t)&&n.a.WithinEpsilon(this.w,e.w,t)},e.prototype.equalsToFloats=function(e,t,i,n){return this.x===e&&this.y===t&&this.z===i&&this.w===n},e.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this},e.prototype.multiply=function(t){return new e(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},e.prototype.multiplyToRef=function(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,this},e.prototype.multiplyByFloats=function(t,i,n,r){return new e(this.x*t,this.y*i,this.z*n,this.w*r)},e.prototype.divide=function(t){return new e(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},e.prototype.divideToRef=function(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,this},e.prototype.divideInPlace=function(e){return this.divideToRef(e,this)},e.prototype.minimizeInPlace=function(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},e.prototype.maximizeInPlace=function(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},e.prototype.floor=function(){return new e(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))},e.prototype.fract=function(){return new e(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},e.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},e.prototype.normalize=function(){var e=this.length();return 0===e?this:this.scaleInPlace(1/e)},e.prototype.toVector3=function(){return new c(this.x,this.y,this.z)},e.prototype.clone=function(){return new e(this.x,this.y,this.z,this.w)},e.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},e.prototype.copyFromFloats=function(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this},e.prototype.set=function(e,t,i,n){return this.copyFromFloats(e,t,i,n)},e.prototype.setAll=function(e){return this.x=this.y=this.z=this.w=e,this},e.FromArray=function(t,i){return i||(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3]},e.FromFloatArrayToRef=function(t,i,n){e.FromArrayToRef(t,i,n)},e.FromFloatsToRef=function(e,t,i,n,r){r.x=e,r.y=t,r.z=i,r.w=n},e.Zero=function(){return new e(0,0,0,0)},e.One=function(){return new e(1,1,1,1)},e.Normalize=function(t){var i=e.Zero();return e.NormalizeToRef(t,i),i},e.NormalizeToRef=function(e,t){t.copyFrom(e),t.normalize()},e.Minimize=function(e,t){var i=e.clone();return i.minimizeInPlace(t),i},e.Maximize=function(e,t){var i=e.clone();return i.maximizeInPlace(t),i},e.Distance=function(t,i){return Math.sqrt(e.DistanceSquared(t,i))},e.DistanceSquared=function(e,t){var i=e.x-t.x,n=e.y-t.y,r=e.z-t.z,o=e.w-t.w;return i*i+n*n+r*r+o*o},e.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},e.TransformNormal=function(t,i){var n=e.Zero();return e.TransformNormalToRef(t,i,n),n},e.TransformNormalToRef=function(e,t,i){var n=t.m,r=e.x*n[0]+e.y*n[4]+e.z*n[8],o=e.x*n[1]+e.y*n[5]+e.z*n[9],a=e.x*n[2]+e.y*n[6]+e.z*n[10];i.x=r,i.y=o,i.z=a,i.w=e.w},e.TransformNormalFromFloatsToRef=function(e,t,i,n,r,o){var a=r.m;o.x=e*a[0]+t*a[4]+i*a[8],o.y=e*a[1]+t*a[5]+i*a[9],o.z=e*a[2]+t*a[6]+i*a[10],o.w=n},e.FromVector3=function(t,i){return void 0===i&&(i=0),new e(t.x,t.y,t.z,i)},e}(),u=function(){function e(e,t,i,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=1),this.x=e,this.y=t,this.z=i,this.w=n}return e.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+" W:"+this.w+"}"},e.prototype.getClassName=function(){return"Quaternion"},e.prototype.getHashCode=function(){var e=0|this.x;return e=397*(e=397*(e=397*e^(0|this.y))^(0|this.z))^(0|this.w)},e.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},e.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},e.prototype.equalsWithEpsilon=function(e,t){return void 0===t&&(t=r.a),e&&n.a.WithinEpsilon(this.x,e.x,t)&&n.a.WithinEpsilon(this.y,e.y,t)&&n.a.WithinEpsilon(this.z,e.z,t)&&n.a.WithinEpsilon(this.w,e.w,t)},e.prototype.clone=function(){return new e(this.x,this.y,this.z,this.w)},e.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},e.prototype.copyFromFloats=function(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this},e.prototype.set=function(e,t,i,n){return this.copyFromFloats(e,t,i,n)},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},e.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this},e.prototype.subtract=function(t){return new e(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},e.prototype.scale=function(t){return new e(this.x*t,this.y*t,this.z*t,this.w*t)},e.prototype.scaleToRef=function(e,t){return t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,t.w=this.w*e,this},e.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},e.prototype.scaleAndAddToRef=function(e,t){return t.x+=this.x*e,t.y+=this.y*e,t.z+=this.z*e,t.w+=this.w*e,this},e.prototype.multiply=function(t){var i=new e(0,0,0,1);return this.multiplyToRef(t,i),i},e.prototype.multiplyToRef=function(e,t){var i=this.x*e.w+this.y*e.z-this.z*e.y+this.w*e.x,n=-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,o=-this.x*e.x-this.y*e.y-this.z*e.z+this.w*e.w;return t.copyFromFloats(i,n,r,o),this},e.prototype.multiplyInPlace=function(e){return this.multiplyToRef(e,this),this},e.prototype.conjugateToRef=function(e){return e.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},e.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},e.prototype.conjugate=function(){return new e(-this.x,-this.y,-this.z,this.w)},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},e.prototype.normalize=function(){var e=this.length();if(0===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},e.prototype.toEulerAngles=function(e){void 0===e&&(e="YZX");var t=c.Zero();return this.toEulerAnglesToRef(t),t},e.prototype.toEulerAnglesToRef=function(e){var t=this.z,i=this.x,n=this.y,r=this.w,o=r*r,a=t*t,s=i*i,c=n*n,l=n*t-i*r;return l<-.4999999?(e.y=2*Math.atan2(n,r),e.x=Math.PI/2,e.z=0):l>.4999999?(e.y=2*Math.atan2(n,r),e.x=-Math.PI/2,e.z=0):(e.z=Math.atan2(2*(i*n+t*r),-a-s+c+o),e.x=Math.asin(-2*(t*n-i*r)),e.y=Math.atan2(2*(t*i+n*r),a-s-c+o)),this},e.prototype.toRotationMatrix=function(e){return h.FromQuaternionToRef(this,e),this},e.prototype.fromRotationMatrix=function(t){return e.FromRotationMatrixToRef(t,this),this},e.FromRotationMatrix=function(t){var i=new e;return e.FromRotationMatrixToRef(t,i),i},e.FromRotationMatrixToRef=function(e,t){var i,n=e.m,r=n[0],o=n[4],a=n[8],s=n[1],c=n[5],l=n[9],u=n[2],h=n[6],d=n[10],f=r+c+d;f>0?(i=.5/Math.sqrt(f+1),t.w=.25/i,t.x=(h-l)*i,t.y=(a-u)*i,t.z=(s-o)*i):r>c&&r>d?(i=2*Math.sqrt(1+r-c-d),t.w=(h-l)/i,t.x=.25*i,t.y=(o+s)/i,t.z=(a+u)/i):c>d?(i=2*Math.sqrt(1+c-r-d),t.w=(a-u)/i,t.x=(o+s)/i,t.y=.25*i,t.z=(l+h)/i):(i=2*Math.sqrt(1+d-r-c),t.w=(s-o)/i,t.x=(a+u)/i,t.y=(l+h)/i,t.z=.25*i)},e.Dot=function(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w},e.AreClose=function(t,i){return e.Dot(t,i)>=0},e.Zero=function(){return new e(0,0,0,0)},e.Inverse=function(t){return new e(-t.x,-t.y,-t.z,t.w)},e.InverseToRef=function(e,t){return t.set(-e.x,-e.y,-e.z,e.w),t},e.Identity=function(){return new e(0,0,0,1)},e.IsIdentity=function(e){return e&&0===e.x&&0===e.y&&0===e.z&&1===e.w},e.RotationAxis=function(t,i){return e.RotationAxisToRef(t,i,new e)},e.RotationAxisToRef=function(e,t,i){var n=Math.sin(t/2);return e.normalize(),i.w=Math.cos(t/2),i.x=e.x*n,i.y=e.y*n,i.z=e.z*n,i},e.FromArray=function(t,i){return i||(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.FromEulerAngles=function(t,i,n){var r=new e;return e.RotationYawPitchRollToRef(i,t,n,r),r},e.FromEulerAnglesToRef=function(t,i,n,r){return e.RotationYawPitchRollToRef(i,t,n,r),r},e.FromEulerVector=function(t){var i=new e;return e.RotationYawPitchRollToRef(t.y,t.x,t.z,i),i},e.FromEulerVectorToRef=function(t,i){return e.RotationYawPitchRollToRef(t.y,t.x,t.z,i),i},e.RotationYawPitchRoll=function(t,i,n){var r=new e;return e.RotationYawPitchRollToRef(t,i,n,r),r},e.RotationYawPitchRollToRef=function(e,t,i,n){var r=.5*i,o=.5*t,a=.5*e,s=Math.sin(r),c=Math.cos(r),l=Math.sin(o),u=Math.cos(o),h=Math.sin(a),d=Math.cos(a);n.x=d*l*c+h*u*s,n.y=h*u*c-d*l*s,n.z=d*u*s-h*l*c,n.w=d*u*c+h*l*s},e.RotationAlphaBetaGamma=function(t,i,n){var r=new e;return e.RotationAlphaBetaGammaToRef(t,i,n,r),r},e.RotationAlphaBetaGammaToRef=function(e,t,i,n){var r=.5*(i+e),o=.5*(i-e),a=.5*t;n.x=Math.cos(o)*Math.sin(a),n.y=Math.sin(o)*Math.sin(a),n.z=Math.sin(r)*Math.cos(a),n.w=Math.cos(r)*Math.cos(a)},e.RotationQuaternionFromAxis=function(t,i,n){var r=new e(0,0,0,0);return e.RotationQuaternionFromAxisToRef(t,i,n,r),r},e.RotationQuaternionFromAxisToRef=function(t,i,n,r){var o=d.Matrix[0];h.FromXYZAxesToRef(t.normalize(),i.normalize(),n.normalize(),o),e.FromRotationMatrixToRef(o,r)},e.Slerp=function(t,i,n){var r=e.Identity();return e.SlerpToRef(t,i,n,r),r},e.SlerpToRef=function(e,t,i,n){var r,o,a=e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w,s=!1;if(a<0&&(s=!0,a=-a),a>.999999)o=1-i,r=s?-i:i;else{var c=Math.acos(a),l=1/Math.sin(c);o=Math.sin((1-i)*c)*l,r=s?-Math.sin(i*c)*l:Math.sin(i*c)*l}n.x=o*e.x+r*t.x,n.y=o*e.y+r*t.y,n.z=o*e.z+r*t.z,n.w=o*e.w+r*t.w},e.Hermite=function(t,i,n,r,o){var a=o*o,s=o*a,c=2*s-3*a+1,l=-2*s+3*a,u=s-2*a+o,h=s-a;return new e(t.x*c+n.x*l+i.x*u+r.x*h,t.y*c+n.y*l+i.y*u+r.y*h,t.z*c+n.z*l+i.z*u+r.z*h,t.w*c+n.w*l+i.w*u+r.w*h)},e}(),h=function(){function e(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,this._m=new Float32Array(16),this._updateIdentityStatus(!1)}return Object.defineProperty(e.prototype,"m",{get:function(){return this._m},enumerable:!0,configurable:!0}),e.prototype._markAsUpdated=function(){this.updateFlag=e._updateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0},e.prototype._updateIdentityStatus=function(t,i,n,r){void 0===i&&(i=!1),void 0===n&&(n=!1),void 0===r&&(r=!0),this.updateFlag=e._updateFlagSeed++,this._isIdentity=t,this._isIdentity3x2=t||n,this._isIdentityDirty=!this._isIdentity&&i,this._isIdentity3x2Dirty=!this._isIdentity3x2&&r},e.prototype.isIdentity=function(){if(this._isIdentityDirty){this._isIdentityDirty=!1;var e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity},e.prototype.isIdentityAs3x2=function(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]?this._isIdentity3x2=!1:0!==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]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2},e.prototype.determinant=function(){if(!0===this._isIdentity)return 1;var e=this._m,t=e[0],i=e[1],n=e[2],r=e[3],o=e[4],a=e[5],s=e[6],c=e[7],l=e[8],u=e[9],h=e[10],d=e[11],f=e[12],p=e[13],_=e[14],m=e[15],g=h*m-_*d,v=u*m-p*d,y=u*_-p*h,b=l*m-f*d,T=l*_-h*f,E=l*p-f*u;return t*+(a*g-s*v+c*y)+i*-(o*g-s*b+c*T)+n*+(o*v-a*b+c*E)+r*-(o*y-a*T+s*E)},e.prototype.toArray=function(){return this._m},e.prototype.asArray=function(){return this._m},e.prototype.invert=function(){return this.invertToRef(this),this},e.prototype.reset=function(){return e.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this},e.prototype.add=function(t){var i=new e;return this.addToRef(t,i),i},e.prototype.addToRef=function(e,t){for(var i=this._m,n=t._m,r=e.m,o=0;o<16;o++)n[o]=i[o]+r[o];return t._markAsUpdated(),this},e.prototype.addToSelf=function(e){for(var t=this._m,i=e.m,n=0;n<16;n++)t[n]+=i[n];return this._markAsUpdated(),this},e.prototype.invertToRef=function(t){if(!0===this._isIdentity)return e.IdentityToRef(t),this;var i=this._m,n=i[0],r=i[1],o=i[2],a=i[3],s=i[4],c=i[5],l=i[6],u=i[7],h=i[8],d=i[9],f=i[10],p=i[11],_=i[12],m=i[13],g=i[14],v=i[15],y=f*v-g*p,b=d*v-m*p,T=d*g-m*f,E=h*v-_*p,x=h*g-f*_,P=h*m-_*d,A=+(c*y-l*b+u*T),S=-(s*y-l*E+u*x),C=+(s*b-c*E+u*P),R=-(s*T-c*x+l*P),O=n*A+r*S+o*C+a*R;if(0===O)return t.copyFrom(this),this;var M=1/O,I=l*v-g*u,D=c*v-m*u,w=c*g-m*l,L=s*v-_*u,N=s*g-_*l,F=s*m-_*c,B=l*p-f*u,U=c*p-d*u,V=c*f-d*l,k=s*p-h*u,z=s*f-h*l,G=s*d-h*c,j=-(r*y-o*b+a*T),W=+(n*y-o*E+a*x),X=-(n*b-r*E+a*P),H=+(n*T-r*x+o*P),Y=+(r*I-o*D+a*w),K=-(n*I-o*L+a*N),Q=+(n*D-r*L+a*F),q=-(n*w-r*N+o*F),Z=-(r*B-o*U+a*V),J=+(n*B-o*k+a*z),$=-(n*U-r*k+a*G),ee=+(n*V-r*z+o*G);return e.FromValuesToRef(A*M,j*M,Y*M,Z*M,S*M,W*M,K*M,J*M,C*M,X*M,Q*M,$*M,R*M,H*M,q*M,ee*M,t),this},e.prototype.addAtIndex=function(e,t){return this._m[e]+=t,this._markAsUpdated(),this},e.prototype.multiplyAtIndex=function(e,t){return this._m[e]*=t,this._markAsUpdated(),this},e.prototype.setTranslationFromFloats=function(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this._markAsUpdated(),this},e.prototype.addTranslationFromFloats=function(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this._markAsUpdated(),this},e.prototype.setTranslation=function(e){return this.setTranslationFromFloats(e.x,e.y,e.z)},e.prototype.getTranslation=function(){return new c(this._m[12],this._m[13],this._m[14])},e.prototype.getTranslationToRef=function(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],this},e.prototype.removeRotationAndScaling=function(){var t=this.m;return e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t[12],t[13],t[14],t[15],this),this._updateIdentityStatus(0===t[12]&&0===t[13]&&0===t[14]&&1===t[15]),this},e.prototype.multiply=function(t){var i=new e;return this.multiplyToRef(t,i),i},e.prototype.copyFrom=function(e){e.copyToArray(this._m);var t=e;return this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this},e.prototype.copyToArray=function(e,t){void 0===t&&(t=0);var i=this._m;return 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],this},e.prototype.multiplyToRef=function(e,t){return this._isIdentity?(t.copyFrom(e),this):e._isIdentity?(t.copyFrom(this),this):(this.multiplyToArray(e,t._m,0),t._markAsUpdated(),this)},e.prototype.multiplyToArray=function(e,t,i){var n=this._m,r=e.m,o=n[0],a=n[1],s=n[2],c=n[3],l=n[4],u=n[5],h=n[6],d=n[7],f=n[8],p=n[9],_=n[10],m=n[11],g=n[12],v=n[13],y=n[14],b=n[15],T=r[0],E=r[1],x=r[2],P=r[3],A=r[4],S=r[5],C=r[6],R=r[7],O=r[8],M=r[9],I=r[10],D=r[11],w=r[12],L=r[13],N=r[14],F=r[15];return t[i]=o*T+a*A+s*O+c*w,t[i+1]=o*E+a*S+s*M+c*L,t[i+2]=o*x+a*C+s*I+c*N,t[i+3]=o*P+a*R+s*D+c*F,t[i+4]=l*T+u*A+h*O+d*w,t[i+5]=l*E+u*S+h*M+d*L,t[i+6]=l*x+u*C+h*I+d*N,t[i+7]=l*P+u*R+h*D+d*F,t[i+8]=f*T+p*A+_*O+m*w,t[i+9]=f*E+p*S+_*M+m*L,t[i+10]=f*x+p*C+_*I+m*N,t[i+11]=f*P+p*R+_*D+m*F,t[i+12]=g*T+v*A+y*O+b*w,t[i+13]=g*E+v*S+y*M+b*L,t[i+14]=g*x+v*C+y*I+b*N,t[i+15]=g*P+v*R+y*D+b*F,this},e.prototype.equals=function(e){var t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;var i=this.m,n=t.m;return i[0]===n[0]&&i[1]===n[1]&&i[2]===n[2]&&i[3]===n[3]&&i[4]===n[4]&&i[5]===n[5]&&i[6]===n[6]&&i[7]===n[7]&&i[8]===n[8]&&i[9]===n[9]&&i[10]===n[10]&&i[11]===n[11]&&i[12]===n[12]&&i[13]===n[13]&&i[14]===n[14]&&i[15]===n[15]},e.prototype.clone=function(){var t=new e;return t.copyFrom(this),t},e.prototype.getClassName=function(){return"Matrix"},e.prototype.getHashCode=function(){for(var e=0|this._m[0],t=1;t<16;t++)e=397*e^(0|this._m[t]);return e},e.prototype.decompose=function(t,i,n){if(this._isIdentity)return n&&n.setAll(0),t&&t.setAll(1),i&&i.copyFromFloats(0,0,0,1),!0;var r=this._m;if(n&&n.copyFromFloats(r[12],r[13],r[14]),(t=t||d.Vector3[0]).x=Math.sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]),t.y=Math.sqrt(r[4]*r[4]+r[5]*r[5]+r[6]*r[6]),t.z=Math.sqrt(r[8]*r[8]+r[9]*r[9]+r[10]*r[10]),this.determinant()<=0&&(t.y*=-1),0===t.x||0===t.y||0===t.z)return i&&i.copyFromFloats(0,0,0,1),!1;if(i){var o=1/t.x,a=1/t.y,s=1/t.z;e.FromValuesToRef(r[0]*o,r[1]*o,r[2]*o,0,r[4]*a,r[5]*a,r[6]*a,0,r[8]*s,r[9]*s,r[10]*s,0,0,0,0,1,d.Matrix[0]),u.FromRotationMatrixToRef(d.Matrix[0],i)}return!0},e.prototype.getRow=function(e){if(e<0||e>3)return null;var t=4*e;return new l(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])},e.prototype.setRow=function(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)},e.prototype.transpose=function(){return e.Transpose(this)},e.prototype.transposeToRef=function(t){return e.TransposeToRef(this,t),this},e.prototype.setRowFromFloats=function(e,t,i,n,r){if(e<0||e>3)return this;var o=4*e;return this._m[o+0]=t,this._m[o+1]=i,this._m[o+2]=n,this._m[o+3]=r,this._markAsUpdated(),this},e.prototype.scale=function(t){var i=new e;return this.scaleToRef(t,i),i},e.prototype.scaleToRef=function(e,t){for(var i=0;i<16;i++)t._m[i]=this._m[i]*e;return t._markAsUpdated(),this},e.prototype.scaleAndAddToRef=function(e,t){for(var i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t._markAsUpdated(),this},e.prototype.toNormalMatrix=function(t){var i=d.Matrix[0];this.invertToRef(i),i.transposeToRef(t);var n=t._m;e.FromValuesToRef(n[0],n[1],n[2],0,n[4],n[5],n[6],0,n[8],n[9],n[10],0,0,0,0,1,t)},e.prototype.getRotationMatrix=function(){var t=new e;return this.getRotationMatrixToRef(t),t},e.prototype.getRotationMatrixToRef=function(t){var i=d.Vector3[0];if(!this.decompose(i))return e.IdentityToRef(t),this;var n=this._m,r=1/i.x,o=1/i.y,a=1/i.z;return e.FromValuesToRef(n[0]*r,n[1]*r,n[2]*r,0,n[4]*o,n[5]*o,n[6]*o,0,n[8]*a,n[9]*a,n[10]*a,0,0,0,0,1,t),this},e.prototype.toggleModelMatrixHandInPlace=function(){var e=this._m;e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this._markAsUpdated()},e.prototype.toggleProjectionMatrixHandInPlace=function(){var e=this._m;e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this._markAsUpdated()},e.FromArray=function(t,i){void 0===i&&(i=0);var n=new e;return e.FromArrayToRef(t,i,n),n},e.FromArrayToRef=function(e,t,i){for(var n=0;n<16;n++)i._m[n]=e[n+t];i._markAsUpdated()},e.FromFloat32ArrayToRefScaled=function(e,t,i,n){for(var r=0;r<16;r++)n._m[r]=e[r+t]*i;n._markAsUpdated()},Object.defineProperty(e,"IdentityReadOnly",{get:function(){return e._identityReadOnly},enumerable:!0,configurable:!0}),e.FromValuesToRef=function(e,t,i,n,r,o,a,s,c,l,u,h,d,f,p,_,m){var g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=n,g[4]=r,g[5]=o,g[6]=a,g[7]=s,g[8]=c,g[9]=l,g[10]=u,g[11]=h,g[12]=d,g[13]=f,g[14]=p,g[15]=_,m._markAsUpdated()},e.FromValues=function(t,i,n,r,o,a,s,c,l,u,h,d,f,p,_,m){var g=new e,v=g._m;return v[0]=t,v[1]=i,v[2]=n,v[3]=r,v[4]=o,v[5]=a,v[6]=s,v[7]=c,v[8]=l,v[9]=u,v[10]=h,v[11]=d,v[12]=f,v[13]=p,v[14]=_,v[15]=m,g._markAsUpdated(),g},e.Compose=function(t,i,n){var r=new e;return e.ComposeToRef(t,i,n,r),r},e.ComposeToRef=function(e,t,i,n){var r=n._m,o=t.x,a=t.y,s=t.z,c=t.w,l=o+o,u=a+a,h=s+s,d=o*l,f=o*u,p=o*h,_=a*u,m=a*h,g=s*h,v=c*l,y=c*u,b=c*h,T=e.x,E=e.y,x=e.z;r[0]=(1-(_+g))*T,r[1]=(f+b)*T,r[2]=(p-y)*T,r[3]=0,r[4]=(f-b)*E,r[5]=(1-(d+g))*E,r[6]=(m+v)*E,r[7]=0,r[8]=(p+y)*x,r[9]=(m-v)*x,r[10]=(1-(d+_))*x,r[11]=0,r[12]=i.x,r[13]=i.y,r[14]=i.z,r[15]=1,n._markAsUpdated()},e.Identity=function(){var t=e.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return t._updateIdentityStatus(!0),t},e.IdentityToRef=function(t){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(!0)},e.Zero=function(){var t=e.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return t._updateIdentityStatus(!1),t},e.RotationX=function(t){var i=new e;return e.RotationXToRef(t,i),i},e.Invert=function(t){var i=new e;return t.invertToRef(i),i},e.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);e.FromValuesToRef(1,0,0,0,0,r,n,0,0,-n,r,0,0,0,0,1,i),i._updateIdentityStatus(1===r&&0===n)},e.RotationY=function(t){var i=new e;return e.RotationYToRef(t,i),i},e.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);e.FromValuesToRef(r,0,-n,0,0,1,0,0,n,0,r,0,0,0,0,1,i),i._updateIdentityStatus(1===r&&0===n)},e.RotationZ=function(t){var i=new e;return e.RotationZToRef(t,i),i},e.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);e.FromValuesToRef(r,n,0,0,-n,r,0,0,0,0,1,0,0,0,0,1,i),i._updateIdentityStatus(1===r&&0===n)},e.RotationAxis=function(t,i){var n=new e;return e.RotationAxisToRef(t,i,n),n},e.RotationAxisToRef=function(e,t,i){var n=Math.sin(-t),r=Math.cos(-t),o=1-r;e.normalize();var a=i._m;a[0]=e.x*e.x*o+r,a[1]=e.x*e.y*o-e.z*n,a[2]=e.x*e.z*o+e.y*n,a[3]=0,a[4]=e.y*e.x*o+e.z*n,a[5]=e.y*e.y*o+r,a[6]=e.y*e.z*o-e.x*n,a[7]=0,a[8]=e.z*e.x*o-e.y*n,a[9]=e.z*e.y*o+e.x*n,a[10]=e.z*e.z*o+r,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,i._markAsUpdated()},e.RotationAlignToRef=function(e,t,i){var n=c.Cross(t,e),r=c.Dot(t,e),o=1/(1+r),a=i._m;a[0]=n.x*n.x*o+r,a[1]=n.y*n.x*o-n.z,a[2]=n.z*n.x*o+n.y,a[3]=0,a[4]=n.x*n.y*o+n.z,a[5]=n.y*n.y*o+r,a[6]=n.z*n.y*o-n.x,a[7]=0,a[8]=n.x*n.z*o-n.y,a[9]=n.y*n.z*o+n.x,a[10]=n.z*n.z*o+r,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,i._markAsUpdated()},e.RotationYawPitchRoll=function(t,i,n){var r=new e;return e.RotationYawPitchRollToRef(t,i,n,r),r},e.RotationYawPitchRollToRef=function(e,t,i,n){u.RotationYawPitchRollToRef(e,t,i,d.Quaternion[0]),d.Quaternion[0].toRotationMatrix(n)},e.Scaling=function(t,i,n){var r=new e;return e.ScalingToRef(t,i,n,r),r},e.ScalingToRef=function(t,i,n,r){e.FromValuesToRef(t,0,0,0,0,i,0,0,0,0,n,0,0,0,0,1,r),r._updateIdentityStatus(1===t&&1===i&&1===n)},e.Translation=function(t,i,n){var r=new e;return e.TranslationToRef(t,i,n,r),r},e.TranslationToRef=function(t,i,n,r){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,n,1,r),r._updateIdentityStatus(0===t&&0===i&&0===n)},e.Lerp=function(t,i,n){var r=new e;return e.LerpToRef(t,i,n,r),r},e.LerpToRef=function(e,t,i,n){for(var r=n._m,o=e.m,a=t.m,s=0;s<16;s++)r[s]=o[s]*(1-i)+a[s]*i;n._markAsUpdated()},e.DecomposeLerp=function(t,i,n){var r=new e;return e.DecomposeLerpToRef(t,i,n,r),r},e.DecomposeLerpToRef=function(t,i,n,r){var o=d.Vector3[0],a=d.Quaternion[0],s=d.Vector3[1];t.decompose(o,a,s);var l=d.Vector3[2],h=d.Quaternion[1],f=d.Vector3[3];i.decompose(l,h,f);var p=d.Vector3[4];c.LerpToRef(o,l,n,p);var _=d.Quaternion[2];u.SlerpToRef(a,h,n,_);var m=d.Vector3[5];c.LerpToRef(s,f,n,m),e.ComposeToRef(p,_,m,r)},e.LookAtLH=function(t,i,n){var r=new e;return e.LookAtLHToRef(t,i,n,r),r},e.LookAtLHToRef=function(t,i,n,r){var o=d.Vector3[0],a=d.Vector3[1],s=d.Vector3[2];i.subtractToRef(t,s),s.normalize(),c.CrossToRef(n,s,o);var l=o.lengthSquared();0===l?o.x=1:o.normalizeFromLength(Math.sqrt(l)),c.CrossToRef(s,o,a),a.normalize();var u=-c.Dot(o,t),h=-c.Dot(a,t),f=-c.Dot(s,t);e.FromValuesToRef(o.x,a.x,s.x,0,o.y,a.y,s.y,0,o.z,a.z,s.z,0,u,h,f,1,r)},e.LookAtRH=function(t,i,n){var r=new e;return e.LookAtRHToRef(t,i,n,r),r},e.LookAtRHToRef=function(t,i,n,r){var o=d.Vector3[0],a=d.Vector3[1],s=d.Vector3[2];t.subtractToRef(i,s),s.normalize(),c.CrossToRef(n,s,o);var l=o.lengthSquared();0===l?o.x=1:o.normalizeFromLength(Math.sqrt(l)),c.CrossToRef(s,o,a),a.normalize();var u=-c.Dot(o,t),h=-c.Dot(a,t),f=-c.Dot(s,t);e.FromValuesToRef(o.x,a.x,s.x,0,o.y,a.y,s.y,0,o.z,a.z,s.z,0,u,h,f,1,r)},e.OrthoLH=function(t,i,n,r){var o=new e;return e.OrthoLHToRef(t,i,n,r,o),o},e.OrthoLHToRef=function(t,i,n,r,o){var a=2/t,s=2/i,c=2/(r-n),l=-(r+n)/(r-n);e.FromValuesToRef(a,0,0,0,0,s,0,0,0,0,c,0,0,0,l,1,o),o._updateIdentityStatus(1===a&&1===s&&1===c&&0===l)},e.OrthoOffCenterLH=function(t,i,n,r,o,a){var s=new e;return e.OrthoOffCenterLHToRef(t,i,n,r,o,a,s),s},e.OrthoOffCenterLHToRef=function(t,i,n,r,o,a,s){var c=2/(i-t),l=2/(r-n),u=2/(a-o),h=-(a+o)/(a-o),d=(t+i)/(t-i),f=(r+n)/(n-r);e.FromValuesToRef(c,0,0,0,0,l,0,0,0,0,u,0,d,f,h,1,s),s._markAsUpdated()},e.OrthoOffCenterRH=function(t,i,n,r,o,a){var s=new e;return e.OrthoOffCenterRHToRef(t,i,n,r,o,a,s),s},e.OrthoOffCenterRHToRef=function(t,i,n,r,o,a,s){e.OrthoOffCenterLHToRef(t,i,n,r,o,a,s),s._m[10]*=-1},e.PerspectiveLH=function(t,i,n,r){var o=new e,a=2*n/t,s=2*n/i,c=(r+n)/(r-n),l=-2*r*n/(r-n);return e.FromValuesToRef(a,0,0,0,0,s,0,0,0,0,c,1,0,0,l,0,o),o._updateIdentityStatus(!1),o},e.PerspectiveFovLH=function(t,i,n,r){var o=new e;return e.PerspectiveFovLHToRef(t,i,n,r,o),o},e.PerspectiveFovLHToRef=function(t,i,n,r,o,a){void 0===a&&(a=!0);var s=n,c=r,l=1/Math.tan(.5*t),u=a?l/i:l,h=a?l:l*i,d=(c+s)/(c-s),f=-2*c*s/(c-s);e.FromValuesToRef(u,0,0,0,0,h,0,0,0,0,d,1,0,0,f,0,o),o._updateIdentityStatus(!1)},e.PerspectiveFovReverseLHToRef=function(t,i,n,r,o,a){void 0===a&&(a=!0);var s=1/Math.tan(.5*t),c=a?s/i:s,l=a?s:s*i;e.FromValuesToRef(c,0,0,0,0,l,0,0,0,0,-n,1,0,0,1,0,o),o._updateIdentityStatus(!1)},e.PerspectiveFovRH=function(t,i,n,r){var o=new e;return e.PerspectiveFovRHToRef(t,i,n,r,o),o},e.PerspectiveFovRHToRef=function(t,i,n,r,o,a){void 0===a&&(a=!0);var s=n,c=r,l=1/Math.tan(.5*t),u=a?l/i:l,h=a?l:l*i,d=-(c+s)/(c-s),f=-2*c*s/(c-s);e.FromValuesToRef(u,0,0,0,0,h,0,0,0,0,d,-1,0,0,f,0,o),o._updateIdentityStatus(!1)},e.PerspectiveFovReverseRHToRef=function(t,i,n,r,o,a){void 0===a&&(a=!0);var s=1/Math.tan(.5*t),c=a?s/i:s,l=a?s:s*i;e.FromValuesToRef(c,0,0,0,0,l,0,0,0,0,-n,-1,0,0,-1,0,o),o._updateIdentityStatus(!1)},e.PerspectiveFovWebVRToRef=function(e,t,i,n,r){void 0===r&&(r=!1);var o=r?-1:1,a=Math.tan(e.upDegrees*Math.PI/180),s=Math.tan(e.downDegrees*Math.PI/180),c=Math.tan(e.leftDegrees*Math.PI/180),l=Math.tan(e.rightDegrees*Math.PI/180),u=2/(c+l),h=2/(a+s),d=n._m;d[0]=u,d[1]=d[2]=d[3]=d[4]=0,d[5]=h,d[6]=d[7]=0,d[8]=(c-l)*u*.5,d[9]=-(a-s)*h*.5,d[10]=-i/(t-i),d[11]=1*o,d[12]=d[13]=d[15]=0,d[14]=-2*i*t/(i-t),n._markAsUpdated()},e.GetFinalMatrix=function(t,i,n,r,o,a){var s=t.width,c=t.height,l=t.x,u=t.y,h=e.FromValues(s/2,0,0,0,0,-c/2,0,0,0,0,a-o,0,l+s/2,c/2+u,o,1),f=d.Matrix[0];return i.multiplyToRef(n,f),f.multiplyToRef(r,f),f.multiply(h)},e.GetAsMatrix2x2=function(e){var t=e.m;return new Float32Array([t[0],t[1],t[4],t[5]])},e.GetAsMatrix3x3=function(e){var t=e.m;return new Float32Array([t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]])},e.Transpose=function(t){var i=new e;return e.TransposeToRef(t,i),i},e.TransposeToRef=function(e,t){var i=t._m,n=e.m;i[0]=n[0],i[1]=n[4],i[2]=n[8],i[3]=n[12],i[4]=n[1],i[5]=n[5],i[6]=n[9],i[7]=n[13],i[8]=n[2],i[9]=n[6],i[10]=n[10],i[11]=n[14],i[12]=n[3],i[13]=n[7],i[14]=n[11],i[15]=n[15],t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty)},e.Reflection=function(t){var i=new e;return e.ReflectionToRef(t,i),i},e.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,a=-2*n,s=-2*r,c=-2*o;e.FromValuesToRef(a*n+1,s*n,c*n,0,a*r,s*r+1,c*r,0,a*o,s*o,c*o+1,0,a*t.d,s*t.d,c*t.d,1,i)},e.FromXYZAxesToRef=function(t,i,n,r){e.FromValuesToRef(t.x,t.y,t.z,0,i.x,i.y,i.z,0,n.x,n.y,n.z,0,0,0,0,1,r)},e.FromQuaternionToRef=function(e,t){var i=e.x*e.x,n=e.y*e.y,r=e.z*e.z,o=e.x*e.y,a=e.z*e.w,s=e.z*e.x,c=e.y*e.w,l=e.y*e.z,u=e.x*e.w;t._m[0]=1-2*(n+r),t._m[1]=2*(o+a),t._m[2]=2*(s-c),t._m[3]=0,t._m[4]=2*(o-a),t._m[5]=1-2*(r+i),t._m[6]=2*(l+u),t._m[7]=0,t._m[8]=2*(s+c),t._m[9]=2*(l-u),t._m[10]=1-2*(n+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t._markAsUpdated()},e._updateFlagSeed=0,e._identityReadOnly=e.Identity(),e}(),d=function(){function e(){}return e.Vector3=o.a.BuildArray(6,c.Zero),e.Matrix=o.a.BuildArray(2,h.Identity),e.Quaternion=o.a.BuildArray(3,u.Zero),e}(),f=function(){function e(){}return e.Vector2=o.a.BuildArray(3,s.Zero),e.Vector3=o.a.BuildArray(13,c.Zero),e.Vector4=o.a.BuildArray(3,l.Zero),e.Quaternion=o.a.BuildArray(2,u.Zero),e.Matrix=o.a.BuildArray(8,h.Identity),e}();a.a.RegisteredTypes["BABYLON.Vector2"]=s,a.a.RegisteredTypes["BABYLON.Vector3"]=c,a.a.RegisteredTypes["BABYLON.Vector4"]=l,a.a.RegisteredTypes["BABYLON.Matrix"]=h},function(e,t,i){"use strict";i.d(t,"d",function(){return r}),i.d(t,"a",function(){return o}),i.d(t,"c",function(){return a}),i.d(t,"b",function(){return s}),i.d(t,"e",function(){return c});
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
var n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)};function r(e,t){function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}var o=function(){return(o=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}).apply(this,arguments)};function a(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}function s(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{c(n.next(e))}catch(e){o(e)}}function s(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){e.done?r(e.value):new i(function(t){t(e.value)}).then(a,s)}c((n=n.apply(e,t||[])).next())})}function c(e,t){var i,n,r,o,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(r=(r=a.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return e.ALPHA_DISABLE=0,e.ALPHA_ADD=1,e.ALPHA_COMBINE=2,e.ALPHA_SUBTRACT=3,e.ALPHA_MULTIPLY=4,e.ALPHA_MAXIMIZED=5,e.ALPHA_ONEONE=6,e.ALPHA_PREMULTIPLIED=7,e.ALPHA_PREMULTIPLIED_PORTERDUFF=8,e.ALPHA_INTERPOLATE=9,e.ALPHA_SCREENMODE=10,e.ALPHA_ONEONE_ONEONE=11,e.ALPHA_ALPHATOCOLOR=12,e.ALPHA_REVERSEONEMINUS=13,e.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,e.ALPHA_ONEONE_ONEZERO=15,e.ALPHA_EXCLUSION=16,e.ALPHA_EQUATION_ADD=0,e.ALPHA_EQUATION_SUBSTRACT=1,e.ALPHA_EQUATION_REVERSE_SUBTRACT=2,e.ALPHA_EQUATION_MAX=3,e.ALPHA_EQUATION_MIN=4,e.ALPHA_EQUATION_DARKEN=5,e.DELAYLOADSTATE_NONE=0,e.DELAYLOADSTATE_LOADED=1,e.DELAYLOADSTATE_LOADING=2,e.DELAYLOADSTATE_NOTLOADED=4,e.NEVER=512,e.ALWAYS=519,e.LESS=513,e.EQUAL=514,e.LEQUAL=515,e.GREATER=516,e.GEQUAL=518,e.NOTEQUAL=517,e.KEEP=7680,e.REPLACE=7681,e.INCR=7682,e.DECR=7683,e.INVERT=5386,e.INCR_WRAP=34055,e.DECR_WRAP=34056,e.TEXTURE_CLAMP_ADDRESSMODE=0,e.TEXTURE_WRAP_ADDRESSMODE=1,e.TEXTURE_MIRROR_ADDRESSMODE=2,e.TEXTUREFORMAT_ALPHA=0,e.TEXTUREFORMAT_LUMINANCE=1,e.TEXTUREFORMAT_LUMINANCE_ALPHA=2,e.TEXTUREFORMAT_RGB=4,e.TEXTUREFORMAT_RGBA=5,e.TEXTUREFORMAT_RED=6,e.TEXTUREFORMAT_R=6,e.TEXTUREFORMAT_RG=7,e.TEXTUREFORMAT_RED_INTEGER=8,e.TEXTUREFORMAT_R_INTEGER=8,e.TEXTUREFORMAT_RG_INTEGER=9,e.TEXTUREFORMAT_RGB_INTEGER=10,e.TEXTUREFORMAT_RGBA_INTEGER=11,e.TEXTURETYPE_UNSIGNED_BYTE=0,e.TEXTURETYPE_UNSIGNED_INT=0,e.TEXTURETYPE_FLOAT=1,e.TEXTURETYPE_HALF_FLOAT=2,e.TEXTURETYPE_BYTE=3,e.TEXTURETYPE_SHORT=4,e.TEXTURETYPE_UNSIGNED_SHORT=5,e.TEXTURETYPE_INT=6,e.TEXTURETYPE_UNSIGNED_INTEGER=7,e.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,e.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,e.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,e.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,e.TEXTURETYPE_UNSIGNED_INT_24_8=12,e.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,e.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,e.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,e.TEXTURE_NEAREST_SAMPLINGMODE=1,e.TEXTURE_NEAREST_NEAREST=1,e.TEXTURE_BILINEAR_SAMPLINGMODE=2,e.TEXTURE_LINEAR_LINEAR=2,e.TEXTURE_TRILINEAR_SAMPLINGMODE=3,e.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,e.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,e.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,e.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,e.TEXTURE_NEAREST_LINEAR=7,e.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,e.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,e.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,e.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,e.TEXTURE_LINEAR_NEAREST=12,e.TEXTURE_EXPLICIT_MODE=0,e.TEXTURE_SPHERICAL_MODE=1,e.TEXTURE_PLANAR_MODE=2,e.TEXTURE_CUBIC_MODE=3,e.TEXTURE_PROJECTION_MODE=4,e.TEXTURE_SKYBOX_MODE=5,e.TEXTURE_INVCUBIC_MODE=6,e.TEXTURE_EQUIRECTANGULAR_MODE=7,e.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,e.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,e.SCALEMODE_FLOOR=1,e.SCALEMODE_NEAREST=2,e.SCALEMODE_CEILING=3,e.MATERIAL_TextureDirtyFlag=1,e.MATERIAL_LightDirtyFlag=2,e.MATERIAL_FresnelDirtyFlag=4,e.MATERIAL_AttributesDirtyFlag=8,e.MATERIAL_MiscDirtyFlag=16,e.MATERIAL_AllDirtyFlag=31,e.MATERIAL_TriangleFillMode=0,e.MATERIAL_WireFrameFillMode=1,e.MATERIAL_PointFillMode=2,e.MATERIAL_PointListDrawMode=3,e.MATERIAL_LineListDrawMode=4,e.MATERIAL_LineLoopDrawMode=5,e.MATERIAL_LineStripDrawMode=6,e.MATERIAL_TriangleStripDrawMode=7,e.MATERIAL_TriangleFanDrawMode=8,e.MATERIAL_ClockWiseSideOrientation=0,e.MATERIAL_CounterClockWiseSideOrientation=1,e.ACTION_NothingTrigger=0,e.ACTION_OnPickTrigger=1,e.ACTION_OnLeftPickTrigger=2,e.ACTION_OnRightPickTrigger=3,e.ACTION_OnCenterPickTrigger=4,e.ACTION_OnPickDownTrigger=5,e.ACTION_OnDoublePickTrigger=6,e.ACTION_OnPickUpTrigger=7,e.ACTION_OnPickOutTrigger=16,e.ACTION_OnLongPressTrigger=8,e.ACTION_OnPointerOverTrigger=9,e.ACTION_OnPointerOutTrigger=10,e.ACTION_OnEveryFrameTrigger=11,e.ACTION_OnIntersectionEnterTrigger=12,e.ACTION_OnIntersectionExitTrigger=13,e.ACTION_OnKeyDownTrigger=14,e.ACTION_OnKeyUpTrigger=15,e.PARTICLES_BILLBOARDMODE_Y=2,e.PARTICLES_BILLBOARDMODE_ALL=7,e.PARTICLES_BILLBOARDMODE_STRETCHED=8,e.MESHES_CULLINGSTRATEGY_STANDARD=0,e.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,e.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,e.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,e.SCENELOADER_NO_LOGGING=0,e.SCENELOADER_MINIMAL_LOGGING=1,e.SCENELOADER_SUMMARY_LOGGING=2,e.SCENELOADER_DETAILED_LOGGING=3,e}()},function(e,t,i){"use strict";i.d(t,"b",function(){return d}),i.d(t,"c",function(){return f}),i.d(t,"m",function(){return p}),i.d(t,"e",function(){return _}),i.d(t,"h",function(){return m}),i.d(t,"n",function(){return g}),i.d(t,"o",function(){return v}),i.d(t,"k",function(){return y}),i.d(t,"g",function(){return b}),i.d(t,"f",function(){return T}),i.d(t,"i",function(){return E}),i.d(t,"l",function(){return x}),i.d(t,"j",function(){return P}),i.d(t,"d",function(){return A}),i.d(t,"a",function(){return S});var n=i(35),r=i(0),o=i(19),a=i(10),s={},c={},l=function(e,t,i){var r=e();n.a&&n.a.AddTagsTo(r,t.tags);var o=u(r);for(var a in o){var s=o[a],c=t[a],l=s.type;if(null!=c&&"uniqueId"!==a)switch(l){case 0:case 6:case 11:r[a]=c;break;case 1:r[a]=i||c.isRenderTarget?c:c.clone();break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:r[a]=i?c:c.clone()}}return r};function u(e){var t=e.getClassName();if(c[t])return c[t];c[t]={};for(var i=c[t],n=e,r=t;r;){var o=s[r];for(var a in o)i[a]=o[a];var l=void 0,u=!1;do{if(!(l=Object.getPrototypeOf(n)).getClassName){u=!0;break}if(l.getClassName()!==r)break;n=l}while(l);if(u)break;r=l.getClassName(),n=l}return i}function h(e,t){return function(i,n){var r=function(e){var t=e.getClassName();return s[t]||(s[t]={}),s[t]}(i);r[n]||(r[n]={type:e,sourceName:t})}}function d(e,t){return void 0===t&&(t=null),function(e,t){return void 0===t&&(t=null),function(i,n){var r=t||"_"+n;Object.defineProperty(i,n,{get:function(){return this[r]},set:function(t){this[r]!==t&&(this[r]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function f(e){return h(0,e)}function p(e){return h(1,e)}function _(e){return h(2,e)}function m(e){return h(3,e)}function g(e){return h(4,e)}function v(e){return h(5,e)}function y(e){return h(6,e)}function b(e){return h(7,e)}function T(e){return h(8,e)}function E(e){return h(9,e)}function x(e){return h(10,e)}function P(e){return h(12,e)}function A(e){return h(11,e)}var S=function(){function e(){}return e.AppendSerializedAnimations=function(e,t){if(e.animations){t.animations=[];for(var i=0;i<e.animations.length;i++){var n=e.animations[i];t.animations.push(n.serialize())}}},e.Serialize=function(e,t){t||(t={}),n.a&&(t.tags=n.a.GetTags(e));var i=u(e);for(var r in i){var o=i[r],a=o.sourceName||r,s=o.type,c=e[r];if(null!=c)switch(s){case 0:t[a]=c;break;case 1:t[a]=c.serialize();break;case 2:t[a]=c.asArray();break;case 3:t[a]=c.serialize();break;case 4:case 5:t[a]=c.asArray();break;case 6:t[a]=c.id;break;case 7:t[a]=c.serialize();break;case 8:t[a]=c.asArray();break;case 9:t[a]=c.serialize();break;case 10:t[a]=c.asArray();break;case 11:t[a]=c.id;case 12:t[a]=c.asArray()}}return t},e.Parse=function(t,i,o,s){void 0===s&&(s=null);var c=t();s||(s=""),n.a&&n.a.AddTagsTo(c,i.tags);var l=u(c);for(var h in l){var d=l[h],f=i[d.sourceName||h],p=d.type;if(null!=f){var _=c;switch(p){case 0:_[h]=f;break;case 1:o&&(_[h]=e._TextureParser(f,o,s));break;case 2:_[h]=a.a.FromArray(f);break;case 3:_[h]=e._FresnelParametersParser(f);break;case 4:_[h]=r.d.FromArray(f);break;case 5:_[h]=r.e.FromArray(f);break;case 6:o&&(_[h]=o.getLastMeshByID(f));break;case 7:_[h]=e._ColorCurvesParser(f);break;case 8:_[h]=a.b.FromArray(f);break;case 9:_[h]=e._ImageProcessingConfigurationParser(f);break;case 10:_[h]=r.b.FromArray(f);break;case 11:o&&(_[h]=o.getCameraByID(f));case 12:_[h]=r.a.FromArray(f)}}}return c},e.Clone=function(e,t){return l(e,t,!1)},e.Instanciate=function(e,t){return l(e,t,!0)},e._ImageProcessingConfigurationParser=function(e){throw o.a.WarnImport("ImageProcessingConfiguration")},e._FresnelParametersParser=function(e){throw o.a.WarnImport("FresnelParameters")},e._ColorCurvesParser=function(e){throw o.a.WarnImport("ColorCurves")},e._TextureParser=function(e,t,i){throw o.a.WarnImport("Texture")},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n}),i.d(t,"b",function(){return r});var n=function(){function e(e,t,i,n,r,o,a,s){void 0===n&&(n=0),void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===a&&(a=!1),e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=o,this._divisor=s||1,this._data=t,this.byteStride=a?n:n*Float32Array.BYTES_PER_ELEMENT,r||this.create()}return e.prototype.createVertexBuffer=function(e,t,i,n,o,a,s){void 0===a&&(a=!1);var c=a?t:t*Float32Array.BYTES_PER_ELEMENT,l=n?a?n:n*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new r(this._engine,this,e,this._updatable,!0,l,void 0===o?this._instanced:o,c,i,void 0,void 0,!0,this._divisor||s)},e.prototype.isUpdatable=function(){return this._updatable},e.prototype.getData=function(){return this._data},e.prototype.getBuffer=function(){return this._buffer},e.prototype.getStrideSize=function(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT},e.prototype.create=function(e){void 0===e&&(e=null),!e&&this._buffer||(e=e||this._data)&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e),this._data=e):this._buffer=this._engine.createVertexBuffer(e))},e.prototype._rebuild=function(){this._buffer=null,this.create(this._data)},e.prototype.update=function(e){this.create(e)},e.prototype.updateDirectly=function(e,t,i,n){void 0===n&&(n=!1),this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,n?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),this._data=null)},e.prototype.dispose=function(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)},e}(),r=function(){function e(t,i,r,o,a,s,c,l,u,h,d,f,p){if(void 0===d&&(d=!1),void 0===f&&(f=!1),void 0===p&&(p=1),i instanceof n?(this._buffer=i,this._ownsBuffer=!1):(this._buffer=new n(t,i,o,s,a,c,f),this._ownsBuffer=!0),this._kind=r,null==h){var _=this.getData();this.type=e.FLOAT,_ instanceof Int8Array?this.type=e.BYTE:_ instanceof Uint8Array?this.type=e.UNSIGNED_BYTE:_ instanceof Int16Array?this.type=e.SHORT:_ instanceof Uint16Array?this.type=e.UNSIGNED_SHORT:_ instanceof Int32Array?this.type=e.INT:_ instanceof Uint32Array&&(this.type=e.UNSIGNED_INT)}else this.type=h;var m=e.GetTypeByteLength(this.type);f?(this._size=u||(s?s/m:e.DeduceStride(r)),this.byteStride=s||this._buffer.byteStride||this._size*m,this.byteOffset=l||0):(this._size=u||s||e.DeduceStride(r),this.byteStride=s?s*m:this._buffer.byteStride||this._size*m,this.byteOffset=(l||0)*m),this.normalized=d,this._instanced=void 0!==c&&c,this._instanceDivisor=c?p:0}return Object.defineProperty(e.prototype,"instanceDivisor",{get:function(){return this._instanceDivisor},set:function(e){this._instanceDivisor=e,this._instanced=0!=e},enumerable:!0,configurable:!0}),e.prototype._rebuild=function(){this._buffer&&this._buffer._rebuild()},e.prototype.getKind=function(){return this._kind},e.prototype.isUpdatable=function(){return this._buffer.isUpdatable()},e.prototype.getData=function(){return this._buffer.getData()},e.prototype.getBuffer=function(){return this._buffer.getBuffer()},e.prototype.getStrideSize=function(){return this.byteStride/e.GetTypeByteLength(this.type)},e.prototype.getOffset=function(){return this.byteOffset/e.GetTypeByteLength(this.type)},e.prototype.getSize=function(){return this._size},e.prototype.getIsInstanced=function(){return this._instanced},e.prototype.getInstanceDivisor=function(){return this._instanceDivisor},e.prototype.create=function(e){this._buffer.create(e)},e.prototype.update=function(e){this._buffer.update(e)},e.prototype.updateDirectly=function(e,t,i){void 0===i&&(i=!1),this._buffer.updateDirectly(e,t,void 0,i)},e.prototype.dispose=function(){this._ownsBuffer&&this._buffer.dispose()},e.prototype.forEach=function(t,i){e.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,t,this.normalized,i)},e.DeduceStride=function(t){switch(t){case e.UVKind:case e.UV2Kind:case e.UV3Kind:case e.UV4Kind:case e.UV5Kind:case e.UV6Kind:return 2;case e.NormalKind:case e.PositionKind:return 3;case e.ColorKind:case e.MatricesIndicesKind:case e.MatricesIndicesExtraKind:case e.MatricesWeightsKind:case e.MatricesWeightsExtraKind:case e.TangentKind:return 4;default:throw new Error("Invalid kind '"+t+"'")}},e.GetTypeByteLength=function(t){switch(t){case e.BYTE:case e.UNSIGNED_BYTE:return 1;case e.SHORT:case e.UNSIGNED_SHORT:return 2;case e.INT:case e.UNSIGNED_INT:case e.FLOAT:return 4;default:throw new Error("Invalid type '"+t+"'")}},e.ForEach=function(t,i,n,r,o,a,s,c){if(t instanceof Array)for(var l=i/4,u=n/4,h=0;h<a;h+=r){for(var d=0;d<r;d++)c(t[l+d],h+d);l+=u}else{var f=t instanceof ArrayBuffer?new DataView(t):new DataView(t.buffer,t.byteOffset,t.byteLength),p=e.GetTypeByteLength(o);for(h=0;h<a;h+=r){var _=i;for(d=0;d<r;d++){c(e._GetFloatValue(f,o,_,s),h+d),_+=p}i+=n}}},e._GetFloatValue=function(t,i,n,r){switch(i){case e.BYTE:var o=t.getInt8(n);return r&&(o=Math.max(o/127,-1)),o;case e.UNSIGNED_BYTE:o=t.getUint8(n);return r&&(o/=255),o;case e.SHORT:o=t.getInt16(n,!0);return r&&(o=Math.max(o/32767,-1)),o;case e.UNSIGNED_SHORT:o=t.getUint16(n,!0);return r&&(o/=65535),o;case e.INT:return t.getInt32(n,!0);case e.UNSIGNED_INT:return t.getUint32(n,!0);case e.FLOAT:return t.getFloat32(n,!0);default:throw new Error("Invalid component type "+i)}},e.BYTE=5120,e.UNSIGNED_BYTE=5121,e.SHORT=5122,e.UNSIGNED_SHORT=5123,e.INT=5124,e.UNSIGNED_INT=5125,e.FLOAT=5126,e.PositionKind="position",e.NormalKind="normal",e.TangentKind="tangent",e.UVKind="uv",e.UV2Kind="uv2",e.UV3Kind="uv3",e.UV4Kind="uv4",e.UV5Kind="uv5",e.UV6Kind="uv6",e.ColorKind="color",e.MatricesIndicesKind="matricesIndices",e.MatricesWeightsKind="matricesWeights",e.MatricesIndicesExtraKind="matricesIndicesExtra",e.MatricesWeightsExtraKind="matricesWeightsExtra",e}()},function(e,t,i){"use strict";i.d(t,"b",function(){return R}),i.d(t,"c",function(){return M}),i.d(t,"a",function(){return D});var n=i(1),r=i(6),o=i(13),a=i(33),s=i(35),c=i(0),l=i(10),u=i(26),h=i(4),d=i(15),f=i(69),p=i(27),_=i(57),m=i(44),g=i(29),v=i(71),y=i(67),b=i(2),T=i(3),E=i(7),x=i(12),P=i(19),A=i(17),S=i(135),C=i(70),R=function(){},O=function(){this.visibleInstances={},this.batchCache=new M,this.instancesBufferSize=2048},M=function(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=new Array,this.hardwareInstancedRendering=new Array},I=function(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._morphTargetManager=null},D=function(e){function t(i,n,r,o,c,l){void 0===n&&(n=null),void 0===r&&(r=null),void 0===o&&(o=null),void 0===l&&(l=!0);var u=e.call(this,i,n)||this;if(u._internalMeshDataInfo=new I,u.delayLoadState=b.a.DELAYLOADSTATE_NONE,u.instances=new Array,u._creationDataStorage=null,u._geometry=null,u._instanceDataStorage=new O,u._effectiveMaterial=null,u._shouldGenerateFlatShading=!1,u._originalBuilderSideOrientation=t.DEFAULTSIDE,u.overrideMaterialSideOrientation=null,n=u.getScene(),o){if(o._geometry&&o._geometry.applyToMesh(u),a.a.DeepCopy(o,u,["name","material","skeleton","instances","parent","uniqueId","source","metadata","hasLODLevels","geometry","isBlocked","areNormalsFrozen","onBeforeDrawObservable","onBeforeRenderObservable","onAfterRenderObservable","onBeforeDraw","onAfterWorldMatrixUpdateObservable","onCollideObservable","onCollisionPositionChangeObservable","onRebuildObservable","onDisposeObservable","lightSources","morphTargetManager"],["_poseMatrix"]),u._internalMeshDataInfo._source=o,n.useClonedMeshMap&&(o._internalMeshDataInfo.meshMap||(o._internalMeshDataInfo.meshMap={}),o._internalMeshDataInfo.meshMap[u.uniqueId]=u),u._originalBuilderSideOrientation=o._originalBuilderSideOrientation,u._creationDataStorage=o._creationDataStorage,o._ranges){var h=o._ranges;for(var i in h)h.hasOwnProperty(i)&&h[i]&&u.createAnimationRange(i,h[i].from,h[i].to)}var d;if(o.metadata&&o.metadata.clone?u.metadata=o.metadata.clone():u.metadata=o.metadata,s.a&&s.a.HasTags(o)&&s.a.AddTagsTo(u,s.a.GetTags(o,!0)),u.parent=o.parent,u.setPivotMatrix(o.getPivotMatrix()),u.id=i+"."+o.id,u.material=o.material,!c)for(var f=o.getDescendants(!0),p=0;p<f.length;p++){var _=f[p];_.clone&&_.clone(i+"."+_.name,u)}if(o.morphTargetManager&&(u.morphTargetManager=o.morphTargetManager),n.getPhysicsEngine){var m=n.getPhysicsEngine();if(l&&m){var g=m.getImpostorForPhysicsObject(o);g&&(u.physicsImpostor=g.clone(u))}}for(d=0;d<n.particleSystems.length;d++){var v=n.particleSystems[d];v.emitter===o&&v.clone(v.name,u)}u.refreshBoundingInfo(),u.computeWorldMatrix(!0)}return null!==r&&(u.parent=r),u._instanceDataStorage.hardwareInstancedRendering=u.getEngine().getCaps().instancedArrays,u}return Object(n.d)(t,e),t._GetDefaultSideOrientation=function(e){return e||t.FRONTSIDE},Object.defineProperty(t.prototype,"onBeforeRenderObservable",{get:function(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new r.c),this._internalMeshDataInfo._onBeforeRenderObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBeforeBindObservable",{get:function(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new r.c),this._internalMeshDataInfo._onBeforeBindObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onAfterRenderObservable",{get:function(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new r.c),this._internalMeshDataInfo._onAfterRenderObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBeforeDrawObservable",{get:function(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new r.c),this._internalMeshDataInfo._onBeforeDrawObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBeforeDraw",{set:function(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasInstances",{get:function(){return this.instances.length>0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"morphTargetManager",{get:function(){return this._internalMeshDataInfo._morphTargetManager},set:function(e){this._internalMeshDataInfo._morphTargetManager!==e&&(this._internalMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"source",{get:function(){return this._internalMeshDataInfo._source},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isUnIndexed",{get:function(){return this._unIndexed},set:function(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"worldMatrixInstancedBuffer",{get:function(){return this._instanceDataStorage.instancesData},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"manualUpdateOfWorldMatrixInstancedBuffer",{get:function(){return this._instanceDataStorage.manualUpdate},set:function(e){this._instanceDataStorage.manualUpdate=e},enumerable:!0,configurable:!0}),t.prototype.instantiateHierarchy=function(e,t,i){void 0===e&&(e=null);var n=!(this.getTotalVertices()>0)||t&&t.doNotInstantiate?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));n&&(n.parent=e||this.parent,n.position=this.position.clone(),n.scaling=this.scaling.clone(),this.rotationQuaternion?n.rotationQuaternion=this.rotationQuaternion.clone():n.rotation=this.rotation.clone(),i&&i(this,n));for(var r=0,o=this.getChildTransformNodes(!0);r<o.length;r++){o[r].instantiateHierarchy(n,t,i)}return n},t.prototype.getClassName=function(){return"Mesh"},Object.defineProperty(t.prototype,"_isMesh",{get:function(){return!0},enumerable:!0,configurable:!0}),t.prototype.toString=function(t){var i=e.prototype.toString.call(this,t);if(i+=", n vertices: "+this.getTotalVertices(),i+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(var n=0;n<this.animations.length;n++)i+=", animation[0]: "+this.animations[n].toString(t);if(t)if(this._geometry){var r=this.getIndices(),o=this.getVerticesData(h.b.PositionKind);o&&r&&(i+=", flat shading: "+(o.length/3===r.length?"YES":"NO"))}else i+=", flat shading: UNKNOWN";return i},t.prototype._unBindEffect=function(){e.prototype._unBindEffect.call(this);for(var t=0,i=this.instances;t<i.length;t++){i[t]._unBindEffect()}},Object.defineProperty(t.prototype,"hasLODLevels",{get:function(){return this._internalMeshDataInfo._LODLevels.length>0},enumerable:!0,configurable:!0}),t.prototype.getLODLevels=function(){return this._internalMeshDataInfo._LODLevels},t.prototype._sortLODLevels=function(){this._internalMeshDataInfo._LODLevels.sort(function(e,t){return e.distance<t.distance?1:e.distance>t.distance?-1:0})},t.prototype.addLODLevel=function(e,t){if(t&&t._masterMesh)return E.a.Warn("You cannot use a mesh as LOD level twice"),this;var i=new S.a(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this},t.prototype.getLODLevelAtDistance=function(e){for(var t=this._internalMeshDataInfo,i=0;i<t._LODLevels.length;i++){var n=t._LODLevels[i];if(n.distance===e)return n.mesh}return null},t.prototype.removeLODLevel=function(e){for(var t=this._internalMeshDataInfo,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},t.prototype.getLOD=function(e,t){var i,n=this._internalMeshDataInfo;if(!n._LODLevels||0===n._LODLevels.length)return this;t?i=t:i=this.getBoundingInfo().boundingSphere;var r=i.centerWorld.subtract(e.globalPosition).length();if(n._LODLevels[n._LODLevels.length-1].distance>r)return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,this),this;for(var o=0;o<n._LODLevels.length;o++){var a=n._LODLevels[o];if(a.distance<r)return a.mesh&&(a.mesh._preActivate(),a.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)),this.onLODLevelSelection&&this.onLODLevelSelection(r,this,a.mesh),a.mesh}return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,this),this},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._geometry},enumerable:!0,configurable:!0}),t.prototype.getTotalVertices=function(){return null===this._geometry||void 0===this._geometry?0:this._geometry.getTotalVertices()},t.prototype.getVerticesData=function(e,t,i){return this._geometry?this._geometry.getVerticesData(e,t,i):null},t.prototype.getVertexBuffer=function(e){return this._geometry?this._geometry.getVertexBuffer(e):null},t.prototype.isVerticesDataPresent=function(e){return this._geometry?this._geometry.isVerticesDataPresent(e):!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)},t.prototype.isVertexBufferUpdatable=function(e){return this._geometry?this._geometry.isVertexBufferUpdatable(e):!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)},t.prototype.getVerticesDataKinds=function(){if(!this._geometry){var e=new Array;return this._delayInfo&&this._delayInfo.forEach(function(t){e.push(t)}),e}return this._geometry.getVerticesDataKinds()},t.prototype.getTotalIndices=function(){return this._geometry?this._geometry.getTotalIndices():0},t.prototype.getIndices=function(e,t){return this._geometry?this._geometry.getIndices(e,t):[]},Object.defineProperty(t.prototype,"isBlocked",{get:function(){return null!==this._masterMesh&&void 0!==this._masterMesh},enumerable:!0,configurable:!0}),t.prototype.isReady=function(t,i){if(void 0===t&&(t=!1),void 0===i&&(i=!1),this.delayLoadState===b.a.DELAYLOADSTATE_LOADING)return!1;if(!e.prototype.isReady.call(this,t))return!1;if(!this.subMeshes||0===this.subMeshes.length)return!0;if(!t)return!0;var n=this.getEngine(),r=this.getScene(),o=i||n.getCaps().instancedArrays&&this.instances.length>0;this.computeWorldMatrix();var a=this.material||r.defaultMaterial;if(a)if(a._storeEffectOnSubMeshes)for(var s=0,c=this.subMeshes;s<c.length;s++){var l=(_=c[s]).getMaterial();if(l)if(l._storeEffectOnSubMeshes){if(!l.isReadyForSubMesh(this,_,o))return!1}else if(!l.isReady(this,o))return!1}else if(!a.isReady(this,o))return!1;for(var u=0,h=this.lightSources;u<h.length;u++){var d=h[u].getShadowGenerator();if(d)for(var f=0,p=this.subMeshes;f<p.length;f++){var _=p[f];if(!d.isReady(_,o))return!1}}for(var m=0,g=this._internalMeshDataInfo._LODLevels;m<g.length;m++){var v=g[m];if(v.mesh&&!v.mesh.isReady(o))return!1}return!0},Object.defineProperty(t.prototype,"areNormalsFrozen",{get:function(){return this._internalMeshDataInfo._areNormalsFrozen},enumerable:!0,configurable:!0}),t.prototype.freezeNormals=function(){return this._internalMeshDataInfo._areNormalsFrozen=!0,this},t.prototype.unfreezeNormals=function(){return this._internalMeshDataInfo._areNormalsFrozen=!1,this},Object.defineProperty(t.prototype,"overridenInstanceCount",{set:function(e){this._instanceDataStorage.overridenInstanceCount=e},enumerable:!0,configurable:!0}),t.prototype._preActivate=function(){var e=this._internalMeshDataInfo,t=this.getScene().getRenderId();return e._preActivateId===t?this:(e._preActivateId=t,this._instanceDataStorage.visibleInstances=null,this)},t.prototype._preActivateForIntermediateRendering=function(e){return this._instanceDataStorage.visibleInstances&&(this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId=e),this},t.prototype._registerInstanceForRenderId=function(e,t){return this._instanceDataStorage.visibleInstances||(this._instanceDataStorage.visibleInstances={defaultRenderId:t,selfDefaultRenderId:this._renderId}),this._instanceDataStorage.visibleInstances[t]||(this._instanceDataStorage.visibleInstances[t]=new Array),this._instanceDataStorage.visibleInstances[t].push(e),this},t.prototype.refreshBoundingInfo=function(e){if(void 0===e&&(e=!1),this._boundingInfo&&this._boundingInfo.isLocked)return this;var t=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getPositionData(e),t),this},t.prototype._createGlobalSubMesh=function(e){var t=this.getTotalVertices();if(!t||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){var i=this.getIndices();if(!i)return null;var n=i.length,r=!1;if(e)r=!0;else for(var o=0,a=this.subMeshes;o<a.length;o++){var s=a[o];if(s.indexStart+s.indexCount>=n){r=!0;break}if(s.verticesStart+s.verticesCount>=t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new _.b(0,0,t,0,this.getTotalIndices(),this)},t.prototype.subdivide=function(e){if(!(e<1)){for(var t=this.getTotalIndices(),i=t/e|0,n=0;i%3!=0;)i++;this.releaseSubMeshes();for(var r=0;r<e&&!(n>=t);r++)_.b.CreateFromIndices(0,n,Math.min(i,t-n),this),n+=i;this.synchronizeInstances()}},t.prototype.setVerticesData=function(e,t,i,n){if(void 0===i&&(i=!1),this._geometry)this._geometry.setVerticesData(e,t,i,n);else{var r=new d.a;r.set(t,e);var o=this.getScene();new f.a(f.a.RandomId(),o,r,i,this)}return this},t.prototype.removeVerticesData=function(e){this._geometry&&this._geometry.removeVerticesData(e)},t.prototype.markVerticesDataAsUpdatable=function(e,t){void 0===t&&(t=!0);var i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)},t.prototype.setVerticesBuffer=function(e){return this._geometry||(this._geometry=f.a.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e),this},t.prototype.updateVerticesData=function(e,t,i,n){return this._geometry?(n?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this},t.prototype.updateMeshPositions=function(e,t){void 0===t&&(t=!0);var i=this.getVerticesData(h.b.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(h.b.PositionKind,i,!1,!1),t){var n=this.getIndices(),r=this.getVerticesData(h.b.NormalKind);if(!r)return this;d.a.ComputeNormals(i,n,r),this.updateVerticesData(h.b.NormalKind,r,!1,!1)}return this},t.prototype.makeGeometryUnique=function(){if(!this._geometry)return this;var e=this._geometry,t=this._geometry.copy(f.a.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this},t.prototype.setIndices=function(e,t,i){if(void 0===t&&(t=null),void 0===i&&(i=!1),this._geometry)this._geometry.setIndices(e,t,i);else{var n=new d.a;n.indices=e;var r=this.getScene();new f.a(f.a.RandomId(),r,n,i,this)}return this},t.prototype.updateIndices=function(e,t,i){return void 0===i&&(i=!1),this._geometry?(this._geometry.updateIndices(e,t,i),this):this},t.prototype.toLeftHanded=function(){return this._geometry?(this._geometry.toLeftHanded(),this):this},t.prototype._bind=function(e,t,i){if(!this._geometry)return this;var n,r=this.getScene().getEngine();if(this._unIndexed)n=null;else switch(i){case g.a.PointFillMode:n=null;break;case g.a.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case g.a.TriangleFillMode:n=this._geometry.getIndexBuffer()}return this._geometry._bind(t,n),this},t.prototype._draw=function(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);var n=this.getScene().getEngine();return this._unIndexed||t==g.a.PointFillMode?n.drawArraysType(t,e.verticesStart,e.verticesCount,i):t==g.a.WireFrameFillMode?n.drawElementsType(t,0,e._linesIndexCount,i):n.drawElementsType(t,e.indexStart,e.indexCount,i),this},t.prototype.registerBeforeRender=function(e){return this.onBeforeRenderObservable.add(e),this},t.prototype.unregisterBeforeRender=function(e){return this.onBeforeRenderObservable.removeCallback(e),this},t.prototype.registerAfterRender=function(e){return this.onAfterRenderObservable.add(e),this},t.prototype.unregisterAfterRender=function(e){return this.onAfterRenderObservable.removeCallback(e),this},t.prototype._getInstancesRenderList=function(e,t){if(void 0===t&&(t=!1),this._instanceDataStorage.isFrozen&&this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch;var i=this.getScene(),n=i._isInIntermediateRendering(),r=n?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,o=this._instanceDataStorage.batchCache;if(o.mustReturn=!1,o.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,o.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){var a=this._instanceDataStorage.visibleInstances,s=i.getRenderId(),c=n?a.intermediateDefaultRenderId:a.defaultRenderId;o.visibleInstances[e]=a[s],!o.visibleInstances[e]&&c&&(o.visibleInstances[e]=a[c])}return o.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==o.visibleInstances[e]&&void 0!==o.visibleInstances[e],this._instanceDataStorage.previousBatch=o,o},t.prototype._renderWithInstances=function(e,t,i,n,r){var o=i.visibleInstances[e._id];if(!o)return this;for(var a=this._instanceDataStorage,s=a.instancesBufferSize,c=a.instancesBuffer,l=16*(o.length+1)*4;a.instancesBufferSize<l;)a.instancesBufferSize*=2;a.instancesData&&s==a.instancesBufferSize||(a.instancesData=new Float32Array(a.instancesBufferSize/4));var u=0,d=0,f=i.renderSelf[e._id];if(this._instanceDataStorage.manualUpdate)d=(f?1:0)+o.length;else{var p=this._effectiveMesh.getWorldMatrix();if(f&&(p.copyToArray(a.instancesData,u),u+=16,d++),o)for(var _=0;_<o.length;_++){o[_].getWorldMatrix().copyToArray(a.instancesData,u),u+=16,d++}}return c&&s==a.instancesBufferSize?c.updateDirectly(a.instancesData,0,d):(c&&c.dispose(),c=new h.a(r,a.instancesData,!0,16,!1,!0),a.instancesBuffer=c,this.setVerticesBuffer(c.createVertexBuffer("world0",0,4)),this.setVerticesBuffer(c.createVertexBuffer("world1",4,4)),this.setVerticesBuffer(c.createVertexBuffer("world2",8,4)),this.setVerticesBuffer(c.createVertexBuffer("world3",12,4))),this._processInstancedBuffers(o,f),this.getScene()._activeIndices.addCount(e.indexCount*d,!1),this._bind(e,n,t),this._draw(e,t,d),r.unbindInstanceAttributes(),this},t.prototype._processInstancedBuffers=function(e,t){},t.prototype._processRendering=function(e,t,i,n,r,o,a){var s=this.getScene(),c=s.getEngine();if(r)this._renderWithInstances(e,i,n,t,c);else{var l=0;n.renderSelf[e._id]&&(o&&o(!1,this._effectiveMesh.getWorldMatrix(),a),l++,this._draw(e,i,this._instanceDataStorage.overridenInstanceCount));var u=n.visibleInstances[e._id];if(u){var h=u.length;l+=h;for(var d=0;d<h;d++){var f=u[d].getWorldMatrix();o&&o(!0,f,a),this._draw(e,i)}}s._activeIndices.addCount(e.indexCount*l,!1)}return this},t.prototype._rebuild=function(){this._instanceDataStorage.instancesBuffer&&(this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null),e.prototype._rebuild.call(this)},t.prototype._freeze=function(){if(this.subMeshes){for(var e=0;e<this.subMeshes.length;e++)this._getInstancesRenderList(e);this._effectiveMaterial=null,this._instanceDataStorage.isFrozen=!0}},t.prototype._unFreeze=function(){this._instanceDataStorage.isFrozen=!1,this._instanceDataStorage.previousBatch=null},t.prototype.render=function(e,t,i){var n=this.getScene();if(this._internalAbstractMeshDataInfo._isActiveIntermediate?this._internalAbstractMeshDataInfo._isActiveIntermediate=!1:this._internalAbstractMeshDataInfo._isActive=!1,this._checkOcclusionQuery())return this;var r=this._getInstancesRenderList(e._id,!!i);if(r.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);var o,a=n.getEngine(),s=r.hardwareInstancedRendering[e._id],c=this._instanceDataStorage,l=e.getMaterial();if(!l)return this;if(!c.isFrozen||!this._effectiveMaterial||this._effectiveMaterial!==l){if(l._storeEffectOnSubMeshes){if(!l.isReadyForSubMesh(this,e,s))return this}else if(!l.isReady(this,s))return this;this._effectiveMaterial=l}t&&a.setAlphaMode(this._effectiveMaterial.alphaMode);for(var u=0,h=n._beforeRenderingMeshStage;u<h.length;u++){h[u].action(this,e,r)}if(!(o=this._effectiveMaterial._storeEffectOnSubMeshes?e.effect:this._effectiveMaterial.getEffect()))return this;var d,f=i||this._effectiveMesh;if(!c.isFrozen&&this._effectiveMaterial.backFaceCulling){var p=f._getWorldMatrixDeterminant();null==(d=this.overrideMaterialSideOrientation)&&(d=this._effectiveMaterial.sideOrientation),p<0&&(d=d===g.a.ClockWiseSideOrientation?g.a.CounterClockWiseSideOrientation:g.a.ClockWiseSideOrientation),c.sideOrientation=d}else d=c.sideOrientation;var _=this._effectiveMaterial._preBind(o,d);this._effectiveMaterial.forceDepthWrite&&a.setDepthWrite(!0);var m=n.forcePointsCloud?g.a.PointFillMode:n.forceWireframe?g.a.WireFrameFillMode:this._effectiveMaterial.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),s||this._bind(e,o,m);var v=f.getWorldMatrix();this._effectiveMaterial._storeEffectOnSubMeshes?this._effectiveMaterial.bindForSubMesh(v,this,e):this._effectiveMaterial.bind(v,this),!this._effectiveMaterial.backFaceCulling&&this._effectiveMaterial.separateCullingPass&&(a.setState(!0,this._effectiveMaterial.zOffset,!1,!_),this._processRendering(e,o,m,r,s,this._onBeforeDraw,this._effectiveMaterial),a.setState(!0,this._effectiveMaterial.zOffset,!1,_)),this._processRendering(e,o,m,r,s,this._onBeforeDraw,this._effectiveMaterial),this._effectiveMaterial.unbind();for(var y=0,b=n._afterRenderingMeshStage;y<b.length;y++){b[y].action(this,e,r)}return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),this},t.prototype._onBeforeDraw=function(e,t,i){e&&i&&i.bindOnlyWorldMatrix(t)},t.prototype.cleanMatrixWeights=function(){this.isVerticesDataPresent(h.b.MatricesWeightsKind)&&(this.isVerticesDataPresent(h.b.MatricesWeightsExtraKind)?this.normalizeSkinWeightsAndExtra():this.normalizeSkinFourWeights())},t.prototype.normalizeSkinFourWeights=function(){for(var e=this.getVerticesData(h.b.MatricesWeightsKind),t=e.length,i=0;i<t;i+=4){var n=e[i]+e[i+1]+e[i+2]+e[i+3];if(0===n)e[i]=1;else{var r=1/n;e[i]*=r,e[i+1]*=r,e[i+2]*=r,e[i+3]*=r}}this.setVerticesData(h.b.MatricesWeightsKind,e)},t.prototype.normalizeSkinWeightsAndExtra=function(){for(var e=this.getVerticesData(h.b.MatricesWeightsExtraKind),t=this.getVerticesData(h.b.MatricesWeightsKind),i=t.length,n=0;n<i;n+=4){var r=t[n]+t[n+1]+t[n+2]+t[n+3];if(0===(r+=e[n]+e[n+1]+e[n+2]+e[n+3]))t[n]=1;else{var o=1/r;t[n]*=o,t[n+1]*=o,t[n+2]*=o,t[n+3]*=o,e[n]*=o,e[n+1]*=o,e[n+2]*=o,e[n+3]*=o}}this.setVerticesData(h.b.MatricesWeightsKind,t),this.setVerticesData(h.b.MatricesWeightsKind,e)},t.prototype.validateSkinning=function(){var e=this.getVerticesData(h.b.MatricesWeightsExtraKind),t=this.getVerticesData(h.b.MatricesWeightsKind);if(null===t||null==this.skeleton)return{skinned:!1,valid:!0,report:"not skinned"};for(var i=t.length,n=0,r=0,o=0,a=0,s=null===e?4:8,c=new Array,l=0;l<=s;l++)c[l]=0;for(l=0;l<i;l+=4){for(var u=t[l],d=u,f=0===d?0:1,p=1;p<s;p++){var _=p<4?t[l+p]:e[l+p-4];_>u&&n++,0!==_&&f++,d+=_,u=_}if(c[f]++,f>o&&(o=f),0===d)r++;else{var m=1/d,g=0;for(p=0;p<s;p++)g+=p<4?Math.abs(t[l+p]-t[l+p]*m):Math.abs(e[l+p-4]-e[l+p-4]*m);g>.001&&a++}}var v=this.skeleton.bones.length,y=this.getVerticesData(h.b.MatricesIndicesKind),b=this.getVerticesData(h.b.MatricesIndicesExtraKind),T=0;for(l=0;l<i;l++)for(p=0;p<s;p++){var E=p<4?y[p]:b[p-4];(E>=v||E<0)&&T++}return{skinned:!0,valid:0===r&&0===a&&0===T,report:"Number of Weights = "+i/4+"\nMaximum influences = "+o+"\nMissing Weights = "+r+"\nNot Sorted = "+n+"\nNot Normalized = "+a+"\nWeightCounts = ["+c+"]\nNumber of bones = "+v+"\nBad Bone Indices = "+T}},t.prototype._checkDelayState=function(){var e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===b.a.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=b.a.DELAYLOADSTATE_LOADING,this._queueLoad(e)),this},t.prototype._queueLoad=function(e){var t=this;e._addPendingData(this);var i=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return o.b.LoadFile(this.delayLoadingFile,function(i){i instanceof ArrayBuffer?t._delayLoadingFunction(i,t):t._delayLoadingFunction(JSON.parse(i),t),t.instances.forEach(function(e){e.refreshBoundingInfo(),e._syncSubMeshes()}),t.delayLoadState=b.a.DELAYLOADSTATE_LOADED,e._removePendingData(t)},function(){},e.offlineProvider,i),this},t.prototype.isInFrustum=function(t){return this.delayLoadState!==b.a.DELAYLOADSTATE_LOADING&&(!!e.prototype.isInFrustum.call(this,t)&&(this._checkDelayState(),!0))},t.prototype.setMaterialByID=function(e){var t,i=this.getScene().materials;for(t=i.length-1;t>-1;t--)if(i[t].id===e)return this.material=i[t],this;var n=this.getScene().multiMaterials;for(t=n.length-1;t>-1;t--)if(n[t].id===e)return this.material=n[t],this;return this},t.prototype.getAnimatables=function(){var e=new Array;return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e},t.prototype.bakeTransformIntoVertices=function(e){if(!this.isVerticesDataPresent(h.b.PositionKind))return this;var t=this.subMeshes.splice(0);this._resetPointsArrayCache();var i,n=this.getVerticesData(h.b.PositionKind),r=new Array;for(i=0;i<n.length;i+=3)c.e.TransformCoordinates(c.e.FromArray(n,i),e).toArray(r,i);if(this.setVerticesData(h.b.PositionKind,r,this.getVertexBuffer(h.b.PositionKind).isUpdatable()),this.isVerticesDataPresent(h.b.NormalKind)){for(n=this.getVerticesData(h.b.NormalKind),r=[],i=0;i<n.length;i+=3)c.e.TransformNormal(c.e.FromArray(n,i),e).normalize().toArray(r,i);this.setVerticesData(h.b.NormalKind,r,this.getVertexBuffer(h.b.NormalKind).isUpdatable())}return e.m[0]*e.m[5]*e.m[10]<0&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=t,this},t.prototype.bakeCurrentTransformIntoVertices=function(e){return void 0===e&&(e=!0),this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this},Object.defineProperty(t.prototype,"_positions",{get:function(){return this._geometry?this._geometry._positions:null},enumerable:!0,configurable:!0}),t.prototype._resetPointsArrayCache=function(){return this._geometry&&this._geometry._resetPointsArrayCache(),this},t.prototype._generatePointsArray=function(){return!!this._geometry&&this._geometry._generatePointsArray()},t.prototype.clone=function(e,i,n,r){return void 0===e&&(e=""),void 0===i&&(i=null),void 0===r&&(r=!0),new t(e,this.getScene(),i,this,n,r)},t.prototype.dispose=function(t,i){void 0===i&&(i=!1),this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);var n=this._internalMeshDataInfo;if(n._onBeforeDrawObservable&&n._onBeforeDrawObservable.clear(),n._onBeforeBindObservable&&n._onBeforeBindObservable.clear(),n._onBeforeRenderObservable&&n._onBeforeRenderObservable.clear(),n._onAfterRenderObservable&&n._onAfterRenderObservable.clear(),this._scene.useClonedMeshMap){if(n.meshMap)for(var r in n.meshMap){(s=n.meshMap[r])&&(s._internalMeshDataInfo._source=null,n.meshMap[r]=void 0)}n._source&&n._source._internalMeshDataInfo.meshMap&&(n._source._internalMeshDataInfo.meshMap[this.uniqueId]=void 0)}else for(var o=0,a=this.getScene().meshes;o<a.length;o++){var s;(s=a[o])._internalMeshDataInfo&&s._internalMeshDataInfo._source&&s._internalMeshDataInfo._source===this&&(s._internalMeshDataInfo._source=null)}n._source=null,this._disposeInstanceSpecificData(),e.prototype.dispose.call(this,t,i)},t.prototype._disposeInstanceSpecificData=function(){},t.prototype.applyDisplacementMap=function(e,t,i,n,r,a,s){var c=this;void 0===s&&(s=!1);var l=this.getScene();return o.b.LoadImage(e,function(e){var o=e.width,l=e.height,u=C.a.CreateCanvas(o,l).getContext("2d");u.drawImage(e,0,0);var h=u.getImageData(0,0,o,l).data;c.applyDisplacementMapFromBuffer(h,o,l,t,i,r,a,s),n&&n(c)},function(){},l.offlineProvider),this},t.prototype.applyDisplacementMapFromBuffer=function(e,t,i,n,r,o,a,s){if(void 0===s&&(s=!1),!this.isVerticesDataPresent(h.b.PositionKind)||!this.isVerticesDataPresent(h.b.NormalKind)||!this.isVerticesDataPresent(h.b.UVKind))return E.a.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;var l=this.getVerticesData(h.b.PositionKind,!0,!0),u=this.getVerticesData(h.b.NormalKind),f=this.getVerticesData(h.b.UVKind),p=c.e.Zero(),_=c.e.Zero(),m=c.d.Zero();o=o||c.d.Zero(),a=a||new c.d(1,1);for(var g=0;g<l.length;g+=3){c.e.FromArrayToRef(l,g,p),c.e.FromArrayToRef(u,g,_),c.d.FromArrayToRef(f,g/3*2,m);var v=4*((Math.abs(m.x*a.x+o.x)*t%t|0)+(Math.abs(m.y*a.y+o.y)*i%i|0)*t),y=.3*(e[v]/255)+.59*(e[v+1]/255)+.11*(e[v+2]/255);_.normalize(),_.scaleInPlace(n+(r-n)*y),(p=p.add(_)).toArray(l,g)}return d.a.ComputeNormals(l,this.getIndices(),u),s?(this.setVerticesData(h.b.PositionKind,l),this.setVerticesData(h.b.NormalKind,u)):(this.updateVerticesData(h.b.PositionKind,l),this.updateVerticesData(h.b.NormalKind,u)),this},t.prototype.convertToFlatShadedMesh=function(){var e,t,i=this.getVerticesDataKinds(),n={},r={},o={},a=!1;for(e=0;e<i.length;e++){t=i[e];var s=this.getVertexBuffer(t);t!==h.b.NormalKind?(n[t]=s,r[t]=n[t].getData(),o[t]=[]):(a=s.isUpdatable(),i.splice(e,1),e--)}var l,u=this.subMeshes.slice(0),d=this.getIndices(),f=this.getTotalIndices();for(l=0;l<f;l++){var p=d[l];for(e=0;e<i.length;e++)for(var m=n[t=i[e]].getStrideSize(),g=0;g<m;g++)o[t].push(r[t][p*m+g])}var v=[],y=o[h.b.PositionKind];for(l=0;l<f;l+=3){d[l]=l,d[l+1]=l+1,d[l+2]=l+2;for(var b=c.e.FromArray(y,3*l),T=c.e.FromArray(y,3*(l+1)),E=c.e.FromArray(y,3*(l+2)),x=b.subtract(T),P=E.subtract(T),A=c.e.Normalize(c.e.Cross(x,P)),S=0;S<3;S++)v.push(A.x),v.push(A.y),v.push(A.z)}for(this.setIndices(d),this.setVerticesData(h.b.NormalKind,v,a),e=0;e<i.length;e++)t=i[e],this.setVerticesData(t,o[t],n[t].isUpdatable());this.releaseSubMeshes();for(var C=0;C<u.length;C++){var R=u[C];_.b.AddToMesh(R.materialIndex,R.indexStart,R.indexCount,R.indexStart,R.indexCount,this)}return this.synchronizeInstances(),this},t.prototype.convertToUnIndexedMesh=function(){var e,t,i=this.getVerticesDataKinds(),n={},r={},o={};for(e=0;e<i.length;e++){t=i[e];var a=this.getVertexBuffer(t);n[t]=a,r[t]=n[t].getData(),o[t]=[]}var s,c=this.subMeshes.slice(0),l=this.getIndices(),u=this.getTotalIndices();for(s=0;s<u;s++){var h=l[s];for(e=0;e<i.length;e++)for(var d=n[t=i[e]].getStrideSize(),f=0;f<d;f++)o[t].push(r[t][h*d+f])}for(s=0;s<u;s+=3)l[s]=s,l[s+1]=s+1,l[s+2]=s+2;for(this.setIndices(l),e=0;e<i.length;e++)t=i[e],this.setVerticesData(t,o[t],n[t].isUpdatable());this.releaseSubMeshes();for(var p=0;p<c.length;p++){var m=c[p];_.b.AddToMesh(m.materialIndex,m.indexStart,m.indexCount,m.indexStart,m.indexCount,this)}return this._unIndexed=!0,this.synchronizeInstances(),this},t.prototype.flipFaces=function(e){void 0===e&&(e=!1);var t,i,n=d.a.ExtractFromMesh(this);if(e&&this.isVerticesDataPresent(h.b.NormalKind)&&n.normals)for(t=0;t<n.normals.length;t++)n.normals[t]*=-1;if(n.indices)for(t=0;t<n.indices.length;t+=3)i=n.indices[t+1],n.indices[t+1]=n.indices[t+2],n.indices[t+2]=i;return n.applyToMesh(this,this.isVertexBufferUpdatable(h.b.PositionKind)),this},t.prototype.increaseVertices=function(e){var t=d.a.ExtractFromMesh(this),i=t.uvs,n=t.indices,r=t.positions,o=t.normals;if(null===n||null===r||null===o||null===i)E.a.Warn("VertexData contains null entries");else{for(var a,s,l=e+1,u=new Array,f=0;f<l+1;f++)u[f]=new Array;var p,_=new c.e(0,0,0),m=new c.e(0,0,0),g=new c.d(0,0),v=new Array,y=new Array,b=new Array,T=r.length,x=i.length;for(f=0;f<n.length;f+=3){y[0]=n[f],y[1]=n[f+1],y[2]=n[f+2];for(var P=0;P<3;P++)if(a=y[P],s=y[(P+1)%3],void 0===b[a]&&void 0===b[s]?(b[a]=new Array,b[s]=new Array):(void 0===b[a]&&(b[a]=new Array),void 0===b[s]&&(b[s]=new Array)),void 0===b[a][s]&&void 0===b[s][a]){b[a][s]=[],_.x=(r[3*s]-r[3*a])/l,_.y=(r[3*s+1]-r[3*a+1])/l,_.z=(r[3*s+2]-r[3*a+2])/l,m.x=(o[3*s]-o[3*a])/l,m.y=(o[3*s+1]-o[3*a+1])/l,m.z=(o[3*s+2]-o[3*a+2])/l,g.x=(i[2*s]-i[2*a])/l,g.y=(i[2*s+1]-i[2*a+1])/l,b[a][s].push(a);for(var A=1;A<l;A++)b[a][s].push(r.length/3),r[T]=r[3*a]+A*_.x,o[T++]=o[3*a]+A*m.x,r[T]=r[3*a+1]+A*_.y,o[T++]=o[3*a+1]+A*m.y,r[T]=r[3*a+2]+A*_.z,o[T++]=o[3*a+2]+A*m.z,i[x++]=i[2*a]+A*g.x,i[x++]=i[2*a+1]+A*g.y;b[a][s].push(s),b[s][a]=new Array,p=b[a][s].length;for(var S=0;S<p;S++)b[s][a][S]=b[a][s][p-1-S]}u[0][0]=n[f],u[1][0]=b[n[f]][n[f+1]][1],u[1][1]=b[n[f]][n[f+2]][1];for(A=2;A<l;A++){u[A][0]=b[n[f]][n[f+1]][A],u[A][A]=b[n[f]][n[f+2]][A],_.x=(r[3*u[A][A]]-r[3*u[A][0]])/A,_.y=(r[3*u[A][A]+1]-r[3*u[A][0]+1])/A,_.z=(r[3*u[A][A]+2]-r[3*u[A][0]+2])/A,m.x=(o[3*u[A][A]]-o[3*u[A][0]])/A,m.y=(o[3*u[A][A]+1]-o[3*u[A][0]+1])/A,m.z=(o[3*u[A][A]+2]-o[3*u[A][0]+2])/A,g.x=(i[2*u[A][A]]-i[2*u[A][0]])/A,g.y=(i[2*u[A][A]+1]-i[2*u[A][0]+1])/A;for(P=1;P<A;P++)u[A][P]=r.length/3,r[T]=r[3*u[A][0]]+P*_.x,o[T++]=o[3*u[A][0]]+P*m.x,r[T]=r[3*u[A][0]+1]+P*_.y,o[T++]=o[3*u[A][0]+1]+P*m.y,r[T]=r[3*u[A][0]+2]+P*_.z,o[T++]=o[3*u[A][0]+2]+P*m.z,i[x++]=i[2*u[A][0]]+P*g.x,i[x++]=i[2*u[A][0]+1]+P*g.y}u[l]=b[n[f+1]][n[f+2]],v.push(u[0][0],u[1][0],u[1][1]);for(A=1;A<l;A++){for(P=0;P<A;P++)v.push(u[A][P],u[A+1][P],u[A+1][P+1]),v.push(u[A][P],u[A+1][P+1],u[A][P+1]);v.push(u[A][P],u[A+1][P],u[A+1][P+1])}}t.indices=v,t.applyToMesh(this,this.isVertexBufferUpdatable(h.b.PositionKind))}},t.prototype.forceSharedVertices=function(){var e=d.a.ExtractFromMesh(this),t=e.uvs,i=e.indices,n=e.positions,r=e.colors;if(void 0===i||void 0===n||null===i||null===n)E.a.Warn("VertexData contains empty entries");else{for(var o,a,s=new Array,c=new Array,l=new Array,u=new Array,f=new Array,p=0,_=new Array,m=0;m<i.length;m+=3){a=[i[m],i[m+1],i[m+2]],f=new Array;for(var g=0;g<3;g++){f[g]="";for(var v=0;v<3;v++)Math.abs(n[3*a[g]+v])<1e-8&&(n[3*a[g]+v]=0),f[g]+=n[3*a[g]+v]+"|";f[g]=f[g].slice(0,-1)}if(f[0]!=f[1]&&f[0]!=f[2]&&f[1]!=f[2])for(g=0;g<3;g++){if((o=_.indexOf(f[g]))<0){_.push(f[g]),o=p++;for(v=0;v<3;v++)s.push(n[3*a[g]+v]);if(null!=r)for(v=0;v<4;v++)u.push(r[4*a[g]+v]);if(null!=t)for(v=0;v<2;v++)l.push(t[2*a[g]+v])}c.push(o)}}var y=new Array;d.a.ComputeNormals(s,c,y),e.positions=s,e.indices=c,e.normals=y,null!=t&&(e.uvs=l),null!=r&&(e.colors=u),e.applyToMesh(this,this.isVertexBufferUpdatable(h.b.PositionKind))}},t._instancedMeshFactory=function(e,t){throw P.a.WarnImport("InstancedMesh")},t._PhysicsImpostorParser=function(e,t,i){throw P.a.WarnImport("PhysicsImpostor")},t.prototype.createInstance=function(e){return t._instancedMeshFactory(e,this)},t.prototype.synchronizeInstances=function(){for(var e=0;e<this.instances.length;e++){this.instances[e]._syncSubMeshes()}return this},t.prototype.optimizeIndices=function(e){var t=this,i=this.getIndices(),n=this.getVerticesData(h.b.PositionKind);if(!n||!i)return this;for(var r=new Array,a=0;a<n.length;a+=3)r.push(c.e.FromArray(n,a));var s=new Array;return o.a.SyncAsyncForLoop(r.length,40,function(e){for(var t=r.length-1-e,i=r[t],n=0;n<t;++n){var o=r[n];if(i.equals(o)){s[t]=n;break}}},function(){for(var n=0;n<i.length;++n)i[n]=s[i[n]]||i[n];var r=t.subMeshes.slice(0);t.setIndices(i),t.subMeshes=r,e&&e(t)}),this},t.prototype.serialize=function(e){e.name=this.name,e.id=this.id,e.type=this.getClassName(),s.a&&s.a.HasTags(this)&&(e.tags=s.a.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.checkCollisions=this.checkCollisions,e.isBlocker=this.isBlocker,e.overrideMaterialSideOrientation=this.overrideMaterialSideOrientation,this.parent&&(e.parentId=this.parent.id),e.isUnIndexed=this.isUnIndexed;var t=this._geometry;if(t){var i=t.id;e.geometryId=i,e.subMeshes=[];for(var n=0;n<this.subMeshes.length;n++){var r=this.subMeshes[n];e.subMeshes.push({materialIndex:r.materialIndex,verticesStart:r.verticesStart,verticesCount:r.verticesCount,indexStart:r.indexStart,indexCount:r.indexCount})}}if(this.material?this.material.doNotSerialize||(e.materialId=this.material.id):this.material=null,this.morphTargetManager&&(e.morphTargetManagerId=this.morphTargetManager.uniqueId),this.skeleton&&(e.skeletonId=this.skeleton.id),this.getScene()._getComponent(A.a.NAME_PHYSICSENGINE)){var o=this.getPhysicsImpostor();o&&(e.physicsMass=o.getParam("mass"),e.physicsFriction=o.getParam("friction"),e.physicsRestitution=o.getParam("mass"),e.physicsImpostor=o.type)}this.metadata&&(e.metadata=this.metadata),e.instances=[];for(var a=0;a<this.instances.length;a++){var c=this.instances[a];if(!c.doNotSerialize){var l={name:c.name,id:c.id,position:c.position.asArray(),scaling:c.scaling.asArray()};c.parent&&(l.parentId=c.parent.id),c.rotationQuaternion?l.rotationQuaternion=c.rotationQuaternion.asArray():c.rotation&&(l.rotation=c.rotation.asArray()),e.instances.push(l),T.a.AppendSerializedAnimations(c,l),l.ranges=c.serializeAnimationRanges()}}T.a.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))},t.prototype._syncGeometryWithMorphTargetManager=function(){if(this.geometry){this._markSubMeshesAsAttributesDirty();var e=this._internalMeshDataInfo._morphTargetManager;if(e&&e.vertexCount){if(e.vertexCount!==this.getTotalVertices())return E.a.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."),void(this.morphTargetManager=null);for(var t=0;t<e.numInfluencers;t++){var i=e.getActiveTarget(t),n=i.getPositions();if(!n)return void E.a.Error("Invalid morph target. Target must have positions.");this.geometry.setVerticesData(h.b.PositionKind+t,n,!1,3);var r=i.getNormals();r&&this.geometry.setVerticesData(h.b.NormalKind+t,r,!1,3);var o=i.getTangents();o&&this.geometry.setVerticesData(h.b.TangentKind+t,o,!1,3);var a=i.getUVs();a&&this.geometry.setVerticesData(h.b.UVKind+"_"+t,a,!1,2)}}else for(t=0;this.geometry.isVerticesDataPresent(h.b.PositionKind+t);)this.geometry.removeVerticesData(h.b.PositionKind+t),this.geometry.isVerticesDataPresent(h.b.NormalKind+t)&&this.geometry.removeVerticesData(h.b.NormalKind+t),this.geometry.isVerticesDataPresent(h.b.TangentKind+t)&&this.geometry.removeVerticesData(h.b.TangentKind+t),this.geometry.isVerticesDataPresent(h.b.UVKind+t)&&this.geometry.removeVerticesData(h.b.UVKind+"_"+t),t++}},t.Parse=function(e,i,n){var r;if((r=e.type&&"GroundMesh"===e.type?t._GroundMeshParser(e,i):new t(e.name,i)).id=e.id,s.a&&s.a.AddTagsTo(r,e.tags),r.position=c.e.FromArray(e.position),void 0!==e.metadata&&(r.metadata=e.metadata),e.rotationQuaternion?r.rotationQuaternion=c.b.FromArray(e.rotationQuaternion):e.rotation&&(r.rotation=c.e.FromArray(e.rotation)),r.scaling=c.e.FromArray(e.scaling),e.localMatrix?r.setPreTransformMatrix(c.a.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(c.a.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r.isVisible=e.isVisible,r.infiniteDistance=e.infiniteDistance,r.showBoundingBox=e.showBoundingBox,r.showSubMeshesBoundingBox=e.showSubMeshesBoundingBox,void 0!==e.applyFog&&(r.applyFog=e.applyFog),void 0!==e.pickable&&(r.isPickable=e.pickable),void 0!==e.alphaIndex&&(r.alphaIndex=e.alphaIndex),r.receiveShadows=e.receiveShadows,r.billboardMode=e.billboardMode,void 0!==e.visibility&&(r.visibility=e.visibility),r.checkCollisions=e.checkCollisions,r.overrideMaterialSideOrientation=e.overrideMaterialSideOrientation,void 0!==e.isBlocker&&(r.isBlocker=e.isBlocker),r._shouldGenerateFlatShading=e.useFlatShading,e.freezeWorldMatrix&&(r._waitingData.freezeWorldMatrix=e.freezeWorldMatrix),e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.actions&&(r._waitingData.actions=e.actions),void 0!==e.overlayAlpha&&(r.overlayAlpha=e.overlayAlpha),void 0!==e.overlayColor&&(r.overlayColor=l.a.FromArray(e.overlayColor)),void 0!==e.renderOverlay&&(r.renderOverlay=e.renderOverlay),r.isUnIndexed=!!e.isUnIndexed,r.hasVertexAlpha=e.hasVertexAlpha,e.delayLoadingFile?(r.delayLoadState=b.a.DELAYLOADSTATE_NOTLOADED,r.delayLoadingFile=n+e.delayLoadingFile,r._boundingInfo=new m.a(c.e.FromArray(e.boundingBoxMinimum),c.e.FromArray(e.boundingBoxMaximum)),e._binaryInfo&&(r._binaryInfo=e._binaryInfo),r._delayInfo=[],e.hasUVs&&r._delayInfo.push(h.b.UVKind),e.hasUVs2&&r._delayInfo.push(h.b.UV2Kind),e.hasUVs3&&r._delayInfo.push(h.b.UV3Kind),e.hasUVs4&&r._delayInfo.push(h.b.UV4Kind),e.hasUVs5&&r._delayInfo.push(h.b.UV5Kind),e.hasUVs6&&r._delayInfo.push(h.b.UV6Kind),e.hasColors&&r._delayInfo.push(h.b.ColorKind),e.hasMatricesIndices&&r._delayInfo.push(h.b.MatricesIndicesKind),e.hasMatricesWeights&&r._delayInfo.push(h.b.MatricesWeightsKind),r._delayLoadingFunction=f.a._ImportGeometry,y.a.ForceFullSceneLoadingForIncremental&&r._checkDelayState()):f.a._ImportGeometry(e,r),e.materialId?r.setMaterialByID(e.materialId):r.material=null,e.morphTargetManagerId>-1&&(r.morphTargetManager=i.getMorphTargetManagerById(e.morphTargetManagerId)),e.skeletonId>-1&&(r.skeleton=i.getLastSkeletonByID(e.skeletonId),e.numBoneInfluencers&&(r.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(var o=0;o<e.animations.length;o++){var a=e.animations[o];(g=x.a.GetClass("BABYLON.Animation"))&&r.animations.push(g.Parse(a))}u.a.ParseAnimationRanges(r,e,i)}if(e.autoAnimate&&i.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.layerMask&&!isNaN(e.layerMask)?r.layerMask=Math.abs(parseInt(e.layerMask)):r.layerMask=268435455,e.physicsImpostor&&t._PhysicsImpostorParser(i,r,e),e.lodMeshIds&&(r._waitingData.lods={ids:e.lodMeshIds,distances:e.lodDistances?e.lodDistances:null,coverages:e.lodCoverages?e.lodCoverages:null}),e.instances)for(var d=0;d<e.instances.length;d++){var p=e.instances[d],_=r.createInstance(p.name);if(p.id&&(_.id=p.id),s.a&&(p.tags?s.a.AddTagsTo(_,p.tags):s.a.AddTagsTo(_,e.tags)),_.position=c.e.FromArray(p.position),void 0!==p.metadata&&(_.metadata=p.metadata),p.parentId&&(_._waitingParentId=p.parentId),p.rotationQuaternion?_.rotationQuaternion=c.b.FromArray(p.rotationQuaternion):p.rotation&&(_.rotation=c.e.FromArray(p.rotation)),_.scaling=c.e.FromArray(p.scaling),null!=p.checkCollisions&&null!=p.checkCollisions&&(_.checkCollisions=p.checkCollisions),null!=p.pickable&&null!=p.pickable&&(_.isPickable=p.pickable),null!=p.showBoundingBox&&null!=p.showBoundingBox&&(_.showBoundingBox=p.showBoundingBox),null!=p.showSubMeshesBoundingBox&&null!=p.showSubMeshesBoundingBox&&(_.showSubMeshesBoundingBox=p.showSubMeshesBoundingBox),null!=p.alphaIndex&&null!=p.showSubMeshesBoundingBox&&(_.alphaIndex=p.alphaIndex),p.physicsImpostor&&t._PhysicsImpostorParser(i,_,p),p.animations){for(o=0;o<p.animations.length;o++){var g;a=p.animations[o],(g=x.a.GetClass("BABYLON.Animation"))&&_.animations.push(g.Parse(a))}u.a.ParseAnimationRanges(_,p,i),p.autoAnimate&&i.beginAnimation(_,p.autoAnimateFrom,p.autoAnimateTo,p.autoAnimateLoop,p.autoAnimateSpeed||1)}}return r},t.CreateRibbon=function(e,t,i,n,r,o,a,s,c){throw P.a.WarnImport("MeshBuilder")},t.CreateDisc=function(e,t,i,n,r,o){throw void 0===n&&(n=null),P.a.WarnImport("MeshBuilder")},t.CreateBox=function(e,t,i,n,r){throw void 0===i&&(i=null),P.a.WarnImport("MeshBuilder")},t.CreateSphere=function(e,t,i,n,r,o){throw P.a.WarnImport("MeshBuilder")},t.CreateHemisphere=function(e,t,i,n){throw P.a.WarnImport("MeshBuilder")},t.CreateCylinder=function(e,t,i,n,r,o,a,s,c){throw P.a.WarnImport("MeshBuilder")},t.CreateTorus=function(e,t,i,n,r,o,a){throw P.a.WarnImport("MeshBuilder")},t.CreateTorusKnot=function(e,t,i,n,r,o,a,s,c,l){throw P.a.WarnImport("MeshBuilder")},t.CreateLines=function(e,t,i,n,r){throw void 0===i&&(i=null),void 0===n&&(n=!1),void 0===r&&(r=null),P.a.WarnImport("MeshBuilder")},t.CreateDashedLines=function(e,t,i,n,r,o,a,s){throw void 0===o&&(o=null),P.a.WarnImport("MeshBuilder")},t.CreatePolygon=function(e,t,i,n,r,o,a){throw void 0===a&&(a=earcut),P.a.WarnImport("MeshBuilder")},t.ExtrudePolygon=function(e,t,i,n,r,o,a,s){throw void 0===s&&(s=earcut),P.a.WarnImport("MeshBuilder")},t.ExtrudeShape=function(e,t,i,n,r,o,a,s,c,l){throw void 0===a&&(a=null),P.a.WarnImport("MeshBuilder")},t.ExtrudeShapeCustom=function(e,t,i,n,r,o,a,s,c,l,u,h){throw P.a.WarnImport("MeshBuilder")},t.CreateLathe=function(e,t,i,n,r,o,a){throw P.a.WarnImport("MeshBuilder")},t.CreatePlane=function(e,t,i,n,r){throw P.a.WarnImport("MeshBuilder")},t.CreateGround=function(e,t,i,n,r,o){throw P.a.WarnImport("MeshBuilder")},t.CreateTiledGround=function(e,t,i,n,r,o,a,s,c){throw P.a.WarnImport("MeshBuilder")},t.CreateGroundFromHeightMap=function(e,t,i,n,r,o,a,s,c,l,u){throw P.a.WarnImport("MeshBuilder")},t.CreateTube=function(e,t,i,n,r,o,a,s,c,l){throw P.a.WarnImport("MeshBuilder")},t.CreatePolyhedron=function(e,t,i){throw P.a.WarnImport("MeshBuilder")},t.CreateIcoSphere=function(e,t,i){throw P.a.WarnImport("MeshBuilder")},t.CreateDecal=function(e,t,i,n,r,o){throw P.a.WarnImport("MeshBuilder")},t.prototype.setPositionsForCPUSkinning=function(){var e=this._internalMeshDataInfo;if(!e._sourcePositions){var t=this.getVerticesData(h.b.PositionKind);if(!t)return e._sourcePositions;e._sourcePositions=new Float32Array(t),this.isVertexBufferUpdatable(h.b.PositionKind)||this.setVerticesData(h.b.PositionKind,t,!0)}return e._sourcePositions},t.prototype.setNormalsForCPUSkinning=function(){var e=this._internalMeshDataInfo;if(!e._sourceNormals){var t=this.getVerticesData(h.b.NormalKind);if(!t)return e._sourceNormals;e._sourceNormals=new Float32Array(t),this.isVertexBufferUpdatable(h.b.NormalKind)||this.setVerticesData(h.b.NormalKind,t,!0)}return e._sourceNormals},t.prototype.applySkeleton=function(e){if(!this.geometry)return this;if(this.geometry._softwareSkinningFrameId==this.getScene().getFrameId())return this;if(this.geometry._softwareSkinningFrameId=this.getScene().getFrameId(),!this.isVerticesDataPresent(h.b.PositionKind))return this;if(!this.isVerticesDataPresent(h.b.NormalKind))return this;if(!this.isVerticesDataPresent(h.b.MatricesIndicesKind))return this;if(!this.isVerticesDataPresent(h.b.MatricesWeightsKind))return this;var t=this._internalMeshDataInfo;if(!t._sourcePositions){var i=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=i}t._sourceNormals||this.setNormalsForCPUSkinning();var n=this.getVerticesData(h.b.PositionKind);if(!n)return this;n instanceof Float32Array||(n=new Float32Array(n));var r=this.getVerticesData(h.b.NormalKind);if(!r)return this;r instanceof Float32Array||(r=new Float32Array(r));var o=this.getVerticesData(h.b.MatricesIndicesKind),a=this.getVerticesData(h.b.MatricesWeightsKind);if(!a||!o)return this;for(var s,l=this.numBoneInfluencers>4,u=l?this.getVerticesData(h.b.MatricesIndicesExtraKind):null,d=l?this.getVerticesData(h.b.MatricesWeightsExtraKind):null,f=e.getTransformMatrices(this),p=c.e.Zero(),_=new c.a,m=new c.a,g=0,v=0;v<n.length;v+=3,g+=4){var y;for(s=0;s<4;s++)(y=a[g+s])>0&&(c.a.FromFloat32ArrayToRefScaled(f,Math.floor(16*o[g+s]),y,m),_.addToSelf(m));if(l)for(s=0;s<4;s++)(y=d[g+s])>0&&(c.a.FromFloat32ArrayToRefScaled(f,Math.floor(16*u[g+s]),y,m),_.addToSelf(m));c.e.TransformCoordinatesFromFloatsToRef(t._sourcePositions[v],t._sourcePositions[v+1],t._sourcePositions[v+2],_,p),p.toArray(n,v),c.e.TransformNormalFromFloatsToRef(t._sourceNormals[v],t._sourceNormals[v+1],t._sourceNormals[v+2],_,p),p.toArray(r,v),_.reset()}return this.updateVerticesData(h.b.PositionKind,n),this.updateVerticesData(h.b.NormalKind,r),this},t.MinMax=function(e){var t=null,i=null;return e.forEach(function(e){var n=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(n.minimumWorld),i.maximizeInPlace(n.maximumWorld)):(t=n.minimumWorld,i=n.maximumWorld)}),t&&i?{min:t,max:i}:{min:c.e.Zero(),max:c.e.Zero()}},t.Center=function(e){var i=e instanceof Array?t.MinMax(e):e;return c.e.Center(i.min,i.max)},t.MergeMeshes=function(e,i,n,r,o,a){var s;if(void 0===i&&(i=!0),!n){var c=0;for(s=0;s<e.length;s++)if(e[s]&&(c+=e[s].getTotalVertices())>=65536)return E.a.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}if(a){var l,u,h=null;o=!1}var f,p=new Array,m=new Array,g=null,y=new Array,b=null;for(s=0;s<e.length;s++)if(e[s]){var T=e[s];if(T.isAnInstance)return E.a.Warn("Cannot merge instance meshes."),null;var x=T.computeWorldMatrix(!0);if((f=d.a.ExtractFromMesh(T,!0,!0)).transform(x),g?g.merge(f,n):(g=f,b=T),o&&y.push(T.getTotalIndices()),a)if(T.material){var P=T.material;if(P instanceof v.a){for(u=0;u<P.subMaterials.length;u++)p.indexOf(P.subMaterials[u])<0&&p.push(P.subMaterials[u]);for(l=0;l<T.subMeshes.length;l++)m.push(p.indexOf(P.subMaterials[T.subMeshes[l].materialIndex])),y.push(T.subMeshes[l].indexCount)}else for(p.indexOf(P)<0&&p.push(P),l=0;l<T.subMeshes.length;l++)m.push(p.indexOf(P)),y.push(T.subMeshes[l].indexCount)}else for(l=0;l<T.subMeshes.length;l++)m.push(0),y.push(T.subMeshes[l].indexCount)}if(b=b,r||(r=new t(b.name+"_merged",b.getScene())),g.applyToMesh(r),r.checkCollisions=b.checkCollisions,i)for(s=0;s<e.length;s++)e[s]&&e[s].dispose();if(o||a){r.releaseSubMeshes(),s=0;for(var A=0;s<y.length;)_.b.CreateFromIndices(0,A,y[s],r),A+=y[s],s++}if(a){for((h=new v.a(b.name+"_merged",b.getScene())).subMaterials=p,l=0;l<r.subMeshes.length;l++)r.subMeshes[l].materialIndex=m[l];r.material=h}else r.material=b.material;return r},t.prototype.addInstance=function(e){e._indexInSourceMeshInstanceArray=this.instances.length,this.instances.push(e)},t.prototype.removeInstance=function(e){var t=e._indexInSourceMeshInstanceArray;if(-1!=t){if(t!==this.instances.length-1){var i=this.instances[this.instances.length-1];this.instances[t]=i,i._indexInSourceMeshInstanceArray=t}e._indexInSourceMeshInstanceArray=-1,this.instances.pop()}},t.FRONTSIDE=d.a.FRONTSIDE,t.BACKSIDE=d.a.BACKSIDE,t.DOUBLESIDE=d.a.DOUBLESIDE,t.DEFAULTSIDE=d.a.DEFAULTSIDE,t.NO_CAP=0,t.CAP_START=1,t.CAP_END=2,t.CAP_ALL=3,t.NO_FLIP=0,t.FLIP_TILE=1,t.ROTATE_TILE=2,t.FLIP_ROW=3,t.ROTATE_ROW=4,t.FLIP_N_ROTATE_TILE=5,t.FLIP_N_ROTATE_ROW=6,t.CENTER=0,t.LEFT=1,t.RIGHT=2,t.TOP=3,t.BOTTOM=4,t._GroundMeshParser=function(e,t){throw P.a.WarnImport("GroundMesh")},t}(p.a)},function(e,t,i){"use strict";i.d(t,"a",function(){return n}),i.d(t,"d",function(){return r}),i.d(t,"b",function(){return o}),i.d(t,"c",function(){return a});var n=function(){function e(e,t,i,n){void 0===t&&(t=!1),this.initalize(e,t,i,n)}return e.prototype.initalize=function(e,t,i,n){return void 0===t&&(t=!1),this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=n,this},e}(),r=function(e,t,i){void 0===i&&(i=null),this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1},o=function(){function e(){}return e.prototype.dispose=function(){if(this._observers&&this._observables)for(var e=0;e<this._observers.length;e++)this._observables[e].remove(this._observers[e]);this._observers=null,this._observables=null},e.Watch=function(t,i,n,r){void 0===n&&(n=-1),void 0===r&&(r=null);var o=new e;o._observers=new Array,o._observables=t;for(var a=0,s=t;a<s.length;a++){var c=s[a].add(i,n,!1,r);c&&o._observers.push(c)}return o},e}(),a=function(){function e(e){this._observers=new Array,this._eventState=new n(0),e&&(this._onObserverAdded=e)}return Object.defineProperty(e.prototype,"observers",{get:function(){return this._observers},enumerable:!0,configurable:!0}),e.prototype.add=function(e,t,i,n,o){if(void 0===t&&(t=-1),void 0===i&&(i=!1),void 0===n&&(n=null),void 0===o&&(o=!1),!e)return null;var a=new r(e,t,n);return a.unregisterOnNextCall=o,i?this._observers.unshift(a):this._observers.push(a),this._onObserverAdded&&this._onObserverAdded(a),a},e.prototype.addOnce=function(e){return this.add(e,void 0,void 0,void 0,!0)},e.prototype.remove=function(e){return!!e&&(-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))},e.prototype.removeCallback=function(e,t){for(var i=0;i<this._observers.length;i++){var n=this._observers[i];if(!n._willBeUnregistered&&(n.callback===e&&(!t||t===n.scope)))return this._deferUnregister(n),!0}return!1},e.prototype._deferUnregister=function(e){var t=this;e.unregisterOnNextCall=!1,e._willBeUnregistered=!0,setTimeout(function(){t._remove(e)},0)},e.prototype._remove=function(e){if(!e)return!1;var t=this._observers.indexOf(e);return-1!==t&&(this._observers.splice(t,1),!0)},e.prototype.makeObserverTopPriority=function(e){this._remove(e),this._observers.unshift(e)},e.prototype.makeObserverBottomPriority=function(e){this._remove(e),this._observers.push(e)},e.prototype.notifyObservers=function(e,t,i,n){if(void 0===t&&(t=-1),!this._observers.length)return!0;var r=this._eventState;r.mask=t,r.target=i,r.currentTarget=n,r.skipNextObservers=!1,r.lastReturnValue=e;for(var o=0,a=this._observers;o<a.length;o++){var s=a[o];if(!s._willBeUnregistered&&(s.mask&t&&(s.scope?r.lastReturnValue=s.callback.apply(s.scope,[e,r]):r.lastReturnValue=s.callback(e,r),s.unregisterOnNextCall&&this._deferUnregister(s)),r.skipNextObservers))return!1}return!0},e.prototype.notifyObserversWithPromise=function(e,t,i,n){var r=this;void 0===t&&(t=-1);var o=Promise.resolve(e);if(!this._observers.length)return o;var a=this._eventState;return a.mask=t,a.target=i,a.currentTarget=n,a.skipNextObservers=!1,this._observers.forEach(function(i){a.skipNextObservers||i._willBeUnregistered||i.mask&t&&(o=i.scope?o.then(function(t){return a.lastReturnValue=t,i.callback.apply(i.scope,[e,a])}):o.then(function(t){return a.lastReturnValue=t,i.callback(e,a)}),i.unregisterOnNextCall&&r._deferUnregister(i))}),o.then(function(){return e})},e.prototype.notifyObserver=function(e,t,i){void 0===i&&(i=-1);var n=this._eventState;n.mask=i,n.skipNextObservers=!1,e.callback(t,n)},e.prototype.hasObservers=function(){return this._observers.length>0},e.prototype.clear=function(){this._observers=new Array,this._onObserverAdded=null},e.prototype.clone=function(){var t=new e;return t._observers=this._observers.slice(0),t},e.prototype.hasSpecificMask=function(e){void 0===e&&(e=-1);for(var t=0,i=this._observers;t<i.length;t++){var n=i[t];if(n.mask&e||n.mask===e)return!0}return!1},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return e._AddLogEntry=function(t){e._LogCache=t+e._LogCache,e.OnNewCacheEntry&&e.OnNewCacheEntry(t)},e._FormatMessage=function(e){var t=function(e){return e<10?"0"+e:""+e},i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e},e._LogDisabled=function(e){},e._LogEnabled=function(t){var i=e._FormatMessage(t);console.log("BJS - "+i);var n="<div style='color:white'>"+i+"</div><br>";e._AddLogEntry(n)},e._WarnDisabled=function(e){},e._WarnEnabled=function(t){var i=e._FormatMessage(t);console.warn("BJS - "+i);var n="<div style='color:orange'>"+i+"</div><br>";e._AddLogEntry(n)},e._ErrorDisabled=function(e){},e._ErrorEnabled=function(t){e.errorsCount++;var i=e._FormatMessage(t);console.error("BJS - "+i);var n="<div style='color:red'>"+i+"</div><br>";e._AddLogEntry(n)},Object.defineProperty(e,"LogCache",{get:function(){return e._LogCache},enumerable:!0,configurable:!0}),e.ClearLogCache=function(){e._LogCache="",e.errorsCount=0},Object.defineProperty(e,"LogLevels",{set:function(t){(t&e.MessageLogLevel)===e.MessageLogLevel?e.Log=e._LogEnabled:e.Log=e._LogDisabled,(t&e.WarningLogLevel)===e.WarningLogLevel?e.Warn=e._WarnEnabled:e.Warn=e._WarnDisabled,(t&e.ErrorLogLevel)===e.ErrorLogLevel?e.Error=e._ErrorEnabled:e.Error=e._ErrorDisabled},enumerable:!0,configurable:!0}),e.NoneLogLevel=0,e.MessageLogLevel=1,e.WarningLogLevel=2,e.ErrorLogLevel=4,e.AllLogLevel=7,e._LogCache="",e.errorsCount=0,e.Log=e._LogEnabled,e.Warn=e._WarnEnabled,e.Error=e._ErrorEnabled,e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return c});var n=i(6),r=i(2),o=i(38),a=i(7),s=i(116),c=function(){function e(t,i,r,a,c,l,u,h,d,f){var p,_,m=this;if(void 0===a&&(a=null),void 0===l&&(l=null),void 0===u&&(u=null),void 0===h&&(h=null),void 0===d&&(d=null),this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new n.c,this.onErrorObservable=new n.c,this._onBindObservable=null,this._wasPreviouslyReady=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._valueCache={},this.name=t,i.attributes){var g=i;if(this._engine=r,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,g.uniformBuffersNames)for(var v=0;v<g.uniformBuffersNames.length;v++)this._uniformBuffersNames[g.uniformBuffersNames[v]]=v}else this._engine=c,this.defines=null==l?"":l,this._uniformsNames=r.concat(a),this._samplerList=a?a.slice():[],this._attributesNames=i,this.onError=d,this.onCompiled=h,this._indexParameters=f,this._fallbacks=u;this._attributeLocationByName={},this.uniqueId=e._uniqueIdSeed++;var y=o.a.IsWindowObjectExist()?this._engine.getHostDocument():null;t.vertexSource?p="source:"+t.vertexSource:t.vertexElement?(p=y?y.getElementById(t.vertexElement):null)||(p=t.vertexElement):p=t.vertex||t,t.fragmentSource?_="source:"+t.fragmentSource:t.fragmentElement?(_=y?y.getElementById(t.fragmentElement):null)||(_=t.fragmentElement):_=t.fragment||t;var b={defines:this.defines.split("\n"),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:this._engine._shaderProcessor,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:e.ShadersRepository,includesShadersStore:e.IncludesShadersStore,version:(100*this._engine.webGLVersion).toString(),platformName:this._engine.webGLVersion>=2?"WEBGL2":"WEBGL1"};this._loadShader(p,"Vertex","",function(e){m._loadShader(_,"Fragment","Pixel",function(i){s.a.Process(e,b,function(e){b.isFragment=!0,s.a.Process(i,b,function(i){m._useFinalCode(e,i,t)})})})})}return Object.defineProperty(e.prototype,"onBindObservable",{get:function(){return this._onBindObservable||(this._onBindObservable=new n.c),this._onBindObservable},enumerable:!0,configurable:!0}),e.prototype._useFinalCode=function(e,t,i){if(i){var n=i.vertexElement||i.vertex||i.spectorName||i,r=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode="#define SHADER_NAME vertex:"+n+"\n"+e,this._fragmentSourceCode="#define SHADER_NAME fragment:"+r+"\n"+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;this._prepareEffect()},Object.defineProperty(e.prototype,"key",{get:function(){return this._key},enumerable:!0,configurable:!0}),e.prototype.isReady=function(){try{return this._isReadyInternal()}catch(e){return!1}},e.prototype._isReadyInternal=function(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady},e.prototype.getEngine=function(){return this._engine},e.prototype.getPipelineContext=function(){return this._pipelineContext},e.prototype.getAttributesNames=function(){return this._attributesNames},e.prototype.getAttributeLocation=function(e){return this._attributes[e]},e.prototype.getAttributeLocationByName=function(e){return this._attributeLocationByName[e]},e.prototype.getAttributesCount=function(){return this._attributes.length},e.prototype.getUniformIndex=function(e){return this._uniformsNames.indexOf(e)},e.prototype.getUniform=function(e){return this._uniforms[e]},e.prototype.getSamplers=function(){return this._samplerList},e.prototype.getCompilationError=function(){return this._compilationError},e.prototype.allFallbacksProcessed=function(){return this._allFallbacksProcessed},e.prototype.executeWhenCompiled=function(e){var t=this;this.isReady()?e(this):(this.onCompileObservable.add(function(t){e(t)}),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout(function(){t._checkIsReady(null)},16))},e.prototype._checkIsReady=function(e){var t=this;try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}setTimeout(function(){t._checkIsReady(e)},16)},e.prototype._loadShader=function(t,i,n,r){var a;if("undefined"!=typeof HTMLElement&&t instanceof HTMLElement)return void r(o.a.GetDOMTextContent(t));"source:"!==t.substr(0,7)?"base64:"!==t.substr(0,7)?e.ShadersStore[t+i+"Shader"]?r(e.ShadersStore[t+i+"Shader"]):n&&e.ShadersStore[t+n+"Shader"]?r(e.ShadersStore[t+n+"Shader"]):(a="."===t[0]||"/"===t[0]||t.indexOf("http")>-1?t:e.ShadersRepository+t,this._engine._loadFile(a+"."+i.toLowerCase()+".fx",r)):r(window.atob(t.substr(7))):r(t.substr(7))},e.prototype._rebuildProgram=function(e,t,i,n){var o=this;this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=function(e,t){n&&n(t)},this.onCompiled=function(){var e=o.getEngine().scenes;if(e)for(var t=0;t<e.length;t++)e[t].markAllMaterialsAsDirty(r.a.MATERIAL_AllDirtyFlag);o._pipelineContext._handlesSpectorRebuildCallback(i)},this._fallbacks=null,this._prepareEffect()},e.prototype._prepareEffect=function(){var e=this,t=this._attributesNames,i=this.defines;this._valueCache={};var n=this._pipelineContext;try{var r=this._engine;this._pipelineContext=r.createPipelineContext();var o=this._rebuildProgram.bind(this);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?r._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,o,null,this._transformFeedbackVaryings):r._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,o,i,this._transformFeedbackVaryings),r._executeWhenRenderingStateIsCompiled(this._pipelineContext,function(){if(r.supportsUniformBuffers)for(var i in e._uniformBuffersNames)e.bindUniformBlock(i,e._uniformBuffersNames[i]);var o;if(r.getUniforms(e._pipelineContext,e._uniformsNames).forEach(function(t,i){e._uniforms[e._uniformsNames[i]]=t}),e._attributes=r.getAttributes(e._pipelineContext,t),t)for(var a=0;a<t.length;a++){var s=t[a];e._attributeLocationByName[s]=e._attributes[a]}for(o=0;o<e._samplerList.length;o++){null==e.getUniform(e._samplerList[o])&&(e._samplerList.splice(o,1),o--)}e._samplerList.forEach(function(t,i){e._samplers[t]=i}),r.bindSamplers(e),e._compilationError="",e._isReady=!0,e.onCompiled&&e.onCompiled(e),e.onCompileObservable.notifyObservers(e),e.onCompileObservable.clear(),e._fallbacks&&e._fallbacks.unBindMesh(),n&&e.getEngine()._deletePipelineContext(n)}),this._pipelineContext.isAsync&&this._checkIsReady(n)}catch(e){this._processCompilationErrors(e,n)}},e.prototype._processCompilationErrors=function(e,t){void 0===t&&(t=null),this._compilationError=e.message;var i=this._attributesNames,n=this._fallbacks;a.a.Error("Unable to compile effect:"),a.a.Error("Uniforms: "+this._uniformsNames.map(function(e){return" "+e})),a.a.Error("Attributes: "+i.map(function(e){return" "+e})),a.a.Error("Defines:\r\n"+this.defines),a.a.Error("Error: "+this._compilationError),t&&(this._pipelineContext=t,this._isReady=!0,this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)),n?(this._pipelineContext=null,n.hasMoreFallbacks?(this._allFallbacksProcessed=!1,a.a.Error("Trying next fallback."),this.defines=n.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):this._allFallbacksProcessed=!0},Object.defineProperty(e.prototype,"isSupported",{get:function(){return""===this._compilationError},enumerable:!0,configurable:!0}),e.prototype._bindTexture=function(e,t){this._engine._bindTexture(this._samplers[e],t)},e.prototype.setTexture=function(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t)},e.prototype.setDepthStencilTexture=function(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t)},e.prototype.setTextureArray=function(e,t){var i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){for(var n=this._samplerList.indexOf(e),r=1;r<t.length;r++){var o=i+(r-1).toString();this._samplerList.splice(n+r,0,o)}for(var a=0,s=0,c=this._samplerList;s<c.length;s++){var l=c[s];this._samplers[l]=a,a+=1}}this._engine.setTextureArray(this._samplers[e],this._uniforms[e],t)},e.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t)},e.prototype.setTextureFromPostProcessOutput=function(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t)},e.prototype._cacheMatrix=function(e,t){var i=this._valueCache[e],n=t.updateFlag;return(void 0===i||i!==n)&&(this._valueCache[e]=n,!0)},e.prototype._cacheFloat2=function(e,t,i){var n=this._valueCache[e];if(!n||2!==n.length)return n=[t,i],this._valueCache[e]=n,!0;var r=!1;return n[0]!==t&&(n[0]=t,r=!0),n[1]!==i&&(n[1]=i,r=!0),r},e.prototype._cacheFloat3=function(e,t,i,n){var r=this._valueCache[e];if(!r||3!==r.length)return r=[t,i,n],this._valueCache[e]=r,!0;var o=!1;return r[0]!==t&&(r[0]=t,o=!0),r[1]!==i&&(r[1]=i,o=!0),r[2]!==n&&(r[2]=n,o=!0),o},e.prototype._cacheFloat4=function(e,t,i,n,r){var o=this._valueCache[e];if(!o||4!==o.length)return o=[t,i,n,r],this._valueCache[e]=o,!0;var a=!1;return o[0]!==t&&(o[0]=t,a=!0),o[1]!==i&&(o[1]=i,a=!0),o[2]!==n&&(o[2]=n,a=!0),o[3]!==r&&(o[3]=r,a=!0),a},e.prototype.bindUniformBuffer=function(t,i){var n=this._uniformBuffersNames[i];void 0!==n&&e._baseCache[n]!==t&&(e._baseCache[n]=t,this._engine.bindUniformBufferBase(t,n))},e.prototype.bindUniformBlock=function(e,t){this._engine.bindUniformBlock(this._pipelineContext,e,t)},e.prototype.setInt=function(e,t){var i=this._valueCache[e];return void 0!==i&&i===t?this:(this._valueCache[e]=t,this._engine.setInt(this._uniforms[e],t),this)},e.prototype.setIntArray=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t),this},e.prototype.setIntArray2=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t),this},e.prototype.setIntArray3=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t),this},e.prototype.setIntArray4=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t),this},e.prototype.setFloatArray=function(e,t){return this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t),this},e.prototype.setFloatArray2=function(e,t){return this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t),this},e.prototype.setFloatArray3=function(e,t){return this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t),this},e.prototype.setFloatArray4=function(e,t){return this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t),this},e.prototype.setArray=function(e,t){return this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t),this},e.prototype.setArray2=function(e,t){return this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t),this},e.prototype.setArray3=function(e,t){return this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t),this},e.prototype.setArray4=function(e,t){return this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t),this},e.prototype.setMatrices=function(e,t){return t?(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t),this):this},e.prototype.setMatrix=function(e,t){return this._cacheMatrix(e,t)&&this._engine.setMatrices(this._uniforms[e],t.toArray()),this},e.prototype.setMatrix3x3=function(e,t){return this._valueCache[e]=null,this._engine.setMatrix3x3(this._uniforms[e],t),this},e.prototype.setMatrix2x2=function(e,t){return this._valueCache[e]=null,this._engine.setMatrix2x2(this._uniforms[e],t),this},e.prototype.setFloat=function(e,t){var i=this._valueCache[e];return void 0!==i&&i===t?this:(this._valueCache[e]=t,this._engine.setFloat(this._uniforms[e],t),this)},e.prototype.setBool=function(e,t){var i=this._valueCache[e];return void 0!==i&&i===t?this:(this._valueCache[e]=t,this._engine.setInt(this._uniforms[e],t?1:0),this)},e.prototype.setVector2=function(e,t){return this._cacheFloat2(e,t.x,t.y)&&this._engine.setFloat2(this._uniforms[e],t.x,t.y),this},e.prototype.setFloat2=function(e,t,i){return this._cacheFloat2(e,t,i)&&this._engine.setFloat2(this._uniforms[e],t,i),this},e.prototype.setVector3=function(e,t){return this._cacheFloat3(e,t.x,t.y,t.z)&&this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z),this},e.prototype.setFloat3=function(e,t,i,n){return this._cacheFloat3(e,t,i,n)&&this._engine.setFloat3(this._uniforms[e],t,i,n),this},e.prototype.setVector4=function(e,t){return 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},e.prototype.setFloat4=function(e,t,i,n,r){return this._cacheFloat4(e,t,i,n,r)&&this._engine.setFloat4(this._uniforms[e],t,i,n,r),this},e.prototype.setColor3=function(e,t){return this._cacheFloat3(e,t.r,t.g,t.b)&&this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b),this},e.prototype.setColor4=function(e,t,i){return this._cacheFloat4(e,t.r,t.g,t.b,i)&&this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i),this},e.prototype.setDirectColor4=function(e,t){return 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},e.prototype.dispose=function(){this._engine._releaseEffect(this)},e.RegisterShader=function(t,i,n){i&&(e.ShadersStore[t+"PixelShader"]=i),n&&(e.ShadersStore[t+"VertexShader"]=n)},e.ResetCache=function(){e._baseCache={}},e.ShadersRepository="src/Shaders/",e._uniqueIdSeed=0,e._baseCache={},e.ShadersStore={},e.IncludesShadersStore={},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return _});var n=i(1),r=i(3),o=i(6),a=i(0),s=i(49),c=i(2),l=i(12),u=i(19),h=i(115),d=i(112),f=i(60),p=i(36),_=function(e){function t(i,n,r,a,s,l,u,d,f,p,_){void 0===r&&(r=!1),void 0===a&&(a=!0),void 0===s&&(s=t.TRILINEAR_SAMPLINGMODE),void 0===l&&(l=null),void 0===u&&(u=null),void 0===d&&(d=null),void 0===f&&(f=!1);var m=e.call(this,n&&"Scene"===n.getClassName()?n:null)||this;m.url=null,m.uOffset=0,m.vOffset=0,m.uScale=1,m.vScale=1,m.uAng=0,m.vAng=0,m.wAng=0,m.uRotationCenter=.5,m.vRotationCenter=.5,m.wRotationCenter=.5,m.inspectableCustomProperties=null,m._noMipmap=!1,m._invertY=!1,m._rowGenerationMatrix=null,m._cachedTextureMatrix=null,m._projectionModeMatrix=null,m._t0=null,m._t1=null,m._t2=null,m._cachedUOffset=-1,m._cachedVOffset=-1,m._cachedUScale=0,m._cachedVScale=0,m._cachedUAng=-1,m._cachedVAng=-1,m._cachedWAng=-1,m._cachedProjectionMatrixId=-1,m._cachedCoordinatesMode=-1,m._initialSamplingMode=t.BILINEAR_SAMPLINGMODE,m._buffer=null,m._deleteBuffer=!1,m._format=null,m._delayedOnLoad=null,m._delayedOnError=null,m.onLoadObservable=new o.c,m._isBlocking=!0,m.name=i||"",m.url=i,m._noMipmap=r,m._invertY=a,m._initialSamplingMode=s,m._buffer=d,m._deleteBuffer=f,m._mimeType=_,p&&(m._format=p);var g=m.getScene(),v=n&&n.getCaps?n:g?g.getEngine():null;if(!v)return m;v.onBeforeTextureInitObservable.notifyObservers(m);var y=function(){m._texture&&(m._texture._invertVScale&&(m.vScale*=-1,m.vOffset+=1),null!==m._texture._cachedWrapU&&(m.wrapU=m._texture._cachedWrapU,m._texture._cachedWrapU=null),null!==m._texture._cachedWrapV&&(m.wrapV=m._texture._cachedWrapV,m._texture._cachedWrapV=null),null!==m._texture._cachedWrapR&&(m.wrapR=m._texture._cachedWrapR,m._texture._cachedWrapR=null)),m.onLoadObservable.hasObservers()&&m.onLoadObservable.notifyObservers(m),l&&l(),!m.isBlocking&&g&&g.resetCachedMaterial()};return m.url?(m._texture=m._getFromCache(m.url,r,s,a),m._texture?m._texture.isReady?h.a.SetImmediate(function(){return y()}):m._texture.onLoadedObservable.add(y):g&&g.useDelayedTextureLoading?(m.delayLoadState=c.a.DELAYLOADSTATE_NOTLOADED,m._delayedOnLoad=y,m._delayedOnError=u):(m._texture=v.createTexture(m.url,r,a,g,s,y,u,m._buffer,void 0,m._format,null,_),f&&delete m._buffer),m):(m._delayedOnLoad=y,m._delayedOnError=u,m)}return Object(n.d)(t,e),Object.defineProperty(t.prototype,"noMipmap",{get:function(){return this._noMipmap},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isBlocking",{get:function(){return this._isBlocking},set:function(e){this._isBlocking=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"samplingMode",{get:function(){return this._texture?this._texture.samplingMode:this._initialSamplingMode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"invertY",{get:function(){return this._invertY},enumerable:!0,configurable:!0}),t.prototype.updateURL=function(e,t,i){void 0===t&&(t=null),this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(c.a.MATERIAL_TextureDirtyFlag)),this.name&&!p.a.StartsWith(this.name,"data:")||(this.name=e),this.url=e,this._buffer=t,this.delayLoadState=c.a.DELAYLOADSTATE_NOTLOADED,i&&(this._delayedOnLoad=i),this.delayLoad()},t.prototype.delayLoad=function(){if(this.delayLoadState===c.a.DELAYLOADSTATE_NOTLOADED){var e=this.getScene();e&&(this.delayLoadState=c.a.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY),this._texture?this._delayedOnLoad&&(this._texture.isReady?h.a.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,null,this._mimeType),this._deleteBuffer&&delete this._buffer),this._delayedOnLoad=null,this._delayedOnError=null)}},t.prototype._prepareRowForTextureGeneration=function(e,t,i,n){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,a.e.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,n),n.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,n.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,n.z+=this.wRotationCenter},t.prototype.getTextureMatrix=function(e){var t=this;if(void 0===e&&(e=1),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)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._cachedTextureMatrix||(this._cachedTextureMatrix=a.a.Zero(),this._rowGenerationMatrix=new a.a,this._t0=a.e.Zero(),this._t1=a.e.Zero(),this._t2=a.e.Zero()),a.a.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),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),a.a.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);var i=this.getScene();return i?(i.markAllMaterialsAsDirty(c.a.MATERIAL_TextureDirtyFlag,function(e){return e.hasTexture(t)}),this._cachedTextureMatrix):this._cachedTextureMatrix},t.prototype.getReflectionTextureMatrix=function(){var e=this,i=this.getScene();if(!i)return this._cachedTextureMatrix;if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale===this._cachedUScale&&this.vScale===this._cachedVScale&&this.coordinatesMode===this._cachedCoordinatesMode){if(this.coordinatesMode!==t.PROJECTION_MODE)return this._cachedTextureMatrix;if(this._cachedProjectionMatrixId===i.getProjectionMatrix().updateFlag)return this._cachedTextureMatrix}switch(this._cachedTextureMatrix||(this._cachedTextureMatrix=a.a.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=a.a.Zero()),this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale,this._cachedVScale=this.vScale,this._cachedCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case t.PLANAR_MODE:a.a.IdentityToRef(this._cachedTextureMatrix),this._cachedTextureMatrix[0]=this.uScale,this._cachedTextureMatrix[5]=this.vScale,this._cachedTextureMatrix[12]=this.uOffset,this._cachedTextureMatrix[13]=this.vOffset;break;case t.PROJECTION_MODE:a.a.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);var n=i.getProjectionMatrix();this._cachedProjectionMatrixId=n.updateFlag,n.multiplyToRef(this._projectionModeMatrix,this._cachedTextureMatrix);break;default:a.a.IdentityToRef(this._cachedTextureMatrix)}return i.markAllMaterialsAsDirty(c.a.MATERIAL_TextureDirtyFlag,function(t){return-1!==t.getActiveTextures().indexOf(e)}),this._cachedTextureMatrix},t.prototype.clone=function(){var e=this;return r.a.Clone(function(){return new t(e._texture?e._texture.url:null,e.getScene(),e._noMipmap,e._invertY,e.samplingMode,void 0,void 0,e._texture?e._texture._buffer:void 0)},this)},t.prototype.serialize=function(){var i=this.name;t.SerializeBuffers||p.a.StartsWith(this.name,"data:")&&(this.name="");var n=e.prototype.serialize.call(this);return n?(t.SerializeBuffers&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(n.base64String=this._buffer,n.name=n.name.replace("data:","")):this.url&&p.a.StartsWith(this.url,"data:")&&this._buffer instanceof Uint8Array&&(n.base64String="data:image/png;base64,"+p.a.EncodeArrayBufferToBase64(this._buffer))),n.invertY=this._invertY,n.samplingMode=this.samplingMode,this.name=i,n):null},t.prototype.getClassName=function(){return"Texture"},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null},t.Parse=function(e,i,n){if(e.customType){var o=d.a.Instantiate(e.customType).Parse(e,i,n);return e.samplingMode&&o.updateSamplingMode&&o._samplingMode&&o._samplingMode!==e.samplingMode&&o.updateSamplingMode(e.samplingMode),o}if(e.isCube&&!e.isRenderTarget)return t._CubeTextureParser(e,i,n);if(!e.name&&!e.isRenderTarget)return null;var a=r.a.Parse(function(){var r,o=!0;if(e.noMipmap&&(o=!1),e.mirrorPlane){var a=t._CreateMirror(e.name,e.renderTargetSize,i,o);return a._waitingRenderList=e.renderList,a.mirrorPlane=f.a.FromArray(e.mirrorPlane),a}if(e.isRenderTarget){var s=null;if(e.isCube){if(i.reflectionProbes)for(var c=0;c<i.reflectionProbes.length;c++){var l=i.reflectionProbes[c];if(l.name===e.name)return l.cubeTexture}}else(s=t._CreateRenderTargetTexture(e.name,e.renderTargetSize,i,o))._waitingRenderList=e.renderList;return s}if(e.base64String)r=t.CreateFromBase64String(e.base64String,e.name,i,!o,e.invertY);else{var u=n+e.name;t.UseSerializedUrlIfAny&&e.url&&(u=e.url),r=new t(u,i,!o,e.invertY)}return r},e,i);if(a&&a._texture&&(a._texture._cachedWrapU=null,a._texture._cachedWrapV=null,a._texture._cachedWrapR=null),e.samplingMode){var s=e.samplingMode;a&&a.samplingMode!==s&&a.updateSamplingMode(s)}if(a&&e.animations)for(var c=0;c<e.animations.length;c++){var u=e.animations[c],h=l.a.GetClass("BABYLON.Animation");h&&a.animations.push(h.Parse(u))}return a},t.CreateFromBase64String=function(e,i,n,r,o,a,s,l,u){return void 0===a&&(a=t.TRILINEAR_SAMPLINGMODE),void 0===s&&(s=null),void 0===l&&(l=null),void 0===u&&(u=c.a.TEXTUREFORMAT_RGBA),new t("data:"+i,n,r,o,a,s,l,e,!1,u)},t.LoadFromDataString=function(e,i,n,r,o,a,s,l,u,h){return void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===a&&(a=!0),void 0===s&&(s=t.TRILINEAR_SAMPLINGMODE),void 0===l&&(l=null),void 0===u&&(u=null),void 0===h&&(h=c.a.TEXTUREFORMAT_RGBA),"data:"!==e.substr(0,5)&&(e="data:"+e),new t(e,n,o,a,s,l,u,i,r,h)},t.SerializeBuffers=!0,t._CubeTextureParser=function(e,t,i){throw u.a.WarnImport("CubeTexture")},t._CreateMirror=function(e,t,i,n){throw u.a.WarnImport("MirrorTexture")},t._CreateRenderTargetTexture=function(e,t,i,n){throw u.a.WarnImport("RenderTargetTexture")},t.NEAREST_SAMPLINGMODE=c.a.TEXTURE_NEAREST_SAMPLINGMODE,t.NEAREST_NEAREST_MIPLINEAR=c.a.TEXTURE_NEAREST_NEAREST_MIPLINEAR,t.BILINEAR_SAMPLINGMODE=c.a.TEXTURE_BILINEAR_SAMPLINGMODE,t.LINEAR_LINEAR_MIPNEAREST=c.a.TEXTURE_LINEAR_LINEAR_MIPNEAREST,t.TRILINEAR_SAMPLINGMODE=c.a.TEXTURE_TRILINEAR_SAMPLINGMODE,t.LINEAR_LINEAR_MIPLINEAR=c.a.TEXTURE_LINEAR_LINEAR_MIPLINEAR,t.NEAREST_NEAREST_MIPNEAREST=c.a.TEXTURE_NEAREST_NEAREST_MIPNEAREST,t.NEAREST_LINEAR_MIPNEAREST=c.a.TEXTURE_NEAREST_LINEAR_MIPNEAREST,t.NEAREST_LINEAR_MIPLINEAR=c.a.TEXTURE_NEAREST_LINEAR_MIPLINEAR,t.NEAREST_LINEAR=c.a.TEXTURE_NEAREST_LINEAR,t.NEAREST_NEAREST=c.a.TEXTURE_NEAREST_NEAREST,t.LINEAR_NEAREST_MIPNEAREST=c.a.TEXTURE_LINEAR_NEAREST_MIPNEAREST,t.LINEAR_NEAREST_MIPLINEAR=c.a.TEXTURE_LINEAR_NEAREST_MIPLINEAR,t.LINEAR_LINEAR=c.a.TEXTURE_LINEAR_LINEAR,t.LINEAR_NEAREST=c.a.TEXTURE_LINEAR_NEAREST,t.EXPLICIT_MODE=c.a.TEXTURE_EXPLICIT_MODE,t.SPHERICAL_MODE=c.a.TEXTURE_SPHERICAL_MODE,t.PLANAR_MODE=c.a.TEXTURE_PLANAR_MODE,t.CUBIC_MODE=c.a.TEXTURE_CUBIC_MODE,t.PROJECTION_MODE=c.a.TEXTURE_PROJECTION_MODE,t.SKYBOX_MODE=c.a.TEXTURE_SKYBOX_MODE,t.INVCUBIC_MODE=c.a.TEXTURE_INVCUBIC_MODE,t.EQUIRECTANGULAR_MODE=c.a.TEXTURE_EQUIRECTANGULAR_MODE,t.FIXED_EQUIRECTANGULAR_MODE=c.a.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,t.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=c.a.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,t.CLAMP_ADDRESSMODE=c.a.TEXTURE_CLAMP_ADDRESSMODE,t.WRAP_ADDRESSMODE=c.a.TEXTURE_WRAP_ADDRESSMODE,t.MIRROR_ADDRESSMODE=c.a.TEXTURE_MIRROR_ADDRESSMODE,t.UseSerializedUrlIfAny=!1,Object(n.c)([Object(r.c)()],t.prototype,"url",void 0),Object(n.c)([Object(r.c)()],t.prototype,"uOffset",void 0),Object(n.c)([Object(r.c)()],t.prototype,"vOffset",void 0),Object(n.c)([Object(r.c)()],t.prototype,"uScale",void 0),Object(n.c)([Object(r.c)()],t.prototype,"vScale",void 0),Object(n.c)([Object(r.c)()],t.prototype,"uAng",void 0),Object(n.c)([Object(r.c)()],t.prototype,"vAng",void 0),Object(n.c)([Object(r.c)()],t.prototype,"wAng",void 0),Object(n.c)([Object(r.c)()],t.prototype,"uRotationCenter",void 0),Object(n.c)([Object(r.c)()],t.prototype,"vRotationCenter",void 0),Object(n.c)([Object(r.c)()],t.prototype,"wRotationCenter",void 0),Object(n.c)([Object(r.c)()],t.prototype,"isBlocking",null),t}(s.a);r.a._TextureParser=_.Parse},function(e,t,i){"use strict";i.d(t,"a",function(){return s}),i.d(t,"b",function(){return c}),i.d(t,"c",function(){return l});var n=i(14),r=i(28),o=i(42),a=i(12),s=function(){function e(e,t,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),this.r=e,this.g=t,this.b=i}return e.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"},e.prototype.getClassName=function(){return"Color3"},e.prototype.getHashCode=function(){var e=255*this.r|0;return e=397*(e=397*e^(255*this.g|0))^(255*this.b|0)},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this},e.prototype.toColor4=function(e){return void 0===e&&(e=1),new c(this.r,this.g,this.b,e)},e.prototype.asArray=function(){var e=new Array;return this.toArray(e,0),e},e.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},e.prototype.multiply=function(t){return new e(this.r*t.r,this.g*t.g,this.b*t.b)},e.prototype.multiplyToRef=function(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,this},e.prototype.equals=function(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b},e.prototype.equalsFloats=function(e,t,i){return this.r===e&&this.g===t&&this.b===i},e.prototype.scale=function(t){return new e(this.r*t,this.g*t,this.b*t)},e.prototype.scaleToRef=function(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,this},e.prototype.scaleAndAddToRef=function(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,this},e.prototype.clampToRef=function(e,t,i){return void 0===e&&(e=0),void 0===t&&(t=1),i.r=n.a.Clamp(this.r,e,t),i.g=n.a.Clamp(this.g,e,t),i.b=n.a.Clamp(this.b,e,t),this},e.prototype.add=function(t){return new e(this.r+t.r,this.g+t.g,this.b+t.b)},e.prototype.addToRef=function(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,this},e.prototype.subtract=function(t){return new e(this.r-t.r,this.g-t.g,this.b-t.b)},e.prototype.subtractToRef=function(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,this},e.prototype.clone=function(){return new e(this.r,this.g,this.b)},e.prototype.copyFrom=function(e){return this.r=e.r,this.g=e.g,this.b=e.b,this},e.prototype.copyFromFloats=function(e,t,i){return this.r=e,this.g=t,this.b=i,this},e.prototype.set=function(e,t,i){return this.copyFromFloats(e,t,i)},e.prototype.toHexString=function(){var e=255*this.r|0,t=255*this.g|0,i=255*this.b|0;return"#"+n.a.ToHex(e)+n.a.ToHex(t)+n.a.ToHex(i)},e.prototype.toLinearSpace=function(){var t=new e;return this.toLinearSpaceToRef(t),t},e.prototype.toHSV=function(){var t=new e;return this.toHSVToRef(t),t},e.prototype.toHSVToRef=function(e){var t=this.r,i=this.g,n=this.b,r=Math.max(t,i,n),o=Math.min(t,i,n),a=0,s=0,c=r,l=r-o;0!==r&&(s=l/r),r!=o&&(r==t?(a=(i-n)/l,i<n&&(a+=6)):r==i?a=(n-t)/l+2:r==n&&(a=(t-i)/l+4),a*=60),e.r=a,e.g=s,e.b=c},e.prototype.toLinearSpaceToRef=function(e){return e.r=Math.pow(this.r,r.c),e.g=Math.pow(this.g,r.c),e.b=Math.pow(this.b,r.c),this},e.prototype.toGammaSpace=function(){var t=new e;return this.toGammaSpaceToRef(t),t},e.prototype.toGammaSpaceToRef=function(e){return e.r=Math.pow(this.r,r.b),e.g=Math.pow(this.g,r.b),e.b=Math.pow(this.b,r.b),this},e.HSVtoRGBToRef=function(e,t,i,n){var r=i*t,o=e/60,a=r*(1-Math.abs(o%2-1)),s=0,c=0,l=0;o>=0&&o<=1?(s=r,c=a):o>=1&&o<=2?(s=a,c=r):o>=2&&o<=3?(c=r,l=a):o>=3&&o<=4?(c=a,l=r):o>=4&&o<=5?(s=a,l=r):o>=5&&o<=6&&(s=r,l=a);var u=i-r;n.set(s+u,c+u,l+u)},e.FromHexString=function(t){if("#"!==t.substring(0,1)||7!==t.length)return new e(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),r=parseInt(t.substring(5,7),16);return e.FromInts(i,n,r)},e.FromArray=function(t,i){return void 0===i&&(i=0),new e(t[i],t[i+1],t[i+2])},e.FromInts=function(t,i,n){return new e(t/255,i/255,n/255)},e.Lerp=function(t,i,n){var r=new e(0,0,0);return e.LerpToRef(t,i,n,r),r},e.LerpToRef=function(e,t,i,n){n.r=e.r+(t.r-e.r)*i,n.g=e.g+(t.g-e.g)*i,n.b=e.b+(t.b-e.b)*i},e.Red=function(){return new e(1,0,0)},e.Green=function(){return new e(0,1,0)},e.Blue=function(){return new e(0,0,1)},e.Black=function(){return new e(0,0,0)},Object.defineProperty(e,"BlackReadOnly",{get:function(){return e._BlackReadOnly},enumerable:!0,configurable:!0}),e.White=function(){return new e(1,1,1)},e.Purple=function(){return new e(.5,0,.5)},e.Magenta=function(){return new e(1,0,1)},e.Yellow=function(){return new e(1,1,0)},e.Gray=function(){return new e(.5,.5,.5)},e.Teal=function(){return new e(0,1,1)},e.Random=function(){return new e(Math.random(),Math.random(),Math.random())},e._BlackReadOnly=e.Black(),e}(),c=function(){function e(e,t,i,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=1),this.r=e,this.g=t,this.b=i,this.a=n}return e.prototype.addInPlace=function(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this},e.prototype.asArray=function(){var e=new Array;return this.toArray(e,0),e},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this},e.prototype.equals=function(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a},e.prototype.add=function(t){return new e(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},e.prototype.subtract=function(t){return new e(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},e.prototype.subtractToRef=function(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,this},e.prototype.scale=function(t){return new e(this.r*t,this.g*t,this.b*t,this.a*t)},e.prototype.scaleToRef=function(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,this},e.prototype.scaleAndAddToRef=function(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,this},e.prototype.clampToRef=function(e,t,i){return void 0===e&&(e=0),void 0===t&&(t=1),i.r=n.a.Clamp(this.r,e,t),i.g=n.a.Clamp(this.g,e,t),i.b=n.a.Clamp(this.b,e,t),i.a=n.a.Clamp(this.a,e,t),this},e.prototype.multiply=function(t){return new e(this.r*t.r,this.g*t.g,this.b*t.b,this.a*t.a)},e.prototype.multiplyToRef=function(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},e.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"},e.prototype.getClassName=function(){return"Color4"},e.prototype.getHashCode=function(){var e=255*this.r|0;return e=397*(e=397*(e=397*e^(255*this.g|0))^(255*this.b|0))^(255*this.a|0)},e.prototype.clone=function(){return new e(this.r,this.g,this.b,this.a)},e.prototype.copyFrom=function(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this},e.prototype.copyFromFloats=function(e,t,i,n){return this.r=e,this.g=t,this.b=i,this.a=n,this},e.prototype.set=function(e,t,i,n){return this.copyFromFloats(e,t,i,n)},e.prototype.toHexString=function(){var e=255*this.r|0,t=255*this.g|0,i=255*this.b|0,r=255*this.a|0;return"#"+n.a.ToHex(e)+n.a.ToHex(t)+n.a.ToHex(i)+n.a.ToHex(r)},e.prototype.toLinearSpace=function(){var t=new e;return this.toLinearSpaceToRef(t),t},e.prototype.toLinearSpaceToRef=function(e){return e.r=Math.pow(this.r,r.c),e.g=Math.pow(this.g,r.c),e.b=Math.pow(this.b,r.c),e.a=this.a,this},e.prototype.toGammaSpace=function(){var t=new e;return this.toGammaSpaceToRef(t),t},e.prototype.toGammaSpaceToRef=function(e){return e.r=Math.pow(this.r,r.b),e.g=Math.pow(this.g,r.b),e.b=Math.pow(this.b,r.b),e.a=this.a,this},e.FromHexString=function(t){if("#"!==t.substring(0,1)||9!==t.length)return new e(0,0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),r=parseInt(t.substring(5,7),16),o=parseInt(t.substring(7,9),16);return e.FromInts(i,n,r,o)},e.Lerp=function(t,i,n){var r=new e(0,0,0,0);return e.LerpToRef(t,i,n,r),r},e.LerpToRef=function(e,t,i,n){n.r=e.r+(t.r-e.r)*i,n.g=e.g+(t.g-e.g)*i,n.b=e.b+(t.b-e.b)*i,n.a=e.a+(t.a-e.a)*i},e.FromColor3=function(t,i){return void 0===i&&(i=1),new e(t.r,t.g,t.b,i)},e.FromArray=function(t,i){return void 0===i&&(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.FromInts=function(t,i,n,r){return new e(t/255,i/255,n/255,r/255)},e.CheckColors4=function(e,t){if(e.length===3*t){for(var i=[],n=0;n<e.length;n+=3){var r=n/3*4;i[r]=e[n],i[r+1]=e[n+1],i[r+2]=e[n+2],i[r+3]=1}return i}return e},e}(),l=function(){function e(){}return e.Color3=o.a.BuildArray(3,s.Black),e.Color4=o.a.BuildArray(3,function(){return new c(0,0,0,0)}),e}();a.a.RegisteredTypes["BABYLON.Color3"]=s,a.a.RegisteredTypes["BABYLON.Color4"]=c},function(e,t,i){"use strict";var n=i(1),r=i(6),o=i(38),a=i(23),s=i(19),c=i(31),l=i(2),u=i(132),h=i(51),d=i(84),f=i(7);c.a.prototype.setAlphaConstants=function(e,t,i,n){this._alphaState.setAlphaBlendConstants(e,t,i,n)},c.a.prototype.setAlphaMode=function(e,t){if(void 0===t&&(t=!1),this._alphaMode!==e){switch(e){case l.a.ALPHA_DISABLE:this._alphaState.alphaBlend=!1;break;case l.a.ALPHA_PREMULTIPLIED:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case l.a.ALPHA_PREMULTIPLIED_PORTERDUFF:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case l.a.ALPHA_COMBINE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case l.a.ALPHA_ONEONE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case l.a.ALPHA_ADD:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case l.a.ALPHA_SUBTRACT:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case l.a.ALPHA_MULTIPLY:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case l.a.ALPHA_MAXIMIZED:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case l.a.ALPHA_INTERPOLATE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case l.a.ALPHA_SCREENMODE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case l.a.ALPHA_ONEONE_ONEONE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case l.a.ALPHA_ALPHATOCOLOR:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case l.a.ALPHA_REVERSEONEMINUS:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case l.a.ALPHA_SRC_DSTONEMINUSSRCALPHA:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case l.a.ALPHA_ONEONE_ONEZERO:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case l.a.ALPHA_EXCLUSION:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0}t||(this.depthCullingState.depthMask=e===l.a.ALPHA_DISABLE),this._alphaMode=e}},c.a.prototype.getAlphaMode=function(){return this._alphaMode},c.a.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case l.a.ALPHA_EQUATION_ADD:this._alphaState.setAlphaEquationParameters(this._gl.FUNC_ADD,this._gl.FUNC_ADD);break;case l.a.ALPHA_EQUATION_SUBSTRACT:this._alphaState.setAlphaEquationParameters(this._gl.FUNC_SUBTRACT,this._gl.FUNC_SUBTRACT);break;case l.a.ALPHA_EQUATION_REVERSE_SUBTRACT:this._alphaState.setAlphaEquationParameters(this._gl.FUNC_REVERSE_SUBTRACT,this._gl.FUNC_REVERSE_SUBTRACT);break;case l.a.ALPHA_EQUATION_MAX:this._alphaState.setAlphaEquationParameters(this._gl.MAX,this._gl.MAX);break;case l.a.ALPHA_EQUATION_MIN:this._alphaState.setAlphaEquationParameters(this._gl.MIN,this._gl.MIN);break;case l.a.ALPHA_EQUATION_DARKEN:this._alphaState.setAlphaEquationParameters(this._gl.MIN,this._gl.FUNC_ADD)}this._alphaEquation=e}},c.a.prototype.getAlphaEquation=function(){return this._alphaEquation},i.d(t,"a",function(){return p});var p=function(e){function t(i,n,a,s){void 0===s&&(s=!1);var c=e.call(this,i,n,a,s)||this;if(c.enableOfflineSupport=!1,c.disableManifestCheck=!1,c.scenes=new Array,c.onNewSceneAddedObservable=new r.c,c.postProcesses=new Array,c.isPointerLock=!1,c.onResizeObservable=new r.c,c.onCanvasBlurObservable=new r.c,c.onCanvasFocusObservable=new r.c,c.onCanvasPointerOutObservable=new r.c,c.onBeginFrameObservable=new r.c,c.customAnimationFrameRequester=null,c.onEndFrameObservable=new r.c,c.onBeforeShaderCompilationObservable=new r.c,c.onAfterShaderCompilationObservable=new r.c,c._deterministicLockstep=!1,c._lockstepMaxSteps=4,c._timeStep=1/60,c._fps=60,c._deltaTime=0,c._drawCalls=new h.a,c.canvasTabIndex=1,c.disablePerformanceMonitorInBackground=!1,c._performanceMonitor=new u.a,!i)return c;if(a=c._creationOptions,t.Instances.push(c),i.getContext){var l=i;if(c._onCanvasFocus=function(){c.onCanvasFocusObservable.notifyObservers(c)},c._onCanvasBlur=function(){c.onCanvasBlurObservable.notifyObservers(c)},l.addEventListener("focus",c._onCanvasFocus),l.addEventListener("blur",c._onCanvasBlur),c._onBlur=function(){c.disablePerformanceMonitorInBackground&&c._performanceMonitor.disable(),c._windowIsBackground=!0},c._onFocus=function(){c.disablePerformanceMonitorInBackground&&c._performanceMonitor.enable(),c._windowIsBackground=!1},c._onCanvasPointerOut=function(e){c.onCanvasPointerOutObservable.notifyObservers(e)},l.addEventListener("pointerout",c._onCanvasPointerOut),o.a.IsWindowObjectExist()){var d=c.getHostWindow();d.addEventListener("blur",c._onBlur),d.addEventListener("focus",c._onFocus);var f=document;c._onFullscreenChange=function(){void 0!==f.fullscreen?c.isFullscreen=f.fullscreen:void 0!==f.mozFullScreen?c.isFullscreen=f.mozFullScreen:void 0!==f.webkitIsFullScreen?c.isFullscreen=f.webkitIsFullScreen:void 0!==f.msIsFullScreen&&(c.isFullscreen=f.msIsFullScreen),c.isFullscreen&&c._pointerLockRequested&&l&&t._RequestPointerlock(l)},document.addEventListener("fullscreenchange",c._onFullscreenChange,!1),document.addEventListener("mozfullscreenchange",c._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",c._onFullscreenChange,!1),document.addEventListener("msfullscreenchange",c._onFullscreenChange,!1),c._onPointerLockChange=function(){c.isPointerLock=f.mozPointerLockElement===l||f.webkitPointerLockElement===l||f.msPointerLockElement===l||f.pointerLockElement===l},document.addEventListener("pointerlockchange",c._onPointerLockChange,!1),document.addEventListener("mspointerlockchange",c._onPointerLockChange,!1),document.addEventListener("mozpointerlockchange",c._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",c._onPointerLockChange,!1),!t.audioEngine&&a.audioEngine&&t.AudioEngineFactory&&(t.audioEngine=t.AudioEngineFactory(c.getRenderingCanvas()))}c._connectVREvents(),c.enableOfflineSupport=void 0!==t.OfflineProviderFactory,a.doNotHandleTouchAction||c._disableTouchAction(),c._deterministicLockstep=!!a.deterministicLockstep,c._lockstepMaxSteps=a.lockstepMaxSteps||0,c._timeStep=a.timeStep||1/60}return c._prepareVRComponent(),a.autoEnableWebVR&&c.initWebVR(),c}return Object(n.d)(t,e),Object.defineProperty(t,"NpmPackage",{get:function(){return c.a.NpmPackage},enumerable:!0,configurable:!0}),Object.defineProperty(t,"Version",{get:function(){return c.a.Version},enumerable:!0,configurable:!0}),Object.defineProperty(t,"Instances",{get:function(){return a.a.Instances},enumerable:!0,configurable:!0}),Object.defineProperty(t,"LastCreatedEngine",{get:function(){return a.a.LastCreatedEngine},enumerable:!0,configurable:!0}),Object.defineProperty(t,"LastCreatedScene",{get:function(){return a.a.LastCreatedScene},enumerable:!0,configurable:!0}),t.MarkAllMaterialsAsDirty=function(e,i){for(var n=0;n<t.Instances.length;n++)for(var r=t.Instances[n],o=0;o<r.scenes.length;o++)r.scenes[o].markAllMaterialsAsDirty(e,i)},t.DefaultLoadingScreenFactory=function(e){throw s.a.WarnImport("LoadingScreen")},Object.defineProperty(t.prototype,"_supportsHardwareTextureRescaling",{get:function(){return!!t._RescalePostProcessFactory},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"performanceMonitor",{get:function(){return this._performanceMonitor},enumerable:!0,configurable:!0}),t.prototype.getInputElement=function(){return this._renderingCanvas},t.prototype.getAspectRatio=function(e,t){void 0===t&&(t=!1);var i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)},t.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)},t.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null},t.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null},t.prototype.isDeterministicLockStep=function(){return this._deterministicLockstep},t.prototype.getLockstepMaxSteps=function(){return this._lockstepMaxSteps},t.prototype.getTimeStep=function(){return 1e3*this._timeStep},t.prototype.generateMipMapsForCubemap=function(e,t){if(void 0===t&&(t=!0),e.generateMipMaps){var i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}},t.prototype.setState=function(e,t,i,n){void 0===t&&(t=0),void 0===n&&(n=!1),(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);var r=this.cullBackFaces?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==r||i)&&(this._depthCullingState.cullFace=r),this.setZOffset(t);var o=n?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==o||i)&&(this._depthCullingState.frontFace=o)},t.prototype.setZOffset=function(e){this._depthCullingState.zOffset=e},t.prototype.getZOffset=function(){return this._depthCullingState.zOffset},t.prototype.setDepthBuffer=function(e){this._depthCullingState.depthTest=e},t.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},t.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},t.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},t.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},t.prototype.getStencilMask=function(){return this._stencilState.stencilMask},t.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},t.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},t.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},t.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},t.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},t.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},t.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},t.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},t.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},t.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},t.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},t.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},t.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},t.prototype.setDitheringState=function(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)},t.prototype.setRasterizerState=function(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)},t.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},t.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},t.prototype.setDepthFunctionToGreater=function(){this._depthCullingState.depthFunc=this._gl.GREATER},t.prototype.setDepthFunctionToGreaterOrEqual=function(){this._depthCullingState.depthFunc=this._gl.GEQUAL},t.prototype.setDepthFunctionToLess=function(){this._depthCullingState.depthFunc=this._gl.LESS},t.prototype.setDepthFunctionToLessOrEqual=function(){this._depthCullingState.depthFunc=this._gl.LEQUAL},t.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()},t.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)},t.prototype.setDirectViewport=function(e,t,i,n){var r=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,n),r},t.prototype.scissorClear=function(e,t,i,n,r){this.enableScissor(e,t,i,n),this.clear(r,!0,!0,!0),this.disableScissor()},t.prototype.enableScissor=function(e,t,i,n){var r=this._gl;r.enable(r.SCISSOR_TEST),r.scissor(e,t,i,n)},t.prototype.disableScissor=function(){var e=this._gl;e.disable(e.SCISSOR_TEST)},t.prototype._reportDrawCall=function(){this._drawCalls.addCount(1,!1)},t.prototype.initWebVR=function(){throw s.a.WarnImport("WebVRCamera")},t.prototype._prepareVRComponent=function(){},t.prototype._connectVREvents=function(e,t){},t.prototype._submitVRFrame=function(){},t.prototype.disableVR=function(){},t.prototype.isVRPresenting=function(){return!1},t.prototype._requestVRFrame=function(){},t.prototype._loadFileAsync=function(e,t,i){var n=this;return new Promise(function(r,o){n._loadFile(e,function(e){r(e)},void 0,t,i,function(e,t){o(t)})})},t.prototype.getVertexShaderSource=function(e){var t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null},t.prototype.getFragmentShaderSource=function(e){var t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null},t.prototype.setDepthStencilTexture=function(e,t,i){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0):this._setTexture(e,null))},t.prototype.setTextureFromPostProcess=function(e,t){this._bindTexture(e,t?t._textures.data[t._currentRenderTextureInd]:null)},t.prototype.setTextureFromPostProcessOutput=function(e,t){this._bindTexture(e,t?t._outputTexture:null)},t.prototype._convertRGBtoRGBATextureData=function(e,t,i,n){var r;r=n===l.a.TEXTURETYPE_FLOAT?new Float32Array(t*i*4):new Uint32Array(t*i*4);for(var o=0;o<t;o++)for(var a=0;a<i;a++){var s=3*(a*t+o),c=4*(a*t+o);r[c+0]=e[s+0],r[c+1]=e[s+1],r[c+2]=e[s+2],r[c+3]=1}return r},t.prototype._rebuildBuffers=function(){for(var t=0,i=this.scenes;t<i.length;t++){var n=i[t];n.resetCachedMaterial(),n._rebuildGeometries(),n._rebuildTextures()}e.prototype._rebuildBuffers.call(this)},t.prototype._renderFrame=function(){for(var e=0;e<this._activeRenderLoops.length;e++){(0,this._activeRenderLoops[e])()}},t.prototype._renderLoop=function(){if(!this._contextWasLost){var e=!0;!this.renderEvenInBackground&&this._windowIsBackground&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0?this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this.isVRPresenting()?this._requestVRFrame():this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1},t.prototype._renderViews=function(){return!1},t.prototype.switchFullscreen=function(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)},t.prototype.enterFullscreen=function(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&t._RequestFullscreen(this._renderingCanvas))},t.prototype.exitFullscreen=function(){this.isFullscreen&&t._ExitFullscreen()},t.prototype.enterPointerlock=function(){this._renderingCanvas&&t._RequestPointerlock(this._renderingCanvas)},t.prototype.exitPointerlock=function(){t._ExitPointerlock()},t.prototype.beginFrame=function(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),e.prototype.beginFrame.call(this)},t.prototype.endFrame=function(){e.prototype.endFrame.call(this),this._submitVRFrame(),this.onEndFrameObservable.notifyObservers(this)},t.prototype.resize=function(){this.isVRPresenting()||e.prototype.resize.call(this)},t.prototype.setSize=function(t,i){if(this._renderingCanvas&&(e.prototype.setSize.call(this,t,i),this.scenes)){for(var n=0;n<this.scenes.length;n++)for(var r=this.scenes[n],o=0;o<r.cameras.length;o++){r.cameras[o]._currentRenderId=0}this.onResizeObservable.hasObservers&&this.onResizeObservable.notifyObservers(this)}},t.prototype.updateDynamicVertexBuffer=function(e,t,i,n){this.bindArrayBuffer(e),void 0===i&&(i=0);var r=t.length||t.byteLength;void 0===n||n>=r&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+n)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,n):new Uint8Array(t.buffer,t.byteOffset+i,n),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()},t.prototype._deletePipelineContext=function(t){var i=t;i&&i.program&&i.transformFeedback&&(this.deleteTransformFeedback(i.transformFeedback),i.transformFeedback=null),e.prototype._deletePipelineContext.call(this,t)},t.prototype.createShaderProgram=function(t,i,n,r,o,a){void 0===a&&(a=null),o=o||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);var s=e.prototype.createShaderProgram.call(this,t,i,n,r,o,a);return this.onAfterShaderCompilationObservable.notifyObservers(this),s},t.prototype._createShaderProgram=function(e,t,i,n,r){void 0===r&&(r=null);var o=n.createProgram();if(e.program=o,!o)throw new Error("Unable to create program");if(n.attachShader(o,t),n.attachShader(o,i),this.webGLVersion>1&&r){var a=this.createTransformFeedback();this.bindTransformFeedback(a),this.setTranformFeedbackVaryings(o,r),e.transformFeedback=a}return n.linkProgram(o),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=n,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),o},t.prototype._releaseTexture=function(t){e.prototype._releaseTexture.call(this,t),this.scenes.forEach(function(e){e.postProcesses.forEach(function(e){e._outputTexture==t&&(e._outputTexture=null)}),e.cameras.forEach(function(e){e._postProcesses.forEach(function(e){e&&e._outputTexture==t&&(e._outputTexture=null)})})})},t.prototype._rescaleTexture=function(e,i,n,r,o){var a=this;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);var s=this.createRenderTargetTexture({width:i.width,height:i.height},{generateMipMaps:!1,type:l.a.TEXTURETYPE_UNSIGNED_INT,samplingMode:l.a.TEXTURE_BILINEAR_SAMPLINGMODE,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&t._RescalePostProcessFactory&&(this._rescalePostProcess=t._RescalePostProcessFactory(this)),this._rescalePostProcess.getEffect().executeWhenCompiled(function(){a._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};var t=n;t||(t=a.scenes[a.scenes.length-1]),t.postProcessManager.directRender([a._rescalePostProcess],s,!0),a._bindTextureDirectly(a._gl.TEXTURE_2D,i,!0),a._gl.copyTexImage2D(a._gl.TEXTURE_2D,0,r,0,0,i.width,i.height,0),a.unBindFramebuffer(s),a._releaseTexture(s),o&&o()})},t.prototype.getFps=function(){return this._fps},t.prototype.getDeltaTime=function(){return this._deltaTime},t.prototype._measureFps=function(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0},t.prototype._uploadImageToTexture=function(e,t,i,n){void 0===i&&(i=0),void 0===n&&(n=0);var r=this._gl,o=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),s=this._getRGBABufferInternalSizedFormat(e.type,a),c=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(c,e,!0),this._unpackFlipY(e.invertY);var l=r.TEXTURE_2D;e.isCube&&(l=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(l,n,s,a,o,t),this._bindTextureDirectly(c,null,!0)},t.prototype.updateDynamicIndexBuffer=function(e,t,i){var n;void 0===i&&(i=0),this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),n=t instanceof Uint16Array||t instanceof Uint32Array?t:e.is32Bits?new Uint32Array(t):new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,n,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},t.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e)return 1;if(e.samples===t)return t;var i=this._gl;if(t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),e._MSAARenderBuffer&&(i.deleteRenderbuffer(e._MSAARenderBuffer),e._MSAARenderBuffer=null),t>1&&i.renderbufferStorageMultisample){var n=i.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(e._MSAAFramebuffer);var r=i.createRenderbuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");i.bindRenderbuffer(i.RENDERBUFFER,r),i.renderbufferStorageMultisample(i.RENDERBUFFER,t,this._getRGBAMultiSampleBufferFormat(e.type),e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,r),e._MSAARenderBuffer=r}else this._bindUnboundFramebuffer(e._framebuffer);return e.samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.width,e.height,t),this._bindUnboundFramebuffer(null),t},t.prototype.updateTextureComparisonFunction=function(e,t){if(1!==this.webGLVersion){var i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,l.a.LEQUAL),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),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,l.a.LEQUAL),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}else f.a.Error("WebGL 1 does not support texture comparison.")},t.prototype.createInstancesBuffer=function(e){var t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");var i=new d.a(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i},t.prototype.deleteInstancesBuffer=function(e){this._gl.deleteBuffer(e)},t.prototype._clientWaitAsync=function(e,t,i){void 0===t&&(t=0),void 0===i&&(i=10);var n=this._gl;return new Promise(function(r,o){var a=function(){var s=n.clientWaitSync(e,t,0);s!=n.WAIT_FAILED?s!=n.TIMEOUT_EXPIRED?r():setTimeout(a,i):o()};a()})},t.prototype._readPixelsAsync=function(e,t,i,n,r,o,a){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");var s=this._gl,c=s.createBuffer();s.bindBuffer(s.PIXEL_PACK_BUFFER,c),s.bufferData(s.PIXEL_PACK_BUFFER,a.byteLength,s.STREAM_READ),s.readPixels(e,t,i,n,r,o,0),s.bindBuffer(s.PIXEL_PACK_BUFFER,null);var l=s.fenceSync(s.SYNC_GPU_COMMANDS_COMPLETE,0);return l?(s.flush(),this._clientWaitAsync(l,0,10).then(function(){return s.deleteSync(l),s.bindBuffer(s.PIXEL_PACK_BUFFER,c),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,a),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),s.deleteBuffer(c),a})):null},t.prototype._readTexturePixels=function(e,t,i,n,r,o){void 0===n&&(n=-1),void 0===r&&(r=0),void 0===o&&(o=null);var a=this._gl;if(!this._dummyFramebuffer){var s=a.createFramebuffer();if(!s)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=s}a.bindFramebuffer(a.FRAMEBUFFER,this._dummyFramebuffer),n>-1?a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+n,e._webGLTexture,r):a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,e._webGLTexture,r);var c=void 0!==e.type?this._getWebGLTextureType(e.type):a.UNSIGNED_BYTE;switch(c){case a.UNSIGNED_BYTE:o||(o=new Uint8Array(4*t*i)),c=a.UNSIGNED_BYTE;break;default:o||(o=new Float32Array(4*t*i)),c=a.FLOAT}return a.readPixels(0,0,t,i,a.RGBA,c,o),a.bindFramebuffer(a.FRAMEBUFFER,this._currentFramebuffer),o},t.prototype.dispose=function(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();1===t.Instances.length&&t.audioEngine&&t.audioEngine.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.disableVR(),o.a.IsWindowObjectExist()&&(window.removeEventListener("blur",this._onBlur),window.removeEventListener("focus",this._onFocus),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut)),document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange)),e.prototype.dispose.call(this);var i=t.Instances.indexOf(this);i>=0&&t.Instances.splice(i,1),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()},t.prototype._disableTouchAction=function(){this._renderingCanvas&&this._renderingCanvas.setAttribute&&(this._renderingCanvas.setAttribute("touch-action","none"),this._renderingCanvas.style.touchAction="none",this._renderingCanvas.style.msTouchAction="none")},t.prototype.displayLoadingUI=function(){if(o.a.IsWindowObjectExist()){var e=this.loadingScreen;e&&e.displayLoadingUI()}},t.prototype.hideLoadingUI=function(){if(o.a.IsWindowObjectExist()){var e=this._loadingScreen;e&&e.hideLoadingUI()}},Object.defineProperty(t.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=t.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"loadingUIText",{set:function(e){this.loadingScreen.loadingUIText=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"loadingUIBackgroundColor",{set:function(e){this.loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),t._RequestPointerlock=function(e){e.requestPointerLock=e.requestPointerLock||e.msRequestPointerLock||e.mozRequestPointerLock||e.webkitRequestPointerLock,e.requestPointerLock&&e.requestPointerLock()},t._ExitPointerlock=function(){var e=document;document.exitPointerLock=document.exitPointerLock||e.msExitPointerLock||e.mozExitPointerLock||e.webkitExitPointerLock,document.exitPointerLock&&document.exitPointerLock()},t._RequestFullscreen=function(e){var t=e.requestFullscreen||e.msRequestFullscreen||e.webkitRequestFullscreen||e.mozRequestFullScreen;t&&t.call(e)},t._ExitFullscreen=function(){var e=document;document.exitFullscreen?document.exitFullscreen():e.mozCancelFullScreen?e.mozCancelFullScreen():e.webkitCancelFullScreen?e.webkitCancelFullScreen():e.msCancelFullScreen&&e.msCancelFullScreen()},t.ALPHA_DISABLE=l.a.ALPHA_DISABLE,t.ALPHA_ADD=l.a.ALPHA_ADD,t.ALPHA_COMBINE=l.a.ALPHA_COMBINE,t.ALPHA_SUBTRACT=l.a.ALPHA_SUBTRACT,t.ALPHA_MULTIPLY=l.a.ALPHA_MULTIPLY,t.ALPHA_MAXIMIZED=l.a.ALPHA_MAXIMIZED,t.ALPHA_ONEONE=l.a.ALPHA_ONEONE,t.ALPHA_PREMULTIPLIED=l.a.ALPHA_PREMULTIPLIED,t.ALPHA_PREMULTIPLIED_PORTERDUFF=l.a.ALPHA_PREMULTIPLIED_PORTERDUFF,t.ALPHA_INTERPOLATE=l.a.ALPHA_INTERPOLATE,t.ALPHA_SCREENMODE=l.a.ALPHA_SCREENMODE,t.DELAYLOADSTATE_NONE=l.a.DELAYLOADSTATE_NONE,t.DELAYLOADSTATE_LOADED=l.a.DELAYLOADSTATE_LOADED,t.DELAYLOADSTATE_LOADING=l.a.DELAYLOADSTATE_LOADING,t.DELAYLOADSTATE_NOTLOADED=l.a.DELAYLOADSTATE_NOTLOADED,t.NEVER=l.a.NEVER,t.ALWAYS=l.a.ALWAYS,t.LESS=l.a.LESS,t.EQUAL=l.a.EQUAL,t.LEQUAL=l.a.LEQUAL,t.GREATER=l.a.GREATER,t.GEQUAL=l.a.GEQUAL,t.NOTEQUAL=l.a.NOTEQUAL,t.KEEP=l.a.KEEP,t.REPLACE=l.a.REPLACE,t.INCR=l.a.INCR,t.DECR=l.a.DECR,t.INVERT=l.a.INVERT,t.INCR_WRAP=l.a.INCR_WRAP,t.DECR_WRAP=l.a.DECR_WRAP,t.TEXTURE_CLAMP_ADDRESSMODE=l.a.TEXTURE_CLAMP_ADDRESSMODE,t.TEXTURE_WRAP_ADDRESSMODE=l.a.TEXTURE_WRAP_ADDRESSMODE,t.TEXTURE_MIRROR_ADDRESSMODE=l.a.TEXTURE_MIRROR_ADDRESSMODE,t.TEXTUREFORMAT_ALPHA=l.a.TEXTUREFORMAT_ALPHA,t.TEXTUREFORMAT_LUMINANCE=l.a.TEXTUREFORMAT_LUMINANCE,t.TEXTUREFORMAT_LUMINANCE_ALPHA=l.a.TEXTUREFORMAT_LUMINANCE_ALPHA,t.TEXTUREFORMAT_RGB=l.a.TEXTUREFORMAT_RGB,t.TEXTUREFORMAT_RGBA=l.a.TEXTUREFORMAT_RGBA,t.TEXTUREFORMAT_RED=l.a.TEXTUREFORMAT_RED,t.TEXTUREFORMAT_R=l.a.TEXTUREFORMAT_R,t.TEXTUREFORMAT_RG=l.a.TEXTUREFORMAT_RG,t.TEXTUREFORMAT_RED_INTEGER=l.a.TEXTUREFORMAT_RED_INTEGER,t.TEXTUREFORMAT_R_INTEGER=l.a.TEXTUREFORMAT_R_INTEGER,t.TEXTUREFORMAT_RG_INTEGER=l.a.TEXTUREFORMAT_RG_INTEGER,t.TEXTUREFORMAT_RGB_INTEGER=l.a.TEXTUREFORMAT_RGB_INTEGER,t.TEXTUREFORMAT_RGBA_INTEGER=l.a.TEXTUREFORMAT_RGBA_INTEGER,t.TEXTURETYPE_UNSIGNED_BYTE=l.a.TEXTURETYPE_UNSIGNED_BYTE,t.TEXTURETYPE_UNSIGNED_INT=l.a.TEXTURETYPE_UNSIGNED_INT,t.TEXTURETYPE_FLOAT=l.a.TEXTURETYPE_FLOAT,t.TEXTURETYPE_HALF_FLOAT=l.a.TEXTURETYPE_HALF_FLOAT,t.TEXTURETYPE_BYTE=l.a.TEXTURETYPE_BYTE,t.TEXTURETYPE_SHORT=l.a.TEXTURETYPE_SHORT,t.TEXTURETYPE_UNSIGNED_SHORT=l.a.TEXTURETYPE_UNSIGNED_SHORT,t.TEXTURETYPE_INT=l.a.TEXTURETYPE_INT,t.TEXTURETYPE_UNSIGNED_INTEGER=l.a.TEXTURETYPE_UNSIGNED_INTEGER,t.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=l.a.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4,t.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=l.a.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1,t.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=l.a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,t.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=l.a.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV,t.TEXTURETYPE_UNSIGNED_INT_24_8=l.a.TEXTURETYPE_UNSIGNED_INT_24_8,t.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=l.a.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV,t.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=l.a.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV,t.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=l.a.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV,t.TEXTURE_NEAREST_SAMPLINGMODE=l.a.TEXTURE_NEAREST_SAMPLINGMODE,t.TEXTURE_BILINEAR_SAMPLINGMODE=l.a.TEXTURE_BILINEAR_SAMPLINGMODE,t.TEXTURE_TRILINEAR_SAMPLINGMODE=l.a.TEXTURE_TRILINEAR_SAMPLINGMODE,t.TEXTURE_NEAREST_NEAREST_MIPLINEAR=l.a.TEXTURE_NEAREST_NEAREST_MIPLINEAR,t.TEXTURE_LINEAR_LINEAR_MIPNEAREST=l.a.TEXTURE_LINEAR_LINEAR_MIPNEAREST,t.TEXTURE_LINEAR_LINEAR_MIPLINEAR=l.a.TEXTURE_LINEAR_LINEAR_MIPLINEAR,t.TEXTURE_NEAREST_NEAREST_MIPNEAREST=l.a.TEXTURE_NEAREST_NEAREST_MIPNEAREST,t.TEXTURE_NEAREST_LINEAR_MIPNEAREST=l.a.TEXTURE_NEAREST_LINEAR_MIPNEAREST,t.TEXTURE_NEAREST_LINEAR_MIPLINEAR=l.a.TEXTURE_NEAREST_LINEAR_MIPLINEAR,t.TEXTURE_NEAREST_LINEAR=l.a.TEXTURE_NEAREST_LINEAR,t.TEXTURE_NEAREST_NEAREST=l.a.TEXTURE_NEAREST_NEAREST,t.TEXTURE_LINEAR_NEAREST_MIPNEAREST=l.a.TEXTURE_LINEAR_NEAREST_MIPNEAREST,t.TEXTURE_LINEAR_NEAREST_MIPLINEAR=l.a.TEXTURE_LINEAR_NEAREST_MIPLINEAR,t.TEXTURE_LINEAR_LINEAR=l.a.TEXTURE_LINEAR_LINEAR,t.TEXTURE_LINEAR_NEAREST=l.a.TEXTURE_LINEAR_NEAREST,t.TEXTURE_EXPLICIT_MODE=l.a.TEXTURE_EXPLICIT_MODE,t.TEXTURE_SPHERICAL_MODE=l.a.TEXTURE_SPHERICAL_MODE,t.TEXTURE_PLANAR_MODE=l.a.TEXTURE_PLANAR_MODE,t.TEXTURE_CUBIC_MODE=l.a.TEXTURE_CUBIC_MODE,t.TEXTURE_PROJECTION_MODE=l.a.TEXTURE_PROJECTION_MODE,t.TEXTURE_SKYBOX_MODE=l.a.TEXTURE_SKYBOX_MODE,t.TEXTURE_INVCUBIC_MODE=l.a.TEXTURE_INVCUBIC_MODE,t.TEXTURE_EQUIRECTANGULAR_MODE=l.a.TEXTURE_EQUIRECTANGULAR_MODE,t.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=l.a.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,t.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=l.a.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,t.SCALEMODE_FLOOR=l.a.SCALEMODE_FLOOR,t.SCALEMODE_NEAREST=l.a.SCALEMODE_NEAREST,t.SCALEMODE_CEILING=l.a.SCALEMODE_CEILING,t._RescalePostProcessFactory=null,t}(c.a)},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return e.GetClass=function(e){return this.RegisteredTypes&&this.RegisteredTypes[e]?this.RegisteredTypes[e]:null},e.RegisteredTypes={},e}()},function(e,t,i){"use strict";i.d(t,"b",function(){return m}),i.d(t,"c",function(){return g}),i.d(t,"a",function(){return v});var n=i(6),r=i(38),o=i(7),a=i(33),s=i(52),c=i(19),l=i(65),u=i(23),h=i(54),d=i(131),f=i(115),p=i(112),_=i(137),m=function(){function e(){}return Object.defineProperty(e,"BaseUrl",{get:function(){return h.a.BaseUrl},set:function(e){h.a.BaseUrl=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"DefaultRetryStrategy",{get:function(){return h.a.DefaultRetryStrategy},set:function(e){h.a.DefaultRetryStrategy=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"UseFallbackTexture",{get:function(){return u.a.UseFallbackTexture},set:function(e){u.a.UseFallbackTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"RegisteredExternalClasses",{get:function(){return p.a.RegisteredExternalClasses},set:function(e){p.a.RegisteredExternalClasses=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"fallbackTexture",{get:function(){return u.a.FallbackTexture},set:function(e){u.a.FallbackTexture=e},enumerable:!0,configurable:!0}),e.FetchToRef=function(e,t,i,n,r,o){var a=4*((Math.abs(e)*i%i|0)+(Math.abs(t)*n%n|0)*i);o.r=r[a]/255,o.g=r[a+1]/255,o.b=r[a+2]/255,o.a=r[a+3]/255},e.Mix=function(e,t,i){return e*(1-i)+t*i},e.Instantiate=function(e){return p.a.Instantiate(e)},e.Slice=function(e,t,i){return e.slice?e.slice(t,i):Array.prototype.slice.call(e,t,i)},e.SetImmediate=function(e){f.a.SetImmediate(e)},e.IsExponentOfTwo=function(e){var t=1;do{t*=2}while(t<e);return t===e},e.FloatRound=function(t){return Math.fround?Math.fround(t):e._tmpFloatArray[0]=t},e.GetFilename=function(e){var t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)},e.GetFolderPath=function(e,t){void 0===t&&(t=!1);var i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)},e.ToDegrees=function(e){return 180*e/Math.PI},e.ToRadians=function(e){return e*Math.PI/180},e.MakeArray=function(e,t){return!0===t||void 0!==e&&null!=e?Array.isArray(e)?e:[e]:null},e.GetPointerPrefix=function(){var e="pointer";return r.a.IsWindowObjectExist()&&!window.PointerEvent&&r.a.IsNavigatorAvailable()&&!navigator.pointerEnabled&&(e="mouse"),e},e.SetCorsBehavior=function(e,t){h.a.SetCorsBehavior(e,t)},e.CleanUrl=function(e){return e=e.replace(/#/gm,"%23")},Object.defineProperty(e,"PreprocessUrl",{get:function(){return h.a.PreprocessUrl},set:function(e){h.a.PreprocessUrl=e},enumerable:!0,configurable:!0}),e.LoadImage=function(e,t,i,n,r){return h.a.LoadImage(e,t,i,n,r)},e.LoadFile=function(e,t,i,n,r,o){return h.a.LoadFile(e,t,i,n,r,o)},e.LoadFileAsync=function(e,t){return void 0===t&&(t=!0),new Promise(function(i,n){h.a.LoadFile(e,function(e){i(e)},void 0,void 0,t,function(e,t){n(t)})})},e.LoadScript=function(e,t,i,n){if(r.a.IsWindowObjectExist()){var o=document.getElementsByTagName("head")[0],a=document.createElement("script");a.setAttribute("type","text/javascript"),a.setAttribute("src",e),n&&(a.id=n),a.onload=function(){t&&t()},a.onerror=function(t){i&&i("Unable to load script '"+e+"'",t)},o.appendChild(a)}},e.LoadScriptAsync=function(e,t){var i=this;return new Promise(function(t,n){i.LoadScript(e,function(){t()},function(e,t){n(t)})})},e.ReadFileAsDataURL=function(e,t,i){var r=new FileReader,o={onCompleteObservable:new n.c,abort:function(){return r.abort()}};return r.onloadend=function(e){o.onCompleteObservable.notifyObservers(o)},r.onload=function(e){t(e.target.result)},r.onprogress=i,r.readAsDataURL(e),o},e.ReadFile=function(e,t,i,n,r){return h.a.ReadFile(e,t,i,n,r)},e.FileAsURL=function(e){var t=new Blob([e]);return(window.URL||window.webkitURL).createObjectURL(t)},e.Format=function(e,t){return void 0===t&&(t=2),e.toFixed(t)},e.DeepCopy=function(e,t,i,n){a.a.DeepCopy(e,t,i,n)},e.IsEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},e.RegisterTopRootEvents=function(e,t){for(var i=0;i<t.length;i++){var n=t[i];e.addEventListener(n.name,n.handler,!1);try{window.parent&&window.parent.addEventListener(n.name,n.handler,!1)}catch(e){}}},e.UnregisterTopRootEvents=function(e,t){for(var i=0;i<t.length;i++){var n=t[i];e.removeEventListener(n.name,n.handler);try{e.parent&&e.parent.removeEventListener(n.name,n.handler)}catch(e){}}},e.DumpFramebuffer=function(t,i,n,r,o,a){void 0===o&&(o="image/png");for(var s=4*t,c=i/2,l=n.readPixels(0,0,t,i),u=0;u<c;u++)for(var h=0;h<s;h++){var d=h+u*s,f=h+(i-u-1)*s,p=l[d];l[d]=l[f],l[f]=p}e._ScreenshotCanvas||(e._ScreenshotCanvas=document.createElement("canvas")),e._ScreenshotCanvas.width=t,e._ScreenshotCanvas.height=i;var _=e._ScreenshotCanvas.getContext("2d");if(_){var m=_.createImageData(t,i);m.data.set(l),_.putImageData(m,0,0),e.EncodeScreenshotCanvasData(r,o,a)}},e.ToBlob=function(e,t,i){void 0===i&&(i="image/png"),e.toBlob||(e.toBlob=function(e,t,i){var n=this;setTimeout(function(){for(var r=atob(n.toDataURL(t,i).split(",")[1]),o=r.length,a=new Uint8Array(o),s=0;s<o;s++)a[s]=r.charCodeAt(s);e(new Blob([a]))})}),e.toBlob(function(e){t(e)},i)},e.EncodeScreenshotCanvasData=function(t,i,n){(void 0===i&&(i="image/png"),t)?t(e._ScreenshotCanvas.toDataURL(i)):this.ToBlob(e._ScreenshotCanvas,function(t){if("download"in document.createElement("a")){if(!n){var i=new Date,r=(i.getFullYear()+"-"+(i.getMonth()+1)).slice(2)+"-"+i.getDate()+"_"+i.getHours()+"-"+("0"+i.getMinutes()).slice(-2);n="screenshot_"+r+".png"}e.Download(t,n)}else{var o=URL.createObjectURL(t),a=window.open("");if(!a)return;var s=a.document.createElement("img");s.onload=function(){URL.revokeObjectURL(o)},s.src=o,a.document.body.appendChild(s)}},i)},e.Download=function(e,t){if(navigator&&navigator.msSaveBlob)navigator.msSaveBlob(e,t);else{var i=window.URL.createObjectURL(e),n=document.createElement("a");document.body.appendChild(n),n.style.display="none",n.href=i,n.download=t,n.addEventListener("click",function(){n.parentElement&&n.parentElement.removeChild(n)}),n.click(),window.URL.revokeObjectURL(i)}},e.CreateScreenshot=function(e,t,i,n,r){throw void 0===r&&(r="image/png"),c.a.WarnImport("ScreenshotTools")},e.CreateScreenshotAsync=function(e,t,i,n){throw void 0===n&&(n="image/png"),c.a.WarnImport("ScreenshotTools")},e.CreateScreenshotUsingRenderTarget=function(e,t,i,n,r,o,a,s){throw void 0===r&&(r="image/png"),void 0===o&&(o=1),void 0===a&&(a=!1),c.a.WarnImport("ScreenshotTools")},e.CreateScreenshotUsingRenderTargetAsync=function(e,t,i,n,r,o,a){throw void 0===n&&(n="image/png"),void 0===r&&(r=1),void 0===o&&(o=!1),c.a.WarnImport("ScreenshotTools")},e.RandomId=function(){return _.a.RandomId()},e.IsBase64=function(e){return!(e.length<5)&&"data:"===e.substr(0,5)},e.DecodeBase64=function(e){for(var t=atob(e.split(",")[1]),i=t.length,n=new Uint8Array(new ArrayBuffer(i)),r=0;r<i;r++)n[r]=t.charCodeAt(r);return n.buffer},e.GetAbsoluteUrl=function(e){var t=document.createElement("a");return t.href=e,t.href},Object.defineProperty(e,"errorsCount",{get:function(){return o.a.errorsCount},enumerable:!0,configurable:!0}),e.Log=function(e){o.a.Log(e)},e.Warn=function(e){o.a.Warn(e)},e.Error=function(e){o.a.Error(e)},Object.defineProperty(e,"LogCache",{get:function(){return o.a.LogCache},enumerable:!0,configurable:!0}),e.ClearLogCache=function(){o.a.ClearLogCache()},Object.defineProperty(e,"LogLevels",{set:function(e){o.a.LogLevels=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"PerformanceLogLevel",{set:function(t){return(t&e.PerformanceUserMarkLogLevel)===e.PerformanceUserMarkLogLevel?(e.StartPerformanceCounter=e._StartUserMark,void(e.EndPerformanceCounter=e._EndUserMark)):(t&e.PerformanceConsoleLogLevel)===e.PerformanceConsoleLogLevel?(e.StartPerformanceCounter=e._StartPerformanceConsole,void(e.EndPerformanceCounter=e._EndPerformanceConsole)):(e.StartPerformanceCounter=e._StartPerformanceCounterDisabled,void(e.EndPerformanceCounter=e._EndPerformanceCounterDisabled))},enumerable:!0,configurable:!0}),e._StartPerformanceCounterDisabled=function(e,t){},e._EndPerformanceCounterDisabled=function(e,t){},e._StartUserMark=function(t,i){if(void 0===i&&(i=!0),!e._performance){if(!r.a.IsWindowObjectExist())return;e._performance=window.performance}i&&e._performance.mark&&e._performance.mark(t+"-Begin")},e._EndUserMark=function(t,i){void 0===i&&(i=!0),i&&e._performance.mark&&(e._performance.mark(t+"-End"),e._performance.measure(t,t+"-Begin",t+"-End"))},e._StartPerformanceConsole=function(t,i){void 0===i&&(i=!0),i&&(e._StartUserMark(t,i),console.time&&console.time(t))},e._EndPerformanceConsole=function(t,i){void 0===i&&(i=!0),i&&(e._EndUserMark(t,i),console.timeEnd(t))},Object.defineProperty(e,"Now",{get:function(){return s.a.Now},enumerable:!0,configurable:!0}),e.GetClassName=function(e,t){void 0===t&&(t=!1);var i=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object)i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__;i||(i=typeof e)}return i},e.First=function(e,t){for(var i=0,n=e;i<n.length;i++){var r=n[i];if(t(r))return r}return null},e.getFullClassName=function(e,t){void 0===t&&(t=!1);var i=null,n=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){var r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,n=r.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=n?n+".":"")+i:null},e.DelayAsync=function(e){return new Promise(function(t){setTimeout(function(){t()},e)})},e.IsSafari=function(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)},e.UseCustomRequestHeaders=!1,e.CustomRequestHeaders=l.a.CustomRequestHeaders,e.CorsBehavior="anonymous",e._tmpFloatArray=new Float32Array(1),e.GetDOMTextContent=r.a.GetDOMTextContent,e.NoneLogLevel=o.a.NoneLogLevel,e.MessageLogLevel=o.a.MessageLogLevel,e.WarningLogLevel=o.a.WarningLogLevel,e.ErrorLogLevel=o.a.ErrorLogLevel,e.AllLogLevel=o.a.AllLogLevel,e.IsWindowObjectExist=r.a.IsWindowObjectExist,e.PerformanceNoneLogLevel=0,e.PerformanceUserMarkLogLevel=1,e.PerformanceConsoleLogLevel=2,e.StartPerformanceCounter=e._StartPerformanceCounterDisabled,e.EndPerformanceCounter=e._EndPerformanceCounterDisabled,e}();function g(e,t){return function(i){i.__bjsclassName__=e,i.__bjsmoduleName__=null!=t?t:null}}var v=function(){function e(e,t,i,n){void 0===n&&(n=0),this.iterations=e,this.index=n-1,this._done=!1,this._fn=t,this._successCallback=i}return e.prototype.executeNext=function(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())},e.prototype.breakLoop=function(){this._done=!0,this._successCallback()},e.Run=function(t,i,n,r){void 0===r&&(r=0);var o=new e(t,i,n,r);return o.executeNext(),o},e.SyncAsyncForLoop=function(t,i,n,r,o,a){return void 0===a&&(a=0),e.Run(Math.ceil(t/i),function(e){o&&o()?e.breakLoop():setTimeout(function(){for(var r=0;r<i;++r){var a=e.index*i+r;if(a>=t)break;if(n(a),o&&o()){e.breakLoop();break}}e.executeNext()},a)},r)},e}();u.a.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",d.a.Apply()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return e.WithinEpsilon=function(e,t,i){void 0===i&&(i=1401298e-51);var n=e-t;return-i<=n&&n<=i},e.ToHex=function(e){var t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()},e.Sign=function(e){return 0===(e=+e)||isNaN(e)?e:e>0?1:-1},e.Clamp=function(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=1),Math.min(i,Math.max(t,e))},e.Log2=function(e){return Math.log(e)*Math.LOG2E},e.Repeat=function(e,t){return e-Math.floor(e/t)*t},e.Normalize=function(e,t,i){return(e-t)/(i-t)},e.Denormalize=function(e,t,i){return e*(i-t)+t},e.DeltaAngle=function(t,i){var n=e.Repeat(i-t,360);return n>180&&(n-=360),n},e.PingPong=function(t,i){var n=e.Repeat(t,2*i);return i-Math.abs(n-i)},e.SmoothStep=function(t,i,n){var r=e.Clamp(n);return i*(r=-2*r*r*r+3*r*r)+t*(1-r)},e.MoveTowards=function(t,i,n){return Math.abs(i-t)<=n?i:t+e.Sign(i-t)*n},e.MoveTowardsAngle=function(t,i,n){var r=e.DeltaAngle(t,i),o=0;return-n<r&&r<n?o=i:(i=t+r,o=e.MoveTowards(t,i,n)),o},e.Lerp=function(e,t,i){return e+(t-e)*i},e.LerpAngle=function(t,i,n){var r=e.Repeat(i-t,360);return r>180&&(r-=360),t+r*e.Clamp(n)},e.InverseLerp=function(t,i,n){return t!=i?e.Clamp((n-t)/(i-t)):0},e.Hermite=function(e,t,i,n,r){var o=r*r,a=r*o;return e*(2*a-3*o+1)+i*(-2*a+3*o)+t*(a-2*o+r)+n*(a-o)},e.RandomRange=function(e,t){return e===t?e:Math.random()*(t-e)+e},e.RangeToPercent=function(e,t,i){return(e-t)/(i-t)},e.PercentToRange=function(e,t,i){return(i-t)*e+t},e.NormalizeRadians=function(t){return t-=e.TwoPi*Math.floor((t+Math.PI)/e.TwoPi)},e.TwoPi=2*Math.PI,e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return s});var n=i(0),r=i(4),o=i(19),a=i(10),s=function(){function e(){}return e.prototype.set=function(e,t){switch(t){case r.b.PositionKind:this.positions=e;break;case r.b.NormalKind:this.normals=e;break;case r.b.TangentKind:this.tangents=e;break;case r.b.UVKind:this.uvs=e;break;case r.b.UV2Kind:this.uvs2=e;break;case r.b.UV3Kind:this.uvs3=e;break;case r.b.UV4Kind:this.uvs4=e;break;case r.b.UV5Kind:this.uvs5=e;break;case r.b.UV6Kind:this.uvs6=e;break;case r.b.ColorKind:this.colors=e;break;case r.b.MatricesIndicesKind:this.matricesIndices=e;break;case r.b.MatricesWeightsKind:this.matricesWeights=e;break;case r.b.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case r.b.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}},e.prototype.applyToMesh=function(e,t){return this._applyTo(e,t),this},e.prototype.applyToGeometry=function(e,t){return this._applyTo(e,t),this},e.prototype.updateMesh=function(e){return this._update(e),this},e.prototype.updateGeometry=function(e){return this._update(e),this},e.prototype._applyTo=function(e,t){return void 0===t&&(t=!1),this.positions&&e.setVerticesData(r.b.PositionKind,this.positions,t),this.normals&&e.setVerticesData(r.b.NormalKind,this.normals,t),this.tangents&&e.setVerticesData(r.b.TangentKind,this.tangents,t),this.uvs&&e.setVerticesData(r.b.UVKind,this.uvs,t),this.uvs2&&e.setVerticesData(r.b.UV2Kind,this.uvs2,t),this.uvs3&&e.setVerticesData(r.b.UV3Kind,this.uvs3,t),this.uvs4&&e.setVerticesData(r.b.UV4Kind,this.uvs4,t),this.uvs5&&e.setVerticesData(r.b.UV5Kind,this.uvs5,t),this.uvs6&&e.setVerticesData(r.b.UV6Kind,this.uvs6,t),this.colors&&e.setVerticesData(r.b.ColorKind,this.colors,t),this.matricesIndices&&e.setVerticesData(r.b.MatricesIndicesKind,this.matricesIndices,t),this.matricesWeights&&e.setVerticesData(r.b.MatricesWeightsKind,this.matricesWeights,t),this.matricesIndicesExtra&&e.setVerticesData(r.b.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),this.matricesWeightsExtra&&e.setVerticesData(r.b.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),this.indices?e.setIndices(this.indices,null,t):e.setIndices([],null),this},e.prototype._update=function(e,t,i){return this.positions&&e.updateVerticesData(r.b.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(r.b.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(r.b.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(r.b.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(r.b.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(r.b.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(r.b.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(r.b.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(r.b.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(r.b.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(r.b.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(r.b.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(r.b.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(r.b.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this},e.prototype.transform=function(e){var t,i=e.m[0]*e.m[5]*e.m[10]<0,r=n.e.Zero();if(this.positions){var o=n.e.Zero();for(t=0;t<this.positions.length;t+=3)n.e.FromArrayToRef(this.positions,t,o),n.e.TransformCoordinatesToRef(o,e,r),this.positions[t]=r.x,this.positions[t+1]=r.y,this.positions[t+2]=r.z}if(this.normals){var a=n.e.Zero();for(t=0;t<this.normals.length;t+=3)n.e.FromArrayToRef(this.normals,t,a),n.e.TransformNormalToRef(a,e,r),this.normals[t]=r.x,this.normals[t+1]=r.y,this.normals[t+2]=r.z}if(this.tangents){var s=n.f.Zero(),c=n.f.Zero();for(t=0;t<this.tangents.length;t+=4)n.f.FromArrayToRef(this.tangents,t,s),n.f.TransformNormalToRef(s,e,c),this.tangents[t]=c.x,this.tangents[t+1]=c.y,this.tangents[t+2]=c.z,this.tangents[t+3]=c.w}if(i&&this.indices)for(t=0;t<this.indices.length;t+=3){var l=this.indices[t+1];this.indices[t+1]=this.indices[t+2],this.indices[t+2]=l}return this},e.prototype.merge=function(e,t){if(void 0===t&&(t=!1),this._validate(),e._validate(),!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");if(e.indices){this.indices||(this.indices=[]);var i=this.positions?this.positions.length/3:0;if(void 0!==this.indices.BYTES_PER_ELEMENT){var n=this.indices.length+e.indices.length,r=t||this.indices instanceof Uint32Array?new Uint32Array(n):new Uint16Array(n);r.set(this.indices);for(var o=this.indices.length,a=0;a<e.indices.length;a++)r[o+a]=e.indices[a]+i;this.indices=r}else for(a=0;a<e.indices.length;a++)this.indices.push(e.indices[a]+i)}return this.positions=this._mergeElement(this.positions,e.positions),this.normals=this._mergeElement(this.normals,e.normals),this.tangents=this._mergeElement(this.tangents,e.tangents),this.uvs=this._mergeElement(this.uvs,e.uvs),this.uvs2=this._mergeElement(this.uvs2,e.uvs2),this.uvs3=this._mergeElement(this.uvs3,e.uvs3),this.uvs4=this._mergeElement(this.uvs4,e.uvs4),this.uvs5=this._mergeElement(this.uvs5,e.uvs5),this.uvs6=this._mergeElement(this.uvs6,e.uvs6),this.colors=this._mergeElement(this.colors,e.colors),this.matricesIndices=this._mergeElement(this.matricesIndices,e.matricesIndices),this.matricesWeights=this._mergeElement(this.matricesWeights,e.matricesWeights),this.matricesIndicesExtra=this._mergeElement(this.matricesIndicesExtra,e.matricesIndicesExtra),this.matricesWeightsExtra=this._mergeElement(this.matricesWeightsExtra,e.matricesWeightsExtra),this},e.prototype._mergeElement=function(e,t){if(!e)return t;if(!t)return e;var i=t.length+e.length,n=e instanceof Float32Array,r=t instanceof Float32Array;if(n){var o=new Float32Array(i);return o.set(e),o.set(t,e.length),o}if(r){var a=e.slice(0),s=0;for(i=t.length;s<i;s++)a.push(t[s]);return a}return e.concat(t)},e.prototype._validate=function(){if(!this.positions)throw new Error("Positions are required");var e=function(e,t){var i=r.b.DeduceStride(e);if(t.length%i!=0)throw new Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(r.b.PositionKind,this.positions),i=function(i,n){var r=e(i,n);if(r!==t)throw new Error("The "+i+"s element count ("+r+") does not match the positions count ("+t+")")};this.normals&&i(r.b.NormalKind,this.normals),this.tangents&&i(r.b.TangentKind,this.tangents),this.uvs&&i(r.b.UVKind,this.uvs),this.uvs2&&i(r.b.UV2Kind,this.uvs2),this.uvs3&&i(r.b.UV3Kind,this.uvs3),this.uvs4&&i(r.b.UV4Kind,this.uvs4),this.uvs5&&i(r.b.UV5Kind,this.uvs5),this.uvs6&&i(r.b.UV6Kind,this.uvs6),this.colors&&i(r.b.ColorKind,this.colors),this.matricesIndices&&i(r.b.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(r.b.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(r.b.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(r.b.MatricesWeightsExtraKind,this.matricesWeightsExtra)},e.prototype.serialize=function(){var e=this.serialize();return this.positions&&(e.positions=this.positions),this.normals&&(e.normals=this.normals),this.tangents&&(e.tangents=this.tangents),this.uvs&&(e.uvs=this.uvs),this.uvs2&&(e.uvs2=this.uvs2),this.uvs3&&(e.uvs3=this.uvs3),this.uvs4&&(e.uvs4=this.uvs4),this.uvs5&&(e.uvs5=this.uvs5),this.uvs6&&(e.uvs6=this.uvs6),this.colors&&(e.colors=this.colors),this.matricesIndices&&(e.matricesIndices=this.matricesIndices,e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=this.matricesWeights),this.matricesIndicesExtra&&(e.matricesIndicesExtra=this.matricesIndicesExtra,e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=this.matricesWeightsExtra),e.indices=this.indices,e},e.ExtractFromMesh=function(t,i,n){return e._ExtractFrom(t,i,n)},e.ExtractFromGeometry=function(t,i,n){return e._ExtractFrom(t,i,n)},e._ExtractFrom=function(t,i,n){var o=new e;return t.isVerticesDataPresent(r.b.PositionKind)&&(o.positions=t.getVerticesData(r.b.PositionKind,i,n)),t.isVerticesDataPresent(r.b.NormalKind)&&(o.normals=t.getVerticesData(r.b.NormalKind,i,n)),t.isVerticesDataPresent(r.b.TangentKind)&&(o.tangents=t.getVerticesData(r.b.TangentKind,i,n)),t.isVerticesDataPresent(r.b.UVKind)&&(o.uvs=t.getVerticesData(r.b.UVKind,i,n)),t.isVerticesDataPresent(r.b.UV2Kind)&&(o.uvs2=t.getVerticesData(r.b.UV2Kind,i,n)),t.isVerticesDataPresent(r.b.UV3Kind)&&(o.uvs3=t.getVerticesData(r.b.UV3Kind,i,n)),t.isVerticesDataPresent(r.b.UV4Kind)&&(o.uvs4=t.getVerticesData(r.b.UV4Kind,i,n)),t.isVerticesDataPresent(r.b.UV5Kind)&&(o.uvs5=t.getVerticesData(r.b.UV5Kind,i,n)),t.isVerticesDataPresent(r.b.UV6Kind)&&(o.uvs6=t.getVerticesData(r.b.UV6Kind,i,n)),t.isVerticesDataPresent(r.b.ColorKind)&&(o.colors=t.getVerticesData(r.b.ColorKind,i,n)),t.isVerticesDataPresent(r.b.MatricesIndicesKind)&&(o.matricesIndices=t.getVerticesData(r.b.MatricesIndicesKind,i,n)),t.isVerticesDataPresent(r.b.MatricesWeightsKind)&&(o.matricesWeights=t.getVerticesData(r.b.MatricesWeightsKind,i,n)),t.isVerticesDataPresent(r.b.MatricesIndicesExtraKind)&&(o.matricesIndicesExtra=t.getVerticesData(r.b.MatricesIndicesExtraKind,i,n)),t.isVerticesDataPresent(r.b.MatricesWeightsExtraKind)&&(o.matricesWeightsExtra=t.getVerticesData(r.b.MatricesWeightsExtraKind,i,n)),o.indices=t.getIndices(i,n),o},e.CreateRibbon=function(e){throw o.a.WarnImport("ribbonBuilder")},e.CreateBox=function(e){throw o.a.WarnImport("boxBuilder")},e.CreateTiledBox=function(e){throw o.a.WarnImport("tiledBoxBuilder")},e.CreateTiledPlane=function(e){throw o.a.WarnImport("tiledPlaneBuilder")},e.CreateSphere=function(e){throw o.a.WarnImport("sphereBuilder")},e.CreateCylinder=function(e){throw o.a.WarnImport("cylinderBuilder")},e.CreateTorus=function(e){throw o.a.WarnImport("torusBuilder")},e.CreateLineSystem=function(e){throw o.a.WarnImport("linesBuilder")},e.CreateDashedLines=function(e){throw o.a.WarnImport("linesBuilder")},e.CreateGround=function(e){throw o.a.WarnImport("groundBuilder")},e.CreateTiledGround=function(e){throw o.a.WarnImport("groundBuilder")},e.CreateGroundFromHeightMap=function(e){throw o.a.WarnImport("groundBuilder")},e.CreatePlane=function(e){throw o.a.WarnImport("planeBuilder")},e.CreateDisc=function(e){throw o.a.WarnImport("discBuilder")},e.CreatePolygon=function(e,t,i,n,r,a){throw o.a.WarnImport("polygonBuilder")},e.CreateIcoSphere=function(e){throw o.a.WarnImport("icoSphereBuilder")},e.CreatePolyhedron=function(e){throw o.a.WarnImport("polyhedronBuilder")},e.CreateTorusKnot=function(e){throw o.a.WarnImport("torusKnotBuilder")},e.ComputeNormals=function(e,t,i,r){var o=0,a=0,s=0,c=0,l=0,u=0,h=0,d=0,f=0,p=0,_=0,m=0,g=0,v=0,y=0,b=0,T=0,E=0,x=0,P=0,A=!1,S=!1,C=!1,R=!1,O=1,M=0,I=null;if(r&&(A=!!r.facetNormals,S=!!r.facetPositions,C=!!r.facetPartitioning,O=!0===r.useRightHandedSystem?-1:1,M=r.ratio||0,R=!!r.depthSort,I=r.distanceTo,R)){void 0===I&&(I=n.e.Zero());var D=r.depthSortedFacets}var w=0,L=0,N=0,F=0;if(C&&r&&r.bbSize){var B=0,U=0,V=0,k=0,z=0,G=0,j=0,W=0,X=0,H=0,Y=0,K=0,Q=0,q=0,Z=0,J=0,$=r.bbSize.x>r.bbSize.y?r.bbSize.x:r.bbSize.y;$=$>r.bbSize.z?$:r.bbSize.z,w=r.subDiv.X*M/r.bbSize.x,L=r.subDiv.Y*M/r.bbSize.y,N=r.subDiv.Z*M/r.bbSize.z,F=r.subDiv.max*r.subDiv.max,r.facetPartitioning.length=0}for(o=0;o<e.length;o++)i[o]=0;var ee=t.length/3|0;for(o=0;o<ee;o++){if(g=(m=3*t[3*o])+1,v=m+2,b=(y=3*t[3*o+1])+1,T=y+2,x=(E=3*t[3*o+2])+1,P=E+2,a=e[m]-e[y],s=e[g]-e[b],c=e[v]-e[T],l=e[E]-e[y],u=e[x]-e[b],d=O*(s*(h=e[P]-e[T])-c*u),f=O*(c*l-a*h),p=O*(a*u-s*l),d/=_=0===(_=Math.sqrt(d*d+f*f+p*p))?1:_,f/=_,p/=_,A&&r&&(r.facetNormals[o].x=d,r.facetNormals[o].y=f,r.facetNormals[o].z=p),S&&r&&(r.facetPositions[o].x=(e[m]+e[y]+e[E])/3,r.facetPositions[o].y=(e[g]+e[b]+e[x])/3,r.facetPositions[o].z=(e[v]+e[T]+e[P])/3),C&&r&&(B=Math.floor((r.facetPositions[o].x-r.bInfo.minimum.x*M)*w),U=Math.floor((r.facetPositions[o].y-r.bInfo.minimum.y*M)*L),V=Math.floor((r.facetPositions[o].z-r.bInfo.minimum.z*M)*N),k=Math.floor((e[m]-r.bInfo.minimum.x*M)*w),z=Math.floor((e[g]-r.bInfo.minimum.y*M)*L),G=Math.floor((e[v]-r.bInfo.minimum.z*M)*N),j=Math.floor((e[y]-r.bInfo.minimum.x*M)*w),W=Math.floor((e[b]-r.bInfo.minimum.y*M)*L),X=Math.floor((e[T]-r.bInfo.minimum.z*M)*N),H=Math.floor((e[E]-r.bInfo.minimum.x*M)*w),Y=Math.floor((e[x]-r.bInfo.minimum.y*M)*L),K=Math.floor((e[P]-r.bInfo.minimum.z*M)*N),q=k+r.subDiv.max*z+F*G,Z=j+r.subDiv.max*W+F*X,J=H+r.subDiv.max*Y+F*K,Q=B+r.subDiv.max*U+F*V,r.facetPartitioning[Q]=r.facetPartitioning[Q]?r.facetPartitioning[Q]:new Array,r.facetPartitioning[q]=r.facetPartitioning[q]?r.facetPartitioning[q]:new Array,r.facetPartitioning[Z]=r.facetPartitioning[Z]?r.facetPartitioning[Z]:new Array,r.facetPartitioning[J]=r.facetPartitioning[J]?r.facetPartitioning[J]:new Array,r.facetPartitioning[q].push(o),Z!=q&&r.facetPartitioning[Z].push(o),J!=Z&&J!=q&&r.facetPartitioning[J].push(o),Q!=q&&Q!=Z&&Q!=J&&r.facetPartitioning[Q].push(o)),R&&r&&r.facetPositions){var te=D[o];te.ind=3*o,te.sqDistance=n.e.DistanceSquared(r.facetPositions[o],I)}i[m]+=d,i[g]+=f,i[v]+=p,i[y]+=d,i[b]+=f,i[T]+=p,i[E]+=d,i[x]+=f,i[P]+=p}for(o=0;o<i.length/3;o++)d=i[3*o],f=i[3*o+1],p=i[3*o+2],d/=_=0===(_=Math.sqrt(d*d+f*f+p*p))?1:_,f/=_,p/=_,i[3*o]=d,i[3*o+1]=f,i[3*o+2]=p},e._ComputeSides=function(t,i,r,o,a,s,c){var l,u,h=r.length,d=o.length;switch(t=t||e.DEFAULTSIDE){case e.FRONTSIDE:break;case e.BACKSIDE:var f;for(l=0;l<h;l+=3)f=r[l],r[l]=r[l+2],r[l+2]=f;for(u=0;u<d;u++)o[u]=-o[u];break;case e.DOUBLESIDE:for(var p=i.length,_=p/3,m=0;m<p;m++)i[p+m]=i[m];for(l=0;l<h;l+=3)r[l+h]=r[l+2]+_,r[l+1+h]=r[l+1]+_,r[l+2+h]=r[l]+_;for(u=0;u<d;u++)o[d+u]=-o[u];var g=a.length,v=0;for(v=0;v<g;v++)a[v+g]=a[v];for(s=s||new n.f(0,0,1,1),c=c||new n.f(0,0,1,1),v=0,l=0;l<g/2;l++)a[v]=s.x+(s.z-s.x)*a[v],a[v+1]=s.y+(s.w-s.y)*a[v+1],a[v+g]=c.x+(c.z-c.x)*a[v+g],a[v+g+1]=c.y+(c.w-c.y)*a[v+g+1],v+=2}},e.ImportVertexData=function(t,i){var n=new e,o=t.positions;o&&n.set(o,r.b.PositionKind);var s=t.normals;s&&n.set(s,r.b.NormalKind);var c=t.tangents;c&&n.set(c,r.b.TangentKind);var l=t.uvs;l&&n.set(l,r.b.UVKind);var u=t.uv2s;u&&n.set(u,r.b.UV2Kind);var h=t.uv3s;h&&n.set(h,r.b.UV3Kind);var d=t.uv4s;d&&n.set(d,r.b.UV4Kind);var f=t.uv5s;f&&n.set(f,r.b.UV5Kind);var p=t.uv6s;p&&n.set(p,r.b.UV6Kind);var _=t.colors;_&&n.set(a.b.CheckColors4(_,o.length/3),r.b.ColorKind);var m=t.matricesIndices;m&&n.set(m,r.b.MatricesIndicesKind);var g=t.matricesWeights;g&&n.set(g,r.b.MatricesWeightsKind);var v=t.indices;v&&(n.indices=v),i.setAllVerticesData(n,t.updatable)},e.FRONTSIDE=0,e.BACKSIDE=1,e.DOUBLESIDE=2,e.DEFAULTSIDE=0,e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return l});var n=i(7),r=i(18),o=i(23),a=i(4),s=i(50),c=i(10),l=function(){function e(){}return e.BindEyePosition=function(e,t){if(t._forcedViewPosition)e.setVector3("vEyePosition",t._forcedViewPosition);else{var i=t.activeCamera.globalPosition;i||(i=t.activeCamera.devicePosition),e.setVector3("vEyePosition",t._mirroredCameraPosition?t._mirroredCameraPosition:i)}},e.PrepareDefinesForMergedUV=function(e,t,i){t._needUVs=!0,t[i]=!0,e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,0===e.coordinatesIndex?t.MAINUV1=!0:t.MAINUV2=!0):t[i+"DIRECTUV"]=0},e.BindTextureMatrix=function(e,t,i){var n=e.getTextureMatrix();t.updateMatrix(i+"Matrix",n)},e.GetFogState=function(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==r.a.FOGMODE_NONE},e.PrepareDefinesForMisc=function(e,t,i,n,r,o,a){a._areMiscDirty&&(a.LOGARITHMICDEPTH=i,a.POINTSIZE=n,a.FOG=r&&this.GetFogState(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=o)},e.PrepareDefinesForFrameBoundValues=function(e,t,i,n,r){void 0===r&&(r=null);var o,a,s,c,l,u,h=!1;o=null==r?void 0!==e.clipPlane&&null!==e.clipPlane:r,a=null==r?void 0!==e.clipPlane2&&null!==e.clipPlane2:r,s=null==r?void 0!==e.clipPlane3&&null!==e.clipPlane3:r,c=null==r?void 0!==e.clipPlane4&&null!==e.clipPlane4:r,l=null==r?void 0!==e.clipPlane5&&null!==e.clipPlane5:r,u=null==r?void 0!==e.clipPlane6&&null!==e.clipPlane6:r,i.CLIPPLANE!==o&&(i.CLIPPLANE=o,h=!0),i.CLIPPLANE2!==a&&(i.CLIPPLANE2=a,h=!0),i.CLIPPLANE3!==s&&(i.CLIPPLANE3=s,h=!0),i.CLIPPLANE4!==c&&(i.CLIPPLANE4=c,h=!0),i.CLIPPLANE5!==l&&(i.CLIPPLANE5=l,h=!0),i.CLIPPLANE6!==u&&(i.CLIPPLANE6=u,h=!0),i.DEPTHPREPASS!==!t.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,h=!0),i.INSTANCES!==n&&(i.INSTANCES=n,h=!0),h&&i.markAsUnprocessed()},e.PrepareDefinesForBones=function(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;var i=void 0!==t.BONETEXTURE;e.skeleton.isUsingTextureForMatrices&&i?t.BONETEXTURE=!0:(t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0)}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0},e.PrepareDefinesForMorphTargets=function(e,t){var i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.MORPHTARGETS=i.numInfluencers>0,t.NUM_MORPH_INFLUENCERS=i.numInfluencers):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)},e.PrepareDefinesForAttributes=function(e,t,i,n,r,o){if(void 0===r&&(r=!1),void 0===o&&(o=!0),!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;if(t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent(a.b.NormalKind),t._needNormals&&e.isVerticesDataPresent(a.b.TangentKind)&&(t.TANGENT=!0),t._needUVs?(t.UV1=e.isVerticesDataPresent(a.b.UVKind),t.UV2=e.isVerticesDataPresent(a.b.UV2Kind)):(t.UV1=!1,t.UV2=!1),i){var s=e.useVertexColors&&e.isVerticesDataPresent(a.b.ColorKind);t.VERTEXCOLOR=s,t.VERTEXALPHA=e.hasVertexAlpha&&s&&o}return n&&this.PrepareDefinesForBones(e,t),r&&this.PrepareDefinesForMorphTargets(e,t),!0},e.PrepareDefinesForMultiview=function(e,t){if(e.activeCamera){var i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}},e.PrepareDefinesForLight=function(e,t,i,n,r,o,a){switch(a.needNormals=!0,void 0===r["LIGHT"+n]&&(a.needRebuild=!0),r["LIGHT"+n]=!0,r["SPOTLIGHT"+n]=!1,r["HEMILIGHT"+n]=!1,r["POINTLIGHT"+n]=!1,r["DIRLIGHT"+n]=!1,i.prepareLightSpecificDefines(r,n),r["LIGHT_FALLOFF_PHYSICAL"+n]=!1,r["LIGHT_FALLOFF_GLTF"+n]=!1,r["LIGHT_FALLOFF_STANDARD"+n]=!1,i.falloffType){case s.a.FALLOFF_GLTF:r["LIGHT_FALLOFF_GLTF"+n]=!0;break;case s.a.FALLOFF_PHYSICAL:r["LIGHT_FALLOFF_PHYSICAL"+n]=!0;break;case s.a.FALLOFF_STANDARD:r["LIGHT_FALLOFF_STANDARD"+n]=!0}if(o&&!i.specular.equalsFloats(0,0,0)&&(a.specularEnabled=!0),r["SHADOW"+n]=!1,r["SHADOWCSM"+n]=!1,r["SHADOWCSMDEBUG"+n]=!1,r["SHADOWCSMNUM_CASCADES"+n]=!1,r["SHADOWCSMUSESHADOWMAXZ"+n]=!1,r["SHADOWCSMNOBLEND"+n]=!1,r["SHADOWCSM_RIGHTHANDED"+n]=!1,r["SHADOWPCF"+n]=!1,r["SHADOWPCSS"+n]=!1,r["SHADOWPOISSON"+n]=!1,r["SHADOWESM"+n]=!1,r["SHADOWCUBE"+n]=!1,r["SHADOWLOWQUALITY"+n]=!1,r["SHADOWMEDIUMQUALITY"+n]=!1,t&&t.receiveShadows&&e.shadowsEnabled&&i.shadowEnabled){var c=i.getShadowGenerator();if(c){var l=c.getShadowMap();l&&l.renderList&&l.renderList.length>0&&(a.shadowEnabled=!0,c.prepareDefines(r,n))}}i.lightmapMode!=s.a.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+n]=!0,r["LIGHTMAPNOSPECULAR"+n]=i.lightmapMode==s.a.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+n]=!1,r["LIGHTMAPNOSPECULAR"+n]=!1)},e.PrepareDefinesForLights=function(e,t,i,n,r,o){if(void 0===r&&(r=4),void 0===o&&(o=!1),!i._areLightsDirty)return i._needNormals;var a=0,s={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!o)for(var c=0,l=t.lightSources;c<l.length;c++){var u=l[c];if(this.PrepareDefinesForLight(e,t,u,a,i,n,s),++a===r)break}i.SPECULARTERM=s.specularEnabled,i.SHADOWS=s.shadowEnabled;for(var h=a;h<r;h++)void 0!==i["LIGHT"+h]&&(i["LIGHT"+h]=!1,i["HEMILIGHT"+h]=!1,i["POINTLIGHT"+h]=!1,i["DIRLIGHT"+h]=!1,i["SPOTLIGHT"+h]=!1,i["SHADOW"+h]=!1,i["SHADOWCSM"+h]=!1,i["SHADOWCSMDEBUG"+h]=!1,i["SHADOWCSMNUM_CASCADES"+h]=!1,i["SHADOWCSMUSESHADOWMAXZ"+h]=!1,i["SHADOWCSMNOBLEND"+h]=!1,i["SHADOWCSM_RIGHTHANDED"+h]=!1,i["SHADOWPCF"+h]=!1,i["SHADOWPCSS"+h]=!1,i["SHADOWPOISSON"+h]=!1,i["SHADOWESM"+h]=!1,i["SHADOWCUBE"+h]=!1,i["SHADOWLOWQUALITY"+h]=!1,i["SHADOWMEDIUMQUALITY"+h]=!1);var d=e.getEngine().getCaps();return void 0===i.SHADOWFLOAT&&(s.needRebuild=!0),i.SHADOWFLOAT=s.shadowEnabled&&(d.textureFloatRender&&d.textureFloatLinearFiltering||d.textureHalfFloatRender&&d.textureHalfFloatLinearFiltering),i.LIGHTMAPEXCLUDED=s.lightmapMode,s.needRebuild&&i.rebuild(),s.needNormals},e.PrepareUniformsAndSamplersForLight=function(e,t,i,n,r){void 0===r&&(r=null),t.push("vLightData"+e,"vLightDiffuse"+e,"vLightSpecular"+e,"vLightDirection"+e,"vLightFalloff"+e,"vLightGround"+e,"lightMatrix"+e,"shadowsInfo"+e,"depthValues"+e),r&&r.push("Light"+e),i.push("shadowSampler"+e),i.push("depthSampler"+e),t.push("viewFrustumZ"+e,"cascadeBlendFactor"+e,"lightSizeUVCorrection"+e,"depthCorrection"+e,"penumbraDarkness"+e,"frustumLengths"+e),n&&(i.push("projectionLightSampler"+e),t.push("textureProjectionMatrix"+e))},e.PrepareUniformsAndSamplersList=function(e,t,i,n){var r;void 0===n&&(n=4);var o=null;if(e.uniformsNames){var a=e;r=a.uniformsNames,o=a.uniformBuffersNames,t=a.samplers,i=a.defines,n=a.maxSimultaneousLights||0}else r=e,t||(t=[]);for(var s=0;s<n&&i["LIGHT"+s];s++)this.PrepareUniformsAndSamplersForLight(s,r,t,i["PROJECTEDLIGHTTEXTURE"+s],o);i.NUM_MORPH_INFLUENCERS&&r.push("morphTargetInfluences")},e.HandleFallbacksForShadows=function(e,t,i,n){void 0===i&&(i=4),void 0===n&&(n=0);for(var r=0,o=0;o<i&&e["LIGHT"+o];o++)o>0&&(r=n+o,t.addFallback(r,"LIGHT"+o)),e.SHADOWS||(e["SHADOW"+o]&&t.addFallback(n,"SHADOW"+o),e["SHADOWPCF"+o]&&t.addFallback(n,"SHADOWPCF"+o),e["SHADOWPCSS"+o]&&t.addFallback(n,"SHADOWPCSS"+o),e["SHADOWPOISSON"+o]&&t.addFallback(n,"SHADOWPOISSON"+o),e["SHADOWESM"+o]&&t.addFallback(n,"SHADOWESM"+o));return r++},e.PrepareAttributesForMorphTargetsInfluencers=function(e,t,i){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=i,this.PrepareAttributesForMorphTargets(e,t,this._TmpMorphInfluencers)},e.PrepareAttributesForMorphTargets=function(e,t,i){var r=i.NUM_MORPH_INFLUENCERS;if(r>0&&o.a.LastCreatedEngine)for(var s=o.a.LastCreatedEngine.getCaps().maxVertexAttribs,c=t.morphTargetManager,l=c&&c.supportsNormals&&i.NORMAL,u=c&&c.supportsTangents&&i.TANGENT,h=c&&c.supportsUVs&&i.UV1,d=0;d<r;d++)e.push(a.b.PositionKind+d),l&&e.push(a.b.NormalKind+d),u&&e.push(a.b.TangentKind+d),h&&e.push(a.b.UVKind+"_"+d),e.length>s&&n.a.Error("Cannot add more vertex attributes for mesh "+t.name)},e.PrepareAttributesForBones=function(e,t,i,n){i.NUM_BONE_INFLUENCERS>0&&(n.addCPUSkinningFallback(0,t),e.push(a.b.MatricesIndicesKind),e.push(a.b.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(a.b.MatricesIndicesExtraKind),e.push(a.b.MatricesWeightsExtraKind)))},e.PrepareAttributesForInstances=function(e,t){t.INSTANCES&&this.PushAttributesForInstances(e)},e.PushAttributesForInstances=function(e){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3")},e.BindLightProperties=function(e,t,i){e.transferToEffect(t,i+"")},e.BindLight=function(e,t,i,n,r,o){void 0===o&&(o=!1),e._bindLight(t,i,n,r,o)},e.BindLights=function(e,t,i,n,r,o){void 0===r&&(r=4),void 0===o&&(o=!1);for(var a=Math.min(t.lightSources.length,r),s=0;s<a;s++){var c=t.lightSources[s];this.BindLight(c,s,e,i,"boolean"==typeof n?n:n.SPECULARTERM,o)}},e.BindFogParameters=function(e,t,i,n){void 0===n&&(n=!1),e.fogEnabled&&t.applyFog&&e.fogMode!==r.a.FOGMODE_NONE&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),n?(e.fogColor.toLinearSpaceToRef(this._tempFogColor),i.setColor3("vFogColor",this._tempFogColor)):i.setColor3("vFogColor",e.fogColor))},e.BindBonesParameters=function(e,t){if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){var i=e.skeleton;if(i.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){var n=i.getTransformMatrixTexture(e);t.setTexture("boneSampler",n),t.setFloat("boneTextureWidth",4*(i.bones.length+1))}else{var r=i.getTransformMatrices(e);r&&t.setMatrices("mBones",r)}}},e.BindMorphTargetParameters=function(e,t){var i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)},e.BindLogDepth=function(e,t,i){e.LOGARITHMICDEPTH&&t.setFloat("logarithmicDepthConstant",2/(Math.log(i.activeCamera.maxZ+1)/Math.LN2))},e.BindClipPlane=function(e,t){if(t.clipPlane){var i=t.clipPlane;e.setFloat4("vClipPlane",i.normal.x,i.normal.y,i.normal.z,i.d)}if(t.clipPlane2){i=t.clipPlane2;e.setFloat4("vClipPlane2",i.normal.x,i.normal.y,i.normal.z,i.d)}if(t.clipPlane3){i=t.clipPlane3;e.setFloat4("vClipPlane3",i.normal.x,i.normal.y,i.normal.z,i.d)}if(t.clipPlane4){i=t.clipPlane4;e.setFloat4("vClipPlane4",i.normal.x,i.normal.y,i.normal.z,i.d)}if(t.clipPlane5){i=t.clipPlane5;e.setFloat4("vClipPlane5",i.normal.x,i.normal.y,i.normal.z,i.d)}if(t.clipPlane6){i=t.clipPlane6;e.setFloat4("vClipPlane6",i.normal.x,i.normal.y,i.normal.z,i.d)}},e._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},e._tempFogColor=c.a.Black(),e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r}),i.d(t,"b",function(){return o});var n=i(1),r=function(){function e(){}return e.NAME_EFFECTLAYER="EffectLayer",e.NAME_LAYER="Layer",e.NAME_LENSFLARESYSTEM="LensFlareSystem",e.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",e.NAME_PARTICLESYSTEM="ParticleSystem",e.NAME_GAMEPAD="Gamepad",e.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",e.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",e.NAME_DEPTHRENDERER="DepthRenderer",e.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",e.NAME_SPRITE="Sprite",e.NAME_OUTLINERENDERER="Outline",e.NAME_PROCEDURALTEXTURE="ProceduralTexture",e.NAME_SHADOWGENERATOR="ShadowGenerator",e.NAME_OCTREE="Octree",e.NAME_PHYSICSENGINE="PhysicsEngine",e.NAME_AUDIO="Audio",e.STEP_ISREADYFORMESH_EFFECTLAYER=0,e.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,e.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,e.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER=0,e.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,e.STEP_BEFORECAMERADRAW_EFFECTLAYER=0,e.STEP_BEFORECAMERADRAW_LAYER=1,e.STEP_BEFORERENDERTARGETDRAW_LAYER=0,e.STEP_BEFORERENDERINGMESH_OUTLINE=0,e.STEP_AFTERRENDERINGMESH_OUTLINE=0,e.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,e.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,e.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,e.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,e.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,e.STEP_AFTERRENDERTARGETDRAW_LAYER=0,e.STEP_AFTERCAMERADRAW_EFFECTLAYER=0,e.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=1,e.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=2,e.STEP_AFTERCAMERADRAW_LAYER=3,e.STEP_AFTERRENDER_AUDIO=0,e.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,e.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,e.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,e.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,e.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,e.STEP_POINTERMOVE_SPRITE=0,e.STEP_POINTERDOWN_SPRITE=0,e.STEP_POINTERUP_SPRITE=0,e}(),o=function(e){function t(t){return e.apply(this,t)||this}return Object(n.d)(t,e),t.Create=function(){return Object.create(t.prototype)},t.prototype.registerStep=function(e,t,i){var n=0;for(Number.MAX_VALUE;n<this.length;n++){if(e<this[n].index)break}this.splice(n,0,{index:e,component:t,action:i.bind(t)})},t.prototype.clear=function(){this.length=0},t}(Array)},function(e,t,i){"use strict";var n=i(1),r=i(13),o=i(52),a=i(6),s=i(34),c=i(103),l=i(35),u=i(0),h=i(43),d=i(27),f=i(24),p=i(37),_=i(40),m=i(83),g=i(50),v=i(53),y=i(45),b=i(90),T=i(91),E=i(17),x=i(2),P=i(38),A=i(7),S=i(23),C=i(19),R=i(20),O=i(87),M=i(63),I=function(){function e(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}return Object.defineProperty(e.prototype,"singleClick",{get:function(){return this._singleClick},set:function(e){this._singleClick=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"doubleClick",{get:function(){return this._doubleClick},set:function(e){this._doubleClick=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasSwiped",{get:function(){return this._hasSwiped},set:function(e){this._hasSwiped=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"ignore",{get:function(){return this._ignore},set:function(e){this._ignore=e},enumerable:!0,configurable:!0}),e}(),D=function(){function e(e){this._wheelEventName="",this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._totalPointersPressed=0,this._doubleClickOccured=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new u.d(0,0),this._previousStartingPointerPosition=new u.d(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._scene=e}return Object.defineProperty(e.prototype,"meshUnderPointer",{get:function(){return this._pointerOverMesh},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"unTranslatedPointer",{get:function(){return new u.d(this._unTranslatedPointerX,this._unTranslatedPointerY)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"pointerX",{get:function(){return this._pointerX},set:function(e){this._pointerX=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"pointerY",{get:function(){return this._pointerY},set:function(e){this._pointerY=e},enumerable:!0,configurable:!0}),e.prototype._updatePointerPosition=function(e){var 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)},e.prototype._processPointerMove=function(e,t){var i=this._scene,n=i.getEngine(),r=n.getInputElement();if(r){r.tabIndex=n.canvasTabIndex,i.doNotHandleCursors||(r.style.cursor=i.defaultCursor);var o=!!(e&&e.hit&&e.pickedMesh);o?(i.setPointerOverMesh(e.pickedMesh),this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.hasPointerTriggers&&(i.doNotHandleCursors||(this._pointerOverMesh.actionManager.hoverCursor?r.style.cursor=this._pointerOverMesh.actionManager.hoverCursor:r.style.cursor=i.hoverCursor))):i.setPointerOverMesh(null);for(var a=0,s=i._pointerMoveStage;a<s.length;a++){e=s[a].action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,o,r)}if(e){var c=t.type===this._wheelEventName?R.a.POINTERWHEEL:R.a.POINTERMOVE;if(i.onPointerMove&&i.onPointerMove(t,e,c),i.onPointerObservable.hasObservers()){var l=new R.b(c,t,e);this._setRayOnPointerInfo(l),i.onPointerObservable.notifyObservers(l,c)}}}},e.prototype._setRayOnPointerInfo=function(e){var t=this._scene;e.pickInfo&&!e.pickInfo._pickingUnavailable&&(e.pickInfo.ray||(e.pickInfo.ray=t.createPickingRay(e.event.offsetX,e.event.offsetY,u.a.Identity(),t.activeCamera)))},e.prototype._checkPrePointerObservable=function(e,t,i){var n=this._scene,r=new R.d(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.ray=e.ray),n.onPrePointerObservable.notifyObservers(r,i),!!r.skipOnPointerObservable},e.prototype.simulatePointerMove=function(e,t){var i=new PointerEvent("pointermove",t);this._checkPrePointerObservable(e,i,R.a.POINTERMOVE)||this._processPointerMove(e,i)},e.prototype.simulatePointerDown=function(e,t){var i=new PointerEvent("pointerdown",t);this._checkPrePointerObservable(e,i,R.a.POINTERDOWN)||this._processPointerDown(e,i)},e.prototype._processPointerDown=function(t,i){var n=this,r=this._scene;if(t&&t.hit&&t.pickedMesh){this._pickedDownMesh=t.pickedMesh;var o=t.pickedMesh._getActionManagerForTrigger();if(o){if(o.hasPickTriggers)switch(o.processTrigger(x.a.ACTION_OnPickDownTrigger,y.a.CreateNew(t.pickedMesh,i)),i.button){case 0:o.processTrigger(x.a.ACTION_OnLeftPickTrigger,y.a.CreateNew(t.pickedMesh,i));break;case 1:o.processTrigger(x.a.ACTION_OnCenterPickTrigger,y.a.CreateNew(t.pickedMesh,i));break;case 2:o.processTrigger(x.a.ACTION_OnRightPickTrigger,y.a.CreateNew(t.pickedMesh,i))}o.hasSpecificTrigger(x.a.ACTION_OnLongPressTrigger)&&window.setTimeout(function(){var t=r.pick(n._unTranslatedPointerX,n._unTranslatedPointerY,function(e){return e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(x.a.ACTION_OnLongPressTrigger)&&e==n._pickedDownMesh},!1,r.cameraToUseForPointers);t&&t.hit&&t.pickedMesh&&o&&0!==n._totalPointersPressed&&Date.now()-n._startingPointerTime>e.LongPressDelay&&!n._isPointerSwiping()&&(n._startingPointerTime=0,o.processTrigger(x.a.ACTION_OnLongPressTrigger,y.a.CreateNew(t.pickedMesh,i)))},e.LongPressDelay)}}else for(var a=0,s=r._pointerDownStage;a<s.length;a++){t=s[a].action(this._unTranslatedPointerX,this._unTranslatedPointerY,t,i)}if(t){var c=R.a.POINTERDOWN;if(r.onPointerDown&&r.onPointerDown(i,t,c),r.onPointerObservable.hasObservers()){var l=new R.b(c,i,t);this._setRayOnPointerInfo(l),r.onPointerObservable.notifyObservers(l,c)}}},e.prototype._isPointerSwiping=function(){return Math.abs(this._startingPointerPosition.x-this._pointerX)>e.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>e.DragMovementThreshold},e.prototype.simulatePointerUp=function(e,t,i){var n=new PointerEvent("pointerup",t),r=new I;i?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,n,R.a.POINTERUP)||this._processPointerUp(e,n,r)},e.prototype._processPointerUp=function(e,t,i){var n=this._scene;if(e&&e&&e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(n.onPointerPick&&n.onPointerPick(t,e),i.singleClick&&!i.ignore&&n.onPointerObservable.hasObservers())){var r=R.a.POINTERPICK,o=new R.b(r,t,e);this._setRayOnPointerInfo(o),n.onPointerObservable.notifyObservers(o,r)}var a=e.pickedMesh._getActionManagerForTrigger();if(a&&!i.ignore){a.processTrigger(x.a.ACTION_OnPickUpTrigger,y.a.CreateNew(e.pickedMesh,t)),!i.hasSwiped&&i.singleClick&&a.processTrigger(x.a.ACTION_OnPickTrigger,y.a.CreateNew(e.pickedMesh,t));var s=e.pickedMesh._getActionManagerForTrigger(x.a.ACTION_OnDoublePickTrigger);i.doubleClick&&s&&s.processTrigger(x.a.ACTION_OnDoublePickTrigger,y.a.CreateNew(e.pickedMesh,t))}}else if(!i.ignore)for(var c=0,l=n._pointerUpStage;c<l.length;c++){e=l[c].action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t)}if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){var u=this._pickedDownMesh._getActionManagerForTrigger(x.a.ACTION_OnPickOutTrigger);u&&u.processTrigger(x.a.ACTION_OnPickOutTrigger,y.a.CreateNew(this._pickedDownMesh,t))}var h=0;if(n.onPointerObservable.hasObservers()){if(!i.ignore&&!i.hasSwiped&&(i.singleClick&&n.onPointerObservable.hasSpecificMask(R.a.POINTERTAP)?h=R.a.POINTERTAP:i.doubleClick&&n.onPointerObservable.hasSpecificMask(R.a.POINTERDOUBLETAP)&&(h=R.a.POINTERDOUBLETAP),h)){o=new R.b(h,t,e);this._setRayOnPointerInfo(o),n.onPointerObservable.notifyObservers(o,h)}if(!i.ignore){h=R.a.POINTERUP;o=new R.b(h,t,e);this._setRayOnPointerInfo(o),n.onPointerObservable.notifyObservers(o,h)}}n.onPointerUp&&!i.ignore&&n.onPointerUp(t,e,h)},e.prototype.isPointerCaptured=function(e){return void 0===e&&(e=0),this._pointerCaptures[e]},e.prototype.attachControl=function(t,i,n,o){var a=this;void 0===t&&(t=!0),void 0===i&&(i=!0),void 0===n&&(n=!0),void 0===o&&(o=null);var s=this._scene;if(o||(o=s.getEngine().getInputElement()),o){var c,l=s.getEngine();this._initActionManager=function(e,t){if(!a._meshPickProceed){var i=s.pick(a._unTranslatedPointerX,a._unTranslatedPointerY,s.pointerDownPredicate,!1,s.cameraToUseForPointers);a._currentPickResult=i,i&&(e=i.hit&&i.pickedMesh?i.pickedMesh._getActionManagerForTrigger():null),a._meshPickProceed=!0}return e},this._delayedSimpleClick=function(t,i,n){(Date.now()-a._previousStartingPointerTime>e.DoubleClickDelay&&!a._doubleClickOccured||t!==a._previousButtonPressed)&&(a._doubleClickOccured=!1,i.singleClick=!0,i.ignore=!1,n(i,a._currentPickResult))},this._initClickEvent=function(t,i,n,r){var o=new I;a._currentPickResult=null;var s=null,c=t.hasSpecificMask(R.a.POINTERPICK)||i.hasSpecificMask(R.a.POINTERPICK)||t.hasSpecificMask(R.a.POINTERTAP)||i.hasSpecificMask(R.a.POINTERTAP)||t.hasSpecificMask(R.a.POINTERDOUBLETAP)||i.hasSpecificMask(R.a.POINTERDOUBLETAP);!c&&O.a&&(s=a._initActionManager(s,o))&&(c=s.hasPickTriggers);var l=!1;if(c){var u=n.button;if(o.hasSwiped=a._isPointerSwiping(),!o.hasSwiped){var h=!e.ExclusiveDoubleClickMode;h||(h=!t.hasSpecificMask(R.a.POINTERDOUBLETAP)&&!i.hasSpecificMask(R.a.POINTERDOUBLETAP))&&!O.a.HasSpecificTrigger(x.a.ACTION_OnDoublePickTrigger)&&(s=a._initActionManager(s,o))&&(h=!s.hasSpecificTrigger(x.a.ACTION_OnDoublePickTrigger)),h?(Date.now()-a._previousStartingPointerTime>e.DoubleClickDelay||u!==a._previousButtonPressed)&&(o.singleClick=!0,r(o,a._currentPickResult),l=!0):(a._previousDelayedSimpleClickTimeout=a._delayedSimpleClickTimeout,a._delayedSimpleClickTimeout=window.setTimeout(a._delayedSimpleClick.bind(a,u,o,r),e.DoubleClickDelay));var d=t.hasSpecificMask(R.a.POINTERDOUBLETAP)||i.hasSpecificMask(R.a.POINTERDOUBLETAP);!d&&O.a.HasSpecificTrigger(x.a.ACTION_OnDoublePickTrigger)&&(s=a._initActionManager(s,o))&&(d=s.hasSpecificTrigger(x.a.ACTION_OnDoublePickTrigger)),d&&(u===a._previousButtonPressed&&Date.now()-a._previousStartingPointerTime<e.DoubleClickDelay&&!a._doubleClickOccured?(o.hasSwiped||a._isPointerSwiping()?(a._doubleClickOccured=!1,a._previousStartingPointerTime=a._startingPointerTime,a._previousStartingPointerPosition.x=a._startingPointerPosition.x,a._previousStartingPointerPosition.y=a._startingPointerPosition.y,a._previousButtonPressed=u,e.ExclusiveDoubleClickMode?(a._previousDelayedSimpleClickTimeout&&clearTimeout(a._previousDelayedSimpleClickTimeout),a._previousDelayedSimpleClickTimeout=a._delayedSimpleClickTimeout,r(o,a._previousPickResult)):r(o,a._currentPickResult)):(a._previousStartingPointerTime=0,a._doubleClickOccured=!0,o.doubleClick=!0,o.ignore=!1,e.ExclusiveDoubleClickMode&&a._previousDelayedSimpleClickTimeout&&clearTimeout(a._previousDelayedSimpleClickTimeout),a._previousDelayedSimpleClickTimeout=a._delayedSimpleClickTimeout,r(o,a._currentPickResult)),l=!0):(a._doubleClickOccured=!1,a._previousStartingPointerTime=a._startingPointerTime,a._previousStartingPointerPosition.x=a._startingPointerPosition.x,a._previousStartingPointerPosition.y=a._startingPointerPosition.y,a._previousButtonPressed=u))}}l||r(o,a._currentPickResult)},this._onPointerMove=function(e){if(a._updatePointerPosition(e),!a._checkPrePointerObservable(null,e,e.type===a._wheelEventName?R.a.POINTERWHEEL:R.a.POINTERMOVE)&&(s.cameraToUseForPointers||s.activeCamera)){s.pointerMovePredicate||(s.pointerMovePredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||s.constantlyUpdateMeshUnderPointer||null!=e._getActionManagerForTrigger())&&(!s.cameraToUseForPointers||0!=(s.cameraToUseForPointers.layerMask&e.layerMask))});var t=s.pick(a._unTranslatedPointerX,a._unTranslatedPointerY,s.pointerMovePredicate,!1,s.cameraToUseForPointers);a._processPointerMove(t,e)}},this._onPointerDown=function(e){if(a._totalPointersPressed++,a._pickedDownMesh=null,a._meshPickProceed=!1,a._updatePointerPosition(e),s.preventDefaultOnPointerDown&&o&&(e.preventDefault(),o.focus()),a._startingPointerPosition.x=a._pointerX,a._startingPointerPosition.y=a._pointerY,a._startingPointerTime=Date.now(),!a._checkPrePointerObservable(null,e,R.a.POINTERDOWN)&&(s.cameraToUseForPointers||s.activeCamera)){a._pointerCaptures[e.pointerId]=!0,s.pointerDownPredicate||(s.pointerDownPredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||0!=(s.cameraToUseForPointers.layerMask&e.layerMask))}),a._pickedDownMesh=null;var t=s.pick(a._unTranslatedPointerX,a._unTranslatedPointerY,s.pointerDownPredicate,!1,s.cameraToUseForPointers);a._processPointerDown(t,e)}},this._onPointerUp=function(e){0!==a._totalPointersPressed&&(a._totalPointersPressed--,a._pickedUpMesh=null,a._meshPickProceed=!1,a._updatePointerPosition(e),s.preventDefaultOnPointerUp&&o&&(e.preventDefault(),o.focus()),a._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,e,function(t,i){if(s.onPrePointerObservable.hasObservers()&&!t.ignore){if(!t.hasSwiped){if(t.singleClick&&s.onPrePointerObservable.hasSpecificMask(R.a.POINTERTAP)&&a._checkPrePointerObservable(null,e,R.a.POINTERTAP))return;if(t.doubleClick&&s.onPrePointerObservable.hasSpecificMask(R.a.POINTERDOUBLETAP)&&a._checkPrePointerObservable(null,e,R.a.POINTERDOUBLETAP))return}if(a._checkPrePointerObservable(null,e,R.a.POINTERUP))return}a._pointerCaptures[e.pointerId]&&(a._pointerCaptures[e.pointerId]=!1,(s.cameraToUseForPointers||s.activeCamera)&&(s.pointerUpPredicate||(s.pointerUpPredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||0!=(s.cameraToUseForPointers.layerMask&e.layerMask))}),!a._meshPickProceed&&(O.a&&O.a.HasTriggers||s.onPointerObservable.hasObservers())&&a._initActionManager(null,t),i||(i=a._currentPickResult),a._processPointerUp(i,e,t),a._previousPickResult=a._currentPickResult))}))},this._onKeyDown=function(e){var t=M.a.KEYDOWN;if(s.onPreKeyboardObservable.hasObservers()){var i=new M.c(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnPointerObservable)return}if(s.onKeyboardObservable.hasObservers()){i=new M.b(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(x.a.ACTION_OnKeyDownTrigger,y.a.CreateNewFromScene(s,e))},this._onKeyUp=function(e){var t=M.a.KEYUP;if(s.onPreKeyboardObservable.hasObservers()){var i=new M.c(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnPointerObservable)return}if(s.onKeyboardObservable.hasObservers()){i=new M.b(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(x.a.ACTION_OnKeyUpTrigger,y.a.CreateNewFromScene(s,e))},this._onCanvasFocusObserver=l.onCanvasFocusObservable.add((c=function(){o&&(o.addEventListener("keydown",a._onKeyDown,!1),o.addEventListener("keyup",a._onKeyUp,!1))},document.activeElement===o&&c(),c)),this._onCanvasBlurObserver=l.onCanvasBlurObservable.add(function(){o&&(o.removeEventListener("keydown",a._onKeyDown),o.removeEventListener("keyup",a._onKeyUp))});var u=r.b.GetPointerPrefix();if(n&&(o.addEventListener(u+"move",this._onPointerMove,!1),this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll",o.addEventListener(this._wheelEventName,this._onPointerMove,!1)),i&&o.addEventListener(u+"down",this._onPointerDown,!1),t){var h=s.getEngine().getHostWindow();h&&h.addEventListener(u+"up",this._onPointerUp,!1)}}},e.prototype.detachControl=function(){var e=r.b.GetPointerPrefix(),t=this._scene.getEngine().getInputElement(),i=this._scene.getEngine();t&&(t.removeEventListener(e+"move",this._onPointerMove),t.removeEventListener(this._wheelEventName,this._onPointerMove),t.removeEventListener(e+"down",this._onPointerDown),window.removeEventListener(e+"up",this._onPointerUp),this._onCanvasBlurObserver&&i.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onCanvasFocusObserver&&i.onCanvasFocusObservable.remove(this._onCanvasFocusObserver),t.removeEventListener("keydown",this._onKeyDown),t.removeEventListener("keyup",this._onKeyUp),this._scene.doNotHandleCursors||(t.style.cursor=this._scene.defaultCursor))},e.prototype.setPointerOverMesh=function(e){var t;this._pointerOverMesh!==e&&(this._pointerOverMesh&&(t=this._pointerOverMesh._getActionManagerForTrigger(x.a.ACTION_OnPointerOutTrigger))&&t.processTrigger(x.a.ACTION_OnPointerOutTrigger,y.a.CreateNew(this._pointerOverMesh)),this._pointerOverMesh=e,this._pointerOverMesh&&(t=this._pointerOverMesh._getActionManagerForTrigger(x.a.ACTION_OnPointerOverTrigger))&&t.processTrigger(x.a.ACTION_OnPointerOverTrigger,y.a.CreateNew(this._pointerOverMesh)))},e.prototype.getPointerOverMesh=function(){return this._pointerOverMesh},e.DragMovementThreshold=10,e.LongPressDelay=500,e.DoubleClickDelay=300,e.ExclusiveDoubleClickMode=!1,e}(),w=i(51),L=i(10),N=i(86),F=i(138),B=i(54);i.d(t,"a",function(){return U});var U=function(e){function t(i,r){var o=e.call(this)||this;o._inputManager=new D(o),o.cameraToUseForPointers=null,o._isScene=!0,o._blockEntityCollection=!1,o.autoClear=!0,o.autoClearDepthAndStencil=!0,o.clearColor=new L.b(.2,.2,.3,1),o.ambientColor=new L.a(0,0,0),o._environmentIntensity=1,o._forceWireframe=!1,o._skipFrustumClipping=!1,o._forcePointsCloud=!1,o.animationsEnabled=!0,o._animationPropertiesOverride=null,o.useConstantAnimationDeltaTime=!1,o.constantlyUpdateMeshUnderPointer=!1,o.hoverCursor="pointer",o.defaultCursor="",o.doNotHandleCursors=!1,o.preventDefaultOnPointerDown=!0,o.preventDefaultOnPointerUp=!0,o.metadata=null,o.reservedDataStore=null,o.disableOfflineSupportExceptionRules=new Array,o.onDisposeObservable=new a.c,o._onDisposeObserver=null,o.onBeforeRenderObservable=new a.c,o._onBeforeRenderObserver=null,o.onAfterRenderObservable=new a.c,o.onAfterRenderCameraObservable=new a.c,o._onAfterRenderObserver=null,o.onBeforeAnimationsObservable=new a.c,o.onAfterAnimationsObservable=new a.c,o.onBeforeDrawPhaseObservable=new a.c,o.onAfterDrawPhaseObservable=new a.c,o.onReadyObservable=new a.c,o.onBeforeCameraRenderObservable=new a.c,o._onBeforeCameraRenderObserver=null,o.onAfterCameraRenderObservable=new a.c,o._onAfterCameraRenderObserver=null,o.onBeforeActiveMeshesEvaluationObservable=new a.c,o.onAfterActiveMeshesEvaluationObservable=new a.c,o.onBeforeParticlesRenderingObservable=new a.c,o.onAfterParticlesRenderingObservable=new a.c,o.onDataLoadedObservable=new a.c,o.onNewCameraAddedObservable=new a.c,o.onCameraRemovedObservable=new a.c,o.onNewLightAddedObservable=new a.c,o.onLightRemovedObservable=new a.c,o.onNewGeometryAddedObservable=new a.c,o.onGeometryRemovedObservable=new a.c,o.onNewTransformNodeAddedObservable=new a.c,o.onTransformNodeRemovedObservable=new a.c,o.onNewMeshAddedObservable=new a.c,o.onMeshRemovedObservable=new a.c,o.onNewSkeletonAddedObservable=new a.c,o.onSkeletonRemovedObservable=new a.c,o.onNewMaterialAddedObservable=new a.c,o.onMaterialRemovedObservable=new a.c,o.onNewTextureAddedObservable=new a.c,o.onTextureRemovedObservable=new a.c,o.onBeforeRenderTargetsRenderObservable=new a.c,o.onAfterRenderTargetsRenderObservable=new a.c,o.onBeforeStepObservable=new a.c,o.onAfterStepObservable=new a.c,o.onActiveCameraChanged=new a.c,o.onBeforeRenderingGroupObservable=new a.c,o.onAfterRenderingGroupObservable=new a.c,o.onMeshImportedObservable=new a.c,o.onAnimationFileImportedObservable=new a.c,o._registeredForLateAnimationBindings=new s.b(256),o.onPrePointerObservable=new a.c,o.onPointerObservable=new a.c,o.onPreKeyboardObservable=new a.c,o.onKeyboardObservable=new a.c,o._useRightHandedSystem=!1,o._timeAccumulator=0,o._currentStepId=0,o._currentInternalStep=0,o._fogEnabled=!0,o._fogMode=t.FOGMODE_NONE,o.fogColor=new L.a(.2,.2,.3),o.fogDensity=.1,o.fogStart=0,o.fogEnd=1e3,o._shadowsEnabled=!0,o._lightsEnabled=!0,o.activeCameras=new Array,o._texturesEnabled=!0,o.particlesEnabled=!0,o.spritesEnabled=!0,o._skeletonsEnabled=!0,o.lensFlaresEnabled=!0,o.collisionsEnabled=!0,o.gravity=new u.e(0,-9.807,0),o.postProcessesEnabled=!0,o.postProcesses=new Array,o.renderTargetsEnabled=!0,o.dumpNextRenderTargets=!1,o.customRenderTargets=new Array,o.importedMeshesFiles=new Array,o.probesEnabled=!0,o._meshesForIntersections=new s.b(256),o.proceduralTexturesEnabled=!0,o._totalVertices=new w.a,o._activeIndices=new w.a,o._activeParticles=new w.a,o._activeBones=new w.a,o._animationTime=0,o.animationTimeScale=1,o._renderId=0,o._frameId=0,o._executeWhenReadyTimeoutId=-1,o._intermediateRendering=!1,o._viewUpdateFlag=-1,o._projectionUpdateFlag=-1,o._toBeDisposed=new Array(256),o._activeRequests=new Array,o._pendingData=new Array,o._isDisposed=!1,o.dispatchAllSubMeshesOfActiveMeshes=!1,o._activeMeshes=new s.a(256),o._processedMaterials=new s.a(256),o._renderTargets=new s.b(256),o._activeParticleSystems=new s.a(256),o._activeSkeletons=new s.b(32),o._softwareSkinnedMeshes=new s.b(32),o._activeAnimatables=new Array,o._transformMatrix=u.a.Zero(),o.requireLightSorting=!1,o._components=[],o._serializableComponents=[],o._transientComponents=[],o._beforeCameraUpdateStage=E.b.Create(),o._beforeClearStage=E.b.Create(),o._gatherRenderTargetsStage=E.b.Create(),o._gatherActiveCameraRenderTargetsStage=E.b.Create(),o._isReadyForMeshStage=E.b.Create(),o._beforeEvaluateActiveMeshStage=E.b.Create(),o._evaluateSubMeshStage=E.b.Create(),o._activeMeshStage=E.b.Create(),o._cameraDrawRenderTargetStage=E.b.Create(),o._beforeCameraDrawStage=E.b.Create(),o._beforeRenderTargetDrawStage=E.b.Create(),o._beforeRenderingGroupDrawStage=E.b.Create(),o._beforeRenderingMeshStage=E.b.Create(),o._afterRenderingMeshStage=E.b.Create(),o._afterRenderingGroupDrawStage=E.b.Create(),o._afterCameraDrawStage=E.b.Create(),o._afterRenderTargetDrawStage=E.b.Create(),o._afterRenderStage=E.b.Create(),o._pointerMoveStage=E.b.Create(),o._pointerDownStage=E.b.Create(),o._pointerUpStage=E.b.Create(),o.geometriesByUniqueId=null,o._defaultMeshCandidates={data:[],length:0},o._defaultSubMeshCandidates={data:[],length:0},o._preventFreeActiveMeshesAndRenderingGroups=!1,o._activeMeshesFrozen=!1,o._skipEvaluateActiveMeshesCompletely=!1,o._allowPostProcessClearColor=!0,o.getDeterministicFrameTime=function(){return o._engine.getTimeStep()},o._blockMaterialDirtyMechanism=!1;var c=Object(n.a)({useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1},r);return o._engine=i||S.a.LastCreatedEngine,c.virtual||(S.a._LastCreatedScene=o,o._engine.scenes.push(o)),o._uid=null,o._renderingManager=new T.b(o),b.a&&(o.postProcessManager=new b.a(o)),P.a.IsWindowObjectExist()&&o.attachControl(),o._createUbo(),_.a&&(o._imageProcessingConfiguration=new _.a),o.setDefaultCandidateProviders(),c.useGeometryUniqueIdsMap&&(o.geometriesByUniqueId={}),o.useMaterialMeshMap=c.useMaterialMeshMap,o.useClonedMeshMap=c.useClonedMeshMap,r&&r.virtual||o._engine.onNewSceneAddedObservable.notifyObservers(o),o}return Object(n.d)(t,e),t.DefaultMaterialFactory=function(e){throw C.a.WarnImport("StandardMaterial")},t.CollisionCoordinatorFactory=function(){throw C.a.WarnImport("DefaultCollisionCoordinator")},Object.defineProperty(t.prototype,"environmentTexture",{get:function(){return this._environmentTexture},set:function(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(x.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"environmentIntensity",{get:function(){return this._environmentIntensity},set:function(e){this._environmentIntensity!==e&&(this._environmentIntensity=e,this.markAllMaterialsAsDirty(x.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"forceWireframe",{get:function(){return this._forceWireframe},set:function(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(x.a.MATERIAL_MiscDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skipFrustumClipping",{get:function(){return this._skipFrustumClipping},set:function(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"forcePointsCloud",{get:function(){return this._forcePointsCloud},set:function(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(x.a.MATERIAL_MiscDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"beforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"afterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"beforeCameraRender",{set:function(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"afterCameraRender",{set:function(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"unTranslatedPointer",{get:function(){return this._inputManager.unTranslatedPointer},enumerable:!0,configurable:!0}),Object.defineProperty(t,"DragMovementThreshold",{get:function(){return D.DragMovementThreshold},set:function(e){D.DragMovementThreshold=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"LongPressDelay",{get:function(){return D.LongPressDelay},set:function(e){D.LongPressDelay=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"DoubleClickDelay",{get:function(){return D.DoubleClickDelay},set:function(e){D.DoubleClickDelay=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ExclusiveDoubleClickMode",{get:function(){return D.ExclusiveDoubleClickMode},set:function(e){D.ExclusiveDoubleClickMode=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useRightHandedSystem",{get:function(){return this._useRightHandedSystem},set:function(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(x.a.MATERIAL_MiscDirtyFlag))},enumerable:!0,configurable:!0}),t.prototype.setStepId=function(e){this._currentStepId=e},t.prototype.getStepId=function(){return this._currentStepId},t.prototype.getInternalStep=function(){return this._currentInternalStep},Object.defineProperty(t.prototype,"fogEnabled",{get:function(){return this._fogEnabled},set:function(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(x.a.MATERIAL_MiscDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fogMode",{get:function(){return this._fogMode},set:function(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(x.a.MATERIAL_MiscDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsEnabled",{get:function(){return this._shadowsEnabled},set:function(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(x.a.MATERIAL_LightDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"lightsEnabled",{get:function(){return this._lightsEnabled},set:function(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(x.a.MATERIAL_LightDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activeCamera",{get:function(){return this._activeCamera},set:function(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"defaultMaterial",{get:function(){return this._defaultMaterial||(this._defaultMaterial=t.DefaultMaterialFactory(this)),this._defaultMaterial},set:function(e){this._defaultMaterial=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"texturesEnabled",{get:function(){return this._texturesEnabled},set:function(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(x.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skeletonsEnabled",{get:function(){return this._skeletonsEnabled},set:function(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(x.a.MATERIAL_AttributesDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"collisionCoordinator",{get:function(){return this._collisionCoordinator||(this._collisionCoordinator=t.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"frustumPlanes",{get:function(){return this._frustumPlanes},enumerable:!0,configurable:!0}),t.prototype._registerTransientComponents=function(){if(this._transientComponents.length>0){for(var e=0,t=this._transientComponents;e<t.length;e++){t[e].register()}this._transientComponents=[]}},t.prototype._addComponent=function(e){this._components.push(e),this._transientComponents.push(e);var t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)},t.prototype._getComponent=function(e){for(var t=0,i=this._components;t<i.length;t++){var n=i[t];if(n.name===e)return n}return null},t.prototype.getClassName=function(){return"Scene"},t.prototype._getDefaultMeshCandidates=function(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates},t.prototype._getDefaultSubMeshCandidates=function(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates},t.prototype.setDefaultCandidateProviders=function(){this.getActiveMeshCandidates=this._getDefaultMeshCandidates.bind(this),this.getActiveSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this),this.getIntersectingSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this),this.getCollidingSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this)},Object.defineProperty(t.prototype,"meshUnderPointer",{get:function(){return this._inputManager.meshUnderPointer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pointerX",{get:function(){return this._inputManager.pointerX},set:function(e){this._inputManager.pointerX=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pointerY",{get:function(){return this._inputManager.pointerY},set:function(e){this._inputManager.pointerY=e},enumerable:!0,configurable:!0}),t.prototype.getCachedMaterial=function(){return this._cachedMaterial},t.prototype.getCachedEffect=function(){return this._cachedEffect},t.prototype.getCachedVisibility=function(){return this._cachedVisibility},t.prototype.isCachedMaterialInvalid=function(e,t,i){return void 0===i&&(i=1),this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i},t.prototype.getEngine=function(){return this._engine},t.prototype.getTotalVertices=function(){return this._totalVertices.current},Object.defineProperty(t.prototype,"totalVerticesPerfCounter",{get:function(){return this._totalVertices},enumerable:!0,configurable:!0}),t.prototype.getActiveIndices=function(){return this._activeIndices.current},Object.defineProperty(t.prototype,"totalActiveIndicesPerfCounter",{get:function(){return this._activeIndices},enumerable:!0,configurable:!0}),t.prototype.getActiveParticles=function(){return this._activeParticles.current},Object.defineProperty(t.prototype,"activeParticlesPerfCounter",{get:function(){return this._activeParticles},enumerable:!0,configurable:!0}),t.prototype.getActiveBones=function(){return this._activeBones.current},Object.defineProperty(t.prototype,"activeBonesPerfCounter",{get:function(){return this._activeBones},enumerable:!0,configurable:!0}),t.prototype.getActiveMeshes=function(){return this._activeMeshes},t.prototype.getAnimationRatio=function(){return void 0!==this._animationRatio?this._animationRatio:1},t.prototype.getRenderId=function(){return this._renderId},t.prototype.getFrameId=function(){return this._frameId},t.prototype.incrementRenderId=function(){this._renderId++},t.prototype._createUbo=function(){this._sceneUbo=new m.a(this._engine,void 0,!0),this._sceneUbo.addUniform("viewProjection",16),this._sceneUbo.addUniform("view",16)},t.prototype.simulatePointerMove=function(e,t){return this._inputManager.simulatePointerMove(e,t),this},t.prototype.simulatePointerDown=function(e,t){return this._inputManager.simulatePointerDown(e,t),this},t.prototype.simulatePointerUp=function(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this},t.prototype.isPointerCaptured=function(e){return void 0===e&&(e=0),this._inputManager.isPointerCaptured(e)},t.prototype.attachControl=function(e,t,i){void 0===e&&(e=!0),void 0===t&&(t=!0),void 0===i&&(i=!0),this._inputManager.attachControl(e,t,i)},t.prototype.detachControl=function(){this._inputManager.detachControl()},t.prototype.isReady=function(){if(this._isDisposed)return!1;var e,t=this.getEngine();if(!t.areAllEffectsReady())return!1;if(this._pendingData.length>0)return!1;for(e=0;e<this.meshes.length;e++){var i=this.meshes[e];if(i.isEnabled()&&(i.subMeshes&&0!==i.subMeshes.length)){if(!i.isReady(!0))return!1;for(var n="InstancedMesh"===i.getClassName()||"InstancedLinesMesh"===i.getClassName()||t.getCaps().instancedArrays&&i.instances.length>0,r=0,o=this._isReadyForMeshStage;r<o.length;r++){if(!o[r].action(i,n))return!1}}}for(e=0;e<this.geometries.length;e++){if(this.geometries[e].delayLoadState===x.a.DELAYLOADSTATE_LOADING)return!1}if(this.activeCameras&&this.activeCameras.length>0)for(var a=0,s=this.activeCameras;a<s.length;a++){if(!s[a].isReady(!0))return!1}else if(this.activeCamera&&!this.activeCamera.isReady(!0))return!1;for(var c=0,l=this.particleSystems;c<l.length;c++){if(!l[c].isReady())return!1}return!0},t.prototype.resetCachedMaterial=function(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null},t.prototype.registerBeforeRender=function(e){this.onBeforeRenderObservable.add(e)},t.prototype.unregisterBeforeRender=function(e){this.onBeforeRenderObservable.removeCallback(e)},t.prototype.registerAfterRender=function(e){this.onAfterRenderObservable.add(e)},t.prototype.unregisterAfterRender=function(e){this.onAfterRenderObservable.removeCallback(e)},t.prototype._executeOnceBeforeRender=function(e){var t=this,i=function(){e(),setTimeout(function(){t.unregisterBeforeRender(i)})};this.registerBeforeRender(i)},t.prototype.executeOnceBeforeRender=function(e,t){var i=this;void 0!==t?setTimeout(function(){i._executeOnceBeforeRender(e)},t):this._executeOnceBeforeRender(e)},t.prototype._addPendingData=function(e){this._pendingData.push(e)},t.prototype._removePendingData=function(e){var t=this.isLoading,i=this._pendingData.indexOf(e);-1!==i&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)},t.prototype.getWaitingItemsCount=function(){return this._pendingData.length},Object.defineProperty(t.prototype,"isLoading",{get:function(){return this._pendingData.length>0},enumerable:!0,configurable:!0}),t.prototype.executeWhenReady=function(e){var t=this;this.onReadyObservable.add(e),-1===this._executeWhenReadyTimeoutId&&(this._executeWhenReadyTimeoutId=setTimeout(function(){t._checkIsReady()},150))},t.prototype.whenReadyAsync=function(){var e=this;return new Promise(function(t){e.executeWhenReady(function(){t()})})},t.prototype._checkIsReady=function(){var e=this;return this._registerTransientComponents(),this.isReady()?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=-1)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=-1)):void(this._executeWhenReadyTimeoutId=setTimeout(function(){e._checkIsReady()},150))},Object.defineProperty(t.prototype,"animatables",{get:function(){return this._activeAnimatables},enumerable:!0,configurable:!0}),t.prototype.resetLastAnimationTimeFrame=function(){this._animationTimeLast=o.a.Now},t.prototype.getViewMatrix=function(){return this._viewMatrix},t.prototype.getProjectionMatrix=function(){return this._projectionMatrix},t.prototype.getTransformMatrix=function(){return this._transformMatrix},t.prototype.setTransformMatrix=function(e,t,i,n){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?N.a.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=N.a.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,n):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.update()))},t.prototype.getSceneUniformBuffer=function(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo},t.prototype.getUniqueId=function(){return F.a.UniqueId},t.prototype.addMesh=function(e,t){var i=this;void 0===t&&(t=!1),this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(function(e){i.addMesh(e)}))},t.prototype.removeMesh=function(e,t){var i=this;void 0===t&&(t=!1);var n=this.meshes.indexOf(e);return-1!==n&&(this.meshes[n]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(function(e){i.removeMesh(e)}),n},t.prototype.addTransformNode=function(e){this._blockEntityCollection||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))},t.prototype.removeTransformNode=function(e){var t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){var 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},t.prototype.removeSkeleton=function(e){var t=this.skeletons.indexOf(e);return-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e)),t},t.prototype.removeMorphTargetManager=function(e){var t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t},t.prototype.removeLight=function(e){var t=this.lights.indexOf(e);if(-1!==t){for(var i=0,n=this.meshes;i<n.length;i++){n[i]._removeLightSource(e,!1)}this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t},t.prototype.removeCamera=function(e){var t=this.cameras.indexOf(e);-1!==t&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes());var i=this.activeCameras.indexOf(e);return-1!==i&&this.activeCameras.splice(i,1),this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t},t.prototype.removeParticleSystem=function(e){var t=this.particleSystems.indexOf(e);return-1!==t&&this.particleSystems.splice(t,1),t},t.prototype.removeAnimation=function(e){var t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t},t.prototype.stopAnimation=function(e,t,i){},t.prototype.removeAnimationGroup=function(e){var t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t},t.prototype.removeMultiMaterial=function(e){var t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),t},t.prototype.removeMaterial=function(e){var t=e._indexInSceneMaterialArray;if(-1!==t&&t<this.materials.length){if(t!==this.materials.length-1){var 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},t.prototype.removeActionManager=function(e){var t=this.actionManagers.indexOf(e);return-1!==t&&this.actionManagers.splice(t,1),t},t.prototype.removeTexture=function(e){var t=this.textures.indexOf(e);return-1!==t&&this.textures.splice(t,1),this.onTextureRemovedObservable.notifyObservers(e),t},t.prototype.addLight=function(e){if(!this._blockEntityCollection){this.lights.push(e),this.sortLightsByPriority(),e.parent||e._addToSceneRootNodes();for(var t=0,i=this.meshes;t<i.length;t++){var n=i[t];-1===n.lightSources.indexOf(e)&&(n.lightSources.push(e),n._resyncLightSources())}this.onNewLightAddedObservable.notifyObservers(e)}},t.prototype.sortLightsByPriority=function(){this.requireLightSorting&&this.lights.sort(g.a.CompareLightsPriority)},t.prototype.addCamera=function(e){this._blockEntityCollection||(this.cameras.push(e),this.onNewCameraAddedObservable.notifyObservers(e),e.parent||e._addToSceneRootNodes())},t.prototype.addSkeleton=function(e){this._blockEntityCollection||(this.skeletons.push(e),this.onNewSkeletonAddedObservable.notifyObservers(e))},t.prototype.addParticleSystem=function(e){this._blockEntityCollection||this.particleSystems.push(e)},t.prototype.addAnimation=function(e){this._blockEntityCollection||this.animations.push(e)},t.prototype.addAnimationGroup=function(e){this._blockEntityCollection||this.animationGroups.push(e)},t.prototype.addMultiMaterial=function(e){this._blockEntityCollection||this.multiMaterials.push(e)},t.prototype.addMaterial=function(e){this._blockEntityCollection||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),this.onNewMaterialAddedObservable.notifyObservers(e))},t.prototype.addMorphTargetManager=function(e){this._blockEntityCollection||this.morphTargetManagers.push(e)},t.prototype.addGeometry=function(e){this._blockEntityCollection||(this.geometriesByUniqueId&&(this.geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))},t.prototype.addActionManager=function(e){this.actionManagers.push(e)},t.prototype.addTexture=function(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))},t.prototype.switchActiveCamera=function(e,t){void 0===t&&(t=!0);var i=this._engine.getInputElement();i&&(this.activeCamera&&this.activeCamera.detachControl(i),this.activeCamera=e,t&&e.attachControl(i))},t.prototype.setActiveCameraByID=function(e){var t=this.getCameraByID(e);return t?(this.activeCamera=t,t):null},t.prototype.setActiveCameraByName=function(e){var t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null},t.prototype.getAnimationGroupByName=function(e){for(var t=0;t<this.animationGroups.length;t++)if(this.animationGroups[t].name===e)return this.animationGroups[t];return null},t.prototype.getMaterialByUniqueID=function(e){for(var t=0;t<this.materials.length;t++)if(this.materials[t].uniqueId===e)return this.materials[t];return null},t.prototype.getMaterialByID=function(e){for(var t=0;t<this.materials.length;t++)if(this.materials[t].id===e)return this.materials[t];return null},t.prototype.getLastMaterialByID=function(e){for(var t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];return null},t.prototype.getMaterialByName=function(e){for(var t=0;t<this.materials.length;t++)if(this.materials[t].name===e)return this.materials[t];return null},t.prototype.getTextureByUniqueID=function(e){for(var t=0;t<this.textures.length;t++)if(this.textures[t].uniqueId===e)return this.textures[t];return null},t.prototype.getCameraByID=function(e){for(var t=0;t<this.cameras.length;t++)if(this.cameras[t].id===e)return this.cameras[t];return null},t.prototype.getCameraByUniqueID=function(e){for(var t=0;t<this.cameras.length;t++)if(this.cameras[t].uniqueId===e)return this.cameras[t];return null},t.prototype.getCameraByName=function(e){for(var t=0;t<this.cameras.length;t++)if(this.cameras[t].name===e)return this.cameras[t];return null},t.prototype.getBoneByID=function(e){for(var t=0;t<this.skeletons.length;t++)for(var i=this.skeletons[t],n=0;n<i.bones.length;n++)if(i.bones[n].id===e)return i.bones[n];return null},t.prototype.getBoneByName=function(e){for(var t=0;t<this.skeletons.length;t++)for(var i=this.skeletons[t],n=0;n<i.bones.length;n++)if(i.bones[n].name===e)return i.bones[n];return null},t.prototype.getLightByName=function(e){for(var t=0;t<this.lights.length;t++)if(this.lights[t].name===e)return this.lights[t];return null},t.prototype.getLightByID=function(e){for(var t=0;t<this.lights.length;t++)if(this.lights[t].id===e)return this.lights[t];return null},t.prototype.getLightByUniqueID=function(e){for(var t=0;t<this.lights.length;t++)if(this.lights[t].uniqueId===e)return this.lights[t];return null},t.prototype.getParticleSystemByID=function(e){for(var t=0;t<this.particleSystems.length;t++)if(this.particleSystems[t].id===e)return this.particleSystems[t];return null},t.prototype.getGeometryByID=function(e){for(var t=0;t<this.geometries.length;t++)if(this.geometries[t].id===e)return this.geometries[t];return null},t.prototype._getGeometryByUniqueID=function(e){if(this.geometriesByUniqueId){var t=this.geometriesByUniqueId[e];if(void 0!==t)return this.geometries[t]}else for(var i=0;i<this.geometries.length;i++)if(this.geometries[i].uniqueId===e)return this.geometries[i];return null},t.prototype.pushGeometry=function(e,t){return!(!t&&this._getGeometryByUniqueID(e.uniqueId))&&(this.addGeometry(e),this.onNewGeometryAddedObservable.notifyObservers(e),!0)},t.prototype.removeGeometry=function(e){var t;if(this.geometriesByUniqueId){if(void 0===(t=this.geometriesByUniqueId[e.uniqueId]))return!1}else if((t=this.geometries.indexOf(e))<0)return!1;if(t!==this.geometries.length-1){var i=this.geometries[this.geometries.length-1];this.geometries[t]=i,this.geometriesByUniqueId&&(this.geometriesByUniqueId[i.uniqueId]=t,this.geometriesByUniqueId[e.uniqueId]=void 0)}return this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0},t.prototype.getGeometries=function(){return this.geometries},t.prototype.getMeshByID=function(e){for(var t=0;t<this.meshes.length;t++)if(this.meshes[t].id===e)return this.meshes[t];return null},t.prototype.getMeshesByID=function(e){return this.meshes.filter(function(t){return t.id===e})},t.prototype.getTransformNodeByID=function(e){for(var t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null},t.prototype.getTransformNodeByUniqueID=function(e){for(var t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].uniqueId===e)return this.transformNodes[t];return null},t.prototype.getTransformNodesByID=function(e){return this.transformNodes.filter(function(t){return t.id===e})},t.prototype.getMeshByUniqueID=function(e){for(var t=0;t<this.meshes.length;t++)if(this.meshes[t].uniqueId===e)return this.meshes[t];return null},t.prototype.getLastMeshByID=function(e){for(var t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null},t.prototype.getLastEntryByID=function(e){var 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];return null},t.prototype.getNodeByID=function(e){var t=this.getMeshByID(e);if(t)return t;var i=this.getTransformNodeByID(e);if(i)return i;var n=this.getLightByID(e);if(n)return n;var r=this.getCameraByID(e);if(r)return r;var o=this.getBoneByID(e);return o||null},t.prototype.getNodeByName=function(e){var t=this.getMeshByName(e);if(t)return t;var i=this.getTransformNodeByName(e);if(i)return i;var n=this.getLightByName(e);if(n)return n;var r=this.getCameraByName(e);if(r)return r;var o=this.getBoneByName(e);return o||null},t.prototype.getMeshByName=function(e){for(var t=0;t<this.meshes.length;t++)if(this.meshes[t].name===e)return this.meshes[t];return null},t.prototype.getTransformNodeByName=function(e){for(var t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].name===e)return this.transformNodes[t];return null},t.prototype.getLastSkeletonByID=function(e){for(var t=this.skeletons.length-1;t>=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null},t.prototype.getSkeletonByUniqueId=function(e){for(var t=0;t<this.skeletons.length;t++)if(this.skeletons[t].uniqueId===e)return this.skeletons[t];return null},t.prototype.getSkeletonById=function(e){for(var t=0;t<this.skeletons.length;t++)if(this.skeletons[t].id===e)return this.skeletons[t];return null},t.prototype.getSkeletonByName=function(e){for(var t=0;t<this.skeletons.length;t++)if(this.skeletons[t].name===e)return this.skeletons[t];return null},t.prototype.getMorphTargetManagerById=function(e){for(var t=0;t<this.morphTargetManagers.length;t++)if(this.morphTargetManagers[t].uniqueId===e)return this.morphTargetManagers[t];return null},t.prototype.getMorphTargetById=function(e){for(var t=0;t<this.morphTargetManagers.length;++t)for(var i=this.morphTargetManagers[t],n=0;n<i.numTargets;++n){var r=i.getTarget(n);if(r.id===e)return r}return null},t.prototype.isActiveMesh=function(e){return-1!==this._activeMeshes.indexOf(e)},Object.defineProperty(t.prototype,"uid",{get:function(){return this._uid||(this._uid=r.b.RandomId()),this._uid},enumerable:!0,configurable:!0}),t.prototype.addExternalData=function(e,t){return this._externalData||(this._externalData=new c.a),this._externalData.add(e,t)},t.prototype.getExternalData=function(e){return this._externalData?this._externalData.get(e):null},t.prototype.getOrAddExternalDataWithFactory=function(e,t){return this._externalData||(this._externalData=new c.a),this._externalData.getOrAddWithFactory(e,t)},t.prototype.removeExternalData=function(e){return this._externalData.remove(e)},t.prototype._evaluateSubMesh=function(e,t,i){if(i.hasInstances||i.isAnInstance||this.dispatchAllSubMeshesOfActiveMeshes||this._skipFrustumClipping||t.alwaysSelectAsActiveMesh||1===t.subMeshes.length||e.isInFrustum(this._frustumPlanes)){for(var n=0,r=this._evaluateSubMeshStage;n<r.length;n++){r[n].action(t,e)}var o=e.getMaterial();null!=o&&(o.hasRenderTargetTextures&&null!=o.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(o)&&(this._processedMaterials.push(o),this._renderTargets.concatWithNoDuplicate(o.getRenderTargetTextures())),this._renderingManager.dispatch(e,t,o))}},t.prototype.freeProcessedMaterials=function(){this._processedMaterials.dispose()},Object.defineProperty(t.prototype,"blockfreeActiveMeshesAndRenderingGroups",{get:function(){return this._preventFreeActiveMeshesAndRenderingGroups},set:function(e){this._preventFreeActiveMeshesAndRenderingGroups!==e&&(e&&(this.freeActiveMeshes(),this.freeRenderingGroups()),this._preventFreeActiveMeshesAndRenderingGroups=e)},enumerable:!0,configurable:!0}),t.prototype.freeActiveMeshes=function(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._activeMeshes.dispose(),this.activeCamera&&this.activeCamera._activeMeshes&&this.activeCamera._activeMeshes.dispose(),this.activeCameras))for(var e=0;e<this.activeCameras.length;e++){var t=this.activeCameras[e];t&&t._activeMeshes&&t._activeMeshes.dispose()}},t.prototype.freeRenderingGroups=function(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._renderingManager&&this._renderingManager.freeRenderingGroups(),this.textures))for(var e=0;e<this.textures.length;e++){var t=this.textures[e];t&&t.renderList&&t.freeRenderingGroups()}},t.prototype._isInIntermediateRendering=function(){return this._intermediateRendering},t.prototype.freezeActiveMeshes=function(e){var t=this;return void 0===e&&(e=!1),this.executeWhenReady(function(){if(t.activeCamera){t._frustumPlanes||t.setTransformMatrix(t.activeCamera.getViewMatrix(),t.activeCamera.getProjectionMatrix()),t._evaluateActiveMeshes(),t._activeMeshesFrozen=!0,t._skipEvaluateActiveMeshesCompletely=e;for(var i=0;i<t._activeMeshes.length;i++)t._activeMeshes.data[i]._freeze()}}),this},t.prototype.unfreezeActiveMeshes=function(){for(var e=0;e<this.meshes.length;e++){var t=this.meshes[e];t._internalAbstractMeshDataInfo&&(t._internalAbstractMeshDataInfo._isActive=!1)}for(e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._unFreeze();return this._activeMeshesFrozen=!1,this},t.prototype._evaluateActiveMeshes=function(){if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely)for(var e=this._activeMeshes.length,t=0;t<e;t++){(a=this._activeMeshes.data[t]).computeWorldMatrix()}}else if(this.activeCamera){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();for(var i=0,n=this._beforeEvaluateActiveMeshStage;i<n.length;i++){n[i].action()}var r=this.getActiveMeshCandidates(),o=r.length;for(t=0;t<o;t++){var a;if(!(a=r.data[t]).isBlocked&&(this._totalVertices.addCount(a.getTotalVertices(),!1),a.isReady()&&a.isEnabled()&&0!==a.scaling.lengthSquared())){a.computeWorldMatrix(),a.actionManager&&a.actionManager.hasSpecificTriggers2(x.a.ACTION_OnIntersectionEnterTrigger,x.a.ACTION_OnIntersectionExitTrigger)&&this._meshesForIntersections.pushNoDuplicate(a);var s=this.customLODSelector?this.customLODSelector(a,this.activeCamera):a.getLOD(this.activeCamera);null!=s&&(s!==a&&s.billboardMode!==h.a.BILLBOARDMODE_NONE&&s.computeWorldMatrix(),a._preActivate(),a.isVisible&&a.visibility>0&&0!=(a.layerMask&this.activeCamera.layerMask)&&(this._skipFrustumClipping||a.alwaysSelectAsActiveMesh||a.isInFrustum(this._frustumPlanes))&&(this._activeMeshes.push(a),this.activeCamera._activeMeshes.push(a),s!==a&&s._activate(this._renderId,!1),a._activate(this._renderId,!1)&&(a.isAnInstance?a._internalAbstractMeshDataInfo._actAsRegularMesh&&(s=a):s._internalAbstractMeshDataInfo._onlyForInstances=!1,s._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(a,s)),a._postActivate()))}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(var c=0;c<this.particleSystems.length;c++){var l=this.particleSystems[c];if(l.isStarted()&&l.emitter){var u=l.emitter;u.position&&!u.isEnabled()||(this._activeParticleSystems.push(l),l.animate(),this._renderingManager.dispatchParticles(l))}}this.onAfterParticlesRenderingObservable.notifyObservers(this)}}},t.prototype._activeMesh=function(e,t){this._skeletonsEnabled&&null!==t.skeleton&&void 0!==t.skeleton&&(this._activeSkeletons.pushNoDuplicate(t.skeleton)&&t.skeleton.prepare(),t.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(t));for(var i=0,n=this._activeMeshStage;i<n.length;i++){n[i].action(e,t)}if(null!=t&&void 0!==t.subMeshes&&null!==t.subMeshes&&t.subMeshes.length>0)for(var r=this.getActiveSubMeshCandidates(t),o=r.length,a=0;a<o;a++){var s=r.data[a];this._evaluateSubMesh(s,t,e)}},t.prototype.updateTransformMatrix=function(e){this.activeCamera&&this.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix(e))},t.prototype._bindFrameBuffer=function(){if(this.activeCamera&&this.activeCamera._multiviewTexture)this.activeCamera._multiviewTexture._bindFrameBuffer();else if(this.activeCamera&&this.activeCamera.outputRenderTarget){if(this.getEngine().getCaps().multiview&&this.activeCamera.outputRenderTarget&&this.activeCamera.outputRenderTarget.getViewCount()>1)this.activeCamera.outputRenderTarget._bindFrameBuffer();else{var e=this.activeCamera.outputRenderTarget.getInternalTexture();e?this.getEngine().bindFramebuffer(e):A.a.Error("Camera contains invalid customDefaultRenderTarget")}}else this.getEngine().restoreDefaultFramebuffer()},t.prototype._renderForCamera=function(e,t){if(!e||!e._skipRendering){var i=this._engine;if(this._activeCamera=e,!this.activeCamera)throw new Error("Active camera not set");i.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,this.getEngine().getCaps().multiview&&e.outputRenderTarget&&e.outputRenderTarget.getViewCount()>1?this.setTransformMatrix(e._rigCameras[0].getViewMatrix(),e._rigCameras[0].getProjectionMatrix(),e._rigCameras[1].getViewMatrix(),e._rigCameras[1].getProjectionMatrix()):this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshes();for(var n=0;n<this._softwareSkinnedMeshes.length;n++){var o=this._softwareSkinnedMeshes.data[n];o.applySkeleton(o.skeleton)}this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),e.customRenderTargets&&e.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets);for(var a=0,s=this._gatherActiveCameraRenderTargetsStage;a<s.length;a++){s[a].action(this._renderTargets)}if(this.renderTargetsEnabled){this._intermediateRendering=!0;var c=!1;if(this._renderTargets.length>0){r.b.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(var l=0;l<this._renderTargets.length;l++){var u=this._renderTargets.data[l];if(u._shouldRender()){this._renderId++;var h=u.activeCamera&&u.activeCamera!==this.activeCamera;u.render(h,this.dumpNextRenderTargets),c=!0}}r.b.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}for(var d=0,f=this._cameraDrawRenderTargetStage;d<f.length;d++){c=f[d].action(this.activeCamera)||c}this._intermediateRendering=!1,this.activeCamera&&this.activeCamera.outputRenderTarget&&(c=!0),c&&this._bindFrameBuffer()}this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.postProcessManager&&!e._multiviewTexture&&this.postProcessManager._prepareFrame();for(var p=0,_=this._beforeCameraDrawStage;p<_.length;p++){_[p].action(this.activeCamera)}this.onBeforeDrawPhaseObservable.notifyObservers(this),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(var m=0,g=this._afterCameraDrawStage;m<g.length;m++){g[m].action(this.activeCamera)}this.postProcessManager&&!e._multiviewTexture&&this.postProcessManager._finalizeFrame(e.isIntermediate),this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}},t.prototype._processSubCameras=function(e){if(e.cameraRigMode===f.a.RIG_MODE_NONE||e.outputRenderTarget&&e.outputRenderTarget.getViewCount()>1&&this.getEngine().getCaps().multiview)return this._renderForCamera(e),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else for(var t=0;t<e._rigCameras.length;t++)this._renderForCamera(e._rigCameras[t],e);this._activeCamera=e,this.setTransformMatrix(this._activeCamera.getViewMatrix(),this._activeCamera.getProjectionMatrix()),this.onAfterRenderCameraObservable.notifyObservers(e)},t.prototype._checkIntersections=function(){for(var e=0;e<this._meshesForIntersections.length;e++){var t=this._meshesForIntersections.data[e];if(t.actionManager)for(var i=0;t.actionManager&&i<t.actionManager.actions.length;i++){var n=t.actionManager.actions[i];if(n.trigger===x.a.ACTION_OnIntersectionEnterTrigger||n.trigger===x.a.ACTION_OnIntersectionExitTrigger){var r=n.getTriggerParameter(),o=r instanceof d.a?r:r.mesh,a=o.intersectsMesh(t,r.usePreciseIntersection),s=t._intersectionsInProgress.indexOf(o);a&&-1===s?n.trigger===x.a.ACTION_OnIntersectionEnterTrigger?(n._executeCurrent(y.a.CreateNew(t,void 0,o)),t._intersectionsInProgress.push(o)):n.trigger===x.a.ACTION_OnIntersectionExitTrigger&&t._intersectionsInProgress.push(o):!a&&s>-1&&(n.trigger===x.a.ACTION_OnIntersectionExitTrigger&&n._executeCurrent(y.a.CreateNew(t,void 0,o)),t.actionManager.hasSpecificTrigger(x.a.ACTION_OnIntersectionExitTrigger,function(e){var t=e instanceof d.a?e:e.mesh;return o===t})&&n.trigger!==x.a.ACTION_OnIntersectionExitTrigger||t._intersectionsInProgress.splice(s,1))}}}},t.prototype._advancePhysicsEngineStep=function(e){},t.prototype._animate=function(){},t.prototype.animate=function(){if(this._engine.isDeterministicLockStep()){var e=Math.max(t.MinDeltaTime,Math.min(this._engine.getDeltaTime(),t.MaxDeltaTime))+this._timeAccumulator,i=this._engine.getTimeStep(),n=1e3/i/1e3,r=0,o=this._engine.getLockstepMaxSteps(),a=Math.floor(e/i);for(a=Math.min(a,o);e>0&&r<a;)this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=i*n,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this._advancePhysicsEngineStep(i),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,r++,e-=i;this._timeAccumulator=e<0?0:e}else{e=this.useConstantAnimationDeltaTime?16:Math.max(t.MinDeltaTime,Math.min(this._engine.getDeltaTime(),t.MaxDeltaTime));this._animationRatio=.06*e,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this._advancePhysicsEngineStep(e)}},t.prototype.render=function(e,t){if(void 0===e&&(e=!0),void 0===t&&(t=!1),!this.isDisposed){this._frameId++,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(x.a.ACTION_OnEveryFrameTrigger),t||this.animate();for(var i=0,n=this._beforeCameraUpdateStage;i<n.length;i++){n[i].action()}if(e)if(this.activeCameras.length>0)for(var o=0;o<this.activeCameras.length;o++){var a=this.activeCameras[o];if(a.update(),a.cameraRigMode!==f.a.RIG_MODE_NONE)for(var s=0;s<a._rigCameras.length;s++)a._rigCameras[s].update()}else if(this.activeCamera&&(this.activeCamera.update(),this.activeCamera.cameraRigMode!==f.a.RIG_MODE_NONE))for(s=0;s<this.activeCamera._rigCameras.length;s++)this.activeCamera._rigCameras[s].update();this.onBeforeRenderObservable.notifyObservers(this),this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);var c=this.getEngine(),l=this.activeCamera;if(this.renderTargetsEnabled){r.b.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!0;for(var u=0;u<this.customRenderTargets.length;u++){var h=this.customRenderTargets[u];if(h._shouldRender()){if(this._renderId++,this.activeCamera=h.activeCamera||this.activeCamera,!this.activeCamera)throw new Error("Active camera not set");c.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),h.render(l!==this.activeCamera,this.dumpNextRenderTargets)}}r.b.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!1,this._renderId++}this.activeCamera=l,this._bindFrameBuffer(),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(var d=0,p=this._beforeClearStage;d<p.length;d++){p[d].action()}(this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil);for(var _=0,m=this._gatherRenderTargetsStage;_<m.length;_++){m[_].action(this._renderTargets)}if(this.activeCameras.length>0)for(o=0;o<this.activeCameras.length;o++)o>0&&this._engine.clear(null,!1,!0,!0),this._processSubCameras(this.activeCameras[o]);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera)}this._checkIntersections();for(var g=0,v=this._afterRenderStage;g<v.length;g++){v[g].action()}if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(s=0;s<this._toBeDisposed.length;s++){var y=this._toBeDisposed[s];y&&y.dispose()}this._toBeDisposed=[]}this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0)}},t.prototype.freezeMaterials=function(){for(var e=0;e<this.materials.length;e++)this.materials[e].freeze()},t.prototype.unfreezeMaterials=function(){for(var e=0;e<this.materials.length;e++)this.materials[e].unfreeze()},t.prototype.dispose=function(){this.beforeRender=null,this.afterRender=null,S.a._LastCreatedScene===this&&(S.a._LastCreatedScene=null),this.skeletons=[],this.morphTargetManagers=[],this._transientComponents=[],this._isReadyForMeshStage.clear(),this._beforeEvaluateActiveMeshStage.clear(),this._evaluateSubMeshStage.clear(),this._activeMeshStage.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();for(var e=0,t=this._components;e<t.length;e++){t[e].dispose()}this.importedMeshesFiles=new Array,this.stopAllAnimations&&this.stopAllAnimations(),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed=[];for(var i=0,n=this._activeRequests;i<n.length;i++){n[i].abort()}this.onDisposeObservable.notifyObservers(this),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.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.onMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.detachControl();var r,o=this._engine.getInputElement();if(o)for(r=0;r<this.cameras.length;r++)this.cameras[r].detachControl(o);for(;this.animationGroups.length;)this.animationGroups[0].dispose();for(;this.lights.length;)this.lights[0].dispose();for(;this.meshes.length;)this.meshes[0].dispose(!0);for(;this.transformNodes.length;)this.transformNodes[0].dispose(!0);for(;this.cameras.length;)this.cameras[0].dispose();for(this._defaultMaterial&&this._defaultMaterial.dispose();this.multiMaterials.length;)this.multiMaterials[0].dispose();for(;this.materials.length;)this.materials[0].dispose();for(;this.particleSystems.length;)this.particleSystems[0].dispose();for(;this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.textures.length;)this.textures[0].dispose();this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),(r=this._engine.scenes.indexOf(this))>-1&&this._engine.scenes.splice(r,1),this._engine.wipeCaches(!0),this._isDisposed=!0},Object.defineProperty(t.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!0,configurable:!0}),t.prototype.clearCachedVertexData=function(){for(var e=0;e<this.meshes.length;e++){var t=this.meshes[e].geometry;if(t)for(var i in t._indices=[],t._vertexBuffers)t._vertexBuffers.hasOwnProperty(i)&&(t._vertexBuffers[i]._buffer._data=null)}},t.prototype.cleanCachedTextureBuffer=function(){for(var e=0,t=this.textures;e<t.length;e++){var i=t[e];i._buffer&&(i._buffer=null)}},t.prototype.getWorldExtends=function(e){var t=new u.e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new u.e(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return e=e||function(){return!0},this.meshes.filter(e).forEach(function(e){if(e.computeWorldMatrix(!0),e.subMeshes&&0!==e.subMeshes.length&&!e.infiniteDistance){var n=e.getBoundingInfo(),r=n.boundingBox.minimumWorld,o=n.boundingBox.maximumWorld;u.e.CheckExtends(r,t,i),u.e.CheckExtends(o,t,i)}}),{min:t,max:i}},t.prototype.createPickingRay=function(e,t,i,n,r){throw void 0===r&&(r=!1),C.a.WarnImport("Ray")},t.prototype.createPickingRayToRef=function(e,t,i,n,r,o){throw void 0===o&&(o=!1),C.a.WarnImport("Ray")},t.prototype.createPickingRayInCameraSpace=function(e,t,i){throw C.a.WarnImport("Ray")},t.prototype.createPickingRayInCameraSpaceToRef=function(e,t,i,n){throw C.a.WarnImport("Ray")},t.prototype.pick=function(e,t,i,n,r,o){var a=new v.a;return a._pickingUnavailable=!0,a},t.prototype.pickWithRay=function(e,t,i,n){throw C.a.WarnImport("Ray")},t.prototype.multiPick=function(e,t,i,n,r){throw C.a.WarnImport("Ray")},t.prototype.multiPickWithRay=function(e,t,i){throw C.a.WarnImport("Ray")},t.prototype.setPointerOverMesh=function(e){this._inputManager.setPointerOverMesh(e)},t.prototype.getPointerOverMesh=function(){return this._inputManager.getPointerOverMesh()},t.prototype._rebuildGeometries=function(){for(var e=0,t=this.geometries;e<t.length;e++){t[e]._rebuild()}for(var i=0,n=this.meshes;i<n.length;i++){n[i]._rebuild()}this.postProcessManager&&this.postProcessManager._rebuild();for(var r=0,o=this._components;r<o.length;r++){o[r].rebuild()}for(var a=0,s=this.particleSystems;a<s.length;a++){s[a].rebuild()}},t.prototype._rebuildTextures=function(){for(var e=0,t=this.textures;e<t.length;e++){t[e]._rebuild()}this.markAllMaterialsAsDirty(x.a.MATERIAL_TextureDirtyFlag)},t.prototype._getByTags=function(e,t,i){if(void 0===t)return e;var n=[];for(var r in i=i||function(e){},e){var o=e[r];l.a&&l.a.MatchesQuery(o,t)&&(n.push(o),i(o))}return n},t.prototype.getMeshesByTags=function(e,t){return this._getByTags(this.meshes,e,t)},t.prototype.getCamerasByTags=function(e,t){return this._getByTags(this.cameras,e,t)},t.prototype.getLightsByTags=function(e,t){return this._getByTags(this.lights,e,t)},t.prototype.getMaterialByTags=function(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))},t.prototype.setRenderingOrder=function(e,t,i,n){void 0===t&&(t=null),void 0===i&&(i=null),void 0===n&&(n=null),this._renderingManager.setRenderingOrder(e,t,i,n)},t.prototype.setRenderingAutoClearDepthStencil=function(e,t,i,n){void 0===i&&(i=!0),void 0===n&&(n=!0),this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,n)},t.prototype.getAutoClearDepthStencilSetup=function(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)},Object.defineProperty(t.prototype,"blockMaterialDirtyMechanism",{get:function(){return this._blockMaterialDirtyMechanism},set:function(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(x.a.MATERIAL_AllDirtyFlag))},enumerable:!0,configurable:!0}),t.prototype.markAllMaterialsAsDirty=function(e,t){if(!this._blockMaterialDirtyMechanism)for(var i=0,n=this.materials;i<n.length;i++){var r=n[i];t&&!t(r)||r.markAsDirty(e)}},t.prototype._loadFile=function(e,t,i,n,r,o){var a=this,s=B.a.LoadFile(e,t,i,n?this.offlineProvider:void 0,r,o);return this._activeRequests.push(s),s.onCompleteObservable.add(function(e){a._activeRequests.splice(a._activeRequests.indexOf(e),1)}),s},t.prototype._loadFileAsync=function(e,t,i,n){var r=this;return new Promise(function(o,a){r._loadFile(e,function(e){o(e)},t,i,n,function(e,t){a(t)})})},t.prototype._requestFile=function(e,t,i,n,r,o,a){var s=this,c=B.a.RequestFile(e,t,i,n?this.offlineProvider:void 0,r,o,a);return this._activeRequests.push(c),c.onCompleteObservable.add(function(e){s._activeRequests.splice(s._activeRequests.indexOf(e),1)}),c},t.prototype._requestFileAsync=function(e,t,i,n,r){var o=this;return new Promise(function(a,s){o._requestFile(e,function(e){a(e)},t,i,n,function(e){s(e)},r)})},t.prototype._readFile=function(e,t,i,n,r){var o=this,a=B.a.ReadFile(e,t,i,n,r);return this._activeRequests.push(a),a.onCompleteObservable.add(function(e){o._activeRequests.splice(o._activeRequests.indexOf(e),1)}),a},t.prototype._readFileAsync=function(e,t,i){var n=this;return new Promise(function(r,o){n._readFile(e,function(e){r(e)},t,i,function(e){o(e)})})},t.FOGMODE_NONE=0,t.FOGMODE_EXP=1,t.FOGMODE_EXP2=2,t.FOGMODE_LINEAR=3,t.MinDeltaTime=1,t.MaxDeltaTime=1e3,t}(p.a)},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return e.WarnImport=function(e){return e+" needs to be imported before as it contains a side-effect required by your code."},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return o}),i.d(t,"c",function(){return a}),i.d(t,"d",function(){return s}),i.d(t,"b",function(){return c});var n=i(1),r=i(0),o=function(){function e(){}return e.POINTERDOWN=1,e.POINTERUP=2,e.POINTERMOVE=4,e.POINTERWHEEL=8,e.POINTERPICK=16,e.POINTERTAP=32,e.POINTERDOUBLETAP=64,e}(),a=function(e,t){this.type=e,this.event=t},s=function(e){function t(t,i,n,o){var a=e.call(this,t,i)||this;return a.ray=null,a.skipOnPointerObservable=!1,a.localPosition=new r.d(n,o),a}return Object(n.d)(t,e),t}(a),c=function(e){function t(t,i,n){var r=e.call(this,t,i)||this;return r.pickInfo=n,r}return Object(n.d)(t,e),t}(a)},function(e,t,i){"use strict";i.d(t,"a",function(){return o});var n=i(11),r=i(2),o=function(){function e(){}return Object.defineProperty(e,"DiffuseTextureEnabled",{get:function(){return this._DiffuseTextureEnabled},set:function(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"AmbientTextureEnabled",{get:function(){return this._AmbientTextureEnabled},set:function(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"OpacityTextureEnabled",{get:function(){return this._OpacityTextureEnabled},set:function(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"ReflectionTextureEnabled",{get:function(){return this._ReflectionTextureEnabled},set:function(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"EmissiveTextureEnabled",{get:function(){return this._EmissiveTextureEnabled},set:function(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"SpecularTextureEnabled",{get:function(){return this._SpecularTextureEnabled},set:function(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"BumpTextureEnabled",{get:function(){return this._BumpTextureEnabled},set:function(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"LightmapTextureEnabled",{get:function(){return this._LightmapTextureEnabled},set:function(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"RefractionTextureEnabled",{get:function(){return this._RefractionTextureEnabled},set:function(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"ColorGradingTextureEnabled",{get:function(){return this._ColorGradingTextureEnabled},set:function(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"FresnelEnabled",{get:function(){return this._FresnelEnabled},set:function(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_FresnelDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"ClearCoatTextureEnabled",{get:function(){return this._ClearCoatTextureEnabled},set:function(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"ClearCoatBumpTextureEnabled",{get:function(){return this._ClearCoatBumpTextureEnabled},set:function(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"ClearCoatTintTextureEnabled",{get:function(){return this._ClearCoatTintTextureEnabled},set:function(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"SheenTextureEnabled",{get:function(){return this._SheenTextureEnabled},set:function(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"AnisotropicTextureEnabled",{get:function(){return this._AnisotropicTextureEnabled},set:function(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e,"ThicknessTextureEnabled",{get:function(){return this._ThicknessTextureEnabled},set:function(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,n.a.MarkAllMaterialsAsDirty(r.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),e._DiffuseTextureEnabled=!0,e._AmbientTextureEnabled=!0,e._OpacityTextureEnabled=!0,e._ReflectionTextureEnabled=!0,e._EmissiveTextureEnabled=!0,e._SpecularTextureEnabled=!0,e._BumpTextureEnabled=!0,e._LightmapTextureEnabled=!0,e._RefractionTextureEnabled=!0,e._ColorGradingTextureEnabled=!0,e._FresnelEnabled=!0,e._ClearCoatTextureEnabled=!0,e._ClearCoatBumpTextureEnabled=!0,e._ClearCoatTintTextureEnabled=!0,e._SheenTextureEnabled=!0,e._AnisotropicTextureEnabled=!0,e._ThicknessTextureEnabled=!0,e}()},function(e,t,i){"use strict";i.d(t,"b",function(){return n}),i.d(t,"a",function(){return o});var n,r=i(0);!function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(n||(n={}));var o=function(){function e(){}return e.X=new r.e(1,0,0),e.Y=new r.e(0,1,0),e.Z=new r.e(0,0,1),e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return Object.defineProperty(e,"LastCreatedEngine",{get:function(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]},enumerable:!0,configurable:!0}),Object.defineProperty(e,"LastCreatedScene",{get:function(){return this._LastCreatedScene},enumerable:!0,configurable:!0}),e.Instances=new Array,e._LastCreatedScene=null,e.UseFallbackTexture=!0,e.FallbackTexture="",e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return _});var n=i(1),r=i(3),o=i(34),a=i(13),s=i(6),c=i(0),l=i(26),u=i(7),h=i(12),d=i(19),f=i(61),p=i(86),_=function(e){function t(i,n,r,a){void 0===a&&(a=!0);var l=e.call(this,i,r)||this;return l._position=c.e.Zero(),l.upVector=c.e.Up(),l.orthoLeft=null,l.orthoRight=null,l.orthoBottom=null,l.orthoTop=null,l.fov=.8,l.minZ=1,l.maxZ=1e4,l.inertia=.9,l.mode=t.PERSPECTIVE_CAMERA,l.isIntermediate=!1,l.viewport=new f.a(0,0,1,1),l.layerMask=268435455,l.fovMode=t.FOVMODE_VERTICAL_FIXED,l.cameraRigMode=t.RIG_MODE_NONE,l.customRenderTargets=new Array,l.outputRenderTarget=null,l.onViewMatrixChangedObservable=new s.c,l.onProjectionMatrixChangedObservable=new s.c,l.onAfterCheckInputsObservable=new s.c,l.onRestoreStateObservable=new s.c,l.isRigCamera=!1,l._rigCameras=new Array,l._webvrViewMatrix=c.a.Identity(),l._skipRendering=!1,l._projectionMatrix=new c.a,l._postProcesses=new Array,l._activeMeshes=new o.a(256),l._globalPosition=c.e.Zero(),l._computedViewMatrix=c.a.Identity(),l._doNotComputeProjectionMatrix=!1,l._transformMatrix=c.a.Zero(),l._refreshFrustumPlanes=!0,l._isCamera=!0,l._isLeftCamera=!1,l._isRightCamera=!1,l.getScene().addCamera(l),a&&!l.getScene().activeCamera&&(l.getScene().activeCamera=l),l.position=n,l}return Object(n.d)(t,e),Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this._position=e},enumerable:!0,configurable:!0}),t.prototype.storeState=function(){return this._stateStored=!0,this._storedFov=this.fov,this},t.prototype._restoreStateValues=function(){return!!this._stateStored&&(this.fov=this._storedFov,!0)},t.prototype.restoreState=function(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)},t.prototype.getClassName=function(){return"Camera"},t.prototype.toString=function(e){var t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(var i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t},Object.defineProperty(t.prototype,"globalPosition",{get:function(){return this._globalPosition},enumerable:!0,configurable:!0}),t.prototype.getActiveMeshes=function(){return this._activeMeshes},t.prototype.isActiveMesh=function(e){return-1!==this._activeMeshes.indexOf(e)},t.prototype.isReady=function(t){if(void 0===t&&(t=!1),t)for(var i=0,n=this._postProcesses;i<n.length;i++){var r=n[i];if(r&&!r.isReady())return!1}return e.prototype.isReady.call(this,t)},t.prototype._initCache=function(){e.prototype._initCache.call(this),this._cache.position=new c.e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new c.e(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.renderWidth=void 0,this._cache.renderHeight=void 0},t.prototype._updateCache=function(t){t||e.prototype._updateCache.call(this),this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector)},t.prototype._isSynchronized=function(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()},t.prototype._isSynchronizedViewMatrix=function(){return!!e.prototype._isSynchronized.call(this)&&(this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent())},t.prototype._isSynchronizedProjectionMatrix=function(){var e=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===this.maxZ;if(!e)return!1;var i=this.getEngine();return e=this.mode===t.PERSPECTIVE_CAMERA?this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===i.getAspectRatio(this):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()},t.prototype.attachControl=function(e,t){},t.prototype.detachControl=function(e){},t.prototype.update=function(){this._checkInputs(),this.cameraRigMode!==t.RIG_MODE_NONE&&this._updateRigCameras()},t.prototype._checkInputs=function(){this.onAfterCheckInputsObservable.notifyObservers(this)},Object.defineProperty(t.prototype,"rigCameras",{get:function(){return this._rigCameras},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rigPostProcess",{get:function(){return this._rigPostProcess},enumerable:!0,configurable:!0}),t.prototype._getFirstPostProcess=function(){for(var e=0;e<this._postProcesses.length;e++)if(null!==this._postProcesses[e])return this._postProcesses[e];return null},t.prototype._cascadePostProcessesToRigCams=function(){var e=this._getFirstPostProcess();e&&e.markTextureDirty();for(var t=0,i=this._rigCameras.length;t<i;t++){var n=this._rigCameras[t],r=n._rigPostProcess;if(r)"pass"===r.getEffectName()&&(n.isIntermediate=0===this._postProcesses.length),n._postProcesses=this._postProcesses.slice(0).concat(r),r.markTextureDirty();else n._postProcesses=this._postProcesses.slice(0)}},t.prototype.attachPostProcess=function(e,t){return void 0===t&&(t=null),!e.isReusable()&&this._postProcesses.indexOf(e)>-1?(u.a.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._postProcesses.indexOf(e))},t.prototype.detachPostProcess=function(e){var t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._cascadePostProcessesToRigCams()},t.prototype.getWorldMatrix=function(){return this._isSynchronizedViewMatrix()?this._worldMatrix:(this.getViewMatrix(),this._worldMatrix)},t.prototype._getViewMatrix=function(){return c.a.Identity()},t.prototype.getViewMatrix=function(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(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._computedViewMatrix)},t.prototype.freezeProjectionMatrix=function(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)},t.prototype.unfreezeProjectionMatrix=function(){this._doNotComputeProjectionMatrix=!1},t.prototype.getProjectionMatrix=function(e){if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;var i=this.getEngine(),n=this.getScene();if(this.mode===t.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=i.getAspectRatio(this),this.minZ<=0&&(this.minZ=.1);var r=i.useReverseDepthBuffer;(n.useRightHandedSystem?r?c.a.PerspectiveFovReverseRHToRef:c.a.PerspectiveFovRHToRef:r?c.a.PerspectiveFovReverseLHToRef:c.a.PerspectiveFovLHToRef)(this.fov,i.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===t.FOVMODE_VERTICAL_FIXED)}else{var o=i.getRenderWidth()/2,a=i.getRenderHeight()/2;n.useRightHandedSystem?c.a.OrthoOffCenterRHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-a,this.orthoTop||a,this.minZ,this.maxZ,this._projectionMatrix):c.a.OrthoOffCenterLHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-a,this.orthoTop||a,this.minZ,this.maxZ,this._projectionMatrix),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()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix},t.prototype.getTransformationMatrix=function(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix},t.prototype._updateFrustumPlanes=function(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?p.a.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=p.a.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)},t.prototype.isInFrustum=function(e,t){if(void 0===t&&(t=!1),this._updateFrustumPlanes(),t&&this.rigCameras.length>0){var i=!1;return this.rigCameras.forEach(function(t){t._updateFrustumPlanes(),i=i||e.isInFrustum(t._frustumPlanes)}),i}return e.isInFrustum(this._frustumPlanes)},t.prototype.isCompletelyInFrustum=function(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)},t.prototype.getForwardRay=function(e,t,i){throw void 0===e&&(e=100),d.a.WarnImport("Ray")},t.prototype.dispose=function(i,n){for(void 0===n&&(n=!1),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;){var r=this._rigCameras.pop();r&&r.dispose()}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses=[];else if(this.cameraRigMode!==t.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses=[];else for(var o=this._postProcesses.length;--o>=0;){var a=this._postProcesses[o];a&&a.dispose(this)}for(o=this.customRenderTargets.length;--o>=0;)this.customRenderTargets[o].dispose();this.customRenderTargets=[],this._activeMeshes.dispose(),e.prototype.dispose.call(this,i,n)},Object.defineProperty(t.prototype,"isLeftCamera",{get:function(){return this._isLeftCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isRightCamera",{get:function(){return this._isRightCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"leftCamera",{get:function(){return this._rigCameras.length<1?null:this._rigCameras[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rightCamera",{get:function(){return this._rigCameras.length<2?null:this._rigCameras[1]},enumerable:!0,configurable:!0}),t.prototype.getLeftTarget=function(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()},t.prototype.getRightTarget=function(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()},t.prototype.setCameraRigMode=function(e,i){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){var n=this._rigCameras.pop();n&&n.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=i.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=a.b.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==t.RIG_MODE_NONE){var r=this.createRigCamera(this.name+"_L",0);r&&(r._isLeftCamera=!0);var o=this.createRigCamera(this.name+"_R",1);o&&(o._isRightCamera=!0),r&&o&&(this._rigCameras.push(r),this._rigCameras.push(o))}switch(this.cameraRigMode){case t.RIG_MODE_STEREOSCOPIC_ANAGLYPH:t._setStereoscopicAnaglyphRigMode(this);break;case t.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case t.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case t.RIG_MODE_STEREOSCOPIC_OVERUNDER:case t.RIG_MODE_STEREOSCOPIC_INTERLACED:t._setStereoscopicRigMode(this);break;case t.RIG_MODE_VR:t._setVRRigMode(this,i);break;case t.RIG_MODE_WEBVR:t._setWebVRRigMode(this,i)}this._cascadePostProcessesToRigCams(),this.update()}},t._setStereoscopicRigMode=function(e){throw"Import Cameras/RigModes/stereoscopicRigMode before using stereoscopic rig mode"},t._setStereoscopicAnaglyphRigMode=function(e){throw"Import Cameras/RigModes/stereoscopicAnaglyphRigMode before using stereoscopic anaglyph rig mode"},t._setVRRigMode=function(e,t){throw"Import Cameras/RigModes/vrRigMode before using VR rig mode"},t._setWebVRRigMode=function(e,t){throw"Import Cameras/RigModes/WebVRRigMode before using Web VR rig mode"},t.prototype._getVRProjectionMatrix=function(){return c.a.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix},t.prototype._updateCameraRotationMatrix=function(){},t.prototype._updateWebVRCameraRotationMatrix=function(){},t.prototype._getWebVRProjectionMatrix=function(){return c.a.Identity()},t.prototype._getWebVRViewMatrix=function(){return c.a.Identity()},t.prototype.setCameraRigParameter=function(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=a.b.ToRadians(t/.0637))},t.prototype.createRigCamera=function(e,t){return null},t.prototype._updateRigCameras=function(){for(var e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.maxZ,this._rigCameras[e].fov=this.fov,this._rigCameras[e].upVector.copyFrom(this.upVector);this.cameraRigMode===t.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)},t.prototype._setupInputs=function(){},t.prototype.serialize=function(){var e=r.a.Serialize(this);return e.type=this.getClassName(),this.parent&&(e.parentId=this.parent.id),this.inputs&&this.inputs.serialize(e),r.a.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e},t.prototype.clone=function(e){return r.a.Clone(t.GetConstructorFromName(this.getClassName(),e,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this)},t.prototype.getDirection=function(e){var t=c.e.Zero();return this.getDirectionToRef(e,t),t},Object.defineProperty(t.prototype,"absoluteRotation",{get:function(){var e=c.b.Zero();return this.getWorldMatrix().decompose(void 0,e),e},enumerable:!0,configurable:!0}),t.prototype.getDirectionToRef=function(e,t){c.e.TransformNormalToRef(e,this.getWorldMatrix(),t)},t.GetConstructorFromName=function(e,i,n,r,o){void 0===r&&(r=0),void 0===o&&(o=!0);var a=l.a.Construct(e,i,n,{interaxial_distance:r,isStereoscopicSideBySide:o});return a||function(){return t._createDefaultParsedCamera(i,n)}},t.prototype.computeWorldMatrix=function(){return this.getWorldMatrix()},t.Parse=function(e,i){var n=e.type,o=t.GetConstructorFromName(n,e.name,i,e.interaxial_distance,e.isStereoscopicSideBySide),a=r.a.Parse(o,e,i);if(e.parentId&&(a._waitingParentId=e.parentId),a.inputs&&(a.inputs.parse(e),a._setupInputs()),a.setPosition&&(a.position.copyFromFloats(0,0,0),a.setPosition(c.e.FromArray(e.position))),e.target&&a.setTarget&&a.setTarget(c.e.FromArray(e.target)),e.cameraRigMode){var s=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};a.setCameraRigMode(e.cameraRigMode,s)}if(e.animations){for(var u=0;u<e.animations.length;u++){var d=e.animations[u],f=h.a.GetClass("BABYLON.Animation");f&&a.animations.push(f.Parse(d))}l.a.ParseAnimationRanges(a,e,i)}return e.autoAnimate&&i.beginAnimation(a,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),a},t._createDefaultParsedCamera=function(e,t){throw d.a.WarnImport("UniversalCamera")},t.PERSPECTIVE_CAMERA=0,t.ORTHOGRAPHIC_CAMERA=1,t.FOVMODE_VERTICAL_FIXED=0,t.FOVMODE_HORIZONTAL_FIXED=1,t.RIG_MODE_NONE=0,t.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,t.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,t.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,t.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,t.RIG_MODE_STEREOSCOPIC_INTERLACED=14,t.RIG_MODE_VR=20,t.RIG_MODE_WEBVR=21,t.RIG_MODE_CUSTOM=22,t.ForceAttachControlToAlwaysPreventDefault=!1,Object(n.c)([Object(r.o)("position")],t.prototype,"_position",void 0),Object(n.c)([Object(r.o)()],t.prototype,"upVector",void 0),Object(n.c)([Object(r.c)()],t.prototype,"orthoLeft",void 0),Object(n.c)([Object(r.c)()],t.prototype,"orthoRight",void 0),Object(n.c)([Object(r.c)()],t.prototype,"orthoBottom",void 0),Object(n.c)([Object(r.c)()],t.prototype,"orthoTop",void 0),Object(n.c)([Object(r.c)()],t.prototype,"fov",void 0),Object(n.c)([Object(r.c)()],t.prototype,"minZ",void 0),Object(n.c)([Object(r.c)()],t.prototype,"maxZ",void 0),Object(n.c)([Object(r.c)()],t.prototype,"inertia",void 0),Object(n.c)([Object(r.c)()],t.prototype,"mode",void 0),Object(n.c)([Object(r.c)()],t.prototype,"layerMask",void 0),Object(n.c)([Object(r.c)()],t.prototype,"fovMode",void 0),Object(n.c)([Object(r.c)()],t.prototype,"cameraRigMode",void 0),Object(n.c)([Object(r.c)()],t.prototype,"interaxialDistance",void 0),Object(n.c)([Object(r.c)()],t.prototype,"isStereoscopicSideBySide",void 0),t}(l.a)},function(e,t,i){"use strict";i.d(t,"b",function(){return n}),i.d(t,"a",function(){return c});var n,r=i(6),o=i(95),a=i(2),s=i(19);!function(e){e[e.Unknown=0]="Unknown",e[e.Url=1]="Url",e[e.Temp=2]="Temp",e[e.Raw=3]="Raw",e[e.Dynamic=4]="Dynamic",e[e.RenderTarget=5]="RenderTarget",e[e.MultiRenderTarget=6]="MultiRenderTarget",e[e.Cube=7]="Cube",e[e.CubeRaw=8]="CubeRaw",e[e.CubePrefiltered=9]="CubePrefiltered",e[e.Raw3D=10]="Raw3D",e[e.Raw2DArray=11]="Raw2DArray",e[e.Depth=12]="Depth",e[e.CubeRawRGBD=13]="CubeRawRGBD"}(n||(n={}));var c=function(){function e(e,t,i){void 0===i&&(i=!1),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.samplingMode=-1,this.generateMipMaps=!1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new r.c,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=n.Unknown,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._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._MSAARenderBuffer=null,this._attachments=null,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._isDisabled=!1,this._compression=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._comparisonFunction=0,this._sphericalPolynomial=null,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._webGLTexture=null,this._references=1,this._engine=e,this._source=t,i||(this._webGLTexture=e._createTexture())}return e.prototype.getEngine=function(){return this._engine},Object.defineProperty(e.prototype,"source",{get:function(){return this._source},enumerable:!0,configurable:!0}),e.prototype.incrementReferences=function(){this._references++},e.prototype.updateSize=function(e,t,i){void 0===i&&(i=1),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i},e.prototype._rebuild=function(){var t,i=this;switch(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedAnisotropicFilteringLevel=null,this.source){case n.Temp:return;case n.Url:return void(t=this._engine.createTexture(this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,function(){t._swapAndDie(i),i.isReady=!0},null,this._buffer,void 0,this.format));case n.Raw:return(t=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this),void(this.isReady=!0);case n.Raw3D:return(t=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this),void(this.isReady=!0);case n.Raw2DArray:return(t=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this),void(this.isReady=!0);case n.Dynamic:return(t=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode))._swapAndDie(this),void this._engine.updateDynamicTexture(this,this._engine.getRenderingCanvas(),this.invertY,void 0,void 0,!0);case n.RenderTarget:var r=new o.a;if(r.generateDepthBuffer=this._generateDepthBuffer,r.generateMipMaps=this.generateMipMaps,r.generateStencilBuffer=this._generateStencilBuffer,r.samplingMode=this.samplingMode,r.type=this.type,this.isCube)t=this._engine.createRenderTargetCubeTexture(this.width,r);else{var s={width:this.width,height:this.height,layers:this.is2DArray?this.depth:void 0};t=this._engine.createRenderTargetTexture(s,r)}return t._swapAndDie(this),void(this.isReady=!0);case n.Depth:var c={bilinearFiltering:this.samplingMode!==a.a.TEXTURE_BILINEAR_SAMPLINGMODE,comparisonFunction:this._comparisonFunction,generateStencil:this._generateStencilBuffer,isCube:this.isCube},l={width:this.width,height:this.height,layers:this.is2DArray?this.depth:void 0};return(t=this._engine.createDepthStencilTexture(l,c))._swapAndDie(this),void(this.isReady=!0);case n.Cube:return void(t=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,function(){t._swapAndDie(i),i.isReady=!0},null,this.format,this._extension));case n.CubeRaw:return(t=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this),void(this.isReady=!0);case n.CubeRawRGBD:return t=this._engine.createRawCubeTexture(null,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),void e._UpdateRGBDAsync(t,this._bufferViewArrayArray,this._sphericalPolynomial,this._lodGenerationScale,this._lodGenerationOffset).then(function(){t._swapAndDie(i),i.isReady=!0});case n.CubePrefiltered:return void((t=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,function(e){e&&e._swapAndDie(i),i.isReady=!0},null,this.format,this._extension))._sphericalPolynomial=this._sphericalPolynomial)}},e.prototype._swapAndDie=function(e){e._webGLTexture=this._webGLTexture,e._isRGBD=this._isRGBD,this._framebuffer&&(e._framebuffer=this._framebuffer),this._depthStencilBuffer&&(e._depthStencilBuffer=this._depthStencilBuffer),e._depthStencilTexture=this._depthStencilTexture,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);var t,i=this._engine.getLoadedTexturesCache();-1!==(t=i.indexOf(this))&&i.splice(t,1),-1===(t=i.indexOf(e))&&i.push(e)},e.prototype.dispose=function(){this._webGLTexture&&(this._references--,0===this._references&&(this._engine._releaseTexture(this),this._webGLTexture=null))},e._UpdateRGBDAsync=function(e,t,i,n,r){throw s.a.WarnImport("environmentTextureTools")},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return l});var n=i(1),r=i(0),o=i(3),a=i(6),s=i(23),c=i(19),l=function(){function e(e,t){void 0===t&&(t=null),this.state="",this.metadata=null,this.reservedDataStore=null,this._doNotSerialize=!1,this._isDisposed=!1,this.animations=new Array,this._ranges={},this.onReady=null,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=r.a.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._sceneRootNodesIndex=-1,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new a.c,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||s.a.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}return e.AddNodeConstructor=function(e,t){this._NodeConstructors[e]=t},e.Construct=function(e,t,i,n){var r=this._NodeConstructors[e];return r?r(t,i,n):null},Object.defineProperty(e.prototype,"doNotSerialize",{get:function(){return!!this._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize},set:function(e){this._doNotSerialize=e},enumerable:!0,configurable:!0}),e.prototype.isDisposed=function(){return this._isDisposed},Object.defineProperty(e.prototype,"parent",{get:function(){return this._parentNode},set:function(e){if(this._parentNode!==e){var t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){var i=this._parentNode._children.indexOf(this);-1!==i&&this._parentNode._children.splice(i,1),e||this._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}},enumerable:!0,configurable:!0}),e.prototype._addToSceneRootNodes=function(){-1===this._sceneRootNodesIndex&&(this._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))},e.prototype._removeFromSceneRootNodes=function(){if(-1!==this._sceneRootNodesIndex){var e=this._scene.rootNodes,t=e.length-1;e[this._sceneRootNodesIndex]=e[t],e[this._sceneRootNodesIndex]._sceneRootNodesIndex=this._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._sceneRootNodesIndex=-1}},Object.defineProperty(e.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!0,configurable:!0}),e.prototype.getClassName=function(){return"Node"},Object.defineProperty(e.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),e.prototype.getScene=function(){return this._scene},e.prototype.getEngine=function(){return this._scene.getEngine()},e.prototype.addBehavior=function(e,t){var i=this;return void 0===t&&(t=!1),-1!==this._behaviors.indexOf(e)?this:(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce(function(){e.attach(i)}):e.attach(this),this._behaviors.push(e),this)},e.prototype.removeBehavior=function(e){var t=this._behaviors.indexOf(e);return-1===t?this:(this._behaviors[t].detach(),this._behaviors.splice(t,1),this)},Object.defineProperty(e.prototype,"behaviors",{get:function(){return this._behaviors},enumerable:!0,configurable:!0}),e.prototype.getBehaviorByName=function(e){for(var t=0,i=this._behaviors;t<i.length;t++){var n=i[t];if(n.name===e)return n}return null},e.prototype.getWorldMatrix=function(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix},e.prototype._getWorldMatrixDeterminant=function(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant},Object.defineProperty(e.prototype,"worldMatrixFromCache",{get:function(){return this._worldMatrix},enumerable:!0,configurable:!0}),e.prototype._initCache=function(){this._cache={},this._cache.parent=void 0},e.prototype.updateCache=function(e){!e&&this.isSynchronized()||(this._cache.parent=this.parent,this._updateCache())},e.prototype._getActionManagerForTrigger=function(e,t){return void 0===t&&(t=!0),this.parent?this.parent._getActionManagerForTrigger(e,!1):null},e.prototype._updateCache=function(e){},e.prototype._isSynchronized=function(){return!0},e.prototype._markSyncedWithParent=function(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)},e.prototype.isSynchronizedWithParent=function(){return!this._parentNode||this._parentUpdateId===this._parentNode._childUpdateId&&this._parentNode.isSynchronized()},e.prototype.isSynchronized=function(){return this._cache.parent!=this._parentNode?(this._cache.parent=this._parentNode,!1):!(this._parentNode&&!this.isSynchronizedWithParent())&&this._isSynchronized()},e.prototype.isReady=function(e){return void 0===e&&(e=!1),this._isReady},e.prototype.isEnabled=function(e){return void 0===e&&(e=!0),!1===e?this._isEnabled:!!this._isEnabled&&this._isParentEnabled},e.prototype._syncParentEnabledState=function(){this._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),this._children&&this._children.forEach(function(e){e._syncParentEnabledState()})},e.prototype.setEnabled=function(e){this._isEnabled=e,this._syncParentEnabledState()},e.prototype.isDescendantOf=function(e){return!!this.parent&&(this.parent===e||this.parent.isDescendantOf(e))},e.prototype._getDescendants=function(e,t,i){if(void 0===t&&(t=!1),this._children)for(var n=0;n<this._children.length;n++){var r=this._children[n];i&&!i(r)||e.push(r),t||r._getDescendants(e,!1,i)}},e.prototype.getDescendants=function(e,t){var i=new Array;return this._getDescendants(i,e,t),i},e.prototype.getChildMeshes=function(e,t){var i=[];return this._getDescendants(i,e,function(e){return(!t||t(e))&&void 0!==e.cullingStrategy}),i},e.prototype.getChildren=function(e,t){return void 0===t&&(t=!0),this.getDescendants(t,e)},e.prototype._setReady=function(e){e!==this._isReady&&(e?(this.onReady&&this.onReady(this),this._isReady=!0):this._isReady=!1)},e.prototype.getAnimationByName=function(e){for(var t=0;t<this.animations.length;t++){var i=this.animations[t];if(i.name===e)return i}return null},e.prototype.createAnimationRange=function(t,i,n){if(!this._ranges[t]){this._ranges[t]=e._AnimationRangeFactory(t,i,n);for(var r=0,o=this.animations.length;r<o;r++)this.animations[r]&&this.animations[r].createRange(t,i,n)}},e.prototype.deleteAnimationRange=function(e,t){void 0===t&&(t=!0);for(var i=0,n=this.animations.length;i<n;i++)this.animations[i]&&this.animations[i].deleteRange(e,t);this._ranges[e]=null},e.prototype.getAnimationRange=function(e){return this._ranges[e]},e.prototype.getAnimationRanges=function(){var e,t=[];for(e in this._ranges)t.push(this._ranges[e]);return t},e.prototype.beginAnimation=function(e,t,i,n){var r=this.getAnimationRange(e);return r?this._scene.beginAnimation(this,r.from,r.to,t,i,n):null},e.prototype.serializeAnimationRanges=function(){var e=[];for(var t in this._ranges){var i=this._ranges[t];if(i){var n={};n.name=t,n.from=i.from,n.to=i.to,e.push(n)}}return e},e.prototype.computeWorldMatrix=function(e){return this._worldMatrix||(this._worldMatrix=r.a.Identity()),this._worldMatrix},e.prototype.dispose=function(e,t){if(void 0===t&&(t=!1),this._isDisposed=!0,!e)for(var i=0,n=this.getDescendants(!0);i<n.length;i++){n[i].dispose(e,t)}this.parent?this.parent=null:this._removeFromSceneRootNodes(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear();for(var r=0,o=this._behaviors;r<o.length;r++){o[r].detach()}this._behaviors=[]},e.ParseAnimationRanges=function(e,t,i){if(t.ranges)for(var n=0;n<t.ranges.length;n++){var r=t.ranges[n];e.createAnimationRange(r.name,r.from,r.to)}},e.prototype.getHierarchyBoundingVectors=function(e,t){var i,n;void 0===e&&(e=!0),void 0===t&&(t=null),this.getScene().incrementRenderId(),this.computeWorldMatrix(!0);if(this.getBoundingInfo&&this.subMeshes){var o=this.getBoundingInfo();i=o.boundingBox.minimumWorld.clone(),n=o.boundingBox.maximumWorld.clone()}else i=new r.e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new r.e(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(e)for(var a=0,s=this.getDescendants(!1);a<s.length;a++){var c=s[a];if(c.computeWorldMatrix(!0),(!t||t(c))&&c.getBoundingInfo&&0!==c.getTotalVertices()){var l=c.getBoundingInfo().boundingBox,u=l.minimumWorld,h=l.maximumWorld;r.e.CheckExtends(u,i,n),r.e.CheckExtends(h,i,n)}}return{min:i,max:n}},e._AnimationRangeFactory=function(e,t,i){throw c.a.WarnImport("AnimationRange")},e._NodeConstructors={},Object(n.c)([Object(o.c)()],e.prototype,"name",void 0),Object(n.c)([Object(o.c)()],e.prototype,"id",void 0),Object(n.c)([Object(o.c)()],e.prototype,"uniqueId",void 0),Object(n.c)([Object(o.c)()],e.prototype,"state",void 0),Object(n.c)([Object(o.c)()],e.prototype,"metadata",void 0),e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return E});var n=i(1),r=i(13),o=i(6),a=i(0),s=i(11),c=i(4),l=i(15),u=i(43),h=i(53),d=i(44),f=i(2),p=i(133),_=i(19),m=i(110),g=i(10),v=i(28),y=i(22),b=function(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=a.e.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1},T=function(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new b,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},E=function(e){function t(i,n){void 0===n&&(n=null);var r=e.call(this,i,n,!1)||this;return r._internalAbstractMeshDataInfo=new T,r.cullingStrategy=t.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,r.onCollideObservable=new o.c,r.onCollisionPositionChangeObservable=new o.c,r.onMaterialChangedObservable=new o.c,r.definedFacingForward=!0,r._occlusionQuery=null,r._renderingGroup=null,r.alphaIndex=Number.MAX_VALUE,r.isVisible=!0,r.isPickable=!0,r.showSubMeshesBoundingBox=!1,r.isBlocker=!1,r.enablePointerMoveEvents=!1,r.renderingGroupId=0,r._material=null,r.outlineColor=g.a.Red(),r.outlineWidth=.02,r.overlayColor=g.a.Red(),r.overlayAlpha=.5,r.useOctreeForRenderingSelection=!0,r.useOctreeForPicking=!0,r.useOctreeForCollisions=!0,r.alwaysSelectAsActiveMesh=!1,r.doNotSyncBoundingInfo=!1,r.actionManager=null,r._meshCollisionData=new p.a,r.ellipsoid=new a.e(.5,1,.5),r.ellipsoidOffset=new a.e(0,0,0),r.edgesWidth=1,r.edgesColor=new g.b(1,0,0,1),r._edgesRenderer=null,r._masterMesh=null,r._boundingInfo=null,r._renderId=0,r._intersectionsInProgress=new Array,r._unIndexed=!1,r._lightSources=new Array,r._waitingData={lods:null,actions:null,freezeWorldMatrix:null},r._bonesTransformMatrices=null,r._transformMatrixTexture=null,r.onRebuildObservable=new o.c,r._onCollisionPositionChange=function(e,t,i){void 0===i&&(i=null),t.subtractToRef(r._meshCollisionData._oldPositionForCollisions,r._meshCollisionData._diffPositionForCollisions),r._meshCollisionData._diffPositionForCollisions.length()>s.a.CollisionsEpsilon&&r.position.addInPlace(r._meshCollisionData._diffPositionForCollisions),i&&r.onCollideObservable.notifyObservers(i),r.onCollisionPositionChangeObservable.notifyObservers(r.position)},r.getScene().addMesh(r),r._resyncLightSources(),r}return Object(n.d)(t,e),Object.defineProperty(t,"BILLBOARDMODE_NONE",{get:function(){return u.a.BILLBOARDMODE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(t,"BILLBOARDMODE_X",{get:function(){return u.a.BILLBOARDMODE_X},enumerable:!0,configurable:!0}),Object.defineProperty(t,"BILLBOARDMODE_Y",{get:function(){return u.a.BILLBOARDMODE_Y},enumerable:!0,configurable:!0}),Object.defineProperty(t,"BILLBOARDMODE_Z",{get:function(){return u.a.BILLBOARDMODE_Z},enumerable:!0,configurable:!0}),Object.defineProperty(t,"BILLBOARDMODE_ALL",{get:function(){return u.a.BILLBOARDMODE_ALL},enumerable:!0,configurable:!0}),Object.defineProperty(t,"BILLBOARDMODE_USE_POSITION",{get:function(){return u.a.BILLBOARDMODE_USE_POSITION},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"facetNb",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetNb},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"partitioningSubdivisions",{get:function(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions},set:function(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"partitioningBBoxRatio",{get:function(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio},set:function(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"mustDepthSortFacets",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort},set:function(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"facetDepthSortFrom",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom},set:function(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isFacetDataEnabled",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled},enumerable:!0,configurable:!0}),t.prototype._updateNonUniformScalingState=function(t){return!!e.prototype._updateNonUniformScalingState.call(this,t)&&(this._markSubMeshesAsMiscDirty(),!0)},Object.defineProperty(t.prototype,"onCollide",{set:function(e){this._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._meshCollisionData._onCollideObserver),this._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onCollisionPositionChange",{set:function(e){this._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._meshCollisionData._onCollisionPositionChangeObserver),this._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visibility",{get:function(){return this._internalAbstractMeshDataInfo._visibility},set:function(e){this._internalAbstractMeshDataInfo._visibility!==e&&(this._internalAbstractMeshDataInfo._visibility=e,this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"material",{get:function(){return this._material},set:function(e){this._material!==e&&(this._material&&this._material.meshMap&&(this._material.meshMap[this.uniqueId]=void 0),this._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&this._unBindEffect())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"receiveShadows",{get:function(){return this._internalAbstractMeshDataInfo._receiveShadows},set:function(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasVertexAlpha",{get:function(){return this._internalAbstractMeshDataInfo._hasVertexAlpha},set:function(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useVertexColors",{get:function(){return this._internalAbstractMeshDataInfo._useVertexColors},set:function(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"computeBonesUsingShaders",{get:function(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders},set:function(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"numBoneInfluencers",{get:function(){return this._internalAbstractMeshDataInfo._numBoneInfluencers},set:function(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"applyFog",{get:function(){return this._internalAbstractMeshDataInfo._applyFog},set:function(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"layerMask",{get:function(){return this._internalAbstractMeshDataInfo._layerMask},set:function(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"collisionMask",{get:function(){return this._meshCollisionData._collisionMask},set:function(e){this._meshCollisionData._collisionMask=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"collisionGroup",{get:function(){return this._meshCollisionData._collisionGroup},set:function(e){this._meshCollisionData._collisionGroup=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"lightSources",{get:function(){return this._lightSources},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_positions",{get:function(){return null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skeleton",{get:function(){return this._internalAbstractMeshDataInfo._skeleton},set:function(e){var 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()},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"AbstractMesh"},t.prototype.toString=function(e){var t="Name: "+this.name+", isInstance: "+("InstancedMesh"!==this.getClassName()?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);var 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},t.prototype._getEffectiveParent=function(){return this._masterMesh&&this.billboardMode!==u.a.BILLBOARDMODE_NONE?this._masterMesh:e.prototype._getEffectiveParent.call(this)},t.prototype._getActionManagerForTrigger=function(e,t){if(void 0===t&&(t=!0),this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null},t.prototype._rebuild=function(){if(this.onRebuildObservable.notifyObservers(this),this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes)for(var e=0,t=this.subMeshes;e<t.length;e++){t[e]._rebuild()}},t.prototype._resyncLightSources=function(){this._lightSources.length=0;for(var e=0,t=this.getScene().lights;e<t.length;e++){var i=t[e];i.isEnabled()&&(i.canAffectMesh(this)&&this._lightSources.push(i))}this._markSubMeshesAsLightDirty()},t.prototype._resyncLightSource=function(e){var t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty()},t.prototype._unBindEffect=function(){for(var e=0,t=this.subMeshes;e<t.length;e++){t[e].setEffect(null)}},t.prototype._removeLightSource=function(e,t){var i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))},t.prototype._markSubMeshesAsDirty=function(e){if(this.subMeshes)for(var t=0,i=this.subMeshes;t<i.length;t++){var n=i[t];n._materialDefines&&e(n._materialDefines)}},t.prototype._markSubMeshesAsLightDirty=function(e){void 0===e&&(e=!1),this._markSubMeshesAsDirty(function(t){return t.markAsLightDirty(e)})},t.prototype._markSubMeshesAsAttributesDirty=function(){this._markSubMeshesAsDirty(function(e){return e.markAsAttributesDirty()})},t.prototype._markSubMeshesAsMiscDirty=function(){if(this.subMeshes)for(var e=0,t=this.subMeshes;e<t.length;e++){var i=t[e].getMaterial();i&&i.markAsDirty(f.a.MATERIAL_MiscDirtyFlag)}},Object.defineProperty(t.prototype,"scaling",{get:function(){return this._scaling},set:function(e){this._scaling=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isBlocked",{get:function(){return!1},enumerable:!0,configurable:!0}),t.prototype.getLOD=function(e){return this},t.prototype.getTotalVertices=function(){return 0},t.prototype.getTotalIndices=function(){return 0},t.prototype.getIndices=function(){return null},t.prototype.getVerticesData=function(e){return null},t.prototype.setVerticesData=function(e,t,i,n){return this},t.prototype.updateVerticesData=function(e,t,i,n){return this},t.prototype.setIndices=function(e,t){return this},t.prototype.isVerticesDataPresent=function(e){return!1},t.prototype.getBoundingInfo=function(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfo||this._updateBoundingInfo(),this._boundingInfo)},t.prototype.normalizeToUnitCube=function(t,i,n){return void 0===t&&(t=!0),void 0===i&&(i=!1),e.prototype.normalizeToUnitCube.call(this,t,i,n)},t.prototype.setBoundingInfo=function(e){return this._boundingInfo=e,this},Object.defineProperty(t.prototype,"useBones",{get:function(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(c.b.MatricesIndicesKind)&&this.isVerticesDataPresent(c.b.MatricesWeightsKind)},enumerable:!0,configurable:!0}),t.prototype._preActivate=function(){},t.prototype._preActivateForIntermediateRendering=function(e){},t.prototype._activate=function(e,t){return this._renderId=e,!0},t.prototype._postActivate=function(){},t.prototype._freeze=function(){},t.prototype._unFreeze=function(){},t.prototype.getWorldMatrix=function(){return this._masterMesh&&this.billboardMode===u.a.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():e.prototype.getWorldMatrix.call(this)},t.prototype._getWorldMatrixDeterminant=function(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():e.prototype._getWorldMatrixDeterminant.call(this)},Object.defineProperty(t.prototype,"isAnInstance",{get:function(){return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasInstances",{get:function(){return!1},enumerable:!0,configurable:!0}),t.prototype.movePOV=function(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this},t.prototype.calcMovePOV=function(e,t,i){var n=new a.a;(this.rotationQuaternion?this.rotationQuaternion:a.b.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(n);var r=a.e.Zero(),o=this.definedFacingForward?-1:1;return a.e.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,n,r),r},t.prototype.rotatePOV=function(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this},t.prototype.calcRotatePOV=function(e,t,i){var n=this.definedFacingForward?1:-1;return new a.e(e*n,t,i*n)},t.prototype.refreshBoundingInfo=function(e){return void 0===e&&(e=!1),this._boundingInfo&&this._boundingInfo.isLocked?this:(this._refreshBoundingInfo(this._getPositionData(e),null),this)},t.prototype._refreshBoundingInfo=function(e,t){if(e){var i=Object(m.a)(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new d.a(i.minimum,i.maximum)}if(this.subMeshes)for(var n=0;n<this.subMeshes.length;n++)this.subMeshes[n].refreshBoundingInfo(e);this._updateBoundingInfo()},t.prototype._getPositionData=function(e){var t=this.getVerticesData(c.b.PositionKind);if(t&&e&&this.skeleton){t=r.b.Slice(t),this._generatePointsArray();var i=this.getVerticesData(c.b.MatricesIndicesKind),n=this.getVerticesData(c.b.MatricesWeightsKind);if(n&&i){var o=this.numBoneInfluencers>4,s=o?this.getVerticesData(c.b.MatricesIndicesExtraKind):null,l=o?this.getVerticesData(c.b.MatricesWeightsExtraKind):null;this.skeleton.prepare();for(var u=this.skeleton.getTransformMatrices(this),h=a.c.Vector3[0],d=a.c.Matrix[0],f=a.c.Matrix[1],p=0,_=0;_<t.length;_+=3,p+=4){var m,g;for(d.reset(),m=0;m<4;m++)(g=n[p+m])>0&&(a.a.FromFloat32ArrayToRefScaled(u,Math.floor(16*i[p+m]),g,f),d.addToSelf(f));if(o)for(m=0;m<4;m++)(g=l[p+m])>0&&(a.a.FromFloat32ArrayToRefScaled(u,Math.floor(16*s[p+m]),g,f),d.addToSelf(f));a.e.TransformCoordinatesFromFloatsToRef(t[_],t[_+1],t[_+2],d,h),h.toArray(t,_),this._positions&&this._positions[_/3].copyFrom(h)}}}return t},t.prototype._updateBoundingInfo=function(){var e=this._effectiveMesh;return this._boundingInfo?this._boundingInfo.update(e.worldMatrixFromCache):this._boundingInfo=new d.a(this.absolutePosition,this.absolutePosition,e.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(e.worldMatrixFromCache),this},t.prototype._updateSubMeshesBoundingInfo=function(e){if(!this.subMeshes)return this;for(var t=this.subMeshes.length,i=0;i<t;i++){var n=this.subMeshes[i];(t>1||!n.IsGlobal)&&n.updateBoundingInfo(e)}return this},t.prototype._afterComputeWorldMatrix=function(){this.doNotSyncBoundingInfo||this._updateBoundingInfo()},Object.defineProperty(t.prototype,"_effectiveMesh",{get:function(){return this.skeleton&&this.skeleton.overrideMesh||this},enumerable:!0,configurable:!0}),t.prototype.isInFrustum=function(e){return null!==this._boundingInfo&&this._boundingInfo.isInFrustum(e,this.cullingStrategy)},t.prototype.isCompletelyInFrustum=function(e){return null!==this._boundingInfo&&this._boundingInfo.isCompletelyInFrustum(e)},t.prototype.intersectsMesh=function(e,t,i){if(void 0===t&&(t=!1),!this._boundingInfo||!e._boundingInfo)return!1;if(this._boundingInfo.intersects(e._boundingInfo,t))return!0;if(i)for(var n=0,r=this.getChildMeshes();n<r.length;n++){if(r[n].intersectsMesh(e,t,!0))return!0}return!1},t.prototype.intersectsPoint=function(e){return!!this._boundingInfo&&this._boundingInfo.intersectsPoint(e)},Object.defineProperty(t.prototype,"checkCollisions",{get:function(){return this._meshCollisionData._checkCollisions},set:function(e){this._meshCollisionData._checkCollisions=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"collider",{get:function(){return this._meshCollisionData._collider},enumerable:!0,configurable:!0}),t.prototype.moveWithCollisions=function(e){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._meshCollisionData._oldPositionForCollisions);var t=this.getScene().collisionCoordinator;return this._meshCollisionData._collider||(this._meshCollisionData._collider=t.createCollider()),this._meshCollisionData._collider._radius=this.ellipsoid,t.getNewPosition(this._meshCollisionData._oldPositionForCollisions,e,this._meshCollisionData._collider,3,this,this._onCollisionPositionChange,this.uniqueId),this},t.prototype._collideForSubMesh=function(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=[];for(var n=e.verticesStart,r=e.verticesStart+e.verticesCount,o=n;o<r;o++)e._lastColliderWorldVertices.push(a.e.TransformCoordinates(this._positions[o],t))}return i._collide(e._trianglePlanes,e._lastColliderWorldVertices,this.getIndices(),e.indexStart,e.indexStart+e.indexCount,e.verticesStart,!!e.getMaterial(),this),this},t.prototype._processCollisionsForSubMeshes=function(e,t){for(var i=this._scene.getCollidingSubMeshCandidates(this,e),n=i.length,r=0;r<n;r++){var o=i.data[r];n>1&&!o._checkCollision(e)||this._collideForSubMesh(o,t,e)}return this},t.prototype._checkCollision=function(e){if(!this._boundingInfo||!this._boundingInfo._checkCollision(e))return this;var t=a.c.Matrix[0],i=a.c.Matrix[1];return a.a.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this},t.prototype._generatePointsArray=function(){return!1},t.prototype.intersects=function(e,t,i){var n=new h.a,r="InstancedLinesMesh"===this.getClassName()||"LinesMesh"===this.getClassName()?this.intersectionThreshold:0,o=this._boundingInfo;if(!(this.subMeshes&&o&&e.intersectsSphere(o.boundingSphere,r)&&e.intersectsBox(o.boundingBox,r)))return n;if(!this._generatePointsArray())return n;for(var s=null,c=this._scene.getIntersectingSubMeshCandidates(this,e),l=c.length,u=0;u<l;u++){var d=c.data[u];if(!(l>1)||d.canIntersects(e)){var f=d.intersects(e,this._positions,this.getIndices(),t,i);if(f&&(t||!s||f.distance<s.distance)&&((s=f).subMeshId=u,t))break}}if(s){var p=this.getWorldMatrix(),_=a.c.Vector3[0],m=a.c.Vector3[1];a.e.TransformCoordinatesToRef(e.origin,p,_),e.direction.scaleToRef(s.distance,m);var g=a.e.TransformNormal(m,p).addInPlace(_);return n.hit=!0,n.distance=a.e.Distance(_,g),n.pickedPoint=g,n.pickedMesh=this,n.bu=s.bu||0,n.bv=s.bv||0,n.faceId=s.faceId,n.subMeshId=s.subMeshId,n}return n},t.prototype.clone=function(e,t,i){return null},t.prototype.releaseSubMeshes=function(){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose();else this.subMeshes=new Array;return this},t.prototype.dispose=function(t,i){var n,r=this;for(void 0===i&&(i=!1),this._scene.useMaterialMeshMap&&this._material&&this._material.meshMap&&(this._material.meshMap[this.uniqueId]=void 0),this.getScene().freeActiveMeshes(),this.getScene().freeRenderingGroups(),void 0!==this.actionManager&&null!==this.actionManager&&(this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),n=0;n<this._intersectionsInProgress.length;n++){var o=this._intersectionsInProgress[n],a=o._intersectionsInProgress.indexOf(this);o._intersectionsInProgress.splice(a,1)}this._intersectionsInProgress=[],this.getScene().lights.forEach(function(e){var t=e.includedOnlyMeshes.indexOf(r);-1!==t&&e.includedOnlyMeshes.splice(t,1),-1!==(t=e.excludedMeshes.indexOf(r))&&e.excludedMeshes.splice(t,1);var i=e.getShadowGenerator();if(i){var n=i.getShadowMap();n&&n.renderList&&-1!==(t=n.renderList.indexOf(r))&&n.renderList.splice(t,1)}}),"InstancedMesh"===this.getClassName()&&"InstancedLinesMesh"===this.getClassName()||this.releaseSubMeshes();var s=this.getScene().getEngine();if(this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,s.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),s.wipeCaches(),this.getScene().removeMesh(this),i&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!t)for(n=0;n<this.getScene().particleSystems.length;n++)this.getScene().particleSystems[n].emitter===this&&(this.getScene().particleSystems[n].dispose(),n--);this._internalAbstractMeshDataInfo._facetData.facetDataEnabled&&this.disableFacetData(),this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this.onRebuildObservable.clear(),e.prototype.dispose.call(this,t,i)},t.prototype.addChild=function(e){return e.setParent(this),this},t.prototype.removeChild=function(e){return e.setParent(null),this},t.prototype._initFacetData=function(){var e=this._internalAbstractMeshDataInfo._facetData;e.facetNormals||(e.facetNormals=new Array),e.facetPositions||(e.facetPositions=new Array),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(var t=0;t<e.facetNb;t++)e.facetNormals[t]=a.e.Zero(),e.facetPositions[t]=a.e.Zero();return e.facetDataEnabled=!0,this},t.prototype.updateFacetData=function(){var e=this._internalAbstractMeshDataInfo._facetData;e.facetDataEnabled||this._initFacetData();var t=this.getVerticesData(c.b.PositionKind),i=this.getIndices(),n=this.getVerticesData(c.b.NormalKind),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{for(var o=!1,s=0;s<i.length;s++)if(i[s]>65535){o=!0;break}e.depthSortedIndices=o?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){var u=this.getScene().activeCamera;e.facetDepthSortFrom=u?u.position:a.e.Zero()}e.depthSortedFacets=[];for(var h=0;h<e.facetNb;h++){var d={ind:3*h,sqDistance:0};e.depthSortedFacets.push(d)}e.invertedMatrix=a.a.Identity(),e.facetDepthSortOrigin=a.e.Zero()}e.bbSize.x=r.maximum.x-r.minimum.x>v.a?r.maximum.x-r.minimum.x:v.a,e.bbSize.y=r.maximum.y-r.minimum.y>v.a?r.maximum.y-r.minimum.y:v.a,e.bbSize.z=r.maximum.z-r.minimum.z>v.a?r.maximum.z-r.minimum.z:v.a;var f=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(f=f>e.bbSize.z?f:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/f),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/f),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/f),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),a.e.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,l.a.ComputeNormals(t,i,n,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);var p=e.depthSortedIndices.length/3|0;for(h=0;h<p;h++){var _=e.depthSortedFacets[h].ind;e.depthSortedIndices[3*h]=i[_],e.depthSortedIndices[3*h+1]=i[_+1],e.depthSortedIndices[3*h+2]=i[_+2]}this.updateIndices(e.depthSortedIndices,void 0,!0)}return this},t.prototype.getFacetLocalNormals=function(){var e=this._internalAbstractMeshDataInfo._facetData;return e.facetNormals||this.updateFacetData(),e.facetNormals},t.prototype.getFacetLocalPositions=function(){var e=this._internalAbstractMeshDataInfo._facetData;return e.facetPositions||this.updateFacetData(),e.facetPositions},t.prototype.getFacetLocalPartitioning=function(){var e=this._internalAbstractMeshDataInfo._facetData;return e.facetPartitioning||this.updateFacetData(),e.facetPartitioning},t.prototype.getFacetPosition=function(e){var t=a.e.Zero();return this.getFacetPositionToRef(e,t),t},t.prototype.getFacetPositionToRef=function(e,t){var i=this.getFacetLocalPositions()[e],n=this.getWorldMatrix();return a.e.TransformCoordinatesToRef(i,n,t),this},t.prototype.getFacetNormal=function(e){var t=a.e.Zero();return this.getFacetNormalToRef(e,t),t},t.prototype.getFacetNormalToRef=function(e,t){var i=this.getFacetLocalNormals()[e];return a.e.TransformNormalToRef(i,this.getWorldMatrix(),t),this},t.prototype.getFacetsAtLocalCoordinates=function(e,t,i){var n=this.getBoundingInfo(),r=this._internalAbstractMeshDataInfo._facetData,o=Math.floor((e-n.minimum.x*r.partitioningBBoxRatio)*r.subDiv.X*r.partitioningBBoxRatio/r.bbSize.x),a=Math.floor((t-n.minimum.y*r.partitioningBBoxRatio)*r.subDiv.Y*r.partitioningBBoxRatio/r.bbSize.y),s=Math.floor((i-n.minimum.z*r.partitioningBBoxRatio)*r.subDiv.Z*r.partitioningBBoxRatio/r.bbSize.z);return o<0||o>r.subDiv.max||a<0||a>r.subDiv.max||s<0||s>r.subDiv.max?null:r.facetPartitioning[o+r.subDiv.max*a+r.subDiv.max*r.subDiv.max*s]},t.prototype.getClosestFacetAtCoordinates=function(e,t,i,n,r,o){void 0===r&&(r=!1),void 0===o&&(o=!0);var s=this.getWorldMatrix(),c=a.c.Matrix[5];s.invertToRef(c);var l=a.c.Vector3[8];a.e.TransformCoordinatesFromFloatsToRef(e,t,i,c,l);var u=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,n,r,o);return n&&a.e.TransformCoordinatesFromFloatsToRef(n.x,n.y,n.z,s,n),u},t.prototype.getClosestFacetAtLocalCoordinates=function(e,t,i,n,r,o){void 0===r&&(r=!1),void 0===o&&(o=!0);var a=null,s=0,c=0,l=0,u=0,h=0,d=0,f=0,p=0,_=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;for(var v,y,b,T=Number.MAX_VALUE,E=T,x=0;x<g.length;x++)y=m[v=g[x]],u=(e-(b=_[v]).x)*y.x+(t-b.y)*y.y+(i-b.z)*y.z,(!r||r&&o&&u>=0||r&&!o&&u<=0)&&(u=y.x*b.x+y.y*b.y+y.z*b.z,h=-(y.x*e+y.y*t+y.z*i-u)/(y.x*y.x+y.y*y.y+y.z*y.z),(E=(s=(d=e+y.x*h)-e)*s+(c=(f=t+y.y*h)-t)*c+(l=(p=i+y.z*h)-i)*l)<T&&(T=E,a=v,n&&(n.x=d,n.y=f,n.z=p)));return a},t.prototype.getFacetDataParameters=function(){return this._internalAbstractMeshDataInfo._facetData.facetParameters},t.prototype.disableFacetData=function(){var e=this._internalAbstractMeshDataInfo._facetData;return e.facetDataEnabled&&(e.facetDataEnabled=!1,e.facetPositions=new Array,e.facetNormals=new Array,e.facetPartitioning=new Array,e.facetParameters=null,e.depthSortedIndices=new Uint32Array(0)),this},t.prototype.updateIndices=function(e,t,i){return void 0===i&&(i=!1),this},t.prototype.createNormals=function(e){var t,i=this.getVerticesData(c.b.PositionKind),n=this.getIndices();return t=this.isVerticesDataPresent(c.b.NormalKind)?this.getVerticesData(c.b.NormalKind):[],l.a.ComputeNormals(i,n,t,{useRightHandedSystem:this.getScene().useRightHandedSystem}),this.setVerticesData(c.b.NormalKind,t,e),this},t.prototype.alignWithNormal=function(e,t){t||(t=y.a.Y);var i=a.c.Vector3[0],n=a.c.Vector3[1];return a.e.CrossToRef(t,e,n),a.e.CrossToRef(e,n,i),this.rotationQuaternion?a.b.RotationQuaternionFromAxisToRef(i,e,n,this.rotationQuaternion):a.e.RotationFromAxisToRef(i,e,n,this.rotation),this},t.prototype._checkOcclusionQuery=function(){return!1},t.prototype.disableEdgesRendering=function(){throw _.a.WarnImport("EdgesRenderer")},t.prototype.enableEdgesRendering=function(e,t){throw _.a.WarnImport("EdgesRenderer")},t.OCCLUSION_TYPE_NONE=0,t.OCCLUSION_TYPE_OPTIMISTIC=1,t.OCCLUSION_TYPE_STRICT=2,t.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,t.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,t.CULLINGSTRATEGY_STANDARD=f.a.MESHES_CULLINGSTRATEGY_STANDARD,t.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=f.a.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,t.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=f.a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION,t.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=f.a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY,t}(u.a)},function(e,t,i){"use strict";i.d(t,"b",function(){return n}),i.d(t,"c",function(){return r}),i.d(t,"a",function(){return o});var n=1/2.2,r=2.2,o=.001},function(e,t,i){"use strict";i.d(t,"a",function(){return f});var n=i(1),r=i(3),o=i(13),a=i(6),s=i(23),c=i(57),l=i(83),u=i(2),h=i(7),d=i(60),f=function(){function e(t,i,n){this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new a.c,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=u.a.ALPHA_COMBINE,this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this._effect=null,this._useUBO=!1,this._fillMode=e.TriangleFillMode,this._cachedDepthWriteState=!1,this._cachedDepthFunctionState=0,this._indexInSceneMaterialArray=-1,this.meshMap=null,this.name=t,this.id=t||o.b.RandomId(),this._scene=i||s.a.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._scene.useRightHandedSystem?this.sideOrientation=e.ClockWiseSideOrientation:this.sideOrientation=e.CounterClockWiseSideOrientation,this._uniformBuffer=new l.a(this._scene.getEngine()),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,n||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={})}return Object.defineProperty(e.prototype,"alpha",{get:function(){return this._alpha},set:function(t){this._alpha!==t&&(this._alpha=t,this.markAsDirty(e.MiscDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"backFaceCulling",{get:function(){return this._backFaceCulling},set:function(t){this._backFaceCulling!==t&&(this._backFaceCulling=t,this.markAsDirty(e.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasRenderTargetTextures",{get:function(){return!1},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onBindObservable",{get:function(){return this._onBindObservable||(this._onBindObservable=new a.c),this._onBindObservable},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onBind",{set:function(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onUnBindObservable",{get:function(){return this._onUnBindObservable||(this._onUnBindObservable=new a.c),this._onUnBindObservable},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"alphaMode",{get:function(){return this._alphaMode},set:function(t){this._alphaMode!==t&&(this._alphaMode=t,this.markAsDirty(e.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"needDepthPrePass",{get:function(){return this._needDepthPrePass},set:function(e){this._needDepthPrePass!==e&&(this._needDepthPrePass=e,this._needDepthPrePass&&(this.checkReadyOnEveryCall=!0))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"fogEnabled",{get:function(){return this._fogEnabled},set:function(t){this._fogEnabled!==t&&(this._fogEnabled=t,this.markAsDirty(e.MiscDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"wireframe",{get:function(){switch(this._fillMode){case e.WireFrameFillMode:case e.LineListDrawMode:case e.LineLoopDrawMode:case e.LineStripDrawMode:return!0}return this._scene.forceWireframe},set:function(t){this.fillMode=t?e.WireFrameFillMode:e.TriangleFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"pointsCloud",{get:function(){switch(this._fillMode){case e.PointFillMode:case e.PointListDrawMode:return!0}return this._scene.forcePointsCloud},set:function(t){this.fillMode=t?e.PointFillMode:e.TriangleFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"fillMode",{get:function(){return this._fillMode},set:function(t){this._fillMode!==t&&(this._fillMode=t,this.markAsDirty(e.MiscDirtyFlag))},enumerable:!0,configurable:!0}),e.prototype.toString=function(e){return"Name: "+this.name},e.prototype.getClassName=function(){return"Material"},Object.defineProperty(e.prototype,"isFrozen",{get:function(){return this.checkReadyOnlyOnce},enumerable:!0,configurable:!0}),e.prototype.freeze=function(){this.markDirty(),this.checkReadyOnlyOnce=!0},e.prototype.unfreeze=function(){this.markDirty(),this.checkReadyOnlyOnce=!1},e.prototype.isReady=function(e,t){return!0},e.prototype.isReadyForSubMesh=function(e,t,i){return!1},e.prototype.getEffect=function(){return this._effect},e.prototype.getScene=function(){return this._scene},e.prototype.needAlphaBlending=function(){return this.alpha<1},e.prototype.needAlphaBlendingForMesh=function(e){return this.needAlphaBlending()||e.visibility<1||e.hasVertexAlpha},e.prototype.needAlphaTesting=function(){return!1},e.prototype.getAlphaTestTexture=function(){return null},e.prototype.markDirty=function(){for(var e=0,t=this.getScene().meshes;e<t.length;e++){var i=t[e];if(i.subMeshes)for(var n=0,r=i.subMeshes;n<r.length;n++){var o=r[n];o.getMaterial()===this&&(o.effect&&(o.effect._wasPreviouslyReady=!1))}}},e.prototype._preBind=function(t,i){void 0===i&&(i=null);var n=this._scene.getEngine(),r=(null==i?this.sideOrientation:i)===e.ClockWiseSideOrientation;return n.enableEffect(t||this._effect),n.setState(this.backFaceCulling,this.zOffset,!1,r),r},e.prototype.bind=function(e,t){},e.prototype.bindForSubMesh=function(e,t,i){},e.prototype.bindOnlyWorldMatrix=function(e){},e.prototype.bindSceneUniformBuffer=function(e,t){t.bindToEffect(e,"Scene")},e.prototype.bindView=function(e){this._useUBO?this.bindSceneUniformBuffer(e,this.getScene().getSceneUniformBuffer()):e.setMatrix("view",this.getScene().getViewMatrix())},e.prototype.bindViewProjection=function(e){this._useUBO?this.bindSceneUniformBuffer(e,this.getScene().getSceneUniformBuffer()):e.setMatrix("viewProjection",this.getScene().getTransformMatrix())},e.prototype._shouldTurnAlphaTestOn=function(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()},e.prototype._afterBind=function(e){if(this._scene._cachedMaterial=this,this._scene._cachedVisibility=e?e.visibility:1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){var t=this._scene.getEngine();this._cachedDepthWriteState=t.getDepthWrite(),t.setDepthWrite(!1)}if(0!==this.depthFunction){t=this._scene.getEngine();this._cachedDepthFunctionState=t.getDepthFunction()||0,t.setDepthFunction(this.depthFunction)}},e.prototype.unbind=function(){(this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction)&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState);this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState)},e.prototype.getActiveTextures=function(){return[]},e.prototype.hasTexture=function(e){return!1},e.prototype.clone=function(e){return null},e.prototype.getBindedMeshes=function(){var e=this;if(this.meshMap){var t=new Array;for(var i in this.meshMap){var n=this.meshMap[i];n&&t.push(n)}return t}return this._scene.meshes.filter(function(t){return t.material===e})},e.prototype.forceCompilation=function(e,t,i,r){var o=this,a=Object(n.a)({clipPlane:!1,useInstances:!1},i),s=new c.a,l=this.getScene(),u=function(){if(o._scene&&o._scene.getEngine()){s._materialDefines&&(s._materialDefines._renderId=-1);var i=l.clipPlane;a.clipPlane&&(l.clipPlane=new d.a(0,0,0,1)),o._storeEffectOnSubMeshes?o.isReadyForSubMesh(e,s,a.useInstances)?t&&t(o):s.effect&&s.effect.getCompilationError()&&s.effect.allFallbacksProcessed()?r&&r(s.effect.getCompilationError()):setTimeout(u,16):o.isReady()?t&&t(o):setTimeout(u,16),a.clipPlane&&(l.clipPlane=i)}};u()},e.prototype.forceCompilationAsync=function(e,t){var i=this;return new Promise(function(n,r){i.forceCompilation(e,function(){n()},t,function(e){r(e)})})},e.prototype.markAsDirty=function(t){this.getScene().blockMaterialDirtyMechanism||(e._DirtyCallbackArray.length=0,t&e.TextureDirtyFlag&&e._DirtyCallbackArray.push(e._TextureDirtyCallBack),t&e.LightDirtyFlag&&e._DirtyCallbackArray.push(e._LightsDirtyCallBack),t&e.FresnelDirtyFlag&&e._DirtyCallbackArray.push(e._FresnelDirtyCallBack),t&e.AttributesDirtyFlag&&e._DirtyCallbackArray.push(e._AttributeDirtyCallBack),t&e.MiscDirtyFlag&&e._DirtyCallbackArray.push(e._MiscDirtyCallBack),e._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(e._RunDirtyCallBacks),this.getScene().resetCachedMaterial())},e.prototype._markAllSubMeshesAsDirty=function(e){if(!this.getScene().blockMaterialDirtyMechanism)for(var t=0,i=this.getScene().meshes;t<i.length;t++){var n=i[t];if(n.subMeshes)for(var r=0,o=n.subMeshes;r<o.length;r++){var a=o[r];a.getMaterial()===this&&(a._materialDefines&&e(a._materialDefines))}}},e.prototype._markAllSubMeshesAsAllDirty=function(){this._markAllSubMeshesAsDirty(e._AllDirtyCallBack)},e.prototype._markAllSubMeshesAsImageProcessingDirty=function(){this._markAllSubMeshesAsDirty(e._ImageProcessingDirtyCallBack)},e.prototype._markAllSubMeshesAsTexturesDirty=function(){this._markAllSubMeshesAsDirty(e._TextureDirtyCallBack)},e.prototype._markAllSubMeshesAsFresnelDirty=function(){this._markAllSubMeshesAsDirty(e._FresnelDirtyCallBack)},e.prototype._markAllSubMeshesAsFresnelAndMiscDirty=function(){this._markAllSubMeshesAsDirty(e._FresnelAndMiscDirtyCallBack)},e.prototype._markAllSubMeshesAsLightsDirty=function(){this._markAllSubMeshesAsDirty(e._LightsDirtyCallBack)},e.prototype._markAllSubMeshesAsAttributesDirty=function(){this._markAllSubMeshesAsDirty(e._AttributeDirtyCallBack)},e.prototype._markAllSubMeshesAsMiscDirty=function(){this._markAllSubMeshesAsDirty(e._MiscDirtyCallBack)},e.prototype._markAllSubMeshesAsTexturesAndMiscDirty=function(){this._markAllSubMeshesAsDirty(e._TextureAndMiscDirtyCallBack)},e.prototype.dispose=function(e,t,i){var n=this.getScene();if(n.stopAnimation(this),n.freeProcessedMaterials(),n.removeMaterial(this),!0!==i)if(this.meshMap)for(var r in this.meshMap){(s=this.meshMap[r])&&(s.material=null,this.releaseVertexArrayObject(s,e))}else for(var o=0,a=n.meshes;o<a.length;o++){var s;(s=a[o]).material!==this||s.sourceMesh||(s.material=null,this.releaseVertexArrayObject(s,e))}this._uniformBuffer.dispose(),e&&this._effect&&(this._storeEffectOnSubMeshes||this._effect.dispose(),this._effect=null),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear()},e.prototype.releaseVertexArrayObject=function(e,t){if(e.geometry){var i=e.geometry;if(this._storeEffectOnSubMeshes)for(var n=0,r=e.subMeshes;n<r.length;n++){var o=r[n];i._releaseVertexArrayObject(o._materialEffect),t&&o._materialEffect&&o._materialEffect.dispose()}else i._releaseVertexArrayObject(this._effect)}},e.prototype.serialize=function(){return r.a.Serialize(this)},e.Parse=function(e,t,i){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return h.a.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else e.customType="BABYLON.StandardMaterial";return o.b.Instantiate(e.customType).Parse(e,t,i)},e.TriangleFillMode=u.a.MATERIAL_TriangleFillMode,e.WireFrameFillMode=u.a.MATERIAL_WireFrameFillMode,e.PointFillMode=u.a.MATERIAL_PointFillMode,e.PointListDrawMode=u.a.MATERIAL_PointListDrawMode,e.LineListDrawMode=u.a.MATERIAL_LineListDrawMode,e.LineLoopDrawMode=u.a.MATERIAL_LineLoopDrawMode,e.LineStripDrawMode=u.a.MATERIAL_LineStripDrawMode,e.TriangleStripDrawMode=u.a.MATERIAL_TriangleStripDrawMode,e.TriangleFanDrawMode=u.a.MATERIAL_TriangleFanDrawMode,e.ClockWiseSideOrientation=u.a.MATERIAL_ClockWiseSideOrientation,e.CounterClockWiseSideOrientation=u.a.MATERIAL_CounterClockWiseSideOrientation,e.TextureDirtyFlag=u.a.MATERIAL_TextureDirtyFlag,e.LightDirtyFlag=u.a.MATERIAL_LightDirtyFlag,e.FresnelDirtyFlag=u.a.MATERIAL_FresnelDirtyFlag,e.AttributesDirtyFlag=u.a.MATERIAL_AttributesDirtyFlag,e.MiscDirtyFlag=u.a.MATERIAL_MiscDirtyFlag,e.AllDirtyFlag=u.a.MATERIAL_AllDirtyFlag,e._AllDirtyCallBack=function(e){return e.markAllAsDirty()},e._ImageProcessingDirtyCallBack=function(e){return e.markAsImageProcessingDirty()},e._TextureDirtyCallBack=function(e){return e.markAsTexturesDirty()},e._FresnelDirtyCallBack=function(e){return e.markAsFresnelDirty()},e._MiscDirtyCallBack=function(e){return e.markAsMiscDirty()},e._LightsDirtyCallBack=function(e){return e.markAsLightDirty()},e._AttributeDirtyCallBack=function(e){return e.markAsAttributesDirty()},e._FresnelAndMiscDirtyCallBack=function(t){e._FresnelDirtyCallBack(t),e._MiscDirtyCallBack(t)},e._TextureAndMiscDirtyCallBack=function(t){e._TextureDirtyCallBack(t),e._MiscDirtyCallBack(t)},e._DirtyCallbackArray=[],e._RunDirtyCallBacks=function(t){for(var i=0,n=e._DirtyCallbackArray;i<n.length;i++){(0,n[i])(t)}},Object(n.c)([Object(r.c)()],e.prototype,"id",void 0),Object(n.c)([Object(r.c)()],e.prototype,"uniqueId",void 0),Object(n.c)([Object(r.c)()],e.prototype,"name",void 0),Object(n.c)([Object(r.c)()],e.prototype,"checkReadyOnEveryCall",void 0),Object(n.c)([Object(r.c)()],e.prototype,"checkReadyOnlyOnce",void 0),Object(n.c)([Object(r.c)()],e.prototype,"state",void 0),Object(n.c)([Object(r.c)("alpha")],e.prototype,"_alpha",void 0),Object(n.c)([Object(r.c)("backFaceCulling")],e.prototype,"_backFaceCulling",void 0),Object(n.c)([Object(r.c)()],e.prototype,"sideOrientation",void 0),Object(n.c)([Object(r.c)("alphaMode")],e.prototype,"_alphaMode",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_needDepthPrePass",void 0),Object(n.c)([Object(r.c)()],e.prototype,"disableDepthWrite",void 0),Object(n.c)([Object(r.c)()],e.prototype,"forceDepthWrite",void 0),Object(n.c)([Object(r.c)()],e.prototype,"depthFunction",void 0),Object(n.c)([Object(r.c)()],e.prototype,"separateCullingPass",void 0),Object(n.c)([Object(r.c)("fogEnabled")],e.prototype,"_fogEnabled",void 0),Object(n.c)([Object(r.c)()],e.prototype,"pointSize",void 0),Object(n.c)([Object(r.c)()],e.prototype,"zOffset",void 0),Object(n.c)([Object(r.c)()],e.prototype,"wireframe",null),Object(n.c)([Object(r.c)()],e.prototype,"pointsCloud",null),Object(n.c)([Object(r.c)()],e.prototype,"fillMode",null),e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return u});var n=i(7),r=i(42),o=i(0),a=i(27),s=i(5),c=i(47),l=i(22);s.a._PhysicsImpostorParser=function(e,t,i){return new u(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};var u=function(){function e(e,t,i,r){var a=this;void 0===i&&(i={mass:0}),this.object=e,this.type=t,this._options=i,this._scene=r,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=o.e.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new o.b,this._tmpQuat2=new o.b,this.beforeStep=function(){a._physicsEngine&&(a.object.translate(a._deltaPosition,-1),a._deltaRotationConjugated&&a.object.rotationQuaternion&&a.object.rotationQuaternion.multiplyToRef(a._deltaRotationConjugated,a.object.rotationQuaternion),a.object.computeWorldMatrix(!1),a.object.parent&&a.object.rotationQuaternion?(a.getParentsRotation(),a._tmpQuat.multiplyToRef(a.object.rotationQuaternion,a._tmpQuat)):a._tmpQuat.copyFrom(a.object.rotationQuaternion||new o.b),a._options.disableBidirectionalTransformation||a.object.rotationQuaternion&&a._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(a,a.object.getAbsolutePosition(),a._tmpQuat),a._onBeforePhysicsStepCallbacks.forEach(function(e){e(a)}))},this.afterStep=function(){a._physicsEngine&&(a._onAfterPhysicsStepCallbacks.forEach(function(e){e(a)}),a._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(a),a.object.parent&&a.object.rotationQuaternion&&(a.getParentsRotation(),a._tmpQuat.conjugateInPlace(),a._tmpQuat.multiplyToRef(a.object.rotationQuaternion,a.object.rotationQuaternion)),a.object.setAbsolutePosition(a.object.position),a._deltaRotation&&a.object.rotationQuaternion&&a.object.rotationQuaternion.multiplyToRef(a._deltaRotation,a.object.rotationQuaternion),a.object.translate(a._deltaPosition,1))},this.onCollideEvent=null,this.onCollide=function(e){if((a._onPhysicsCollideCallbacks.length||a.onCollideEvent)&&a._physicsEngine){var t=a._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(a.onCollideEvent&&a.onCollideEvent(a,t),a._onPhysicsCollideCallbacks.filter(function(e){return-1!==e.otherImpostors.indexOf(t)}).forEach(function(e){e.callback(a,t)}))}},this.object?(this.object.parent&&0!==i.mass&&n.a.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),this._scene&&(this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=o.b.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new o.b),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&n.a.Warn("You must affect impostors to children before affecting impostor to parent.")):n.a.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):n.a.Error("No object was provided. A physics object is obligatory")}return Object.defineProperty(e.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"mass",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0},set:function(e){this.setMass(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"friction",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0},set:function(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"restitution",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0},set:function(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"pressure",{get:function(){if(!this._physicsEngine)return 0;var e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0},set:function(e){if(this._physicsEngine){var t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stiffness",{get:function(){if(!this._physicsEngine)return 0;var e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0},set:function(e){if(this._physicsEngine){var t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"velocityIterations",{get:function(){if(!this._physicsEngine)return 0;var e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0},set:function(e){if(this._physicsEngine){var t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"positionIterations",{get:function(){if(!this._physicsEngine)return 0;var e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0},set:function(e){if(this._physicsEngine){var t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}},enumerable:!0,configurable:!0}),e.prototype._init=function(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))},e.prototype._getPhysicsParent=function(){return this.object.parent instanceof a.a?this.object.parent.physicsImpostor:null},e.prototype.isBodyInitRequired=function(){return this._bodyUpdateRequired||!this._physicsBody&&!this._parent},e.prototype.setScalingUpdated=function(){this.forceUpdate()},e.prototype.forceUpdate=function(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()},Object.defineProperty(e.prototype,"physicsBody",{get:function(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody},set:function(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){return!this._options.ignoreParent&&this._parent?this._parent:null},set:function(e){this._parent=e},enumerable:!0,configurable:!0}),e.prototype.resetUpdateFlags=function(){this._bodyUpdateRequired=!1},e.prototype.getObjectExtendSize=function(){if(this.object.getBoundingInfo){var t=this.object.rotationQuaternion;this.object.rotationQuaternion=e.IDENTITY_QUATERNION,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);var i=this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);return this.object.rotationQuaternion=t,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),i}return e.DEFAULT_OBJECT_SIZE},e.prototype.getObjectCenter=function(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.centerWorld:this.object.position},e.prototype.getParam=function(e){return this._options[e]},e.prototype.setParam=function(e,t){this._options[e]=t,this._bodyUpdateRequired=!0},e.prototype.setMass=function(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)},e.prototype.getLinearVelocity=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):o.e.Zero()},e.prototype.setLinearVelocity=function(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)},e.prototype.getAngularVelocity=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):o.e.Zero()},e.prototype.setAngularVelocity=function(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)},e.prototype.executeNativeFunction=function(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)},e.prototype.registerBeforePhysicsStep=function(e){this._onBeforePhysicsStepCallbacks.push(e)},e.prototype.unregisterBeforePhysicsStep=function(e){var t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):n.a.Warn("Function to remove was not found")},e.prototype.registerAfterPhysicsStep=function(e){this._onAfterPhysicsStepCallbacks.push(e)},e.prototype.unregisterAfterPhysicsStep=function(e){var t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):n.a.Warn("Function to remove was not found")},e.prototype.registerOnPhysicsCollide=function(e,t){var i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})},e.prototype.unregisterOnPhysicsCollide=function(e,t){var i=e instanceof Array?e:[e],r=-1;this._onPhysicsCollideCallbacks.some(function(e,n){if(e.callback===t&&e.otherImpostors.length===i.length){var o=e.otherImpostors.every(function(e){return i.indexOf(e)>-1});return o&&(r=n),o}return!1})?this._onPhysicsCollideCallbacks.splice(r,1):n.a.Warn("Function to remove was not found")},e.prototype.getParentsRotation=function(){var e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):o.b.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat},e.prototype.applyForce=function(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this},e.prototype.applyImpulse=function(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this},e.prototype.createJoint=function(e,t,i){var n=new c.e(t,i);return this.addJoint(e,n),this},e.prototype.addJoint=function(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this},e.prototype.addAnchor=function(e,t,i,n,r){if(!this._physicsEngine)return this;var o=this._physicsEngine.getPhysicsPlugin();return o.appendAnchor?(this._physicsEngine&&o.appendAnchor(this,e,t,i,n,r),this):this},e.prototype.addHook=function(e,t,i,n){if(!this._physicsEngine)return this;var r=this._physicsEngine.getPhysicsPlugin();return r.appendAnchor?(this._physicsEngine&&r.appendHook(this,e,t,i,n),this):this},e.prototype.sleep=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this},e.prototype.wakeUp=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this},e.prototype.clone=function(t){return t?new e(t,this.type,this._options,this._scene):null},e.prototype.dispose=function(){var e=this;this._physicsEngine&&(this._joints.forEach(function(t){e._physicsEngine&&e._physicsEngine.removeJoint(e,t.otherImpostor,t.joint)}),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)},e.prototype.setDeltaPosition=function(e){this._deltaPosition.copyFrom(e)},e.prototype.setDeltaRotation=function(e){this._deltaRotation||(this._deltaRotation=new o.b),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()},e.prototype.getBoxSizeToRef=function(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this},e.prototype.getRadius=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0},e.prototype.syncBoneWithImpostor=function(t,i,n,r,o){var a=e._tmpVecs[0],s=this.object;if(s.rotationQuaternion)if(o){var c=e._tmpQuat;s.rotationQuaternion.multiplyToRef(o,c),t.setRotationQuaternion(c,l.b.WORLD,i)}else t.setRotationQuaternion(s.rotationQuaternion,l.b.WORLD,i);a.x=0,a.y=0,a.z=0,n&&(a.x=n.x,a.y=n.y,a.z=n.z,t.getDirectionToRef(a,i,a),null==r&&(r=n.length()),a.x*=r,a.y*=r,a.z*=r),t.getParent()?(a.addInPlace(s.getAbsolutePosition()),t.setAbsolutePosition(a,i)):(i.setAbsolutePosition(s.getAbsolutePosition()),i.position.x-=a.x,i.position.y-=a.y,i.position.z-=a.z)},e.prototype.syncImpostorWithBone=function(t,i,n,r,o,a){var s=this.object;if(s.rotationQuaternion)if(o){var c=e._tmpQuat;t.getRotationQuaternionToRef(l.b.WORLD,i,c),c.multiplyToRef(o,s.rotationQuaternion)}else t.getRotationQuaternionToRef(l.b.WORLD,i,s.rotationQuaternion);var u=e._tmpVecs[0],h=e._tmpVecs[1];a||((a=e._tmpVecs[2]).x=0,a.y=1,a.z=0),t.getDirectionToRef(a,i,h),t.getAbsolutePositionToRef(i,u),null==r&&n&&(r=n.length()),null!=r&&(u.x+=h.x*r,u.y+=h.y*r,u.z+=h.z*r),s.setAbsolutePosition(u)},e.DEFAULT_OBJECT_SIZE=new o.e(1,1,1),e.IDENTITY_QUATERNION=o.b.Identity(),e._tmpVecs=r.a.BuildArray(3,o.e.Zero),e._tmpQuat=o.b.Identity(),e.NoImpostor=0,e.SphereImpostor=1,e.BoxImpostor=2,e.PlaneImpostor=3,e.MeshImpostor=4,e.CapsuleImpostor=6,e.CylinderImpostor=7,e.ParticleImpostor=8,e.HeightmapImpostor=9,e.ConvexHullImpostor=10,e.CustomImpostor=100,e.RopeImpostor=101,e.ClothImpostor=102,e.SoftbodyImpostor=103,e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return y});var n=i(23),r=i(8),o=i(19),a=i(6),s=i(127),c=i(128),l=i(129),u=i(2),h=i(25),d=i(7),f=i(38),p=i(109),_=i(84),m=i(130),g=i(70),v=function(){},y=function(){function e(t,i,n,r){var o=this;void 0===r&&(r=!1),this.forcePOTTextures=!1,this.isFullscreen=!1,this.cullBackFaces=!0,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this.validateShaderPrograms=!1,this.useReverseDepthBuffer=!1,this.disableUniformBuffers=!1,this._uniformBuffers=new Array,this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._renderingQueueLaunched=!1,this._activeRenderLoops=new Array,this.onContextLostObservable=new a.c,this.onContextRestoredObservable=new a.c,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new s.a,this._stencilState=new c.a,this._alphaState=new l.a,this._alphaMode=u.a.ALPHA_ADD,this._alphaEquation=u.a.ALPHA_DISABLE,this._internalTexturesCache=new Array,this._activeChannel=0,this._currentTextureChannel=-1,this._boundTexturesCache={},this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=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._activeRequests=new Array,this._texturesSupported=new Array,this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new a.c,this._viewportCached={x:0,y:0,z:0,w:0},this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._getDepthStencilBuffer=function(e,t,i,n,r,a){var s=o._gl,c=s.createRenderbuffer();return s.bindRenderbuffer(s.RENDERBUFFER,c),i>1&&s.renderbufferStorageMultisample?s.renderbufferStorageMultisample(s.RENDERBUFFER,i,r,e,t):s.renderbufferStorage(s.RENDERBUFFER,n,e,t),s.framebufferRenderbuffer(s.FRAMEBUFFER,a,s.RENDERBUFFER,c),s.bindRenderbuffer(s.RENDERBUFFER,null),c},this._boundUniforms={};var h=null;if(t){if(n=n||{},t.getContext){if(h=t,this._renderingCanvas=h,null!=i&&(n.antialias=i),void 0===n.deterministicLockstep&&(n.deterministicLockstep=!1),void 0===n.lockstepMaxSteps&&(n.lockstepMaxSteps=4),void 0===n.timeStep&&(n.timeStep=1/60),void 0===n.preserveDrawingBuffer&&(n.preserveDrawingBuffer=!1),void 0===n.audioEngine&&(n.audioEngine=!0),void 0===n.stencil&&(n.stencil=!0),!1===n.premultipliedAlpha&&(this.premultipliedAlpha=!1),this._doNotHandleContextLost=!!n.doNotHandleContextLost,navigator&&navigator.userAgent)for(var _=navigator.userAgent,m=0,g=e.ExceptionList;m<g.length;m++){var y=g[m],b=y.key,T=y.targets;if(new RegExp(b).test(_)){if(y.capture&&y.captureConstraint){var E=y.capture,x=y.captureConstraint,P=new RegExp(E).exec(_);if(P&&P.length>0)if(parseInt(P[P.length-1])>=x)continue}for(var A=0,S=T;A<S.length;A++){switch(S[A]){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0}}}}if(this._doNotHandleContextLost||(this._onContextLost=function(e){e.preventDefault(),o._contextWasLost=!0,d.a.Warn("WebGL context lost."),o.onContextLostObservable.notifyObservers(o)},this._onContextRestored=function(){setTimeout(function(){o._initGLContext(),o._rebuildEffects(),o._rebuildInternalTextures(),o._rebuildBuffers(),o.wipeCaches(!0),d.a.Warn("WebGL context successfully restored."),o.onContextRestoredObservable.notifyObservers(o),o._contextWasLost=!1},0)},h.addEventListener("webglcontextlost",this._onContextLost,!1),h.addEventListener("webglcontextrestored",this._onContextRestored,!1),n.powerPreference="high-performance"),!n.disableWebGL2Support)try{this._gl=h.getContext("webgl2",n)||h.getContext("experimental-webgl2",n),this._gl&&(this._webGLVersion=2,this._gl.deleteQuery||(this._webGLVersion=1))}catch(e){}if(!this._gl){if(!h)throw new Error("The provided canvas is null or undefined.");try{this._gl=h.getContext("webgl",n)||h.getContext("experimental-webgl",n)}catch(e){throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=t,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample&&(this._webGLVersion=2);var C=this._gl.getContextAttributes();C&&(n.stencil=C.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==n.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=n.useHighPrecisionFloats);var R=f.a.IsWindowObjectExist()&&window.devicePixelRatio||1,O=n.limitDeviceRatio||R;this._hardwareScalingLevel=r?1/Math.min(O,R):1,this.resize(),this._isStencilEnable=!!n.stencil,this._initGLContext();for(var M=0;M<this._caps.maxVertexAttribs;M++)this._currentBufferPointers[M]=new v;this.webGLVersion>1&&(this._shaderProcessor=new p.a),this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._creationOptions=n,console.log("Babylon.js v"+e.Version+" - "+this.description)}}return Object.defineProperty(e,"NpmPackage",{get:function(){return"babylonjs@4.1.0"},enumerable:!0,configurable:!0}),Object.defineProperty(e,"Version",{get:function(){return"4.1.0"},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"description",{get:function(){var e="WebGL"+this.webGLVersion;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"ShadersRepository",{get:function(){return r.a.ShadersRepository},set:function(e){r.a.ShadersRepository=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"supportsUniformBuffers",{get:function(){return this.webGLVersion>1&&!this.disableUniformBuffers},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_shouldUseHighPrecisionShader",{get:function(){return!(!this._caps.highPrecisionShaderSupported||!this._highPrecisionShadersAllowed)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"needPOTTextures",{get:function(){return this._webGLVersion<2||this.forcePOTTextures},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"doNotHandleContextLost",{get:function(){return this._doNotHandleContextLost},set:function(e){this._doNotHandleContextLost=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_supportsHardwareTextureRescaling",{get:function(){return!1},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"framebufferDimensionsObject",{set:function(e){this._framebufferDimensionsObject=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"texturesSupported",{get:function(){return this._texturesSupported},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentViewport",{get:function(){return this._cachedViewport},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"emptyTexture",{get:function(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,u.a.TEXTUREFORMAT_RGBA,!1,!1,u.a.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"emptyTexture3D",{get:function(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,u.a.TEXTUREFORMAT_RGBA,!1,!1,u.a.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture3D},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"emptyTexture2DArray",{get:function(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,u.a.TEXTUREFORMAT_RGBA,!1,!1,u.a.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture2DArray},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"emptyCubeTexture",{get:function(){if(!this._emptyCubeTexture){var e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,u.a.TEXTUREFORMAT_RGBA,u.a.TEXTURETYPE_UNSIGNED_INT,!1,!1,u.a.TEXTURE_NEAREST_SAMPLINGMODE)}return this._emptyCubeTexture},enumerable:!0,configurable:!0}),e.prototype._rebuildInternalTextures=function(){for(var e=0,t=this._internalTexturesCache.slice();e<t.length;e++){t[e]._rebuild()}},e.prototype._rebuildEffects=function(){for(var e in this._compiledEffects){this._compiledEffects[e]._prepareEffect()}r.a.ResetCache()},e.prototype.areAllEffectsReady=function(){for(var e in this._compiledEffects){if(!this._compiledEffects[e].isReady())return!1}return!0},e.prototype._rebuildBuffers=function(){for(var e=0,t=this._uniformBuffers;e<t.length;e++){t[e]._rebuild()}},e.prototype._initGLContext=function(){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),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile"),standardDerivatives:this._webGLVersion>1||null!==this._gl.getExtension("OES_standard_derivatives"),maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),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||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_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")),blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1},this._glVersion=this._gl.getParameter(this._gl.VERSION);var e=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=e&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor="Unknown vendor"),this._glRenderer||(this._glRenderer="Unknown renderer"),this._gl.HALF_FLOAT_OES=36193,34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(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),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._webGLVersion>1&&(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._gl.getParameter(this._gl.MAX_SAMPLES);else{var t=this._gl.getExtension("WEBGL_draw_buffers");if(null!==t){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=t.drawBuffersWEBGL.bind(t),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(var i=0;i<16;i++)this._gl["COLOR_ATTACHMENT"+i+"_WEBGL"]=t["COLOR_ATTACHMENT"+i+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{var n=this._gl.getExtension("WEBGL_depth_texture");null!=n&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=n.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{var r=this._gl.getExtension("OES_vertex_array_object");null!=r&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=r.createVertexArrayOES.bind(r),this._gl.bindVertexArray=r.bindVertexArrayOES.bind(r),this._gl.deleteVertexArray=r.deleteVertexArrayOES.bind(r))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{var o=this._gl.getExtension("ANGLE_instanced_arrays");null!=o?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=o.drawArraysInstancedANGLE.bind(o),this._gl.drawElementsInstanced=o.drawElementsInstancedANGLE.bind(o),this._gl.vertexAttribDivisor=o.vertexAttribDivisorANGLE.bind(o)):this._caps.instancedArrays=!1}if(this._caps.astc&&this.texturesSupported.push("-astc.ktx"),this._caps.s3tc&&this.texturesSupported.push("-dxt.ktx"),this._caps.pvrtc&&this.texturesSupported.push("-pvrtc.ktx"),this._caps.etc2&&this.texturesSupported.push("-etc2.ktx"),this._caps.etc1&&this.texturesSupported.push("-etc1.ktx"),this._gl.getShaderPrecisionFormat){var a=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),s=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);a&&s&&(this._caps.highPrecisionShaderSupported=0!==a.precision&&0!==s.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{var c=this._gl.getExtension("EXT_blend_minmax");null!=c&&(this._caps.blendMinMax=!0,this._gl.MAX=c.MAX_EXT,this._gl.MIN=c.MIN_EXT)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(var l=0;l<this._maxSimultaneousTextures;l++)this._nextFreeTextureSlots.push(l)},Object.defineProperty(e.prototype,"webGLVersion",{get:function(){return this._webGLVersion},enumerable:!0,configurable:!0}),e.prototype.getClassName=function(){return"ThinEngine"},Object.defineProperty(e.prototype,"isStencilEnable",{get:function(){return this._isStencilEnable},enumerable:!0,configurable:!0}),e.prototype._prepareWorkingCanvas=function(){if(!this._workingCanvas){this._workingCanvas=g.a.CreateCanvas(1,1);var e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}},e.prototype.resetTextureCache=function(){for(var e in this._boundTexturesCache)this._boundTexturesCache.hasOwnProperty(e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1},e.prototype.getGlInfo=function(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}},e.prototype.setHardwareScalingLevel=function(e){this._hardwareScalingLevel=e,this.resize()},e.prototype.getHardwareScalingLevel=function(){return this._hardwareScalingLevel},e.prototype.getLoadedTexturesCache=function(){return this._internalTexturesCache},e.prototype.getCaps=function(){return this._caps},e.prototype.stopRenderLoop=function(e){if(e){var t=this._activeRenderLoops.indexOf(e);t>=0&&this._activeRenderLoops.splice(t,1)}else this._activeRenderLoops=[]},e.prototype._renderLoop=function(){if(!this._contextWasLost){var e=!0;if(!this.renderEvenInBackground&&this._windowIsBackground&&(e=!1),e){this.beginFrame();for(var t=0;t<this._activeRenderLoops.length;t++){(0,this._activeRenderLoops[t])()}this.endFrame()}}this._activeRenderLoops.length>0?this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1},e.prototype.getRenderingCanvas=function(){return this._renderingCanvas},e.prototype.getHostWindow=function(){return f.a.IsWindowObjectExist()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null},e.prototype.getRenderWidth=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth},e.prototype.getRenderHeight=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight},e.prototype._queueNewFrame=function(t,i){return e.QueueNewFrame(t,i)},e.prototype.runRenderLoop=function(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._boundRenderFunction=this._renderLoop.bind(this),this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))},e.prototype.clear=function(e,t,i,n){void 0===n&&(n=!1),this.applyStates();var r=0;t&&e&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),r|=this._gl.COLOR_BUFFER_BIT),i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GREATER,this._gl.clearDepth(0)):this._gl.clearDepth(1),r|=this._gl.DEPTH_BUFFER_BIT),n&&(this._gl.clearStencil(0),r|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(r)},e.prototype._viewport=function(e,t,i,n){e===this._viewportCached.x&&t===this._viewportCached.y&&i===this._viewportCached.z&&n===this._viewportCached.w||(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=n,this._gl.viewport(e,t,i,n))},e.prototype.setViewport=function(e,t,i){var n=t||this.getRenderWidth(),r=i||this.getRenderHeight(),o=e.x||0,a=e.y||0;this._cachedViewport=e,this._viewport(o*n,a*r,n*e.width,r*e.height)},e.prototype.beginFrame=function(){},e.prototype.endFrame=function(){this._badOS&&this.flushFramebuffer()},e.prototype.resize=function(){var e,t;f.a.IsWindowObjectExist()?(e=this._renderingCanvas?this._renderingCanvas.clientWidth:window.innerWidth,t=this._renderingCanvas?this._renderingCanvas.clientHeight:window.innerHeight):(e=this._renderingCanvas?this._renderingCanvas.width:100,t=this._renderingCanvas?this._renderingCanvas.height:100),this.setSize(e/this._hardwareScalingLevel,t/this._hardwareScalingLevel)},e.prototype.setSize=function(e,t){this._renderingCanvas&&(e|=0,t|=0,this._renderingCanvas.width===e&&this._renderingCanvas.height===t||(this._renderingCanvas.width=e,this._renderingCanvas.height=t))},e.prototype.bindFramebuffer=function(e,t,i,n,r,o,a){void 0===t&&(t=0),void 0===o&&(o=0),void 0===a&&(a=0),this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(e._MSAAFramebuffer?e._MSAAFramebuffer:e._framebuffer);var s=this._gl;e.is2DArray?s.framebufferTextureLayer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,e._webGLTexture,o,a):e.isCube&&s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_CUBE_MAP_POSITIVE_X+t,e._webGLTexture,o);var c=e._depthStencilTexture;if(c){var l=c._generateStencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT;e.is2DArray?s.framebufferTextureLayer(s.FRAMEBUFFER,l,c._webGLTexture,o,a):e.isCube?s.framebufferTexture2D(s.FRAMEBUFFER,l,s.TEXTURE_CUBE_MAP_POSITIVE_X+t,c._webGLTexture,o):s.framebufferTexture2D(s.FRAMEBUFFER,l,s.TEXTURE_2D,c._webGLTexture,o)}this._cachedViewport&&!r?this.setViewport(this._cachedViewport,i,n):(i||(i=e.width,o&&(i/=Math.pow(2,o))),n||(n=e.height,o&&(n/=Math.pow(2,o))),this._viewport(0,0,i,n)),this.wipeCaches()},e.prototype._bindUnboundFramebuffer=function(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)},e.prototype.unBindFramebuffer=function(e,t,i){void 0===t&&(t=!1),this._currentRenderTarget=null;var n=this._gl;e._MSAAFramebuffer&&(n.bindFramebuffer(n.READ_FRAMEBUFFER,e._MSAAFramebuffer),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,e._framebuffer),n.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,n.COLOR_BUFFER_BIT,n.NEAREST)),!e.generateMipMaps||t||e.isCube||(this._bindTextureDirectly(n.TEXTURE_2D,e,!0),n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null)),i&&(e._MSAAFramebuffer&&this._bindUnboundFramebuffer(e._framebuffer),i()),this._bindUnboundFramebuffer(null)},e.prototype.flushFramebuffer=function(){this._gl.flush()},e.prototype.restoreDefaultFramebuffer=function(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()},e.prototype._resetVertexBufferBinding=function(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null},e.prototype.createVertexBuffer=function(e){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)},e.prototype._createVertexBuffer=function(e,t){var i=this._gl.createBuffer();if(!i)throw new Error("Unable to create vertex buffer");var n=new _.a(i);return this.bindArrayBuffer(n),e instanceof Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.STATIC_DRAW),this._resetVertexBufferBinding(),n.references=1,n},e.prototype.createDynamicVertexBuffer=function(e){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)},e.prototype._resetIndexBufferBinding=function(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null},e.prototype.createIndexBuffer=function(e,t){var i=this._gl.createBuffer(),n=new _.a(i);if(!i)throw new Error("Unable to create index buffer");this.bindIndexBuffer(n);var r=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),n.references=1,n.is32Bits=4===r.BYTES_PER_ELEMENT,n},e.prototype._normalizeIndexData=function(e){if(e instanceof Uint16Array)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(var t=0;t<e.length;t++)if(e[t]>=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)},e.prototype.bindArrayBuffer=function(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(e,this._gl.ARRAY_BUFFER)},e.prototype.bindUniformBlock=function(e,t,i){var n=e.program,r=this._gl.getUniformBlockIndex(n,t);this._gl.uniformBlockBinding(n,r,i)},e.prototype.bindIndexBuffer=function(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)},e.prototype.bindBuffer=function(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)},e.prototype.updateArrayBuffer=function(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)},e.prototype._vertexAttribPointer=function(e,t,i,n,r,o,a){var s=this._currentBufferPointers[t],c=!1;s.active?(s.buffer!==e&&(s.buffer=e,c=!0),s.size!==i&&(s.size=i,c=!0),s.type!==n&&(s.type=n,c=!0),s.normalized!==r&&(s.normalized=r,c=!0),s.stride!==o&&(s.stride=o,c=!0),s.offset!==a&&(s.offset=a,c=!0)):(c=!0,s.active=!0,s.index=t,s.size=i,s.type=n,s.normalized=r,s.stride=o,s.offset=a,s.buffer=e),(c||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),this._gl.vertexAttribPointer(t,i,n,r,o,a))},e.prototype._bindIndexBufferWithCache=function(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)},e.prototype._bindVertexBuffersAttributes=function(e,t){var i=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var n=0;n<i.length;n++){var r=t.getAttributeLocation(n);if(r>=0){var o=e[i[n]];if(!o)continue;this._gl.enableVertexAttribArray(r),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[r]=!0);var a=o.getBuffer();a&&(this._vertexAttribPointer(a,r,o.getSize(),o.type,o.normalized,o.byteStride,o.byteOffset),o.getIsInstanced()&&(this._gl.vertexAttribDivisor(r,o.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(r),this._currentInstanceBuffers.push(a))))}}},e.prototype.recordVertexArrayObject=function(e,t,i){var n=this._gl.createVertexArray();return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(n),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),n},e.prototype.bindVertexArrayObject=function(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)},e.prototype.bindBuffersDirectly=function(e,t,i,n,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;var o=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var a=0,s=0;s<o;s++)if(s<i.length){var c=r.getAttributeLocation(s);c>=0&&(this._gl.enableVertexAttribArray(c),this._vertexAttribArraysEnabled[c]=!0,this._vertexAttribPointer(e,c,i[s],this._gl.FLOAT,!1,n,a)),a+=4*i[s]}}this._bindIndexBufferWithCache(t)},e.prototype._unbindVertexArrayObject=function(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))},e.prototype.bindBuffers=function(e,t,i){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i)),this._bindIndexBufferWithCache(t)},e.prototype.unbindInstanceAttributes=function(){for(var e,t=0,i=this._currentInstanceLocations.length;t<i;t++){var n=this._currentInstanceBuffers[t];e!=n&&n.references&&(e=n,this.bindArrayBuffer(n));var r=this._currentInstanceLocations[t];this._gl.vertexAttribDivisor(r,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0},e.prototype.releaseVertexArrayObject=function(e){this._gl.deleteVertexArray(e)},e.prototype._releaseBuffer=function(e){return e.references--,0===e.references&&(this._deleteBuffer(e),!0)},e.prototype._deleteBuffer=function(e){this._gl.deleteBuffer(e.underlyingResource)},e.prototype.updateAndBindInstancesBuffer=function(e,t,i){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),void 0!==i[0].index)this.bindInstancesBuffer(e,i,!0);else for(var n=0;n<4;n++){var r=i[n];this._vertexAttribArraysEnabled[r]||(this._gl.enableVertexAttribArray(r),this._vertexAttribArraysEnabled[r]=!0),this._vertexAttribPointer(e,r,4,this._gl.FLOAT,!1,64,16*n),this._gl.vertexAttribDivisor(r,1),this._currentInstanceLocations.push(r),this._currentInstanceBuffers.push(e)}},e.prototype.bindInstancesBuffer=function(e,t,i){void 0===i&&(i=!0),this.bindArrayBuffer(e);var n=0;if(i)for(var r=0;r<t.length;r++){n+=4*(o=t[r]).attributeSize}for(r=0;r<t.length;r++){var o;void 0===(o=t[r]).index&&(o.index=this._currentEffect.getAttributeLocationByName(o.attributeName)),this._vertexAttribArraysEnabled[o.index]||(this._gl.enableVertexAttribArray(o.index),this._vertexAttribArraysEnabled[o.index]=!0),this._vertexAttribPointer(e,o.index,o.attributeSize,o.attributeType||this._gl.FLOAT,o.normalized||!1,n,o.offset),this._gl.vertexAttribDivisor(o.index,void 0===o.divisor?1:o.divisor),this._currentInstanceLocations.push(o.index),this._currentInstanceBuffers.push(e)}},e.prototype.disableInstanceAttributeByName=function(e){if(this._currentEffect){var t=this._currentEffect.getAttributeLocationByName(e);this.disableInstanceAttribute(t)}},e.prototype.disableInstanceAttribute=function(e){for(var t,i=!1;-1!==(t=this._currentInstanceLocations.indexOf(e));)this._currentInstanceLocations.splice(t,1),this._currentInstanceBuffers.splice(t,1),i=!0,t=this._currentInstanceLocations.indexOf(e);i&&(this._gl.vertexAttribDivisor(e,0),this.disableAttributeByIndex(e))},e.prototype.disableAttributeByIndex=function(e){this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1},e.prototype.draw=function(e,t,i,n){this.drawElementsType(e?u.a.MATERIAL_TriangleFillMode:u.a.MATERIAL_WireFrameFillMode,t,i,n)},e.prototype.drawPointClouds=function(e,t,i){this.drawArraysType(u.a.MATERIAL_PointFillMode,e,t,i)},e.prototype.drawUnIndexed=function(e,t,i,n){this.drawArraysType(e?u.a.MATERIAL_TriangleFillMode:u.a.MATERIAL_WireFrameFillMode,t,i,n)},e.prototype.drawElementsType=function(e,t,i,n){this.applyStates(),this._reportDrawCall();var r=this._drawMode(e),o=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,a=this._uintIndicesCurrentlySet?4:2;n?this._gl.drawElementsInstanced(r,i,o,t*a,n):this._gl.drawElements(r,i,o,t*a)},e.prototype.drawArraysType=function(e,t,i,n){this.applyStates(),this._reportDrawCall();var r=this._drawMode(e);n?this._gl.drawArraysInstanced(r,t,i,n):this._gl.drawArrays(r,t,i)},e.prototype._drawMode=function(e){switch(e){case u.a.MATERIAL_TriangleFillMode:return this._gl.TRIANGLES;case u.a.MATERIAL_PointFillMode:return this._gl.POINTS;case u.a.MATERIAL_WireFrameFillMode:return this._gl.LINES;case u.a.MATERIAL_PointListDrawMode:return this._gl.POINTS;case u.a.MATERIAL_LineListDrawMode:return this._gl.LINES;case u.a.MATERIAL_LineLoopDrawMode:return this._gl.LINE_LOOP;case u.a.MATERIAL_LineStripDrawMode:return this._gl.LINE_STRIP;case u.a.MATERIAL_TriangleStripDrawMode:return this._gl.TRIANGLE_STRIP;case u.a.MATERIAL_TriangleFanDrawMode:return this._gl.TRIANGLE_FAN;default:return this._gl.TRIANGLES}},e.prototype._reportDrawCall=function(){},e.prototype._releaseEffect=function(e){this._compiledEffects[e._key]&&(delete this._compiledEffects[e._key],this._deletePipelineContext(e.getPipelineContext()))},e.prototype._deletePipelineContext=function(e){var t=e;t&&t.program&&(t.program.__SPECTOR_rebuildProgram=null,this._gl.deleteProgram(t.program))},e.prototype.createEffect=function(e,t,i,n,o,a,s,c,l){var u=(e.vertexElement||e.vertex||e)+"+"+(e.fragmentElement||e.fragment||e)+"@"+(o||t.defines);if(this._compiledEffects[u]){var h=this._compiledEffects[u];return s&&h.isReady()&&s(h),h}var d=new r.a(e,t,i,n,this,o,a,s,c,l);return d._key=u,this._compiledEffects[u]=d,d},e._ConcatenateShader=function(e,t,i){return void 0===i&&(i=""),i+(t?t+"\n":"")+e},e.prototype._compileShader=function(t,i,n,r){return this._compileRawShader(e._ConcatenateShader(t,n,r),i)},e.prototype._compileRawShader=function(e,t){var i=this._gl,n=i.createShader("vertex"===t?i.VERTEX_SHADER:i.FRAGMENT_SHADER);if(!n)throw new Error("Something went wrong while compile the shader.");return i.shaderSource(n,e),i.compileShader(n),n},e.prototype.createRawShaderProgram=function(e,t,i,n,r){void 0===r&&(r=null),n=n||this._gl;var o=this._compileRawShader(t,"vertex"),a=this._compileRawShader(i,"fragment");return this._createShaderProgram(e,o,a,n,r)},e.prototype.createShaderProgram=function(e,t,i,n,r,o){void 0===o&&(o=null),r=r||this._gl;var a=this._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"",s=this._compileShader(t,"vertex",n,a),c=this._compileShader(i,"fragment",n,a);return this._createShaderProgram(e,s,c,r,o)},e.prototype.createPipelineContext=function(){var e=new m.a;return e.engine=this,this._caps.parallelShaderCompile&&(e.isParallelCompiled=!0),e},e.prototype._createShaderProgram=function(e,t,i,n,r){void 0===r&&(r=null);var o=n.createProgram();if(e.program=o,!o)throw new Error("Unable to create program");return n.attachShader(o,t),n.attachShader(o,i),n.linkProgram(o),e.context=n,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),o},e.prototype._finalizePipelineContext=function(e){var t=e.context,i=e.vertexShader,n=e.fragmentShader,r=e.program;if(!t.getProgramParameter(r,t.LINK_STATUS)){var o,a;if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS))if(o=this._gl.getShaderInfoLog(i))throw e.vertexCompilationError=o,new Error("VERTEX SHADER "+o);if(!this._gl.getShaderParameter(n,this._gl.COMPILE_STATUS))if(o=this._gl.getShaderInfoLog(n))throw e.fragmentCompilationError=o,new Error("FRAGMENT SHADER "+o);if(a=t.getProgramInfoLog(r))throw e.programLinkError=a,new Error(a)}if(this.validateShaderPrograms&&(t.validateProgram(r),!t.getProgramParameter(r,t.VALIDATE_STATUS)&&(a=t.getProgramInfoLog(r))))throw e.programValidationError=a,new Error(a);t.deleteShader(i),t.deleteShader(n),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)},e.prototype._preparePipelineContext=function(e,t,i,n,r,o,a){var s=e;s.program=n?this.createRawShaderProgram(s,t,i,void 0,a):this.createShaderProgram(s,t,i,o,void 0,a),s.program.__SPECTOR_rebuildProgram=r},e.prototype._isRenderingStateCompiled=function(e){var t=e;return!!this._gl.getProgramParameter(t.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)&&(this._finalizePipelineContext(t),!0)},e.prototype._executeWhenRenderingStateIsCompiled=function(e,t){var i=e;if(i.isParallelCompiled){var n=i.onCompiled;i.onCompiled=n?function(){n(),t()}:t}else t()},e.prototype.getUniforms=function(e,t){for(var i=new Array,n=e,r=0;r<t.length;r++)i.push(this._gl.getUniformLocation(n.program,t[r]));return i},e.prototype.getAttributes=function(e,t){for(var i=[],n=e,r=0;r<t.length;r++)try{i.push(this._gl.getAttribLocation(n.program,t[r]))}catch(e){i.push(-1)}return i},e.prototype.enableEffect=function(e){e&&e!==this._currentEffect&&(this.bindSamplers(e),this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))},e.prototype.setInt=function(e,t){e&&this._gl.uniform1i(e,t)},e.prototype.setIntArray=function(e,t){e&&this._gl.uniform1iv(e,t)},e.prototype.setIntArray2=function(e,t){e&&t.length%2==0&&this._gl.uniform2iv(e,t)},e.prototype.setIntArray3=function(e,t){e&&t.length%3==0&&this._gl.uniform3iv(e,t)},e.prototype.setIntArray4=function(e,t){e&&t.length%4==0&&this._gl.uniform4iv(e,t)},e.prototype.setArray=function(e,t){e&&this._gl.uniform1fv(e,t)},e.prototype.setArray2=function(e,t){e&&t.length%2==0&&this._gl.uniform2fv(e,t)},e.prototype.setArray3=function(e,t){e&&t.length%3==0&&this._gl.uniform3fv(e,t)},e.prototype.setArray4=function(e,t){e&&t.length%4==0&&this._gl.uniform4fv(e,t)},e.prototype.setMatrices=function(e,t){e&&this._gl.uniformMatrix4fv(e,!1,t)},e.prototype.setMatrix3x3=function(e,t){e&&this._gl.uniformMatrix3fv(e,!1,t)},e.prototype.setMatrix2x2=function(e,t){e&&this._gl.uniformMatrix2fv(e,!1,t)},e.prototype.setFloat=function(e,t){e&&this._gl.uniform1f(e,t)},e.prototype.setFloat2=function(e,t,i){e&&this._gl.uniform2f(e,t,i)},e.prototype.setFloat3=function(e,t,i,n){e&&this._gl.uniform3f(e,t,i,n)},e.prototype.setFloat4=function(e,t,i,n,r){e&&this._gl.uniform4f(e,t,i,n,r)},e.prototype.applyStates=function(){if(this._depthCullingState.apply(this._gl),this._stencilState.apply(this._gl),this._alphaState.apply(this._gl),this._colorWriteChanged){this._colorWriteChanged=!1;var e=this._colorWrite;this._gl.colorMask(e,e,e,e)}},e.prototype.setColorWrite=function(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)},e.prototype.getColorWrite=function(){return this._colorWrite},Object.defineProperty(e.prototype,"depthCullingState",{get:function(){return this._depthCullingState},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"alphaState",{get:function(){return this._alphaState},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stencilState",{get:function(){return this._stencilState},enumerable:!0,configurable:!0}),e.prototype.clearInternalTexturesCache=function(){this._internalTexturesCache=[]},e.prototype.wipeCaches=function(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._stencilState.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=this._gl.LEQUAL,this._alphaState.reset(),this._alphaMode=u.a.ALPHA_ADD,this._alphaEquation=u.a.ALPHA_DISABLE,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))},e.prototype._getSamplingParameters=function(e,t){var i=this._gl,n=i.NEAREST,r=i.NEAREST;switch(e){case u.a.TEXTURE_LINEAR_LINEAR_MIPNEAREST:n=i.LINEAR,r=t?i.LINEAR_MIPMAP_NEAREST:i.LINEAR;break;case u.a.TEXTURE_LINEAR_LINEAR_MIPLINEAR:n=i.LINEAR,r=t?i.LINEAR_MIPMAP_LINEAR:i.LINEAR;break;case u.a.TEXTURE_NEAREST_NEAREST_MIPLINEAR:n=i.NEAREST,r=t?i.NEAREST_MIPMAP_LINEAR:i.NEAREST;break;case u.a.TEXTURE_NEAREST_NEAREST_MIPNEAREST:n=i.NEAREST,r=t?i.NEAREST_MIPMAP_NEAREST:i.NEAREST;break;case u.a.TEXTURE_NEAREST_LINEAR_MIPNEAREST:n=i.NEAREST,r=t?i.LINEAR_MIPMAP_NEAREST:i.LINEAR;break;case u.a.TEXTURE_NEAREST_LINEAR_MIPLINEAR:n=i.NEAREST,r=t?i.LINEAR_MIPMAP_LINEAR:i.LINEAR;break;case u.a.TEXTURE_NEAREST_LINEAR:n=i.NEAREST,r=i.LINEAR;break;case u.a.TEXTURE_NEAREST_NEAREST:n=i.NEAREST,r=i.NEAREST;break;case u.a.TEXTURE_LINEAR_NEAREST_MIPNEAREST:n=i.LINEAR,r=t?i.NEAREST_MIPMAP_NEAREST:i.NEAREST;break;case u.a.TEXTURE_LINEAR_NEAREST_MIPLINEAR:n=i.LINEAR,r=t?i.NEAREST_MIPMAP_LINEAR:i.NEAREST;break;case u.a.TEXTURE_LINEAR_LINEAR:n=i.LINEAR,r=i.LINEAR;break;case u.a.TEXTURE_LINEAR_NEAREST:n=i.LINEAR,r=i.NEAREST}return{min:r,mag:n}},e.prototype._createTexture=function(){var e=this._gl.createTexture();if(!e)throw new Error("Unable to create texture");return e},e.prototype.createTexture=function(t,i,r,o,a,s,c,l,d,f,p,_){var m=this;void 0===a&&(a=u.a.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===s&&(s=null),void 0===c&&(c=null),void 0===l&&(l=null),void 0===d&&(d=null),void 0===f&&(f=null),void 0===p&&(p=null);for(var g=String(t),v="data:"===g.substr(0,5),y="blob:"===g.substr(0,5),b=v&&-1!==g.indexOf(";base64,"),T=d||new h.a(this,h.b.Url),E=g.lastIndexOf("."),x=p||(E>-1?g.substring(E).toLowerCase():""),P=null,A=0,S=e._TextureLoaders;A<S.length;A++){var C=S[A];if(C.canLoad(x)){P=C;break}}o&&o._addPendingData(T),T.url=g,T.generateMipMaps=!i,T.samplingMode=a,T.invertY=r,this._doNotHandleContextLost||(T._buffer=l);var R=null;s&&!d&&(R=T.onLoadedObservable.add(s)),d||this._internalTexturesCache.push(T);var O=function(e,t){o&&o._removePendingData(T),R&&T.onLoadedObservable.remove(R),n.a.UseFallbackTexture?m.createTexture(n.a.FallbackTexture,i,T.invertY,o,a,null,c,l,T):c&&c(e||"Unknown error",t)};if(P){var M=function(e){P.loadData(e,T,function(e,t,i,n,r,s){s?O("TextureLoader failed to load data"):m._prepareWebGLTexture(T,o,e,t,T.invertY,!i,n,function(){return r(),!1},a)})};l?l instanceof ArrayBuffer?M(new Uint8Array(l)):ArrayBuffer.isView(l)?M(l):c&&c("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(g,function(e){return M(new Uint8Array(e))},void 0,o?o.offlineProvider:void 0,!0,function(e,t){O("Unable to load "+(e&&e.responseURL,t))})}else{var I=function(e){y&&!m._doNotHandleContextLost&&(T._buffer=e),m._prepareWebGLTexture(T,o,e.width,e.height,T.invertY,i,!1,function(t,i,n){var r=m._gl,a=e.width===t&&e.height===i,s=f?m._getInternalFormat(f):".jpg"===x?r.RGB:r.RGBA;if(a)return r.texImage2D(r.TEXTURE_2D,0,s,s,r.UNSIGNED_BYTE,e),!1;var c=m._caps.maxTextureSize;if(e.width>c||e.height>c||!m._supportsHardwareTextureRescaling)return m._prepareWorkingCanvas(),!(!m._workingCanvas||!m._workingContext)&&(m._workingCanvas.width=t,m._workingCanvas.height=i,m._workingContext.drawImage(e,0,0,e.width,e.height,0,0,t,i),r.texImage2D(r.TEXTURE_2D,0,s,s,r.UNSIGNED_BYTE,m._workingCanvas),T.width=t,T.height=i,!1);var l=new h.a(m,h.b.Temp);return m._bindTextureDirectly(r.TEXTURE_2D,l,!0),r.texImage2D(r.TEXTURE_2D,0,s,s,r.UNSIGNED_BYTE,e),m._rescaleTexture(l,T,o,s,function(){m._releaseTexture(l),m._bindTextureDirectly(r.TEXTURE_2D,T,!0),n()}),!0},a)};!v||b?l&&(l.decoding||l.close)?I(l):e._FileToolsLoadImage(g,I,O,o?o.offlineProvider:null,_):"string"==typeof l||l instanceof ArrayBuffer||ArrayBuffer.isView(l)||l instanceof Blob?e._FileToolsLoadImage(l,I,O,o?o.offlineProvider:null,_):l&&I(l)}return T},e._FileToolsLoadImage=function(e,t,i,n,r){throw o.a.WarnImport("FileTools")},e.prototype._rescaleTexture=function(e,t,i,n,r){},e.prototype.createRawTexture=function(e,t,i,n,r,a,s,c,l){throw void 0===c&&(c=null),void 0===l&&(l=u.a.TEXTURETYPE_UNSIGNED_INT),o.a.WarnImport("Engine.RawTexture")},e.prototype.createRawCubeTexture=function(e,t,i,n,r,a,s,c){throw void 0===c&&(c=null),o.a.WarnImport("Engine.RawTexture")},e.prototype.createRawTexture3D=function(e,t,i,n,r,a,s,c,l,h){throw void 0===l&&(l=null),void 0===h&&(h=u.a.TEXTURETYPE_UNSIGNED_INT),o.a.WarnImport("Engine.RawTexture")},e.prototype.createRawTexture2DArray=function(e,t,i,n,r,a,s,c,l,h){throw void 0===l&&(l=null),void 0===h&&(h=u.a.TEXTURETYPE_UNSIGNED_INT),o.a.WarnImport("Engine.RawTexture")},e.prototype._unpackFlipY=function(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))},e.prototype._getUnpackAlignement=function(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)},e.prototype._getTextureTarget=function(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},e.prototype.updateTextureSamplingMode=function(e,t,i){void 0===i&&(i=!1);var n=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.generateMipMaps||i);this._setTextureParameterInteger(n,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(n,this._gl.TEXTURE_MIN_FILTER,r.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(n)),this._bindTextureDirectly(n,null),t.samplingMode=e},e.prototype.updateTextureWrappingMode=function(e,t,i,n){void 0===i&&(i=null),void 0===n&&(n=null);var r=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==n&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(n),e),e._cachedWrapR=n),this._bindTextureDirectly(r,null)},e.prototype._setupDepthStencilTexture=function(e,t,i,n,r){var o=t.width||t,a=t.height||t,s=t.layers||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=s>0,e.depth=s,e.isReady=!0,e.samples=1,e.generateMipMaps=!1,e._generateDepthBuffer=!0,e._generateStencilBuffer=i,e.samplingMode=n?u.a.TEXTURE_BILINEAR_SAMPLINGMODE:u.a.TEXTURE_NEAREST_SAMPLINGMODE,e.type=u.a.TEXTURETYPE_UNSIGNED_INT,e._comparisonFunction=r;var c=this._gl,l=this._getTextureTarget(e),h=this._getSamplingParameters(e.samplingMode,!1);c.texParameteri(l,c.TEXTURE_MAG_FILTER,h.mag),c.texParameteri(l,c.TEXTURE_MIN_FILTER,h.min),c.texParameteri(l,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(l,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),0===r?(c.texParameteri(l,c.TEXTURE_COMPARE_FUNC,u.a.LEQUAL),c.texParameteri(l,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(l,c.TEXTURE_COMPARE_FUNC,r),c.texParameteri(l,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE))},e.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,n,r,o,a){void 0===o&&(o=0),void 0===a&&(a=0);var s=this._gl,c=s.TEXTURE_2D;e.isCube&&(c=s.TEXTURE_CUBE_MAP_POSITIVE_X+o),this._gl.compressedTexImage2D(c,a,t,i,n,0,r)},e.prototype._uploadDataToTextureDirectly=function(e,t,i,n,r,o){void 0===i&&(i=0),void 0===n&&(n=0),void 0===o&&(o=!1);var a=this._gl,s=this._getWebGLTextureType(e.type),c=this._getInternalFormat(e.format),l=void 0===r?this._getRGBABufferInternalSizedFormat(e.type,e.format):this._getInternalFormat(r);this._unpackFlipY(e.invertY);var u=a.TEXTURE_2D;e.isCube&&(u=a.TEXTURE_CUBE_MAP_POSITIVE_X+i);var h=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),f=o?e.width:Math.pow(2,Math.max(h-n,0)),p=o?e.height:Math.pow(2,Math.max(d-n,0));a.texImage2D(u,n,l,f,p,0,c,s,t)},e.prototype.updateTextureData=function(e,t,i,n,r,o,a,s){void 0===a&&(a=0),void 0===s&&(s=0);var c=this._gl,l=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);var h=c.TEXTURE_2D;e.isCube&&(h=c.TEXTURE_CUBE_MAP_POSITIVE_X+a),c.texSubImage2D(h,s,i,n,r,o,u,l,t)},e.prototype._uploadArrayBufferViewToTexture=function(e,t,i,n){void 0===i&&(i=0),void 0===n&&(n=0);var r=this._gl,o=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(o,e,!0),this._uploadDataToTextureDirectly(e,t,i,n),this._bindTextureDirectly(o,null,!0)},e.prototype._prepareWebGLTextureContinuation=function(e,t,i,n,r){var o=this._gl;if(o){var a=this._getSamplingParameters(r,!i);o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,a.mag),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,a.min),i||n||o.generateMipmap(o.TEXTURE_2D),this._bindTextureDirectly(o.TEXTURE_2D,null),t&&t._removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}},e.prototype._prepareWebGLTexture=function(t,i,n,r,o,a,s,c,l){var h=this;void 0===l&&(l=u.a.TEXTURE_TRILINEAR_SAMPLINGMODE);var d=this.getCaps().maxTextureSize,f=Math.min(d,this.needPOTTextures?e.GetExponentOfTwo(n,d):n),p=Math.min(d,this.needPOTTextures?e.GetExponentOfTwo(r,d):r),_=this._gl;_&&(t._webGLTexture?(this._bindTextureDirectly(_.TEXTURE_2D,t,!0),this._unpackFlipY(void 0===o||!!o),t.baseWidth=n,t.baseHeight=r,t.width=f,t.height=p,t.isReady=!0,c(f,p,function(){h._prepareWebGLTextureContinuation(t,i,a,s,l)})||this._prepareWebGLTextureContinuation(t,i,a,s,l)):i&&i._removePendingData(t))},e.prototype._setupFramebufferDepthAttachments=function(e,t,i,n,r){void 0===r&&(r=1);var o=this._gl;if(e&&t)return this._getDepthStencilBuffer(i,n,r,o.DEPTH_STENCIL,o.DEPTH24_STENCIL8,o.DEPTH_STENCIL_ATTACHMENT);if(t){var a=o.DEPTH_COMPONENT16;return this._webGLVersion>1&&(a=o.DEPTH_COMPONENT32F),this._getDepthStencilBuffer(i,n,r,a,a,o.DEPTH_ATTACHMENT)}return e?this._getDepthStencilBuffer(i,n,r,o.STENCIL_INDEX8,o.STENCIL_INDEX8,o.STENCIL_ATTACHMENT):null},e.prototype._releaseFramebufferObjects=function(e){var t=this._gl;e._framebuffer&&(t.deleteFramebuffer(e._framebuffer),e._framebuffer=null),e._depthStencilBuffer&&(t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(t.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),e._MSAARenderBuffer&&(t.deleteRenderbuffer(e._MSAARenderBuffer),e._MSAARenderBuffer=null)},e.prototype._releaseTexture=function(e){this._releaseFramebufferObjects(e),this._deleteTexture(e._webGLTexture),this.unbindAllTextures();var t=this._internalTexturesCache.indexOf(e);-1!==t&&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()},e.prototype._deleteTexture=function(e){this._gl.deleteTexture(e)},e.prototype._setProgram=function(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)},e.prototype.bindSamplers=function(e){var t=e.getPipelineContext();this._setProgram(t.program);for(var i=e.getSamplers(),n=0;n<i.length;n++){var r=e.getUniform(i[n]);r&&(this._boundUniforms[n]=r)}this._currentEffect=null},e.prototype._activateCurrentTexture=function(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)},e.prototype._bindTextureDirectly=function(e,t,i,n){void 0===i&&(i=!1),void 0===n&&(n=!1);var r=!1,o=t&&t._associatedChannel>-1;return i&&o&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||n?(this._activateCurrentTexture(),t&&t.isMultiview?this._gl.bindTexture(e,t?t._colorTextureArray:null):this._gl.bindTexture(e,t?t._webGLTexture:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)):i&&(r=!0,this._activateCurrentTexture()),o&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),r},e.prototype._bindTexture=function(e,t){void 0!==e&&(t&&(t._associatedChannel=e),this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,t))},e.prototype.unbindAllTextures=function(){for(var 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))},e.prototype.setTexture=function(e,t,i){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))},e.prototype._bindSamplerUniformToChannel=function(e,t){var i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)},e.prototype._getTextureWrapMode=function(e){switch(e){case u.a.TEXTURE_WRAP_ADDRESSMODE:return this._gl.REPEAT;case u.a.TEXTURE_CLAMP_ADDRESSMODE:return this._gl.CLAMP_TO_EDGE;case u.a.TEXTURE_MIRROR_ADDRESSMODE:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT},e.prototype._setTexture=function(e,t,i,n){if(void 0===i&&(i=!1),void 0===n&&(n=!1),!t)return null!=this._boundTexturesCache[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))),!1;if(t.video)this._activeChannel=e,t.update();else if(t.delayLoadState===u.a.DELAYLOADSTATE_NOTLOADED)return t.delayLoad(),!1;var r;r=n?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&r&&(r._associatedChannel=e);var o=!0;this._boundTexturesCache[e]===r&&(i||this._bindSamplerUniformToChannel(r._associatedChannel,e),o=!1),this._activeChannel=e;var a=this._getTextureTarget(r);if(o&&this._bindTextureDirectly(a,r,i),r&&!r.isMultiview){if(r.isCube&&r._cachedCoordinatesMode!==t.coordinatesMode){r._cachedCoordinatesMode=t.coordinatesMode;var s=t.coordinatesMode!==u.a.TEXTURE_CUBIC_MODE&&t.coordinatesMode!==u.a.TEXTURE_SKYBOX_MODE?u.a.TEXTURE_WRAP_ADDRESSMODE:u.a.TEXTURE_CLAMP_ADDRESSMODE;t.wrapU=s,t.wrapV=s}r._cachedWrapU!==t.wrapU&&(r._cachedWrapU=t.wrapU,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),r)),r._cachedWrapV!==t.wrapV&&(r._cachedWrapV=t.wrapV,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),r)),r.is3D&&r._cachedWrapR!==t.wrapR&&(r._cachedWrapR=t.wrapR,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),r)),this._setAnisotropicLevel(a,r,t.anisotropicFilteringLevel)}return!0},e.prototype.setTextureArray=function(e,t,i){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(var n=0;n<i.length;n++){var r=i[n].getInternalTexture();r?(this._textureUnits[n]=e+n,r._associatedChannel=e+n):this._textureUnits[n]=-1}this._gl.uniform1iv(t,this._textureUnits);for(var o=0;o<i.length;o++)this._setTexture(this._textureUnits[o],i[o],!0)}},e.prototype._setAnisotropicLevel=function(e,t,i){var n=this._caps.textureAnisotropicFilterExtension;t.samplingMode!==u.a.TEXTURE_LINEAR_LINEAR_MIPNEAREST&&t.samplingMode!==u.a.TEXTURE_LINEAR_LINEAR_MIPLINEAR&&t.samplingMode!==u.a.TEXTURE_LINEAR_LINEAR&&(i=1),n&&t._cachedAnisotropicFilteringLevel!==i&&(this._setTextureParameterFloat(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(i,this._caps.maxAnisotropy),t),t._cachedAnisotropicFilteringLevel=i)},e.prototype._setTextureParameterFloat=function(e,t,i,n){this._bindTextureDirectly(e,n,!0,!0),this._gl.texParameterf(e,t,i)},e.prototype._setTextureParameterInteger=function(e,t,i,n){n&&this._bindTextureDirectly(e,n,!0,!0),this._gl.texParameteri(e,t,i)},e.prototype.unbindAllAttributes=function(){if(this._mustWipeVertexAttributes){this._mustWipeVertexAttributes=!1;for(var e=0;e<this._caps.maxVertexAttribs;e++)this.disableAttributeByIndex(e)}else{e=0;for(var t=this._vertexAttribArraysEnabled.length;e<t;e++)e>=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}},e.prototype.releaseEffects=function(){for(var e in this._compiledEffects){var t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}},e.prototype.dispose=function(){this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this.releaseEffects(),this.unbindAllAttributes(),this._boundUniforms=[],f.a.IsWindowObjectExist()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers=[],this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,r.a.ResetCache();for(var e=0,t=this._activeRequests;e<t.length;e++){t[e].abort()}},e.prototype.attachContextLostEvent=function(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)},e.prototype.attachContextRestoredEvent=function(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)},e.prototype.getError=function(){return this._gl.getError()},e.prototype._canRenderToFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(u.a.TEXTURETYPE_FLOAT)},e.prototype._canRenderToHalfFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(u.a.TEXTURETYPE_HALF_FLOAT)},e.prototype._canRenderToFramebuffer=function(e){for(var t=this._gl;t.getError()!==t.NO_ERROR;);var i=!0,n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),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);var r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);var o=t.checkFramebufferStatus(t.FRAMEBUFFER);if((i=(i=i&&o===t.FRAMEBUFFER_COMPLETE)&&t.getError()===t.NO_ERROR)&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);var a=t.RGBA,s=t.UNSIGNED_BYTE,c=new Uint8Array(4);t.readPixels(0,0,1,1,a,s,c),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(n),t.deleteFramebuffer(r),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i},e.prototype._getWebGLTextureType=function(e){if(1===this._webGLVersion){switch(e){case u.a.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case u.a.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT_OES;case u.a.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE;case u.a.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.UNSIGNED_SHORT_4_4_4_4;case u.a.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.UNSIGNED_SHORT_5_5_5_1;case u.a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case u.a.TEXTURETYPE_BYTE:return this._gl.BYTE;case u.a.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE;case u.a.TEXTURETYPE_SHORT:return this._gl.SHORT;case u.a.TEXTURETYPE_UNSIGNED_SHORT:return this._gl.UNSIGNED_SHORT;case u.a.TEXTURETYPE_INT:return this._gl.INT;case u.a.TEXTURETYPE_UNSIGNED_INTEGER:return this._gl.UNSIGNED_INT;case u.a.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case u.a.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT;case u.a.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.UNSIGNED_SHORT_4_4_4_4;case u.a.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.UNSIGNED_SHORT_5_5_5_1;case u.a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.UNSIGNED_SHORT_5_6_5;case u.a.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case u.a.TEXTURETYPE_UNSIGNED_INT_24_8:return this._gl.UNSIGNED_INT_24_8;case u.a.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case u.a.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case u.a.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE},e.prototype._getInternalFormat=function(e){var t=this._gl.RGBA;switch(e){case u.a.TEXTUREFORMAT_ALPHA:t=this._gl.ALPHA;break;case u.a.TEXTUREFORMAT_LUMINANCE:t=this._gl.LUMINANCE;break;case u.a.TEXTUREFORMAT_LUMINANCE_ALPHA:t=this._gl.LUMINANCE_ALPHA;break;case u.a.TEXTUREFORMAT_RED:t=this._gl.RED;break;case u.a.TEXTUREFORMAT_RG:t=this._gl.RG;break;case u.a.TEXTUREFORMAT_RGB:t=this._gl.RGB;break;case u.a.TEXTUREFORMAT_RGBA:t=this._gl.RGBA}if(this._webGLVersion>1)switch(e){case u.a.TEXTUREFORMAT_RED_INTEGER:t=this._gl.RED_INTEGER;break;case u.a.TEXTUREFORMAT_RG_INTEGER:t=this._gl.RG_INTEGER;break;case u.a.TEXTUREFORMAT_RGB_INTEGER:t=this._gl.RGB_INTEGER;break;case u.a.TEXTUREFORMAT_RGBA_INTEGER:t=this._gl.RGBA_INTEGER}return t},e.prototype._getRGBABufferInternalSizedFormat=function(e,t){if(1===this._webGLVersion){if(void 0!==t)switch(t){case u.a.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case u.a.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case u.a.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA;case u.a.TEXTUREFORMAT_RGB:return this._gl.RGB}return this._gl.RGBA}switch(e){case u.a.TEXTURETYPE_BYTE:switch(t){case u.a.TEXTUREFORMAT_RED:return this._gl.R8_SNORM;case u.a.TEXTUREFORMAT_RG:return this._gl.RG8_SNORM;case u.a.TEXTUREFORMAT_RGB:return this._gl.RGB8_SNORM;case u.a.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8I;case u.a.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8I;case u.a.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8I;case u.a.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case u.a.TEXTURETYPE_UNSIGNED_BYTE:switch(t){case u.a.TEXTUREFORMAT_RED:return this._gl.R8;case u.a.TEXTUREFORMAT_RG:return this._gl.RG8;case u.a.TEXTUREFORMAT_RGB:return this._gl.RGB8;case u.a.TEXTUREFORMAT_RGBA:return this._gl.RGBA8;case u.a.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8UI;case u.a.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8UI;case u.a.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8UI;case u.a.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8UI;case u.a.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case u.a.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case u.a.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case u.a.TEXTURETYPE_SHORT:switch(t){case u.a.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16I;case u.a.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16I;case u.a.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16I;case u.a.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16I}case u.a.TEXTURETYPE_UNSIGNED_SHORT:switch(t){case u.a.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16UI;case u.a.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16UI;case u.a.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16UI;case u.a.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16UI}case u.a.TEXTURETYPE_INT:switch(t){case u.a.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32I;case u.a.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32I;case u.a.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32I;case u.a.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32I}case u.a.TEXTURETYPE_UNSIGNED_INTEGER:switch(t){case u.a.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32UI;case u.a.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32UI;case u.a.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32UI;case u.a.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32UI}case u.a.TEXTURETYPE_FLOAT:switch(t){case u.a.TEXTUREFORMAT_RED:return this._gl.R32F;case u.a.TEXTUREFORMAT_RG:return this._gl.RG32F;case u.a.TEXTUREFORMAT_RGB:return this._gl.RGB32F;case u.a.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA32F}case u.a.TEXTURETYPE_HALF_FLOAT:switch(t){case u.a.TEXTUREFORMAT_RED:return this._gl.R16F;case u.a.TEXTUREFORMAT_RG:return this._gl.RG16F;case u.a.TEXTUREFORMAT_RGB:return this._gl.RGB16F;case u.a.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA16F}case u.a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.RGB565;case u.a.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.R11F_G11F_B10F;case u.a.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.RGB9_E5;case u.a.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.RGBA4;case u.a.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.RGB5_A1;case u.a.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:switch(t){case u.a.TEXTUREFORMAT_RGBA:return this._gl.RGB10_A2;case u.a.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return this._gl.RGBA8},e.prototype._getRGBAMultiSampleBufferFormat=function(e){return e===u.a.TEXTURETYPE_FLOAT?this._gl.RGBA32F:e===u.a.TEXTURETYPE_HALF_FLOAT?this._gl.RGBA16F:this._gl.RGBA8},e.prototype._loadFile=function(t,i,n,r,o,a){var s=this,c=e._FileToolsLoadFile(t,i,n,r,o,a);return this._activeRequests.push(c),c.onCompleteObservable.add(function(e){s._activeRequests.splice(s._activeRequests.indexOf(e),1)}),c},e._FileToolsLoadFile=function(e,t,i,n,r,a){throw o.a.WarnImport("FileTools")},e.prototype.readPixels=function(e,t,i,n,r){void 0===r&&(r=!0);var o=r?4:3,a=r?this._gl.RGBA:this._gl.RGB,s=new Uint8Array(n*i*o);return this._gl.readPixels(e,t,i,n,a,this._gl.UNSIGNED_BYTE,s),s},e.isSupported=function(){if(null===this._isSupported)try{var e=g.a.CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._isSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._isSupported=!1}return this._isSupported},e.CeilingPOT=function(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e},e.FloorPOT=function(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)},e.NearestPOT=function(t){var i=e.CeilingPOT(t),n=e.FloorPOT(t);return i-t>t-n?n:i},e.GetExponentOfTwo=function(t,i,n){var r;switch(void 0===n&&(n=u.a.SCALEMODE_NEAREST),n){case u.a.SCALEMODE_FLOOR:r=e.FloorPOT(t);break;case u.a.SCALEMODE_NEAREST:r=e.NearestPOT(t);break;case u.a.SCALEMODE_CEILING:default:r=e.CeilingPOT(t)}return Math.min(r,i)},e.QueueNewFrame=function(e,t){return f.a.IsWindowObjectExist()?(t||(t=window),t.requestAnimationFrame?t.requestAnimationFrame(e):t.msRequestAnimationFrame?t.msRequestAnimationFrame(e):t.webkitRequestAnimationFrame?t.webkitRequestAnimationFrame(e):t.mozRequestAnimationFrame?t.mozRequestAnimationFrame(e):t.oRequestAnimationFrame?t.oRequestAnimationFrame(e):window.setTimeout(e,16)):"undefined"!=typeof requestAnimationFrame?requestAnimationFrame(e):setTimeout(e,16)},e.prototype.getHostDocument=function(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:document},e.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"]}],e._TextureLoaders=[],e.CollisionsEpsilon=.001,e._isSupported=null,e}()},function(e,t,i){"use strict";var n=i(1),r=i(3),o=i(34),a=i(18),s=i(0),c=i(10),l=i(4),u=i(40),h=i(73),d=i(81),f=i(16),p=i(9),_=i(12),m=i(21),g=i(8),v="uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\nuniform float visibility;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)\nuniform mat4 reflectionMatrix;\n#endif\n#ifndef REFLECTIONMAP_SKYBOX\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif";g.a.IncludesShadersStore.defaultFragmentDeclaration=v;var y="layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor;\nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix;\nvec2 vTangentSpaceParams;\nfloat pointSize;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nfloat visibility;\nvec4 vDiffuseColor;\n};\nuniform Scene {\nmat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif\nmat4 view;\n};\n";g.a.IncludesShadersStore.defaultUboDeclaration=y;i(58),i(97),i(98),i(139),i(117),i(145),i(118),i(99),i(100),i(119),i(106),i(107),i(113),i(101),i(120),i(146),i(121),i(140),i(122);var b="#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\ncolor.a*=visibility;\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n";g.a.ShadersStore.defaultPixelShader=b;var T="\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";g.a.IncludesShadersStore.defaultVertexDeclaration=T;i(74),i(77),i(147),i(108),i(123),i(88),i(89),i(94),i(78),i(75),i(141),i(102),i(142),i(124);g.a.IncludesShadersStore.pointCloudVertex="#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif";i(143);var E="#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR == 0u) {\ngl_Position=viewProjection*worldPos;\n} else {\ngl_Position=viewProjectionR*worldPos;\n}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n";g.a.ShadersStore.defaultVertexShader=E;var x=i(2),P=i(64);i.d(t,"b",function(){return A}),i.d(t,"a",function(){return S});var A=function(e){function t(){var t=e.call(this)||this;return t.MAINUV1=!1,t.MAINUV2=!1,t.DIFFUSE=!1,t.DIFFUSEDIRECTUV=0,t.AMBIENT=!1,t.AMBIENTDIRECTUV=0,t.OPACITY=!1,t.OPACITYDIRECTUV=0,t.OPACITYRGB=!1,t.REFLECTION=!1,t.EMISSIVE=!1,t.EMISSIVEDIRECTUV=0,t.SPECULAR=!1,t.SPECULARDIRECTUV=0,t.BUMP=!1,t.BUMPDIRECTUV=0,t.PARALLAX=!1,t.PARALLAXOCCLUSION=!1,t.SPECULAROVERALPHA=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.ALPHATEST=!1,t.DEPTHPREPASS=!1,t.ALPHAFROMDIFFUSE=!1,t.POINTSIZE=!1,t.FOG=!1,t.SPECULARTERM=!1,t.DIFFUSEFRESNEL=!1,t.OPACITYFRESNEL=!1,t.REFLECTIONFRESNEL=!1,t.REFRACTIONFRESNEL=!1,t.EMISSIVEFRESNEL=!1,t.FRESNEL=!1,t.NORMAL=!1,t.UV1=!1,t.UV2=!1,t.VERTEXCOLOR=!1,t.VERTEXALPHA=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.BONETEXTURE=!1,t.INSTANCES=!1,t.GLOSSINESS=!1,t.ROUGHNESS=!1,t.EMISSIVEASILLUMINATION=!1,t.LINKEMISSIVEWITHDIFFUSE=!1,t.REFLECTIONFRESNELFROMSPECULAR=!1,t.LIGHTMAP=!1,t.LIGHTMAPDIRECTUV=0,t.OBJECTSPACE_NORMALMAP=!1,t.USELIGHTMAPASSHADOWMAP=!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.LOGARITHMICDEPTH=!1,t.REFRACTION=!1,t.REFRACTIONMAP_3D=!1,t.REFLECTIONOVERALPHA=!1,t.TWOSIDEDLIGHTING=!1,t.SHADOWFLOAT=!1,t.MORPHTARGETS=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_UV=!1,t.NUM_MORPH_INFLUENCERS=0,t.NONUNIFORMSCALING=!1,t.PREMULTIPLYALPHA=!1,t.IMAGEPROCESSING=!1,t.VIGNETTE=!1,t.VIGNETTEBLENDMODEMULTIPLY=!1,t.VIGNETTEBLENDMODEOPAQUE=!1,t.TONEMAPPING=!1,t.TONEMAPPING_ACES=!1,t.CONTRAST=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=!1,t.SAMPLER3DBGRMAP=!1,t.IMAGEPROCESSINGPOSTPROCESS=!1,t.MULTIVIEW=!1,t.IS_REFLECTION_LINEAR=!1,t.IS_REFRACTION_LINEAR=!1,t.EXPOSURE=!1,t.rebuild(),t}return Object(n.d)(t,e),t.prototype.setReflectionMode=function(e){for(var t=0,i=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];t<i.length;t++){var n=i[t];this[n]=n===e}},t}(h.a),S=function(e){function t(i,n){var r=e.call(this,i,n)||this;return r._diffuseTexture=null,r._ambientTexture=null,r._opacityTexture=null,r._reflectionTexture=null,r._emissiveTexture=null,r._specularTexture=null,r._bumpTexture=null,r._lightmapTexture=null,r._refractionTexture=null,r.ambientColor=new c.a(0,0,0),r.diffuseColor=new c.a(1,1,1),r.specularColor=new c.a(1,1,1),r.emissiveColor=new c.a(0,0,0),r.specularPower=64,r._useAlphaFromDiffuseTexture=!1,r._useEmissiveAsIllumination=!1,r._linkEmissiveWithDiffuse=!1,r._useSpecularOverAlpha=!1,r._useReflectionOverAlpha=!1,r._disableLighting=!1,r._useObjectSpaceNormalMap=!1,r._useParallax=!1,r._useParallaxOcclusion=!1,r.parallaxScaleBias=.05,r._roughness=0,r.indexOfRefraction=.98,r.invertRefractionY=!0,r.alphaCutOff=.4,r._useLightmapAsShadowmap=!1,r._useReflectionFresnelFromSpecular=!1,r._useGlossinessFromSpecularMapAlpha=!1,r._maxSimultaneousLights=4,r._invertNormalMapX=!1,r._invertNormalMapY=!1,r._twoSidedLighting=!1,r._renderTargets=new o.a(16),r._worldViewProjectionMatrix=s.a.Zero(),r._globalAmbientColor=new c.a(0,0,0),r._rebuildInParallel=!1,r._attachImageProcessingConfiguration(null),r.getRenderTargetTextures=function(){return r._renderTargets.reset(),t.ReflectionTextureEnabled&&r._reflectionTexture&&r._reflectionTexture.isRenderTarget&&r._renderTargets.push(r._reflectionTexture),t.RefractionTextureEnabled&&r._refractionTexture&&r._refractionTexture.isRenderTarget&&r._renderTargets.push(r._refractionTexture),r._renderTargets},r}return Object(n.d)(t,e),Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),t.prototype._attachImageProcessingConfiguration=function(e){var t=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(function(){t._markAllSubMeshesAsImageProcessingDirty()})))},Object.defineProperty(t.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this._imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurves",{get:function(){return this._imageProcessingConfiguration.colorCurves},set:function(e){this._imageProcessingConfiguration.colorCurves=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasRenderTargetTextures",{get:function(){return!!(t.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||!!(t.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"StandardMaterial"},Object.defineProperty(t.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()},enumerable:!0,configurable:!0}),t.prototype.needAlphaBlending=function(){return this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled},t.prototype.needAlphaTesting=function(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha},t.prototype._shouldUseAlphaFromDiffuseTexture=function(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture},t.prototype.getAlphaTestTexture=function(){return this._diffuseTexture},t.prototype.isReadyForSubMesh=function(e,i,n){if(void 0===n&&(n=!1),i.effect&&this.isFrozen&&i.effect._wasPreviouslyReady)return!0;i._materialDefines||(i._materialDefines=new A);var r=this.getScene(),o=i._materialDefines;if(!this.checkReadyOnEveryCall&&i.effect&&o._renderId===r.getRenderId())return!0;var a=r.getEngine();if(o._needNormals=f.a.PrepareDefinesForLights(r,e,o,!0,this._maxSimultaneousLights,this._disableLighting),f.a.PrepareDefinesForMultiview(r,o),o._areTexturesDirty){if(o._needUVs=!1,o.MAINUV1=!1,o.MAINUV2=!1,r.texturesEnabled){if(this._diffuseTexture&&t.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;f.a.PrepareDefinesForMergedUV(this._diffuseTexture,o,"DIFFUSE")}else o.DIFFUSE=!1;if(this._ambientTexture&&t.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;f.a.PrepareDefinesForMergedUV(this._ambientTexture,o,"AMBIENT")}else o.AMBIENT=!1;if(this._opacityTexture&&t.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;f.a.PrepareDefinesForMergedUV(this._opacityTexture,o,"OPACITY"),o.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else o.OPACITY=!1;if(this._reflectionTexture&&t.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(o._needNormals=!0,o.REFLECTION=!0,o.ROUGHNESS=this._roughness>0,o.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,o.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===p.a.INVCUBIC_MODE,o.REFLECTIONMAP_3D=this._reflectionTexture.isCube,this._reflectionTexture.coordinatesMode){case p.a.EXPLICIT_MODE:o.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case p.a.PLANAR_MODE:o.setReflectionMode("REFLECTIONMAP_PLANAR");break;case p.a.PROJECTION_MODE:o.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case p.a.SKYBOX_MODE:o.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case p.a.SPHERICAL_MODE:o.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case p.a.EQUIRECTANGULAR_MODE:o.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case p.a.FIXED_EQUIRECTANGULAR_MODE:o.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case p.a.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:o.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case p.a.CUBIC_MODE:case p.a.INVCUBIC_MODE:default:o.setReflectionMode("REFLECTIONMAP_CUBIC")}o.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else o.REFLECTION=!1;if(this._emissiveTexture&&t.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;f.a.PrepareDefinesForMergedUV(this._emissiveTexture,o,"EMISSIVE")}else o.EMISSIVE=!1;if(this._lightmapTexture&&t.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;f.a.PrepareDefinesForMergedUV(this._lightmapTexture,o,"LIGHTMAP"),o.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap}else o.LIGHTMAP=!1;if(this._specularTexture&&t.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;f.a.PrepareDefinesForMergedUV(this._specularTexture,o,"SPECULAR"),o.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else o.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&t.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;f.a.PrepareDefinesForMergedUV(this._bumpTexture,o,"BUMP"),o.PARALLAX=this._useParallax,o.PARALLAXOCCLUSION=this._useParallaxOcclusion,o.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else o.BUMP=!1;if(this._refractionTexture&&t.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;o._needUVs=!0,o.REFRACTION=!0,o.REFRACTIONMAP_3D=this._refractionTexture.isCube}else o.REFRACTION=!1;o.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else o.DIFFUSE=!1,o.AMBIENT=!1,o.OPACITY=!1,o.REFLECTION=!1,o.EMISSIVE=!1,o.LIGHTMAP=!1,o.BUMP=!1,o.REFRACTION=!1;o.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),o.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,o.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,o.SPECULAROVERALPHA=this._useSpecularOverAlpha,o.PREMULTIPLYALPHA=this.alphaMode===x.a.ALPHA_PREMULTIPLIED||this.alphaMode===x.a.ALPHA_PREMULTIPLIED_PORTERDUFF}if(o._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(o),o.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,o.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}if(o._areFresnelDirty&&(t.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(o.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,o.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,o.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,o.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,o.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,o.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,o._needNormals=!0,o.FRESNEL=!0):o.FRESNEL=!1),f.a.PrepareDefinesForMisc(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),o),f.a.PrepareDefinesForAttributes(e,o,!0,!0,!0),f.a.PrepareDefinesForFrameBoundValues(r,a,o,n),o.isDirty){var s=o._areLightsDisposed;o.markAsProcessed();var c=new P.a;o.REFLECTION&&c.addFallback(0,"REFLECTION"),o.SPECULAR&&c.addFallback(0,"SPECULAR"),o.BUMP&&c.addFallback(0,"BUMP"),o.PARALLAX&&c.addFallback(1,"PARALLAX"),o.PARALLAXOCCLUSION&&c.addFallback(0,"PARALLAXOCCLUSION"),o.SPECULAROVERALPHA&&c.addFallback(0,"SPECULAROVERALPHA"),o.FOG&&c.addFallback(1,"FOG"),o.POINTSIZE&&c.addFallback(0,"POINTSIZE"),o.LOGARITHMICDEPTH&&c.addFallback(0,"LOGARITHMICDEPTH"),f.a.HandleFallbacksForShadows(o,c,this._maxSimultaneousLights),o.SPECULARTERM&&c.addFallback(0,"SPECULARTERM"),o.DIFFUSEFRESNEL&&c.addFallback(1,"DIFFUSEFRESNEL"),o.OPACITYFRESNEL&&c.addFallback(2,"OPACITYFRESNEL"),o.REFLECTIONFRESNEL&&c.addFallback(3,"REFLECTIONFRESNEL"),o.EMISSIVEFRESNEL&&c.addFallback(4,"EMISSIVEFRESNEL"),o.FRESNEL&&c.addFallback(4,"FRESNEL"),o.MULTIVIEW&&c.addFallback(0,"MULTIVIEW");var h=[l.b.PositionKind];o.NORMAL&&h.push(l.b.NormalKind),o.UV1&&h.push(l.b.UVKind),o.UV2&&h.push(l.b.UV2Kind),o.VERTEXCOLOR&&h.push(l.b.ColorKind),f.a.PrepareAttributesForBones(h,e,o,c),f.a.PrepareAttributesForInstances(h,o),f.a.PrepareAttributesForMorphTargets(h,e,o);var d="default",_=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth"],m=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler"],g=["Material","Scene"];u.a&&(u.a.PrepareUniforms(_,o),u.a.PrepareSamplers(m,o)),f.a.PrepareUniformsAndSamplersList({uniformsNames:_,uniformBuffersNames:g,samplers:m,defines:o,maxSimultaneousLights:this._maxSimultaneousLights}),this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,_,g,m,o));var v=o.toString(),y=i.effect,b=r.getEngine().createEffect(d,{attributes:h,uniformsNames:_,uniformBuffersNames:g,samplers:m,defines:v,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:o.NUM_MORPH_INFLUENCERS}},a);if(b)if(this.allowShaderHotSwapping&&y&&!b.isReady()){if(b=y,this._rebuildInParallel=!0,o.markAsUnprocessed(),s)return o._areLightsDisposed=!0,!1}else this._rebuildInParallel=!1,r.resetCachedMaterial(),i.setEffect(b,o),this.buildUniformLayout()}return!(!i.effect||!i.effect.isReady())&&(o._renderId=r.getRenderId(),i.effect._wasPreviouslyReady=!0,!0)},t.prototype.buildUniformLayout=function(){var 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("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),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("reflectionMatrix",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("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("visibility",1),e.addUniform("vDiffuseColor",4),e.create()},t.prototype.unbind=function(){if(this._activeEffect){var t=!1;this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&(this._activeEffect.setTexture("reflection2DSampler",null),t=!0),this._refractionTexture&&this._refractionTexture.isRenderTarget&&(this._activeEffect.setTexture("refraction2DSampler",null),t=!0),t&&this._markAllSubMeshesAsTexturesDirty()}e.prototype.unbind.call(this)},t.prototype.bindForSubMesh=function(e,i,n){var r=this.getScene(),o=n._materialDefines;if(o){var s=n.effect;if(s){this._activeEffect=s,o.INSTANCES||this.bindOnlyWorldMatrix(e),o.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var l=this._mustRebind(r,s,i.visibility);f.a.BindBonesParameters(i,s);var u=this._uniformBuffer;if(l){if(u.bindToEffect(s,"Material"),this.bindViewProjection(s),!u.useUbo||!this.isFrozen||!u.isSync){if(t.FresnelEnabled&&o.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(u.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),u.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&u.updateColor4("opacityParts",new c.a(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(u.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),u.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(u.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),u.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(u.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),u.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),r.texturesEnabled){if(this._diffuseTexture&&t.DiffuseTextureEnabled&&(u.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),f.a.BindTextureMatrix(this._diffuseTexture,u,"diffuse"),this._diffuseTexture.hasAlpha&&s.setFloat("alphaCutOff",this.alphaCutOff)),this._ambientTexture&&t.AmbientTextureEnabled&&(u.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),f.a.BindTextureMatrix(this._ambientTexture,u,"ambient")),this._opacityTexture&&t.OpacityTextureEnabled&&(u.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),f.a.BindTextureMatrix(this._opacityTexture,u,"opacity")),this._reflectionTexture&&t.ReflectionTextureEnabled&&(u.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),u.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){var h=this._reflectionTexture;u.updateVector3("vReflectionPosition",h.boundingBoxPosition),u.updateVector3("vReflectionSize",h.boundingBoxSize)}if(this._emissiveTexture&&t.EmissiveTextureEnabled&&(u.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),f.a.BindTextureMatrix(this._emissiveTexture,u,"emissive")),this._lightmapTexture&&t.LightmapTextureEnabled&&(u.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),f.a.BindTextureMatrix(this._lightmapTexture,u,"lightmap")),this._specularTexture&&t.SpecularTextureEnabled&&(u.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),f.a.BindTextureMatrix(this._specularTexture,u,"specular")),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&t.BumpTextureEnabled&&(u.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),f.a.BindTextureMatrix(this._bumpTexture,u,"bump"),r._mirroredCameraPosition?u.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):u.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&t.RefractionTextureEnabled){var d=1;this._refractionTexture.isCube||(u.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(d=this._refractionTexture.depth)),u.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,d,this.invertRefractionY?-1:1)}}this.pointsCloud&&u.updateFloat("pointSize",this.pointSize),o.SPECULARTERM&&u.updateColor4("vSpecularColor",this.specularColor,this.specularPower),u.updateColor3("vEmissiveColor",t.EmissiveTextureEnabled?this.emissiveColor:c.a.BlackReadOnly),u.updateFloat("visibility",i.visibility),u.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha)}if(r.texturesEnabled&&(this._diffuseTexture&&t.DiffuseTextureEnabled&&s.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&t.AmbientTextureEnabled&&s.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&t.OpacityTextureEnabled&&s.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&t.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?s.setTexture("reflectionCubeSampler",this._reflectionTexture):s.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&t.EmissiveTextureEnabled&&s.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&t.LightmapTextureEnabled&&s.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&t.SpecularTextureEnabled&&s.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&t.BumpTextureEnabled&&s.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&t.RefractionTextureEnabled)){d=1;this._refractionTexture.isCube?s.setTexture("refractionCubeSampler",this._refractionTexture):s.setTexture("refraction2DSampler",this._refractionTexture)}f.a.BindClipPlane(s,r),r.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),f.a.BindEyePosition(s,r),s.setColor3("vAmbientColor",this._globalAmbientColor)}!l&&this.isFrozen||(r.lightsEnabled&&!this._disableLighting&&f.a.BindLights(r,i,s,o,this._maxSimultaneousLights,this._rebuildInParallel),(r.fogEnabled&&i.applyFog&&r.fogMode!==a.a.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture)&&this.bindView(s),f.a.BindFogParameters(r,i,s),o.NUM_MORPH_INFLUENCERS&&f.a.BindMorphTargetParameters(i,s),this.useLogarithmicDepth&&f.a.BindLogDepth(o,s,r),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),u.update(),this._afterBind(i,this._activeEffect)}}},t.prototype.getAnimatables=function(){var e=[];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},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._diffuseTexture&&t.push(this._diffuseTexture),this._ambientTexture&&t.push(this._ambientTexture),this._opacityTexture&&t.push(this._opacityTexture),this._reflectionTexture&&t.push(this._reflectionTexture),this._emissiveTexture&&t.push(this._emissiveTexture),this._specularTexture&&t.push(this._specularTexture),this._bumpTexture&&t.push(this._bumpTexture),this._lightmapTexture&&t.push(this._lightmapTexture),this._refractionTexture&&t.push(this._refractionTexture),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||(this._diffuseTexture===t||(this._ambientTexture===t||(this._opacityTexture===t||(this._reflectionTexture===t||(this._emissiveTexture===t||(this._specularTexture===t||(this._bumpTexture===t||(this._lightmapTexture===t||this._refractionTexture===t))))))))},t.prototype.dispose=function(t,i){i&&(this._diffuseTexture&&this._diffuseTexture.dispose(),this._ambientTexture&&this._ambientTexture.dispose(),this._opacityTexture&&this._opacityTexture.dispose(),this._reflectionTexture&&this._reflectionTexture.dispose(),this._emissiveTexture&&this._emissiveTexture.dispose(),this._specularTexture&&this._specularTexture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._lightmapTexture&&this._lightmapTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e.prototype.dispose.call(this,t,i)},t.prototype.clone=function(e){var i=this,n=r.a.Clone(function(){return new t(e,i.getScene())},this);return n.name=e,n.id=e,n},t.prototype.serialize=function(){return r.a.Serialize(this)},t.Parse=function(e,i,n){return r.a.Parse(function(){return new t(e.name,i)},e,i,n)},Object.defineProperty(t,"DiffuseTextureEnabled",{get:function(){return m.a.DiffuseTextureEnabled},set:function(e){m.a.DiffuseTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"AmbientTextureEnabled",{get:function(){return m.a.AmbientTextureEnabled},set:function(e){m.a.AmbientTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OpacityTextureEnabled",{get:function(){return m.a.OpacityTextureEnabled},set:function(e){m.a.OpacityTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ReflectionTextureEnabled",{get:function(){return m.a.ReflectionTextureEnabled},set:function(e){m.a.ReflectionTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"EmissiveTextureEnabled",{get:function(){return m.a.EmissiveTextureEnabled},set:function(e){m.a.EmissiveTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"SpecularTextureEnabled",{get:function(){return m.a.SpecularTextureEnabled},set:function(e){m.a.SpecularTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"BumpTextureEnabled",{get:function(){return m.a.BumpTextureEnabled},set:function(e){m.a.BumpTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"LightmapTextureEnabled",{get:function(){return m.a.LightmapTextureEnabled},set:function(e){m.a.LightmapTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"RefractionTextureEnabled",{get:function(){return m.a.RefractionTextureEnabled},set:function(e){m.a.RefractionTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ColorGradingTextureEnabled",{get:function(){return m.a.ColorGradingTextureEnabled},set:function(e){m.a.ColorGradingTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"FresnelEnabled",{get:function(){return m.a.FresnelEnabled},set:function(e){m.a.FresnelEnabled=e},enumerable:!0,configurable:!0}),Object(n.c)([Object(r.m)("diffuseTexture")],t.prototype,"_diffuseTexture",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"diffuseTexture",void 0),Object(n.c)([Object(r.m)("ambientTexture")],t.prototype,"_ambientTexture",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientTexture",void 0),Object(n.c)([Object(r.m)("opacityTexture")],t.prototype,"_opacityTexture",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"opacityTexture",void 0),Object(n.c)([Object(r.m)("reflectionTexture")],t.prototype,"_reflectionTexture",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionTexture",void 0),Object(n.c)([Object(r.m)("emissiveTexture")],t.prototype,"_emissiveTexture",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveTexture",void 0),Object(n.c)([Object(r.m)("specularTexture")],t.prototype,"_specularTexture",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"specularTexture",void 0),Object(n.c)([Object(r.m)("bumpTexture")],t.prototype,"_bumpTexture",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"bumpTexture",void 0),Object(n.c)([Object(r.m)("lightmapTexture")],t.prototype,"_lightmapTexture",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"lightmapTexture",void 0),Object(n.c)([Object(r.m)("refractionTexture")],t.prototype,"_refractionTexture",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"refractionTexture",void 0),Object(n.c)([Object(r.e)("ambient")],t.prototype,"ambientColor",void 0),Object(n.c)([Object(r.e)("diffuse")],t.prototype,"diffuseColor",void 0),Object(n.c)([Object(r.e)("specular")],t.prototype,"specularColor",void 0),Object(n.c)([Object(r.e)("emissive")],t.prototype,"emissiveColor",void 0),Object(n.c)([Object(r.c)()],t.prototype,"specularPower",void 0),Object(n.c)([Object(r.c)("useAlphaFromDiffuseTexture")],t.prototype,"_useAlphaFromDiffuseTexture",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAlphaFromDiffuseTexture",void 0),Object(n.c)([Object(r.c)("useEmissiveAsIllumination")],t.prototype,"_useEmissiveAsIllumination",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useEmissiveAsIllumination",void 0),Object(n.c)([Object(r.c)("linkEmissiveWithDiffuse")],t.prototype,"_linkEmissiveWithDiffuse",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"linkEmissiveWithDiffuse",void 0),Object(n.c)([Object(r.c)("useSpecularOverAlpha")],t.prototype,"_useSpecularOverAlpha",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useSpecularOverAlpha",void 0),Object(n.c)([Object(r.c)("useReflectionOverAlpha")],t.prototype,"_useReflectionOverAlpha",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useReflectionOverAlpha",void 0),Object(n.c)([Object(r.c)("disableLighting")],t.prototype,"_disableLighting",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),Object(n.c)([Object(r.c)("useObjectSpaceNormalMap")],t.prototype,"_useObjectSpaceNormalMap",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useObjectSpaceNormalMap",void 0),Object(n.c)([Object(r.c)("useParallax")],t.prototype,"_useParallax",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useParallax",void 0),Object(n.c)([Object(r.c)("useParallaxOcclusion")],t.prototype,"_useParallaxOcclusion",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useParallaxOcclusion",void 0),Object(n.c)([Object(r.c)()],t.prototype,"parallaxScaleBias",void 0),Object(n.c)([Object(r.c)("roughness")],t.prototype,"_roughness",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"roughness",void 0),Object(n.c)([Object(r.c)()],t.prototype,"indexOfRefraction",void 0),Object(n.c)([Object(r.c)()],t.prototype,"invertRefractionY",void 0),Object(n.c)([Object(r.c)()],t.prototype,"alphaCutOff",void 0),Object(n.c)([Object(r.c)("useLightmapAsShadowmap")],t.prototype,"_useLightmapAsShadowmap",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useLightmapAsShadowmap",void 0),Object(n.c)([Object(r.h)("diffuseFresnelParameters")],t.prototype,"_diffuseFresnelParameters",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsFresnelDirty")],t.prototype,"diffuseFresnelParameters",void 0),Object(n.c)([Object(r.h)("opacityFresnelParameters")],t.prototype,"_opacityFresnelParameters",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsFresnelAndMiscDirty")],t.prototype,"opacityFresnelParameters",void 0),Object(n.c)([Object(r.h)("reflectionFresnelParameters")],t.prototype,"_reflectionFresnelParameters",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsFresnelDirty")],t.prototype,"reflectionFresnelParameters",void 0),Object(n.c)([Object(r.h)("refractionFresnelParameters")],t.prototype,"_refractionFresnelParameters",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsFresnelDirty")],t.prototype,"refractionFresnelParameters",void 0),Object(n.c)([Object(r.h)("emissiveFresnelParameters")],t.prototype,"_emissiveFresnelParameters",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsFresnelDirty")],t.prototype,"emissiveFresnelParameters",void 0),Object(n.c)([Object(r.c)("useReflectionFresnelFromSpecular")],t.prototype,"_useReflectionFresnelFromSpecular",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsFresnelDirty")],t.prototype,"useReflectionFresnelFromSpecular",void 0),Object(n.c)([Object(r.c)("useGlossinessFromSpecularMapAlpha")],t.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useGlossinessFromSpecularMapAlpha",void 0),Object(n.c)([Object(r.c)("maxSimultaneousLights")],t.prototype,"_maxSimultaneousLights",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),Object(n.c)([Object(r.c)("invertNormalMapX")],t.prototype,"_invertNormalMapX",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapX",void 0),Object(n.c)([Object(r.c)("invertNormalMapY")],t.prototype,"_invertNormalMapY",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapY",void 0),Object(n.c)([Object(r.c)("twoSidedLighting")],t.prototype,"_twoSidedLighting",void 0),Object(n.c)([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"twoSidedLighting",void 0),Object(n.c)([Object(r.c)()],t.prototype,"useLogarithmicDepth",null),t}(d.a);_.a.RegisteredTypes["BABYLON.StandardMaterial"]=S,a.a.DefaultMaterialFactory=function(e){return new S("default material",e)}},function(e,t,i){"use strict";i.d(t,"a",function(){return o});var n=i(36),r=function(e,t){return e?e.getClassName&&"Mesh"===e.getClassName()?null:e.getClassName&&"SubMesh"===e.getClassName()?e.clone(t):e.clone?e.clone():null:null},o=function(){function e(){}return e.DeepCopy=function(e,t,i,o){for(var a in e)if(("_"!==a[0]||o&&-1!==o.indexOf(a))&&!(n.a.EndsWith(a,"Observable")||i&&-1!==i.indexOf(a))){var s=e[a],c=typeof s;if("function"!==c)try{if("object"===c)if(s instanceof Array){if(t[a]=[],s.length>0)if("object"==typeof s[0])for(var l=0;l<s.length;l++){var u=r(s[l],t);-1===t[a].indexOf(u)&&t[a].push(u)}else t[a]=s.slice(0)}else t[a]=r(s,t);else t[a]=s}catch(e){}}},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r}),i.d(t,"b",function(){return o});var n=i(1),r=function(){function e(t){this.length=0,this.data=new Array(t),this._id=e._GlobalId++}return e.prototype.push=function(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)},e.prototype.forEach=function(e){for(var t=0;t<this.length;t++)e(this.data[t])},e.prototype.sort=function(e){this.data.sort(e)},e.prototype.reset=function(){this.length=0},e.prototype.dispose=function(){this.reset(),this.data&&(this.data.length=0,this.data=[])},e.prototype.concat=function(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t<e.length;t++)this.data[this.length++]=(e.data||e)[t]}},e.prototype.indexOf=function(e){var t=this.data.indexOf(e);return t>=this.length?-1:t},e.prototype.contains=function(e){return-1!==this.indexOf(e)},e._GlobalId=0,e}(),o=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._duplicateId=0,t}return Object(n.d)(t,e),t.prototype.push=function(t){e.prototype.push.call(this,t),t.__smartArrayFlags||(t.__smartArrayFlags={}),t.__smartArrayFlags[this._id]=this._duplicateId},t.prototype.pushNoDuplicate=function(e){return(!e.__smartArrayFlags||e.__smartArrayFlags[this._id]!==this._duplicateId)&&(this.push(e),!0)},t.prototype.reset=function(){e.prototype.reset.call(this),this._duplicateId++},t.prototype.concatWithNoDuplicate=function(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t<e.length;t++){var i=(e.data||e)[t];this.pushNoDuplicate(i)}}},t}(r)},function(e,t,i){"use strict";i.d(t,"a",function(){return r});var n=i(125),r=function(){function e(){}return e.EnableFor=function(t){t._tags=t._tags||{},t.hasTags=function(){return e.HasTags(t)},t.addTags=function(i){return e.AddTagsTo(t,i)},t.removeTags=function(i){return e.RemoveTagsFrom(t,i)},t.matchesTagsQuery=function(i){return e.MatchesQuery(t,i)}},e.DisableFor=function(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery},e.HasTags=function(e){if(!e._tags)return!1;var t=e._tags;for(var i in t)if(t.hasOwnProperty(i))return!0;return!1},e.GetTags=function(e,t){if(void 0===t&&(t=!0),!e._tags)return null;if(t){var i=[];for(var n in e._tags)e._tags.hasOwnProperty(n)&&!0===e._tags[n]&&i.push(n);return i.join(" ")}return e._tags},e.AddTagsTo=function(t,i){i&&("string"==typeof i&&i.split(" ").forEach(function(i,n,r){e._AddTagTo(t,i)}))},e._AddTagTo=function(t,i){""!==(i=i.trim())&&"true"!==i&&"false"!==i&&(i.match(/[\s]/)||i.match(/^([!]|([|]|[&]){2})/)||(e.EnableFor(t),t._tags[i]=!0))},e.RemoveTagsFrom=function(t,i){if(e.HasTags(t)){var n=i.split(" ");for(var r in n)e._RemoveTagFrom(t,n[r])}},e._RemoveTagFrom=function(e,t){delete e._tags[t]},e.MatchesQuery=function(t,i){return void 0===i||(""===i?e.HasTags(t):n.a.Eval(i,function(i){return e.HasTags(t)&&t._tags[i]}))},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return e.EndsWith=function(e,t){return-1!==e.indexOf(t,e.length-t.length)},e.StartsWith=function(e,t){return 0===e.indexOf(t)},e.Decode=function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var t="",i=0;i<e.byteLength;i++)t+=String.fromCharCode(e[i]);return t},e.EncodeArrayBufferToBase64=function(e){for(var t,i,n,r,o,a,s,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l="",u=0,h=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);u<h.length;)r=(t=h[u++])>>2,o=(3&t)<<4|(i=u<h.length?h[u++]:Number.NaN)>>4,a=(15&i)<<2|(n=u<h.length?h[u++]:Number.NaN)>>6,s=63&n,isNaN(i)?a=s=64:isNaN(n)&&(s=64),l+=c.charAt(r)+c.charAt(o)+c.charAt(a)+c.charAt(s);return l},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){this.rootNodes=new Array,this.cameras=new Array,this.lights=new Array,this.meshes=new Array,this.skeletons=new Array,this.particleSystems=new Array,this.animations=[],this.animationGroups=new Array,this.multiMaterials=new Array,this.materials=new Array,this.morphTargetManagers=new Array,this.geometries=new Array,this.transformNodes=new Array,this.actionManagers=new Array,this.textures=new Array,this.environmentTexture=null}return e.AddParser=function(e,t){this._BabylonFileParsers[e]=t},e.GetParser=function(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null},e.AddIndividualParser=function(e,t){this._IndividualBabylonFileParsers[e]=t},e.GetIndividualParser=function(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null},e.Parse=function(e,t,i,n){for(var r in this._BabylonFileParsers)this._BabylonFileParsers.hasOwnProperty(r)&&this._BabylonFileParsers[r](e,t,i,n)},e.prototype.getNodes=function(){var e=new Array;return e=(e=(e=(e=e.concat(this.meshes)).concat(this.lights)).concat(this.cameras)).concat(this.transformNodes),this.skeletons.forEach(function(t){return e=e.concat(t.bones)}),e},e._BabylonFileParsers={},e._IndividualBabylonFileParsers={},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return e.IsWindowObjectExist=function(){return"undefined"!=typeof window},e.IsNavigatorAvailable=function(){return"undefined"!=typeof navigator},e.GetDOMTextContent=function(e){for(var t="",i=e.firstChild;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return l});var n=i(42),r=i(0),o=i(53),a=i(105),s=i(18),c=i(24),l=function(){function e(e,t,i){void 0===i&&(i=Number.MAX_VALUE),this.origin=e,this.direction=t,this.length=i}return e.prototype.intersectsBoxMinMax=function(t,i,n){void 0===n&&(n=0);var r,o,a,s,c=e.TmpVector3[0].copyFromFloats(t.x-n,t.y-n,t.z-n),l=e.TmpVector3[1].copyFromFloats(i.x+n,i.y+n,i.z+n),u=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<c.x||this.origin.x>l.x)return!1}else if(r=1/this.direction.x,o=(c.x-this.origin.x)*r,(a=(l.x-this.origin.x)*r)===-1/0&&(a=1/0),o>a&&(s=o,o=a,a=s),(u=Math.max(o,u))>(h=Math.min(a,h)))return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<c.y||this.origin.y>l.y)return!1}else if(r=1/this.direction.y,o=(c.y-this.origin.y)*r,(a=(l.y-this.origin.y)*r)===-1/0&&(a=1/0),o>a&&(s=o,o=a,a=s),(u=Math.max(o,u))>(h=Math.min(a,h)))return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<c.z||this.origin.z>l.z)return!1}else if(r=1/this.direction.z,o=(c.z-this.origin.z)*r,(a=(l.z-this.origin.z)*r)===-1/0&&(a=1/0),o>a&&(s=o,o=a,a=s),(u=Math.max(o,u))>(h=Math.min(a,h)))return!1;return!0},e.prototype.intersectsBox=function(e,t){return void 0===t&&(t=0),this.intersectsBoxMinMax(e.minimum,e.maximum,t)},e.prototype.intersectsSphere=function(e,t){void 0===t&&(t=0);var i=e.center.x-this.origin.x,n=e.center.y-this.origin.y,r=e.center.z-this.origin.z,o=i*i+n*n+r*r,a=e.radius+t,s=a*a;if(o<=s)return!0;var c=i*this.direction.x+n*this.direction.y+r*this.direction.z;return!(c<0)&&o-c*c<=s},e.prototype.intersectsTriangle=function(t,i,n){var o=e.TmpVector3[0],s=e.TmpVector3[1],c=e.TmpVector3[2],l=e.TmpVector3[3],u=e.TmpVector3[4];i.subtractToRef(t,o),n.subtractToRef(t,s),r.e.CrossToRef(this.direction,s,c);var h=r.e.Dot(o,c);if(0===h)return null;var d=1/h;this.origin.subtractToRef(t,l);var f=r.e.Dot(l,c)*d;if(f<0||f>1)return null;r.e.CrossToRef(l,o,u);var p=r.e.Dot(this.direction,u)*d;if(p<0||f+p>1)return null;var _=r.e.Dot(s,u)*d;return _>this.length?null:new a.a(1-f-p,f,_)},e.prototype.intersectsPlane=function(e){var t,i=r.e.Dot(e.normal,this.direction);if(Math.abs(i)<9.99999997475243e-7)return null;var n=r.e.Dot(e.normal,this.origin);return(t=(-e.d-n)/i)<0?t<-9.99999997475243e-7?null:0:t},e.prototype.intersectsAxis=function(e,t){switch(void 0===t&&(t=0),e){case"y":return(i=(this.origin.y-t)/this.direction.y)>0?null:new r.e(this.origin.x+this.direction.x*-i,t,this.origin.z+this.direction.z*-i);case"x":return(i=(this.origin.x-t)/this.direction.x)>0?null:new r.e(t,this.origin.y+this.direction.y*-i,this.origin.z+this.direction.z*-i);case"z":var i;return(i=(this.origin.z-t)/this.direction.z)>0?null:new r.e(this.origin.x+this.direction.x*-i,this.origin.y+this.direction.y*-i,t);default:return null}},e.prototype.intersectsMesh=function(t,i){var n=r.c.Matrix[0];return t.getWorldMatrix().invertToRef(n),this._tmpRay?e.TransformToRef(this,n,this._tmpRay):this._tmpRay=e.Transform(this,n),t.intersects(this._tmpRay,i)},e.prototype.intersectsMeshes=function(e,t,i){i?i.length=0:i=[];for(var n=0;n<e.length;n++){var r=this.intersectsMesh(e[n],t);r.hit&&i.push(r)}return i.sort(this._comparePickingInfo),i},e.prototype._comparePickingInfo=function(e,t){return e.distance<t.distance?-1:e.distance>t.distance?1:0},e.prototype.intersectionSegment=function(t,i,n){var o=this.origin,a=r.c.Vector3[0],s=r.c.Vector3[1],c=r.c.Vector3[2],l=r.c.Vector3[3];i.subtractToRef(t,a),this.direction.scaleToRef(e.rayl,c),o.addToRef(c,s),t.subtractToRef(o,l);var u,h,d,f,p=r.e.Dot(a,a),_=r.e.Dot(a,c),m=r.e.Dot(c,c),g=r.e.Dot(a,l),v=r.e.Dot(c,l),y=p*m-_*_,b=y,T=y;y<e.smallnum?(h=0,b=1,f=v,T=m):(f=p*v-_*g,(h=_*v-m*g)<0?(h=0,f=v,T=m):h>b&&(h=b,f=v+_,T=m)),f<0?(f=0,-g<0?h=0:-g>p?h=b:(h=-g,b=p)):f>T&&(f=T,-g+_<0?h=0:-g+_>p?h=b:(h=-g+_,b=p)),u=Math.abs(h)<e.smallnum?0:h/b,d=Math.abs(f)<e.smallnum?0:f/T;var E=r.c.Vector3[4];c.scaleToRef(d,E);var x=r.c.Vector3[5];a.scaleToRef(u,x),x.addInPlace(l);var P=r.c.Vector3[6];return x.subtractToRef(E,P),d>0&&d<=this.length&&P.lengthSquared()<n*n?x.length():-1},e.prototype.update=function(e,t,i,n,r,o,a){return this.unprojectRayToRef(e,t,i,n,r,o,a),this},e.Zero=function(){return new e(r.e.Zero(),r.e.Zero())},e.CreateNew=function(t,i,n,r,o,a,s){return e.Zero().update(t,i,n,r,o,a,s)},e.CreateNewFromTo=function(t,i,n){void 0===n&&(n=r.a.IdentityReadOnly);var o=i.subtract(t),a=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),e.Transform(new e(t,o,a),n)},e.Transform=function(t,i){var n=new e(new r.e(0,0,0),new r.e(0,0,0));return e.TransformToRef(t,i,n),n},e.TransformToRef=function(e,t,i){r.e.TransformCoordinatesToRef(e.origin,t,i.origin),r.e.TransformNormalToRef(e.direction,t,i.direction),i.length=e.length;var n=i.direction,o=n.length();if(0!==o&&1!==o){var a=1/o;n.x*=a,n.y*=a,n.z*=a,i.length*=o}},e.prototype.unprojectRayToRef=function(e,t,i,n,o,a,s){var c=r.c.Matrix[0];o.multiplyToRef(a,c),c.multiplyToRef(s,c),c.invert();var l=r.c.Vector3[0];l.x=e/i*2-1,l.y=-(t/n*2-1),l.z=-1;var u=r.c.Vector3[1].copyFromFloats(l.x,l.y,1),h=r.c.Vector3[2],d=r.c.Vector3[3];r.e._UnprojectFromInvertedMatrixToRef(l,c,h),r.e._UnprojectFromInvertedMatrixToRef(u,c,d),this.origin.copyFrom(h),d.subtractToRef(h,this.direction),this.direction.normalize()},e.TmpVector3=n.a.BuildArray(6,r.e.Zero),e.smallnum=1e-8,e.rayl=1e9,e}();s.a.prototype.createPickingRay=function(e,t,i,n,r){void 0===r&&(r=!1);var o=l.Zero();return this.createPickingRayToRef(e,t,i,o,n,r),o},s.a.prototype.createPickingRayToRef=function(e,t,i,n,o,a){void 0===a&&(a=!1);var s=this.getEngine();if(!o){if(!this.activeCamera)return this;o=this.activeCamera}var c=o.viewport.toGlobal(s.getRenderWidth(),s.getRenderHeight());return e=e/s.getHardwareScalingLevel()-c.x,t=t/s.getHardwareScalingLevel()-(s.getRenderHeight()-c.y-c.height),n.update(e,t,c.width,c.height,i||r.a.IdentityReadOnly,a?r.a.IdentityReadOnly:o.getViewMatrix(),o.getProjectionMatrix()),this},s.a.prototype.createPickingRayInCameraSpace=function(e,t,i){var n=l.Zero();return this.createPickingRayInCameraSpaceToRef(e,t,n,i),n},s.a.prototype.createPickingRayInCameraSpaceToRef=function(e,t,i,n){if(!o.a)return this;var a=this.getEngine();if(!n){if(!this.activeCamera)throw new Error("Active camera not set");n=this.activeCamera}var s=n.viewport.toGlobal(a.getRenderWidth(),a.getRenderHeight()),c=r.a.Identity();return e=e/a.getHardwareScalingLevel()-s.x,t=t/a.getHardwareScalingLevel()-(a.getRenderHeight()-s.y-s.height),i.update(e,t,s.width,s.height,c,c,n.getProjectionMatrix()),this},s.a.prototype._internalPick=function(e,t,i,n){if(!o.a)return null;for(var r=null,a=0;a<this.meshes.length;a++){var s=this.meshes[a];if(t){if(!t(s))continue}else if(!s.isEnabled()||!s.isVisible||!s.isPickable)continue;var c=e(s.getWorldMatrix()),l=s.intersects(c,i,n);if(l&&l.hit&&((i||null==r||!(l.distance>=r.distance))&&(r=l,i)))break}return r||new o.a},s.a.prototype._internalMultiPick=function(e,t,i){if(!o.a)return null;for(var n=new Array,r=0;r<this.meshes.length;r++){var a=this.meshes[r];if(t){if(!t(a))continue}else if(!a.isEnabled()||!a.isVisible||!a.isPickable)continue;var s=e(a.getWorldMatrix()),c=a.intersects(s,!1,i);c&&c.hit&&n.push(c)}return n},s.a.prototype.pick=function(e,t,i,n,a,s){var c=this;if(!o.a)return null;var u=this._internalPick(function(i){return c._tempPickingRay||(c._tempPickingRay=l.Zero()),c.createPickingRayToRef(e,t,i,c._tempPickingRay,a||null),c._tempPickingRay},i,n,s);return u&&(u.ray=this.createPickingRay(e,t,r.a.Identity(),a||null)),u},s.a.prototype.pickWithRay=function(e,t,i,n){var o=this,a=this._internalPick(function(t){return o._pickWithRayInverseMatrix||(o._pickWithRayInverseMatrix=r.a.Identity()),t.invertToRef(o._pickWithRayInverseMatrix),o._cachedRayForTransform||(o._cachedRayForTransform=l.Zero()),l.TransformToRef(e,o._pickWithRayInverseMatrix,o._cachedRayForTransform),o._cachedRayForTransform},t,i,n);return a&&(a.ray=e),a},s.a.prototype.multiPick=function(e,t,i,n,r){var o=this;return this._internalMultiPick(function(i){return o.createPickingRay(e,t,i,n||null)},i,r)},s.a.prototype.multiPickWithRay=function(e,t,i){var n=this;return this._internalMultiPick(function(t){return n._pickWithRayInverseMatrix||(n._pickWithRayInverseMatrix=r.a.Identity()),t.invertToRef(n._pickWithRayInverseMatrix),n._cachedRayForTransform||(n._cachedRayForTransform=l.Zero()),l.TransformToRef(e,n._pickWithRayInverseMatrix,n._cachedRayForTransform),n._cachedRayForTransform},t,i)},c.a.prototype.getForwardRay=function(e,t,i){void 0===e&&(e=100),t||(t=this.getWorldMatrix()),i||(i=this.position);var n=this._scene.useRightHandedSystem?new r.e(0,0,-1):new r.e(0,0,1),o=r.e.TransformNormal(n,t),a=r.e.Normalize(o);return new l(i,a,e)}},function(e,t,i){"use strict";i.d(t,"b",function(){return u}),i.d(t,"a",function(){return h});var n=i(1),r=i(3),o=i(6),a=i(13),s=i(10),c=i(73),l=i(111),u=function(e){function t(){var t=e.call(this)||this;return t.IMAGEPROCESSING=!1,t.VIGNETTE=!1,t.VIGNETTEBLENDMODEMULTIPLY=!1,t.VIGNETTEBLENDMODEOPAQUE=!1,t.TONEMAPPING=!1,t.TONEMAPPING_ACES=!1,t.CONTRAST=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=!1,t.SAMPLER3DBGRMAP=!1,t.IMAGEPROCESSINGPOSTPROCESS=!1,t.EXPOSURE=!1,t.rebuild(),t}return Object(n.d)(t,e),t}(c.a),h=function(){function e(){this.colorCurves=new l.a,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=e.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCentreX=0,this.vignetteCentreY=0,this.vignetteWeight=1.5,this.vignetteColor=new s.b(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=e.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new o.c}return Object.defineProperty(e.prototype,"colorCurvesEnabled",{get:function(){return this._colorCurvesEnabled},set:function(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"colorGradingTexture",{get:function(){return this._colorGradingTexture},set:function(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"colorGradingEnabled",{get:function(){return this._colorGradingEnabled},set:function(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"colorGradingWithGreenDepth",{get:function(){return this._colorGradingWithGreenDepth},set:function(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"colorGradingBGR",{get:function(){return this._colorGradingBGR},set:function(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"exposure",{get:function(){return this._exposure},set:function(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"toneMappingEnabled",{get:function(){return this._toneMappingEnabled},set:function(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"toneMappingType",{get:function(){return this._toneMappingType},set:function(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"contrast",{get:function(){return this._contrast},set:function(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"vignetteBlendMode",{get:function(){return this._vignetteBlendMode},set:function(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"vignetteEnabled",{get:function(){return this._vignetteEnabled},set:function(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"applyByPostProcess",{get:function(){return this._applyByPostProcess},set:function(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())},enumerable:!0,configurable:!0}),e.prototype._updateParameters=function(){this.onUpdateParameters.notifyObservers(this)},e.prototype.getClassName=function(){return"ImageProcessingConfiguration"},e.PrepareUniforms=function(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),t.VIGNETTE&&(e.push("vInverseScreenSize"),e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&l.a.PrepareUniforms(e)},e.PrepareSamplers=function(e,t){t.COLORGRADING&&e.push("txColorTransform")},e.prototype.prepareDefines=function(t,i){if(void 0===i&&(i=!1),i!==this.applyByPostProcess||!this._isEnabled)return t.VIGNETTE=!1,t.TONEMAPPING=!1,t.TONEMAPPING_ACES=!1,t.CONTRAST=!1,t.EXPOSURE=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.IMAGEPROCESSING=!1,void(t.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);switch(t.VIGNETTE=this.vignetteEnabled,t.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===e._VIGNETTEMODE_MULTIPLY,t.VIGNETTEBLENDMODEOPAQUE=!t.VIGNETTEBLENDMODEMULTIPLY,t.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType){case e.TONEMAPPING_ACES:t.TONEMAPPING_ACES=!0;break;default:t.TONEMAPPING_ACES=!1}t.CONTRAST=1!==this.contrast,t.EXPOSURE=1!==this.exposure,t.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,t.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,t.COLORGRADING?t.COLORGRADING3D=this.colorGradingTexture.is3D:t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,t.SAMPLER3DBGRMAP=this.colorGradingBGR,t.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,t.IMAGEPROCESSING=t.VIGNETTE||t.TONEMAPPING||t.CONTRAST||t.EXPOSURE||t.COLORCURVES||t.COLORGRADING},e.prototype.isReady=function(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()},e.prototype.bind=function(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&l.a.Bind(this.colorCurves,e),this._vignetteEnabled){var i=1/e.getEngine().getRenderWidth(),n=1/e.getEngine().getRenderHeight();e.setFloat2("vInverseScreenSize",i,n);var r=null!=t?t:n/i,o=Math.tan(.5*this.vignetteCameraFov),s=o*r,c=Math.sqrt(s*o);s=a.b.Mix(s,c,this.vignetteStretch),o=a.b.Mix(o,c,this.vignetteStretch),e.setFloat4("vignetteSettings1",s,o,-s*this.vignetteCentreX,-o*this.vignetteCentreY);var u=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,u)}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);var h=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(h-1)/h,.5/h,h,this.colorGradingTexture.level)}},e.prototype.clone=function(){return r.a.Clone(function(){return new e},this)},e.prototype.serialize=function(){return r.a.Serialize(this)},e.Parse=function(t){return r.a.Parse(function(){return new e},t,null,null)},Object.defineProperty(e,"VIGNETTEMODE_MULTIPLY",{get:function(){return this._VIGNETTEMODE_MULTIPLY},enumerable:!0,configurable:!0}),Object.defineProperty(e,"VIGNETTEMODE_OPAQUE",{get:function(){return this._VIGNETTEMODE_OPAQUE},enumerable:!0,configurable:!0}),e.TONEMAPPING_STANDARD=0,e.TONEMAPPING_ACES=1,e._VIGNETTEMODE_MULTIPLY=0,e._VIGNETTEMODE_OPAQUE=1,Object(n.c)([Object(r.g)()],e.prototype,"colorCurves",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_colorCurvesEnabled",void 0),Object(n.c)([Object(r.m)("colorGradingTexture")],e.prototype,"_colorGradingTexture",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_colorGradingEnabled",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_colorGradingWithGreenDepth",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_colorGradingBGR",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_exposure",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_toneMappingEnabled",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_toneMappingType",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_contrast",void 0),Object(n.c)([Object(r.c)()],e.prototype,"vignetteStretch",void 0),Object(n.c)([Object(r.c)()],e.prototype,"vignetteCentreX",void 0),Object(n.c)([Object(r.c)()],e.prototype,"vignetteCentreY",void 0),Object(n.c)([Object(r.c)()],e.prototype,"vignetteWeight",void 0),Object(n.c)([Object(r.f)()],e.prototype,"vignetteColor",void 0),Object(n.c)([Object(r.c)()],e.prototype,"vignetteCameraFov",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_vignetteBlendMode",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_vignetteEnabled",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_applyByPostProcess",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_isEnabled",void 0),e}();r.a._ImageProcessingConfigurationParser=h.Parse},function(e,t,i){"use strict";i.d(t,"a",function(){return u});var n=i(18),r=i(6),o=i(20),a=i(23),s=i(80),c=i(0),l=i(10),u=function(){function e(e,t){var i=this;void 0===t&&(t=!0),this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.onPointerOutObservable=new r.c,this.utilityLayerScene=new n.a(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add(function(t,n){if(i.utilityLayerScene.activeCamera&&(i.processAllEvents||t.type===o.a.POINTERMOVE||t.type===o.a.POINTERUP||t.type===o.a.POINTERDOWN)){i.utilityLayerScene.pointerX=e.pointerX,i.utilityLayerScene.pointerY=e.pointerY;var r=t.event;if(e.isPointerCaptured(r.pointerId))i._pointerCaptures[r.pointerId]=!1;else{var a=t.ray?i.utilityLayerScene.pickWithRay(t.ray):i.utilityLayerScene.pick(e.pointerX,e.pointerY);if(!t.ray&&a&&(t.ray=a.ray),i.utilityLayerScene.onPrePointerObservable.notifyObservers(t),i.onlyCheckPointerDownEvents&&t.type!=o.a.POINTERDOWN)return t.skipOnPointerObservable||i.utilityLayerScene.onPointerObservable.notifyObservers(new o.b(t.type,t.event,a)),void(t.type===o.a.POINTERUP&&i._pointerCaptures[r.pointerId]&&(i._pointerCaptures[r.pointerId]=!1));if(i.utilityLayerScene.autoClearDepthAndStencil||i.pickUtilitySceneFirst)a&&a.hit&&(t.skipOnPointerObservable||i.utilityLayerScene.onPointerObservable.notifyObservers(new o.b(t.type,t.event,a)),t.skipOnPointerObservable=!0);else{var s=t.ray?e.pickWithRay(t.ray):e.pick(e.pointerX,e.pointerY),c=t.event;s&&a&&(0===a.distance&&s.pickedMesh?i.mainSceneTrackerPredicate&&i.mainSceneTrackerPredicate(s.pickedMesh)?(i._notifyObservers(t,s,c),t.skipOnPointerObservable=!0):t.type===o.a.POINTERDOWN?i._pointerCaptures[c.pointerId]=!0:i._lastPointerEvents[c.pointerId]&&(i.onPointerOutObservable.notifyObservers(c.pointerId),delete i._lastPointerEvents[c.pointerId]):!i._pointerCaptures[c.pointerId]&&(a.distance<s.distance||0===s.distance)?(i._notifyObservers(t,a,c),t.skipOnPointerObservable||(t.skipOnPointerObservable=a.distance>0)):!i._pointerCaptures[c.pointerId]&&a.distance>s.distance&&(i.mainSceneTrackerPredicate&&i.mainSceneTrackerPredicate(s.pickedMesh)?(i._notifyObservers(t,s,c),t.skipOnPointerObservable=!0):i._lastPointerEvents[c.pointerId]&&(i.onPointerOutObservable.notifyObservers(c.pointerId),delete i._lastPointerEvents[c.pointerId])),t.type===o.a.POINTERUP&&i._pointerCaptures[c.pointerId]&&(i._pointerCaptures[c.pointerId]=!1))}}}}),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterCameraRenderObservable.add(function(e){i.shouldRender&&e==i.getRenderCamera()&&i.render()}),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add(function(){i.dispose()}),this._updateCamera()}return e.prototype.getRenderCamera=function(e){if(this._renderCamera)return this._renderCamera;var t=void 0;return t=this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t},e.prototype.setRenderCamera=function(e){this._renderCamera=e},e.prototype._getSharedGizmoLight=function(){return this._sharedGizmoLight||(this._sharedGizmoLight=new s.a("shared gizmo light",new c.e(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=l.a.Gray()),this._sharedGizmoLight},Object.defineProperty(e,"DefaultUtilityLayer",{get:function(){return null==e._DefaultUtilityLayer&&(e._DefaultUtilityLayer=new e(a.a.LastCreatedScene),e._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function(){e._DefaultUtilityLayer=null})),e._DefaultUtilityLayer},enumerable:!0,configurable:!0}),Object.defineProperty(e,"DefaultKeepDepthUtilityLayer",{get:function(){return null==e._DefaultKeepDepthUtilityLayer&&(e._DefaultKeepDepthUtilityLayer=new e(a.a.LastCreatedScene),e._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,e._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function(){e._DefaultKeepDepthUtilityLayer=null})),e._DefaultKeepDepthUtilityLayer},enumerable:!0,configurable:!0}),e.prototype._notifyObservers=function(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new o.b(e.type,e.event,t)),this._lastPointerEvents[i.pointerId]=!0)},e.prototype.render=function(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){var e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}},e.prototype.dispose=function(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()},e.prototype._updateCamera=function(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()},e._DefaultUtilityLayer=null,e._DefaultKeepDepthUtilityLayer=null,e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return e.BuildArray=function(e,t){for(var i=[],n=0;n<e;++n)i.push(t());return i},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return l});var n=i(1),r=i(3),o=i(6),a=i(0),s=i(26),c=i(22),l=function(e){function t(i,n,r){void 0===n&&(n=null),void 0===r&&(r=!0);var s=e.call(this,i,n)||this;return s._forward=new a.e(0,0,1),s._forwardInverted=new a.e(0,0,-1),s._up=new a.e(0,1,0),s._right=new a.e(1,0,0),s._rightInverted=new a.e(-1,0,0),s._position=a.e.Zero(),s._rotation=a.e.Zero(),s._rotationQuaternion=null,s._scaling=a.e.One(),s._isDirty=!1,s._transformToBoneReferal=null,s._isAbsoluteSynced=!1,s._billboardMode=t.BILLBOARDMODE_NONE,s._preserveParentRotationForBillboard=!1,s.scalingDeterminant=1,s._infiniteDistance=!1,s.ignoreNonUniformScaling=!1,s.reIntegrateRotationIntoRotationQuaternion=!1,s._poseMatrix=null,s._localMatrix=a.a.Zero(),s._usePivotMatrix=!1,s._absolutePosition=a.e.Zero(),s._absoluteScaling=a.e.Zero(),s._absoluteRotationQuaternion=a.b.Identity(),s._pivotMatrix=a.a.Identity(),s._postMultiplyPivotMatrix=!1,s._isWorldMatrixFrozen=!1,s._indexInSceneTransformNodesArray=-1,s.onAfterWorldMatrixUpdateObservable=new o.c,s._nonUniformScaling=!1,r&&s.getScene().addTransformNode(s),s}return Object(n.d)(t,e),Object.defineProperty(t.prototype,"billboardMode",{get:function(){return this._billboardMode},set:function(e){this._billboardMode!==e&&(this._billboardMode=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"preserveParentRotationForBillboard",{get:function(){return this._preserveParentRotationForBillboard},set:function(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"infiniteDistance",{get:function(){return this._infiniteDistance},set:function(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"TransformNode"},Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this._position=e,this._isDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return this._rotation},set:function(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this._scaling},set:function(e){this._scaling=e,this._isDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationQuaternion",{get:function(){return this._rotationQuaternion},set:function(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"forward",{get:function(){return a.e.Normalize(a.e.TransformNormal(this.getScene().useRightHandedSystem?this._forwardInverted:this._forward,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"up",{get:function(){return a.e.Normalize(a.e.TransformNormal(this._up,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return a.e.Normalize(a.e.TransformNormal(this.getScene().useRightHandedSystem?this._rightInverted:this._right,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),t.prototype.updatePoseMatrix=function(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)},t.prototype.getPoseMatrix=function(){return this._poseMatrix||(this._poseMatrix=a.a.Identity()),this._poseMatrix},t.prototype._isSynchronized=function(){var e=this._cache;if(this.billboardMode!==e.billboardMode||this.billboardMode!==t.BILLBOARDMODE_NONE)return!1;if(e.pivotMatrixUpdated)return!1;if(this.infiniteDistance)return!1;if(!e.position.equals(this._position))return!1;if(this._rotationQuaternion){if(!e.rotationQuaternion.equals(this._rotationQuaternion))return!1}else if(!e.rotation.equals(this._rotation))return!1;return!!e.scaling.equals(this._scaling)},t.prototype._initCache=function(){e.prototype._initCache.call(this);var t=this._cache;t.localMatrixUpdated=!1,t.position=a.e.Zero(),t.scaling=a.e.Zero(),t.rotation=a.e.Zero(),t.rotationQuaternion=new a.b(0,0,0,0),t.billboardMode=-1,t.infiniteDistance=!1},t.prototype.markAsDirty=function(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this},Object.defineProperty(t.prototype,"absolutePosition",{get:function(){return this._absolutePosition},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"absoluteScaling",{get:function(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"absoluteRotationQuaternion",{get:function(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion},enumerable:!0,configurable:!0}),t.prototype.setPreTransformMatrix=function(e){return this.setPivotMatrix(e,!1)},t.prototype.setPivotMatrix=function(e,t){return void 0===t&&(t=!0),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=a.a.Invert(this._pivotMatrix)),this},t.prototype.getPivotMatrix=function(){return this._pivotMatrix},t.prototype.instantiateHierarchy=function(e,t,i){void 0===e&&(e=null);var n=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);n&&i&&i(this,n);for(var r=0,o=this.getChildTransformNodes(!0);r<o.length;r++){o[r].instantiateHierarchy(n,t,i)}return n},t.prototype.freezeWorldMatrix=function(e){return void 0===e&&(e=null),e?this._worldMatrix=e:(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this},t.prototype.unfreezeWorldMatrix=function(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this},Object.defineProperty(t.prototype,"isWorldMatrixFrozen",{get:function(){return this._isWorldMatrixFrozen},enumerable:!0,configurable:!0}),t.prototype.getAbsolutePosition=function(){return this.computeWorldMatrix(),this._absolutePosition},t.prototype.setAbsolutePosition=function(e){if(!e)return this;var t,i,n;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],n=arguments[2]}else t=e.x,i=e.y,n=e.z;if(this.parent){var r=a.c.Matrix[0];this.parent.getWorldMatrix().invertToRef(r),a.e.TransformCoordinatesFromFloatsToRef(t,i,n,r,this.position)}else this.position.x=t,this.position.y=i,this.position.z=n;return this},t.prototype.setPositionWithLocalVector=function(e){return this.computeWorldMatrix(),this.position=a.e.TransformNormal(e,this._localMatrix),this},t.prototype.getPositionExpressedInLocalSpace=function(){this.computeWorldMatrix();var e=a.c.Matrix[0];return this._localMatrix.invertToRef(e),a.e.TransformNormal(this.position,e)},t.prototype.locallyTranslate=function(e){return this.computeWorldMatrix(!0),this.position=a.e.TransformCoordinates(e,this._localMatrix),this},t.prototype.lookAt=function(e,i,n,r,o){void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=0),void 0===o&&(o=c.b.LOCAL);var s=t._lookAtVectorCache,l=o===c.b.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(l,s),this.setDirection(s,i,n,r),o===c.b.WORLD&&this.parent)if(this.rotationQuaternion){var u=a.c.Matrix[0];this.rotationQuaternion.toRotationMatrix(u);var h=a.c.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(h),h.invert(),u.multiplyToRef(h,u),this.rotationQuaternion.fromRotationMatrix(u)}else{var d=a.c.Quaternion[0];a.b.FromEulerVectorToRef(this.rotation,d);u=a.c.Matrix[0];d.toRotationMatrix(u);h=a.c.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(h),h.invert(),u.multiplyToRef(h,u),d.fromRotationMatrix(u),d.toEulerAnglesToRef(this.rotation)}return this},t.prototype.getDirection=function(e){var t=a.e.Zero();return this.getDirectionToRef(e,t),t},t.prototype.getDirectionToRef=function(e,t){return a.e.TransformNormalToRef(e,this.getWorldMatrix(),t),this},t.prototype.setDirection=function(e,t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0);var r=-Math.atan2(e.z,e.x)+Math.PI/2,o=Math.sqrt(e.x*e.x+e.z*e.z),s=-Math.atan2(e.y,o);return this.rotationQuaternion?a.b.RotationYawPitchRollToRef(r+t,s+i,n,this.rotationQuaternion):(this.rotation.x=s+i,this.rotation.y=r+t,this.rotation.z=n),this},t.prototype.setPivotPoint=function(e,t){void 0===t&&(t=c.b.LOCAL),0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);var i=this.getWorldMatrix();if(t==c.b.WORLD){var n=a.c.Matrix[0];i.invertToRef(n),e=a.e.TransformCoordinates(e,n)}return this.setPivotMatrix(a.a.Translation(-e.x,-e.y,-e.z),!0)},t.prototype.getPivotPoint=function(){var e=a.e.Zero();return this.getPivotPointToRef(e),e},t.prototype.getPivotPointToRef=function(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this},t.prototype.getAbsolutePivotPoint=function(){var e=a.e.Zero();return this.getAbsolutePivotPointToRef(e),e},t.prototype.getAbsolutePivotPointToRef=function(e){return e.x=this._pivotMatrix.m[12],e.y=this._pivotMatrix.m[13],e.z=this._pivotMatrix.m[14],this.getPivotPointToRef(e),a.e.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this},t.prototype.setParent=function(e){if(!e&&!this.parent)return this;var t=a.c.Quaternion[0],i=a.c.Vector3[0],n=a.c.Vector3[1];if(e){var r=a.c.Matrix[0],o=a.c.Matrix[1];this.computeWorldMatrix(!0),e.computeWorldMatrix(!0),e.getWorldMatrix().invertToRef(o),this.getWorldMatrix().multiplyToRef(o,r),r.decompose(n,t,i)}else this.computeWorldMatrix(!0),this.getWorldMatrix().decompose(n,t,i);return this.rotationQuaternion?this.rotationQuaternion.copyFrom(t):t.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(i),this.parent=e,this},Object.defineProperty(t.prototype,"nonUniformScaling",{get:function(){return this._nonUniformScaling},enumerable:!0,configurable:!0}),t.prototype._updateNonUniformScalingState=function(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)},t.prototype.attachToBone=function(e,t){return this._transformToBoneReferal=t,this.parent=e,e.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this},t.prototype.detachFromBone=function(){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=null,this):this},t.prototype.rotate=function(e,i,n){var r;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),n&&n!==c.b.LOCAL){if(this.parent){var o=a.c.Matrix[0];this.parent.getWorldMatrix().invertToRef(o),e=a.e.TransformNormal(e,o)}(r=a.b.RotationAxisToRef(e,i,t._rotationAxisCache)).multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else r=a.b.RotationAxisToRef(e,i,t._rotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);return this},t.prototype.rotateAround=function(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=a.b.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));var n=a.c.Vector3[0],r=a.c.Vector3[1],o=a.c.Vector3[2],s=a.c.Quaternion[0],c=a.c.Matrix[0],l=a.c.Matrix[1],u=a.c.Matrix[2],h=a.c.Matrix[3];return e.subtractToRef(this.position,n),a.a.TranslationToRef(n.x,n.y,n.z,c),a.a.TranslationToRef(-n.x,-n.y,-n.z,l),a.a.RotationAxisToRef(t,i,u),l.multiplyToRef(u,h),h.multiplyToRef(c,h),h.decompose(r,s,o),this.position.addInPlace(o),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this},t.prototype.translate=function(e,t,i){var n=e.scale(t);if(i&&i!==c.b.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(n));else{var r=this.getPositionExpressedInLocalSpace().add(n);this.setPositionWithLocalVector(r)}return this},t.prototype.addRotation=function(e,t,i){var n;this.rotationQuaternion?n=this.rotationQuaternion:(n=a.c.Quaternion[1],a.b.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,n));var r=a.c.Quaternion[0];return a.b.RotationYawPitchRollToRef(t,e,i,r),n.multiplyInPlace(r),this.rotationQuaternion||n.toEulerAnglesToRef(this.rotation),this},t.prototype._getEffectiveParent=function(){return this.parent},t.prototype.computeWorldMatrix=function(e){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;var i=this.getScene().getRenderId();if(!this._isDirty&&!e&&this.isSynchronized())return this._currentRenderId=i,this._worldMatrix;var n=this.getScene().activeCamera,r=0!=(this._billboardMode&t.BILLBOARDMODE_USE_POSITION),o=this._billboardMode!==t.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard;o&&n&&r&&(this.lookAt(n.position),(this.billboardMode&t.BILLBOARDMODE_X)!==t.BILLBOARDMODE_X&&(this.rotation.x=0),(this.billboardMode&t.BILLBOARDMODE_Y)!==t.BILLBOARDMODE_Y&&(this.rotation.y=0),(this.billboardMode&t.BILLBOARDMODE_Z)!==t.BILLBOARDMODE_Z&&(this.rotation.z=0)),this._updateCache();var s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,this._currentRenderId=i,this._childUpdateId++,this._isDirty=!1;var c=this._getEffectiveParent(),l=s.scaling,u=s.position;if(this._infiniteDistance)if(!this.parent&&n){var h=n.getWorldMatrix(),d=new a.e(h.m[12],h.m[13],h.m[14]);u.copyFromFloats(this._position.x+d.x,this._position.y+d.y,this._position.z+d.z)}else u.copyFrom(this._position);else u.copyFrom(this._position);l.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant);var f=s.rotationQuaternion;if(this._rotationQuaternion){if(this.reIntegrateRotationIntoRotationQuaternion)this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(a.b.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0));f.copyFrom(this._rotationQuaternion)}else a.b.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,f),s.rotation.copyFrom(this._rotation);if(this._usePivotMatrix){var p=a.c.Matrix[1];a.a.ScalingToRef(l.x,l.y,l.z,p);var _=a.c.Matrix[0];f.toRotationMatrix(_),this._pivotMatrix.multiplyToRef(p,a.c.Matrix[4]),a.c.Matrix[4].multiplyToRef(_,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(u.x,u.y,u.z)}else a.a.ComposeToRef(l,f,u,this._localMatrix);if(c&&c.getWorldMatrix){if(e&&c.computeWorldMatrix(),o){this._transformToBoneReferal?c.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),a.c.Matrix[7]):a.c.Matrix[7].copyFrom(c.getWorldMatrix());var m=a.c.Vector3[5],g=a.c.Vector3[6];a.c.Matrix[7].decompose(g,void 0,m),a.a.ScalingToRef(g.x,g.y,g.z,a.c.Matrix[7]),a.c.Matrix[7].setTranslation(m),this._localMatrix.multiplyToRef(a.c.Matrix[7],this._worldMatrix)}else this._transformToBoneReferal?(this._localMatrix.multiplyToRef(c.getWorldMatrix(),a.c.Matrix[6]),a.c.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localMatrix.multiplyToRef(c.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(o&&n&&this.billboardMode&&!r){var v=a.c.Vector3[0];if(this._worldMatrix.getTranslationToRef(v),a.c.Matrix[1].copyFrom(n.getViewMatrix()),a.c.Matrix[1].setTranslationFromFloats(0,0,0),a.c.Matrix[1].invertToRef(a.c.Matrix[0]),(this.billboardMode&t.BILLBOARDMODE_ALL)!==t.BILLBOARDMODE_ALL){a.c.Matrix[0].decompose(void 0,a.c.Quaternion[0],void 0);var y=a.c.Vector3[1];a.c.Quaternion[0].toEulerAnglesToRef(y),(this.billboardMode&t.BILLBOARDMODE_X)!==t.BILLBOARDMODE_X&&(y.x=0),(this.billboardMode&t.BILLBOARDMODE_Y)!==t.BILLBOARDMODE_Y&&(y.y=0),(this.billboardMode&t.BILLBOARDMODE_Z)!==t.BILLBOARDMODE_Z&&(y.z=0),a.a.RotationYawPitchRollToRef(y.y,y.x,y.z,a.c.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(a.c.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(a.c.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniform?this._updateNonUniformScalingState(!0):c&&c._nonUniformScaling?this._updateNonUniformScalingState(c._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=a.a.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix},t.prototype.resetLocalMatrix=function(e){if(void 0===e&&(e=!0),this.computeWorldMatrix(),e)for(var t=this.getChildren(),i=0;i<t.length;++i){var n=t[i];if(n){n.computeWorldMatrix();var r=a.c.Matrix[0];n._localMatrix.multiplyToRef(this._localMatrix,r);var o=a.c.Quaternion[0];r.decompose(n.scaling,o,n.position),n.rotationQuaternion?n.rotationQuaternion=o:o.toEulerAnglesToRef(n.rotation)}}this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=a.b.Identity()),this._worldMatrix=a.a.Identity()},t.prototype._afterComputeWorldMatrix=function(){},t.prototype.registerAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this},t.prototype.unregisterAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this},t.prototype.getPositionInCameraSpace=function(e){return void 0===e&&(e=null),e||(e=this.getScene().activeCamera),a.e.TransformCoordinates(this.absolutePosition,e.getViewMatrix())},t.prototype.getDistanceToCamera=function(e){return void 0===e&&(e=null),e||(e=this.getScene().activeCamera),this.absolutePosition.subtract(e.globalPosition).length()},t.prototype.clone=function(e,i,n){var o=this,a=r.a.Clone(function(){return new t(e,o.getScene())},this);if(a.name=e,a.id=e,i&&(a.parent=i),!n)for(var s=this.getDescendants(!0),c=0;c<s.length;c++){var l=s[c];l.clone&&l.clone(e+"."+l.name,a)}return a},t.prototype.serialize=function(e){var t=r.a.Serialize(this,e);return t.type=this.getClassName(),this.parent&&(t.parentId=this.parent.id),t.localMatrix=this.getPivotMatrix().asArray(),t.isEnabled=this.isEnabled(),this.parent&&(t.parentId=this.parent.id),t},t.Parse=function(e,i,n){var o=r.a.Parse(function(){return new t(e.name,i)},e,i,n);return e.localMatrix?o.setPreTransformMatrix(a.a.FromArray(e.localMatrix)):e.pivotMatrix&&o.setPivotMatrix(a.a.FromArray(e.pivotMatrix)),o.setEnabled(e.isEnabled),e.parentId&&(o._waitingParentId=e.parentId),o},t.prototype.getChildTransformNodes=function(e,i){var n=[];return this._getDescendants(n,e,function(e){return(!i||i(e))&&e instanceof t}),n},t.prototype.dispose=function(t,i){if(void 0===i&&(i=!1),this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this.onAfterWorldMatrixUpdateObservable.clear(),t)for(var n=0,r=this.getChildTransformNodes(!0);n<r.length;n++){var o=r[n];o.parent=null,o.computeWorldMatrix(!0)}e.prototype.dispose.call(this,t,i)},t.prototype.normalizeToUnitCube=function(e,t,i){void 0===e&&(e=!0),void 0===t&&(t=!1);var n=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(n=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));var o=this.getHierarchyBoundingVectors(e,i),a=o.max.subtract(o.min),s=Math.max(a.x,a.y,a.z);if(0===s)return this;var c=1/s;return this.scaling.scaleInPlace(c),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&n&&this.rotation.copyFrom(n)),this},t.prototype._syncAbsoluteScalingAndRotation=function(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)},t.BILLBOARDMODE_NONE=0,t.BILLBOARDMODE_X=1,t.BILLBOARDMODE_Y=2,t.BILLBOARDMODE_Z=4,t.BILLBOARDMODE_ALL=7,t.BILLBOARDMODE_USE_POSITION=128,t._lookAtVectorCache=new a.e(0,0,0),t._rotationAxisCache=new a.b,Object(n.c)([Object(r.o)("position")],t.prototype,"_position",void 0),Object(n.c)([Object(r.o)("rotation")],t.prototype,"_rotation",void 0),Object(n.c)([Object(r.l)("rotationQuaternion")],t.prototype,"_rotationQuaternion",void 0),Object(n.c)([Object(r.o)("scaling")],t.prototype,"_scaling",void 0),Object(n.c)([Object(r.c)("billboardMode")],t.prototype,"_billboardMode",void 0),Object(n.c)([Object(r.c)()],t.prototype,"scalingDeterminant",void 0),Object(n.c)([Object(r.c)("infiniteDistance")],t.prototype,"_infiniteDistance",void 0),Object(n.c)([Object(r.c)()],t.prototype,"ignoreNonUniformScaling",void 0),Object(n.c)([Object(r.c)()],t.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0),t}(s.a)},function(e,t,i){"use strict";i.d(t,"a",function(){return d});var n=i(42),r=i(0),o=i(2),a=i(96),s=i(104),c={min:0,max:0},l={min:0,max:0},u=function(e,t,i){var n=r.e.Dot(t.centerWorld,e),o=Math.abs(r.e.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(r.e.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(r.e.Dot(t.directions[2],e))*t.extendSize.z;i.min=n-o,i.max=n+o},h=function(e,t,i){return u(e,t,c),u(e,i,l),!(c.min>l.max||l.min>c.max)},d=function(){function e(e,t,i){this._isLocked=!1,this.boundingBox=new a.a(e,t,i),this.boundingSphere=new s.a(e,t,i)}return e.prototype.reConstruct=function(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)},Object.defineProperty(e.prototype,"minimum",{get:function(){return this.boundingBox.minimum},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maximum",{get:function(){return this.boundingBox.maximum},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isLocked",{get:function(){return this._isLocked},set:function(e){this._isLocked=e},enumerable:!0,configurable:!0}),e.prototype.update=function(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))},e.prototype.centerOn=function(t,i){var n=e.TmpVector3[0].copyFrom(t).subtractInPlace(i),r=e.TmpVector3[1].copyFrom(t).addInPlace(i);return this.boundingBox.reConstruct(n,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(n,r,this.boundingBox.getWorldMatrix()),this},e.prototype.scale=function(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this},e.prototype.isInFrustum=function(e,t){return void 0===t&&(t=o.a.MESHES_CULLINGSTRATEGY_STANDARD),!(t!==o.a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION&&t!==o.a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY||!this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(!(t!==o.a.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY&&t!==o.a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY)||this.boundingBox.isInFrustum(e))},Object.defineProperty(e.prototype,"diagonalLength",{get:function(){var t=this.boundingBox;return t.maximumWorld.subtractToRef(t.minimumWorld,e.TmpVector3[0]).length()},enumerable:!0,configurable:!0}),e.prototype.isCompletelyInFrustum=function(e){return this.boundingBox.isCompletelyInFrustum(e)},e.prototype._checkCollision=function(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)},e.prototype.intersectsPoint=function(e){return!!this.boundingSphere.centerWorld&&(!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e))},e.prototype.intersects=function(e,t){if(!s.a.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!a.a.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;var i=this.boundingBox,n=e.boundingBox;return!!h(i.directions[0],i,n)&&(!!h(i.directions[1],i,n)&&(!!h(i.directions[2],i,n)&&(!!h(n.directions[0],i,n)&&(!!h(n.directions[1],i,n)&&(!!h(n.directions[2],i,n)&&(!!h(r.e.Cross(i.directions[0],n.directions[0]),i,n)&&(!!h(r.e.Cross(i.directions[0],n.directions[1]),i,n)&&(!!h(r.e.Cross(i.directions[0],n.directions[2]),i,n)&&(!!h(r.e.Cross(i.directions[1],n.directions[0]),i,n)&&(!!h(r.e.Cross(i.directions[1],n.directions[1]),i,n)&&(!!h(r.e.Cross(i.directions[1],n.directions[2]),i,n)&&(!!h(r.e.Cross(i.directions[2],n.directions[0]),i,n)&&(!!h(r.e.Cross(i.directions[2],n.directions[1]),i,n)&&!!h(r.e.Cross(i.directions[2],n.directions[2]),i,n))))))))))))))},e.TmpVector3=n.a.BuildArray(2,r.e.Zero),e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(e,t,i,n,r,o){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=n,this.sourceEvent=r,this.additionalData=o}return e.CreateNew=function(t,i,n){var r=t.getScene();return new e(t,r.pointerX,r.pointerY,r.meshUnderPointer||t,i,n)},e.CreateNewFromSprite=function(t,i,n,r){return new e(t,i.pointerX,i.pointerY,i.meshUnderPointer,n,r)},e.CreateNewFromScene=function(t,i){return new e(null,t.pointerX,t.pointerY,t.meshUnderPointer,i)},e.CreateNewFromPrimitive=function(t,i,n,r){return new e(t,i.x,i.y,null,n,r)},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return c});var n=i(0),r=i(5),o=i(15),a=i(92),s=i(4);o.a.CreateLineSystem=function(e){for(var t=[],i=[],n=e.lines,r=e.colors,a=[],s=0,c=0;c<n.length;c++)for(var l=n[c],u=0;u<l.length;u++){if(i.push(l[u].x,l[u].y,l[u].z),r){var h=r[c];a.push(h[u].r,h[u].g,h[u].b,h[u].a)}u>0&&(t.push(s-1),t.push(s)),s++}var d=new o.a;return d.indices=t,d.positions=i,r&&(d.colors=a),d},o.a.CreateDashedLines=function(e){var t,i,r=e.dashSize||3,a=e.gapSize||1,s=e.dashNb||200,c=e.points,l=new Array,u=new Array,h=n.e.Zero(),d=0,f=0,p=0,_=0,m=0;for(m=0;m<c.length-1;m++)c[m+1].subtractToRef(c[m],h),d+=h.length();for(i=r*(t=d/s)/(r+a),m=0;m<c.length-1;m++){c[m+1].subtractToRef(c[m],h),f=Math.floor(h.length()/t),h.normalize();for(var g=0;g<f;g++)p=t*g,l.push(c[m].x+p*h.x,c[m].y+p*h.y,c[m].z+p*h.z),l.push(c[m].x+(p+i)*h.x,c[m].y+(p+i)*h.y,c[m].z+(p+i)*h.z),u.push(_,_+1),_+=2}var v=new o.a;return v.positions=l,v.indices=u,v},r.a.CreateLines=function(e,t,i,n,r){void 0===i&&(i=null),void 0===n&&(n=!1),void 0===r&&(r=null);var o={points:t,updatable:n,instance:r};return c.CreateLines(e,o,i)},r.a.CreateDashedLines=function(e,t,i,n,r,o,a,s){void 0===o&&(o=null);var l={points:t,dashSize:i,gapSize:n,dashNb:r,updatable:a,instance:s};return c.CreateDashedLines(e,l,o)};var c=function(){function e(){}return e.CreateLineSystem=function(e,t,i){var n=t.instance,r=t.lines,c=t.colors;if(n){var l,u,h=n.getVerticesData(s.b.PositionKind);c&&(l=n.getVerticesData(s.b.ColorKind));for(var d=0,f=0,p=0;p<r.length;p++)for(var _=r[p],m=0;m<_.length;m++)h[d]=_[m].x,h[d+1]=_[m].y,h[d+2]=_[m].z,c&&l&&(u=c[p],l[f]=u[m].r,l[f+1]=u[m].g,l[f+2]=u[m].b,l[f+3]=u[m].a,f+=4),d+=3;return n.updateVerticesData(s.b.PositionKind,h,!1,!1),c&&l&&n.updateVerticesData(s.b.ColorKind,l,!1,!1),n}var g=!!c,v=new a.b(e,i,null,void 0,void 0,g,t.useVertexAlpha);return o.a.CreateLineSystem(t).applyToMesh(v,t.updatable),v},e.CreateLines=function(t,i,n){void 0===n&&(n=null);var r=i.colors?[i.colors]:null;return e.CreateLineSystem(t,{lines:[i.points],updatable:i.updatable,instance:i.instance,colors:r,useVertexAlpha:i.useVertexAlpha},n)},e.CreateDashedLines=function(e,t,i){void 0===i&&(i=null);var s=t.points,c=t.instance,l=t.gapSize||1,u=t.dashSize||3;if(c){return c.updateMeshPositions(function(e){var t,i,r=n.e.Zero(),o=e.length/6,a=0,l=0,u=0,h=0,d=0,f=0;for(d=0;d<s.length-1;d++)s[d+1].subtractToRef(s[d],r),a+=r.length();t=a/o;var p=c._creationDataStorage.dashSize;for(i=p*t/(p+c._creationDataStorage.gapSize),d=0;d<s.length-1;d++)for(s[d+1].subtractToRef(s[d],r),l=Math.floor(r.length()/t),r.normalize(),f=0;f<l&&h<e.length;)u=t*f,e[h]=s[d].x+u*r.x,e[h+1]=s[d].y+u*r.y,e[h+2]=s[d].z+u*r.z,e[h+3]=s[d].x+(u+i)*r.x,e[h+4]=s[d].y+(u+i)*r.y,e[h+5]=s[d].z+(u+i)*r.z,h+=6,f++;for(;h<e.length;)e[h]=s[d].x,e[h+1]=s[d].y,e[h+2]=s[d].z,h+=3},!1),c}var h=new a.b(e,i,null,void 0,void 0,void 0,t.useVertexAlpha);return o.a.CreateDashedLines(t).applyToMesh(h,t.updatable),h._creationDataStorage=new r.b,h._creationDataStorage.dashSize=u,h._creationDataStorage.gapSize=l,h},e}()},function(e,t,i){"use strict";i.d(t,"e",function(){return r}),i.d(t,"a",function(){return o}),i.d(t,"d",function(){return a}),i.d(t,"c",function(){return s}),i.d(t,"b",function(){return c});var n=i(1),r=function(){function e(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}return Object.defineProperty(e.prototype,"physicsJoint",{get:function(){return this._physicsJoint},set:function(e){this._physicsJoint,this._physicsJoint=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"physicsPlugin",{set:function(e){this._physicsPlugin=e},enumerable:!0,configurable:!0}),e.prototype.executeNativeFunction=function(e){e(this._physicsPlugin.world,this._physicsJoint)},e.DistanceJoint=0,e.HingeJoint=1,e.BallAndSocketJoint=2,e.WheelJoint=3,e.SliderJoint=4,e.PrismaticJoint=5,e.UniversalJoint=6,e.Hinge2Joint=e.WheelJoint,e.PointToPointJoint=8,e.SpringJoint=9,e.LockJoint=10,e}(),o=function(e){function t(t){return e.call(this,r.DistanceJoint,t)||this}return Object(n.d)(t,e),t.prototype.updateDistance=function(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)},t}(r),a=function(e){function t(t,i){return e.call(this,t,i)||this}return Object(n.d)(t,e),t.prototype.setMotor=function(e,t){this._physicsPlugin.setMotor(this,e||0,t)},t.prototype.setLimit=function(e,t){this._physicsPlugin.setLimit(this,e,t)},t}(r),s=function(e){function t(t){return e.call(this,r.HingeJoint,t)||this}return Object(n.d)(t,e),t.prototype.setMotor=function(e,t){this._physicsPlugin.setMotor(this,e||0,t)},t.prototype.setLimit=function(e,t){this._physicsPlugin.setLimit(this,e,t)},t}(a),c=function(e){function t(t){return e.call(this,r.Hinge2Joint,t)||this}return Object(n.d)(t,e),t.prototype.setMotor=function(e,t,i){void 0===i&&(i=0),this._physicsPlugin.setMotor(this,e||0,t,i)},t.prototype.setLimit=function(e,t,i){void 0===i&&(i=0),this._physicsPlugin.setLimit(this,e,t,i)},t}(a)},function(e,t,i){"use strict";i.d(t,"a",function(){return a});var n=i(0),r=i(5),o=i(15);o.a.CreateSphere=function(e){for(var t=e.segments||32,i=e.diameterX||e.diameter||1,r=e.diameterY||e.diameter||1,a=e.diameterZ||e.diameter||1,s=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,c=e.slice&&e.slice<=0?1:e.slice||1,l=0===e.sideOrientation?0:e.sideOrientation||o.a.DEFAULTSIDE,u=new n.e(i/2,r/2,a/2),h=2+t,d=2*h,f=[],p=[],_=[],m=[],g=0;g<=h;g++){for(var v=g/h,y=v*Math.PI*c,b=0;b<=d;b++){var T=b/d,E=T*Math.PI*2*s,x=n.a.RotationZ(-y),P=n.a.RotationY(E),A=n.e.TransformCoordinates(n.e.Up(),x),S=n.e.TransformCoordinates(A,P),C=S.multiply(u),R=S.divide(u).normalize();p.push(C.x,C.y,C.z),_.push(R.x,R.y,R.z),m.push(T,v)}if(g>0)for(var O=p.length/3,M=O-2*(d+1);M+d+2<O;M++)f.push(M),f.push(M+1),f.push(M+d+1),f.push(M+d+1),f.push(M+1),f.push(M+d+2)}o.a._ComputeSides(l,p,f,_,m,e.frontUVs,e.backUVs);var I=new o.a;return I.indices=f,I.positions=p,I.normals=_,I.uvs=m,I},r.a.CreateSphere=function(e,t,i,n,r,o){var s={segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:o,updatable:r};return a.CreateSphere(e,s,n)};var a=function(){function e(){}return e.CreateSphere=function(e,t,i){void 0===i&&(i=null);var n=new r.a(e,i);return t.sideOrientation=r.a._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,o.a.CreateSphere(t).applyToMesh(n,t.updatable),n},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return h});var n=i(1),r=i(3),o=i(6),a=i(0),s=i(23),c=i(2),l=i(137),u=i(68),h=(i(54),function(){function e(t){this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this.getAlphaFromRGB=!1,this.level=1,this.coordinatesIndex=0,this._coordinatesMode=c.a.TEXTURE_EXPLICIT_MODE,this.wrapU=c.a.TEXTURE_WRAP_ADDRESSMODE,this.wrapV=c.a.TEXTURE_WRAP_ADDRESSMODE,this.wrapR=c.a.TEXTURE_WRAP_ADDRESSMODE,this.anisotropicFilteringLevel=e.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this.gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this.animations=new Array,this.onDisposeObservable=new o.c,this._onDisposeObserver=null,this.delayLoadState=c.a.DELAYLOADSTATE_NONE,this._scene=null,this._texture=null,this._uid=null,this._cachedSize=u.a.Zero(),this._scene=t||s.a.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this)),this._uid=null}return Object.defineProperty(e.prototype,"hasAlpha",{get:function(){return this._hasAlpha},set:function(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(c.a.MATERIAL_TextureDirtyFlag|c.a.MATERIAL_MiscDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"coordinatesMode",{get:function(){return this._coordinatesMode},set:function(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(c.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isCube",{get:function(){return!!this._texture&&this._texture.isCube},set:function(e){this._texture&&(this._texture.isCube=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"is3D",{get:function(){return!!this._texture&&this._texture.is3D},set:function(e){this._texture&&(this._texture.is3D=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"is2DArray",{get:function(){return!!this._texture&&this._texture.is2DArray},set:function(e){this._texture&&(this._texture.is2DArray=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isRGBD",{get:function(){return null!=this._texture&&this._texture._isRGBD},set:function(e){this._texture&&(this._texture._isRGBD=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"noMipmap",{get:function(){return!1},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lodGenerationOffset",{get:function(){return this._texture?this._texture._lodGenerationOffset:0},set:function(e){this._texture&&(this._texture._lodGenerationOffset=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lodGenerationScale",{get:function(){return this._texture?this._texture._lodGenerationScale:0},set:function(e){this._texture&&(this._texture._lodGenerationScale=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"linearSpecularLOD",{get:function(){return!!this._texture&&this._texture._linearSpecularLOD},set:function(e){this._texture&&(this._texture._linearSpecularLOD=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"irradianceTexture",{get:function(){return this._texture?this._texture._irradianceTexture:null},set:function(e){this._texture&&(this._texture._irradianceTexture=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"uid",{get:function(){return this._uid||(this._uid=l.a.RandomId()),this._uid},enumerable:!0,configurable:!0}),e.prototype.toString=function(){return this.name},e.prototype.getClassName=function(){return"BaseTexture"},Object.defineProperty(e.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isBlocking",{get:function(){return!0},enumerable:!0,configurable:!0}),e.prototype.getScene=function(){return this._scene},e.prototype.getTextureMatrix=function(){return a.a.IdentityReadOnly},e.prototype.getReflectionTextureMatrix=function(){return a.a.IdentityReadOnly},e.prototype.getInternalTexture=function(){return this._texture},e.prototype.isReadyOrNotBlocking=function(){return!this.isBlocking||this.isReady()},e.prototype.isReady=function(){return this.delayLoadState===c.a.DELAYLOADSTATE_NOTLOADED?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady},e.prototype.getSize=function(){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},e.prototype.getBaseSize=function(){return this.isReady()&&this._texture?this._texture._size?new u.a(this._texture._size,this._texture._size):new u.a(this._texture.baseWidth,this._texture.baseHeight):u.a.Zero()},e.prototype.updateSamplingMode=function(e){if(this._texture){var t=this.getScene();t&&t.getEngine().updateTextureSamplingMode(e,this._texture)}},e.prototype.scale=function(e){},Object.defineProperty(e.prototype,"canRescale",{get:function(){return!1},enumerable:!0,configurable:!0}),e.prototype._getFromCache=function(e,t,i,n){if(!this._scene)return null;for(var r=this._scene.getEngine().getLoadedTexturesCache(),o=0;o<r.length;o++){var a=r[o];if(!(void 0!==n&&n!==a.invertY||a.url!==e||a.generateMipMaps!==!t||i&&i!==a.samplingMode))return a.incrementReferences(),a}return null},e.prototype._rebuild=function(){},e.prototype.delayLoad=function(){},e.prototype.clone=function(){return null},Object.defineProperty(e.prototype,"textureType",{get:function(){return this._texture&&void 0!==this._texture.type?this._texture.type:c.a.TEXTURETYPE_UNSIGNED_INT},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"textureFormat",{get:function(){return this._texture&&void 0!==this._texture.format?this._texture.format:c.a.TEXTUREFORMAT_RGBA},enumerable:!0,configurable:!0}),e.prototype._markAllSubMeshesAsTexturesDirty=function(){var e=this.getScene();e&&e.markAllMaterialsAsDirty(c.a.MATERIAL_TextureDirtyFlag)},e.prototype.readPixels=function(e,t,i){if(void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=null),!this._texture)return null;var n=this.getSize(),r=n.width,o=n.height,a=this.getScene();if(!a)return null;var s=a.getEngine();return 0!=t&&(r/=Math.pow(2,t),o/=Math.pow(2,t),r=Math.round(r),o=Math.round(o)),this._texture.isCube?s._readTexturePixels(this._texture,r,o,e,t,i):s._readTexturePixels(this._texture,r,o,-1,t,i)},e.prototype.releaseInternalTexture=function(){this._texture&&(this._texture.dispose(),this._texture=null)},Object.defineProperty(e.prototype,"_lodTextureHigh",{get:function(){return this._texture?this._texture._lodTextureHigh:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_lodTextureMid",{get:function(){return this._texture?this._texture._lodTextureMid:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_lodTextureLow",{get:function(){return this._texture?this._texture._lodTextureLow:null},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){if(this._scene){this._scene.stopAnimation&&this._scene.stopAnimation(this),this._scene._removePendingData(this);var e=this._scene.textures.indexOf(this);e>=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this)}void 0!==this._texture&&(this.releaseInternalTexture(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear())},e.prototype.serialize=function(){if(!this.name)return null;var e=r.a.Serialize(this);return r.a.AppendSerializedAnimations(this,e),e},e.WhenAllReady=function(e,t){var i=e.length;if(0!==i)for(var n,r,o=function(){if((n=e[a]).isReady())0==--i&&t();else if(r=n.onLoadObservable){var o=function(){r.removeCallback(o),0==--i&&t()};r.add(o)}},a=0;a<e.length;a++)o();else t()},e.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,Object(n.c)([Object(r.c)()],e.prototype,"uniqueId",void 0),Object(n.c)([Object(r.c)()],e.prototype,"name",void 0),Object(n.c)([Object(r.c)()],e.prototype,"metadata",void 0),Object(n.c)([Object(r.c)("hasAlpha")],e.prototype,"_hasAlpha",void 0),Object(n.c)([Object(r.c)()],e.prototype,"getAlphaFromRGB",void 0),Object(n.c)([Object(r.c)()],e.prototype,"level",void 0),Object(n.c)([Object(r.c)()],e.prototype,"coordinatesIndex",void 0),Object(n.c)([Object(r.c)("coordinatesMode")],e.prototype,"_coordinatesMode",void 0),Object(n.c)([Object(r.c)()],e.prototype,"wrapU",void 0),Object(n.c)([Object(r.c)()],e.prototype,"wrapV",void 0),Object(n.c)([Object(r.c)()],e.prototype,"wrapR",void 0),Object(n.c)([Object(r.c)()],e.prototype,"anisotropicFilteringLevel",void 0),Object(n.c)([Object(r.c)()],e.prototype,"isCube",null),Object(n.c)([Object(r.c)()],e.prototype,"is3D",null),Object(n.c)([Object(r.c)()],e.prototype,"is2DArray",null),Object(n.c)([Object(r.c)(),Object(r.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"gammaSpace",void 0),Object(n.c)([Object(r.c)()],e.prototype,"invertZ",void 0),Object(n.c)([Object(r.c)()],e.prototype,"lodLevelInAlpha",void 0),Object(n.c)([Object(r.c)()],e.prototype,"lodGenerationOffset",null),Object(n.c)([Object(r.c)()],e.prototype,"lodGenerationScale",null),Object(n.c)([Object(r.c)()],e.prototype,"linearSpecularLOD",null),Object(n.c)([Object(r.m)()],e.prototype,"irradianceTexture",null),Object(n.c)([Object(r.c)()],e.prototype,"isRenderTarget",void 0),e}())},function(e,t,i){"use strict";i.d(t,"a",function(){return u});var n=i(1),r=i(3),o=i(0),a=i(10),s=i(26),c=i(83),l=i(12),u=function(e){function t(i,n){var r=e.call(this,i,n)||this;return r.diffuse=new a.a(1,1,1),r.specular=new a.a(1,1,1),r.falloffType=t.FALLOFF_DEFAULT,r.intensity=1,r._range=Number.MAX_VALUE,r._inverseSquaredRange=0,r._photometricScale=1,r._intensityMode=t.INTENSITYMODE_AUTOMATIC,r._radius=1e-5,r.renderPriority=0,r._shadowEnabled=!0,r._excludeWithLayerMask=0,r._includeOnlyWithLayerMask=0,r._lightmapMode=0,r._excludedMeshesIds=new Array,r._includedOnlyMeshesIds=new Array,r._isLight=!0,r.getScene().addLight(r),r._uniformBuffer=new c.a(r.getScene().getEngine()),r._buildUniformLayout(),r.includedOnlyMeshes=new Array,r.excludedMeshes=new Array,r._resyncMeshes(),r}return Object(n.d)(t,e),Object.defineProperty(t.prototype,"range",{get:function(){return this._range},set:function(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"intensityMode",{get:function(){return this._intensityMode},set:function(e){this._intensityMode=e,this._computePhotometricScale()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"radius",{get:function(){return this._radius},set:function(e){this._radius=e,this._computePhotometricScale()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowEnabled",{get:function(){return this._shadowEnabled},set:function(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"includedOnlyMeshes",{get:function(){return this._includedOnlyMeshes},set:function(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"excludedMeshes",{get:function(){return this._excludedMeshes},set:function(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"excludeWithLayerMask",{get:function(){return this._excludeWithLayerMask},set:function(e){this._excludeWithLayerMask=e,this._resyncMeshes()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"includeOnlyWithLayerMask",{get:function(){return this._includeOnlyWithLayerMask},set:function(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"lightmapMode",{get:function(){return this._lightmapMode},set:function(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())},enumerable:!0,configurable:!0}),t.prototype.transferTexturesToEffect=function(e,t){return this},t.prototype._bindLight=function(e,t,i,n,r){void 0===r&&(r=!1);var o=e.toString(),s=!1;if(!r||!this._uniformBuffer._alreadyBound){if(this._uniformBuffer.bindToEffect(i,"Light"+o),this._renderId!==t.getRenderId()||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId();var c=this.getScaledIntensity();this.transferToEffect(i,o),this.diffuse.scaleToRef(c,a.c.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",a.c.Color3[0],this.range,o),n&&(this.specular.scaleToRef(c,a.c.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",a.c.Color3[1],this.radius,o)),s=!0}if(this.transferTexturesToEffect(i,o),t.shadowsEnabled&&this.shadowEnabled){var l=this.getShadowGenerator();l&&(l.bindShadowLight(o,i),s=!0)}s&&this._uniformBuffer.update()}},t.prototype.getClassName=function(){return"Light"},t.prototype.toString=function(e){var t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric"][this.getTypeID()],this.animations)for(var i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t},t.prototype._syncParentEnabledState=function(){e.prototype._syncParentEnabledState.call(this),this.isDisposed()||this._resyncMeshes()},t.prototype.setEnabled=function(t){e.prototype.setEnabled.call(this,t),this._resyncMeshes()},t.prototype.getShadowGenerator=function(){return this._shadowGenerator},t.prototype.getAbsolutePosition=function(){return o.e.Zero()},t.prototype.canAffectMesh=function(e){return!e||!(this.includedOnlyMeshes&&this.includedOnlyMeshes.length>0&&-1===this.includedOnlyMeshes.indexOf(e))&&(!(this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e))&&((0===this.includeOnlyWithLayerMask||0!=(this.includeOnlyWithLayerMask&e.layerMask))&&!(0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask)))},t.CompareLightsPriority=function(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority},t.prototype.dispose=function(t,i){void 0===i&&(i=!1),this._shadowGenerator&&(this._shadowGenerator.dispose(),this._shadowGenerator=null),this.getScene().stopAnimation(this);for(var n=0,r=this.getScene().meshes;n<r.length;n++){r[n]._removeLightSource(this,!0)}this._uniformBuffer.dispose(),this.getScene().removeLight(this),e.prototype.dispose.call(this,t,i)},t.prototype.getTypeID=function(){return 0},t.prototype.getScaledIntensity=function(){return this._photometricScale*this.intensity},t.prototype.clone=function(e){var i=t.GetConstructorFromName(this.getTypeID(),e,this.getScene());return i?r.a.Clone(i,this):null},t.prototype.serialize=function(){var e=r.a.Serialize(this);return e.type=this.getTypeID(),this.parent&&(e.parentId=this.parent.id),this.excludedMeshes.length>0&&(e.excludedMeshesIds=[],this.excludedMeshes.forEach(function(t){e.excludedMeshesIds.push(t.id)})),this.includedOnlyMeshes.length>0&&(e.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach(function(t){e.includedOnlyMeshesIds.push(t.id)})),r.a.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e},t.GetConstructorFromName=function(e,t,i){var n=s.a.Construct("Light_Type_"+e,t,i);return n||null},t.Parse=function(e,i){var n=t.GetConstructorFromName(e.type,e.name,i);if(!n)return null;var o=r.a.Parse(n,e,i);if(e.excludedMeshesIds&&(o._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(o._includedOnlyMeshesIds=e.includedOnlyMeshesIds),e.parentId&&(o._waitingParentId=e.parentId),void 0!==e.falloffType&&(o.falloffType=e.falloffType),void 0!==e.lightmapMode&&(o.lightmapMode=e.lightmapMode),e.animations){for(var a=0;a<e.animations.length;a++){var c=e.animations[a],u=l.a.GetClass("BABYLON.Animation");u&&o.animations.push(u.Parse(c))}s.a.ParseAnimationRanges(o,e,i)}return e.autoAnimate&&i.beginAnimation(o,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),o},t.prototype._hookArrayForExcluded=function(e){var t=this,i=e.push;e.push=function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];for(var o=i.apply(e,n),a=0,s=n;a<s.length;a++){var c=s[a];c._resyncLightSource(t)}return o};var n=e.splice;e.splice=function(i,r){for(var o=n.apply(e,[i,r]),a=0,s=o;a<s.length;a++){s[a]._resyncLightSource(t)}return o};for(var r=0,o=e;r<o.length;r++){o[r]._resyncLightSource(this)}},t.prototype._hookArrayForIncludedOnly=function(e){var t=this,i=e.push;e.push=function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var o=i.apply(e,n);return t._resyncMeshes(),o};var n=e.splice;e.splice=function(i,r){var o=n.apply(e,[i,r]);return t._resyncMeshes(),o},this._resyncMeshes()},t.prototype._resyncMeshes=function(){for(var e=0,t=this.getScene().meshes;e<t.length;e++){t[e]._resyncLightSource(this)}},t.prototype._markMeshesAsLightDirty=function(){for(var e=0,t=this.getScene().meshes;e<t.length;e++){var i=t[e];-1!==i.lightSources.indexOf(this)&&i._markSubMeshesAsLightDirty()}},t.prototype._computePhotometricScale=function(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()},t.prototype._getPhotometricScale=function(){var e=0,i=this.getTypeID(),n=this.intensityMode;switch(n===t.INTENSITYMODE_AUTOMATIC&&(n=i===t.LIGHTTYPEID_DIRECTIONALLIGHT?t.INTENSITYMODE_ILLUMINANCE:t.INTENSITYMODE_LUMINOUSINTENSITY),i){case t.LIGHTTYPEID_POINTLIGHT:case t.LIGHTTYPEID_SPOTLIGHT:switch(n){case t.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case t.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case t.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case t.LIGHTTYPEID_DIRECTIONALLIGHT:switch(n){case t.INTENSITYMODE_ILLUMINANCE:e=1;break;case t.INTENSITYMODE_LUMINANCE:var r=this.radius;r=Math.max(r,.001),e=2*Math.PI*(1-Math.cos(r))}break;case t.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e},t.prototype._reorderLightsInScene=function(){var e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()},t.FALLOFF_DEFAULT=0,t.FALLOFF_PHYSICAL=1,t.FALLOFF_GLTF=2,t.FALLOFF_STANDARD=3,t.LIGHTMAP_DEFAULT=0,t.LIGHTMAP_SPECULAR=1,t.LIGHTMAP_SHADOWSONLY=2,t.INTENSITYMODE_AUTOMATIC=0,t.INTENSITYMODE_LUMINOUSPOWER=1,t.INTENSITYMODE_LUMINOUSINTENSITY=2,t.INTENSITYMODE_ILLUMINANCE=3,t.INTENSITYMODE_LUMINANCE=4,t.LIGHTTYPEID_POINTLIGHT=0,t.LIGHTTYPEID_DIRECTIONALLIGHT=1,t.LIGHTTYPEID_SPOTLIGHT=2,t.LIGHTTYPEID_HEMISPHERICLIGHT=3,Object(n.c)([Object(r.e)()],t.prototype,"diffuse",void 0),Object(n.c)([Object(r.e)()],t.prototype,"specular",void 0),Object(n.c)([Object(r.c)()],t.prototype,"falloffType",void 0),Object(n.c)([Object(r.c)()],t.prototype,"intensity",void 0),Object(n.c)([Object(r.c)()],t.prototype,"range",null),Object(n.c)([Object(r.c)()],t.prototype,"intensityMode",null),Object(n.c)([Object(r.c)()],t.prototype,"radius",null),Object(n.c)([Object(r.c)()],t.prototype,"_renderPriority",void 0),Object(n.c)([Object(r.b)("_reorderLightsInScene")],t.prototype,"renderPriority",void 0),Object(n.c)([Object(r.c)("shadowEnabled")],t.prototype,"_shadowEnabled",void 0),Object(n.c)([Object(r.c)("excludeWithLayerMask")],t.prototype,"_excludeWithLayerMask",void 0),Object(n.c)([Object(r.c)("includeOnlyWithLayerMask")],t.prototype,"_includeOnlyWithLayerMask",void 0),Object(n.c)([Object(r.c)("lightmapMode")],t.prototype,"_lightmapMode",void 0),t}(s.a)},function(e,t,i){"use strict";i.d(t,"a",function(){return r});var n=i(52),r=function(){function e(){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}return Object.defineProperty(e.prototype,"min",{get:function(){return this._min},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"max",{get:function(){return this._max},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"average",{get:function(){return this._average},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lastSecAverage",{get:function(){return this._lastSecAverage},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"current",{get:function(){return this._current},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"total",{get:function(){return this._totalAccumulated},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"count",{get:function(){return this._totalValueCount},enumerable:!0,configurable:!0}),e.prototype.fetchNewFrame=function(){this._totalValueCount++,this._current=0,this._lastSecValueCount++},e.prototype.addCount=function(t,i){e.Enabled&&(this._current+=t,i&&this._fetchResult())},e.prototype.beginMonitoring=function(){e.Enabled&&(this._startMonitoringTime=n.a.Now)},e.prototype.endMonitoring=function(t){if(void 0===t&&(t=!0),e.Enabled){t&&this.fetchNewFrame();var i=n.a.Now;this._current=i-this._startMonitoringTime,t&&this._fetchResult()}},e.prototype._fetchResult=function(){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;var e=n.a.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)},e.Enabled=!0,e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r});var n=i(38),r=function(){function e(){}return Object.defineProperty(e,"Now",{get:function(){return n.a.IsWindowObjectExist()&&window.performance&&window.performance.now?window.performance.now():Date.now()},enumerable:!0,configurable:!0}),e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return o});var n=i(0),r=i(4),o=function(){function e(){this._pickingUnavailable=!1,this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshId=0,this.pickedSprite=null,this.originMesh=null,this.ray=null}return e.prototype.getNormal=function(e,t){if(void 0===e&&(e=!1),void 0===t&&(t=!0),!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(r.b.NormalKind))return null;var i,o=this.pickedMesh.getIndices();if(!o)return null;if(t){var a=this.pickedMesh.getVerticesData(r.b.NormalKind),s=n.e.FromArray(a,3*o[3*this.faceId]),c=n.e.FromArray(a,3*o[3*this.faceId+1]),l=n.e.FromArray(a,3*o[3*this.faceId+2]);s=s.scale(this.bu),c=c.scale(this.bv),l=l.scale(1-this.bu-this.bv),i=new n.e(s.x+c.x+l.x,s.y+c.y+l.y,s.z+c.z+l.z)}else{var u=this.pickedMesh.getVerticesData(r.b.PositionKind),h=n.e.FromArray(u,3*o[3*this.faceId]),d=n.e.FromArray(u,3*o[3*this.faceId+1]),f=n.e.FromArray(u,3*o[3*this.faceId+2]),p=h.subtract(d),_=f.subtract(d);i=n.e.Cross(p,_)}if(e){var m=this.pickedMesh.getWorldMatrix();this.pickedMesh.nonUniformScaling&&(n.c.Matrix[0].copyFrom(m),(m=n.c.Matrix[0]).setTranslationFromFloats(0,0,0),m.invert(),m.transposeToRef(n.c.Matrix[1]),m=n.c.Matrix[1]),i=n.e.TransformNormal(i,m)}return i.normalize(),i},e.prototype.getTextureCoordinates=function(){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(r.b.UVKind))return null;var e=this.pickedMesh.getIndices();if(!e)return null;var t=this.pickedMesh.getVerticesData(r.b.UVKind);if(!t)return null;var i=n.d.FromArray(t,2*e[3*this.faceId]),o=n.d.FromArray(t,2*e[3*this.faceId+1]),a=n.d.FromArray(t,2*e[3*this.faceId+2]);return i=i.scale(this.bu),o=o.scale(this.bv),a=a.scale(1-this.bu-this.bv),new n.d(i.x+o.x+a.x,i.y+o.y+a.y)},e}()},function(e,t,i){"use strict";var n=i(1),r=i(65),o=i(38),a=i(6),s=i(76),c=i(126),l=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(n.d)(t,e),t._setPrototypeOf=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},t}(Error),u=i(36),h=i(31),d=i(116);i.d(t,"b",function(){return f}),i.d(t,"d",function(){return p}),i.d(t,"c",function(){return _}),i.d(t,"a",function(){return m});var f=function(e){function t(i,n){var o=e.call(this,i)||this;return o.name="LoadFileError",l._setPrototypeOf(o,t.prototype),n instanceof r.a?o.request=n:o.file=n,o}return Object(n.d)(t,e),t}(l),p=function(e){function t(i,n){var r=e.call(this,i)||this;return r.request=n,r.name="RequestFileError",l._setPrototypeOf(r,t.prototype),r}return Object(n.d)(t,e),t}(l),_=function(e){function t(i,n){var r=e.call(this,i)||this;return r.file=n,r.name="ReadFileError",l._setPrototypeOf(r,t.prototype),r}return Object(n.d)(t,e),t}(l),m=function(){function e(){}return e._CleanUrl=function(e){return e=e.replace(/#/gm,"%23")},e.SetCorsBehavior=function(t,i){if((!t||0!==t.indexOf("data:"))&&e.CorsBehavior)if("string"==typeof e.CorsBehavior||this.CorsBehavior instanceof String)i.crossOrigin=e.CorsBehavior;else{var n=e.CorsBehavior(t);n&&(i.crossOrigin=n)}},e.LoadImage=function(t,i,n,r,o){var a;void 0===o&&(o="");var c=!1;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)?"undefined"!=typeof Blob?(a=URL.createObjectURL(new Blob([t],{type:o})),c=!0):a="data:"+o+";base64,"+u.a.EncodeArrayBufferToBase64(t):t instanceof Blob?(a=URL.createObjectURL(t),c=!0):(a=e._CleanUrl(t),a=e.PreprocessUrl(t)),"undefined"==typeof Image)return e.LoadFile(a,function(e){createImageBitmap(new Blob([e],{type:o})).then(function(e){i(e),c&&URL.revokeObjectURL(a)}).catch(function(e){n&&n("Error while trying to load image: "+t,e)})},void 0,r||void 0,!0,function(e,i){n&&n("Error while trying to load image: "+t,i)}),null;var l=new Image;e.SetCorsBehavior(a,l);var h=function(){l.removeEventListener("load",h),l.removeEventListener("error",d),i(l),c&&l.src&&URL.revokeObjectURL(l.src)},d=function(e){l.removeEventListener("load",h),l.removeEventListener("error",d),n&&n("Error while trying to load image: "+t,e),c&&l.src&&URL.revokeObjectURL(l.src)};l.addEventListener("load",h),l.addEventListener("error",d);var f=function(){l.src=a};if("data:"!==a.substr(0,5)&&r&&r.enableTexturesOffline)r.open(function(){r&&r.loadImage(a,l)},f);else{if(-1!==a.indexOf("file:")){var p=decodeURIComponent(a.substring(5).toLowerCase());if(s.a.FilesToLoad[p]){try{var _;try{_=URL.createObjectURL(s.a.FilesToLoad[p])}catch(e){_=URL.createObjectURL(s.a.FilesToLoad[p])}l.src=_,c=!0}catch(e){l.src=""}return l}}f()}return l},e.ReadFile=function(e,t,i,n,r){var o=new FileReader,s={onCompleteObservable:new a.c,abort:function(){return o.abort()}};return o.onloadend=function(e){return s.onCompleteObservable.notifyObservers(s)},r&&(o.onerror=function(t){r(new _("Unable to read "+e.name,e))}),o.onload=function(e){t(e.target.result)},i&&(o.onprogress=i),n?o.readAsArrayBuffer(e):o.readAsText(e),s},e.LoadFile=function(t,i,n,r,o,a){if(-1!==t.indexOf("file:")){var c=decodeURIComponent(t.substring(5).toLowerCase());0===c.indexOf("./")&&(c=c.substring(2));var l=s.a.FilesToLoad[c];if(l)return e.ReadFile(l,i,n,o,a?function(e){return a(void 0,new f(e.message,e.file))}:void 0)}return e.RequestFile(t,function(e,t){i(e,t?t.responseURL:void 0)},n,r,o,a?function(e){a(e.request,new f(e.message,e.request))}:void 0)},e.RequestFile=function(t,i,n,s,c,l,u){t=e._CleanUrl(t),t=e.PreprocessUrl(t);var h=e.BaseUrl+t,d=!1,f={onCompleteObservable:new a.c,abort:function(){return d=!0}},_=function(){var t=new r.a,a=null;f.abort=function(){d=!0,t.readyState!==(XMLHttpRequest.DONE||4)&&t.abort(),null!==a&&(clearTimeout(a),a=null)};var s=function(_){t.open("GET",h),u&&u(t),c&&(t.responseType="arraybuffer"),n&&t.addEventListener("progress",n);var m=function(){t.removeEventListener("loadend",m),f.onCompleteObservable.notifyObservers(f),f.onCompleteObservable.clear()};t.addEventListener("loadend",m);var g=function(){if(!d&&t.readyState===(XMLHttpRequest.DONE||4)){if(t.removeEventListener("readystatechange",g),t.status>=200&&t.status<300||0===t.status&&(!o.a.IsWindowObjectExist()||e.IsFileURL()))return void i(c?t.response:t.responseText,t);var n=e.DefaultRetryStrategy;if(n){var u=n(h,t,_);if(-1!==u)return t.removeEventListener("loadend",m),t=new r.a,void(a=setTimeout(function(){return s(_+1)},u))}var f=new p("Error status: "+t.status+" "+t.statusText+" - Unable to load "+h,t);l&&l(f)}};t.addEventListener("readystatechange",g),t.send()};s(0)};if(s&&s.enableSceneOffline){var m=function(e){e&&e.status>400?l&&l(e):_()};s.open(function(){s&&s.loadFile(e.BaseUrl+t,function(e){d||i(e),f.onCompleteObservable.notifyObservers(f)},n?function(e){d||n(e)}:void 0,m,c)},m)}else _();return f},e.IsFileURL=function(){return"file:"===location.protocol},e.DefaultRetryStrategy=c.a.ExponentialBackoff(),e.BaseUrl="",e.CorsBehavior="anonymous",e.PreprocessUrl=function(e){return e},e}();h.a._FileToolsLoadImage=m.LoadImage.bind(m),h.a._FileToolsLoadFile=m.LoadFile.bind(m),d.a._FileToolsLoadFile=m.LoadFile.bind(m)},function(e,t,i){"use strict";i.d(t,"a",function(){return r});var n=i(0),r=function(){function e(){}return e._RemoveAndStorePivotPoint=function(t){t&&0===e._PivotCached&&(t.getPivotPointToRef(e._OldPivotPoint),e._OldPivotPoint.equalsToFloats(0,0,0)||(t.setPivotMatrix(n.a.IdentityReadOnly),e._OldPivotPoint.subtractToRef(t.getPivotPoint(),e._PivotTranslation),e._PivotTmpVector.copyFromFloats(1,1,1),e._PivotTmpVector.subtractInPlace(t.scaling),e._PivotTmpVector.multiplyInPlace(e._PivotTranslation),t.position.addInPlace(e._PivotTmpVector))),e._PivotCached++},e._RestorePivotPoint=function(t){t&&!e._OldPivotPoint.equalsToFloats(0,0,0)&&1===e._PivotCached&&(t.setPivotPoint(e._OldPivotPoint),e._PivotTmpVector.copyFromFloats(1,1,1),e._PivotTmpVector.subtractInPlace(t.scaling),e._PivotTmpVector.multiplyInPlace(e._PivotTranslation),t.position.subtractInPlace(e._PivotTmpVector)),this._PivotCached--},e._PivotCached=0,e._OldPivotPoint=new n.e,e._PivotTranslation=new n.e,e._PivotTmpVector=new n.e,e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return a});var n=i(0),r=i(5),o=i(41),a=function(){function e(e){var t=this;void 0===e&&(e=o.a.DefaultUtilityLayer),this.gizmoLayer=e,this._attachedMesh=null,this.scaleRatio=1,this._customMeshSet=!1,this.updateGizmoRotationToMatchAttachedMesh=!0,this.updateGizmoPositionToMatchAttachedMesh=!0,this.updateScale=!0,this._interactionsEnabled=!0,this._tempVector=new n.e,this._rootMesh=new r.a("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=n.b.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function(){t._update()})}return Object.defineProperty(e.prototype,"attachedMesh",{get:function(){return this._attachedMesh},set:function(e){this._attachedMesh=e,this._rootMesh.setEnabled(!!e),this._attachedMeshChanged(e)},enumerable:!0,configurable:!0}),e.prototype.setCustomMesh=function(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach(function(e){e.dispose()}),e.parent=this._rootMesh,this._customMeshSet=!0},e.prototype._attachedMeshChanged=function(e){},e.prototype._update=function(){if(this.attachedMesh){var e=this.attachedMesh._effectiveMesh||this.attachedMesh;if(this.updateGizmoPositionToMatchAttachedMesh&&this._rootMesh.position.copyFrom(e.absolutePosition),this.updateGizmoRotationToMatchAttachedMesh?e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1),this.updateScale){var t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;t.devicePosition&&(i=t.devicePosition),this._rootMesh.position.subtractToRef(i,this._tempVector);var n=this._tempVector.length()*this.scaleRatio;this._rootMesh.scaling.set(n,n,n),e._getWorldMatrixDeterminant()<0&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}},e.prototype.dispose=function(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return l}),i.d(t,"b",function(){return u});var n=i(1),r=i(4),o=i(105),a=i(44),s=i(2),c=i(110),l=function(){function e(){this._materialDefines=null,this._materialEffect=null}return Object.defineProperty(e.prototype,"materialDefines",{get:function(){return this._materialDefines},set:function(e){this._materialDefines=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"effect",{get:function(){return this._materialEffect},enumerable:!0,configurable:!0}),e.prototype.setEffect=function(e,t){void 0===t&&(t=null),this._materialEffect!==e?(this._materialDefines=t,this._materialEffect=e):e||(this._materialDefines=null)},e}(),u=function(e){function t(t,i,n,r,o,a,s,c){void 0===c&&(c=!0);var l=e.call(this)||this;return l.materialIndex=t,l.verticesStart=i,l.verticesCount=n,l.indexStart=r,l.indexCount=o,l._linesIndexCount=0,l._linesIndexBuffer=null,l._lastColliderWorldVertices=null,l._lastColliderTransformMatrix=null,l._renderId=0,l._alphaIndex=0,l._distanceToCamera=0,l._currentMaterial=null,l._mesh=a,l._renderingMesh=s||a,a.subMeshes.push(l),l._trianglePlanes=[],l._id=a.subMeshes.length-1,c&&(l.refreshBoundingInfo(),a.computeWorldMatrix(!0)),l}return Object(n.d)(t,e),t.AddToMesh=function(e,i,n,r,o,a,s,c){return void 0===c&&(c=!0),new t(e,i,n,r,o,a,s,c)},Object.defineProperty(t.prototype,"IsGlobal",{get:function(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()},enumerable:!0,configurable:!0}),t.prototype.getBoundingInfo=function(){return this.IsGlobal?this._mesh.getBoundingInfo():this._boundingInfo},t.prototype.setBoundingInfo=function(e){return this._boundingInfo=e,this},t.prototype.getMesh=function(){return this._mesh},t.prototype.getRenderingMesh=function(){return this._renderingMesh},t.prototype.getMaterial=function(){var e=this._renderingMesh.material;if(null==e)return this._mesh.getScene().defaultMaterial;if(e.getSubMaterial){var t=e.getSubMaterial(this.materialIndex);return this._currentMaterial!==t&&(this._currentMaterial=t,this._materialDefines=null),t}return e},t.prototype.refreshBoundingInfo=function(e){if(void 0===e&&(e=null),this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(r.b.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;var t,i=this._renderingMesh.getIndices();if(0===this.indexStart&&this.indexCount===i.length){var n=this._renderingMesh.getBoundingInfo();t={minimum:n.minimum.clone(),maximum:n.maximum.clone()}}else t=Object(c.b)(e,i,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(t.minimum,t.maximum):this._boundingInfo=new a.a(t.minimum,t.maximum),this},t.prototype._checkCollision=function(e){return this.getBoundingInfo()._checkCollision(e)},t.prototype.updateBoundingInfo=function(e){var t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this},t.prototype.isInFrustum=function(e){var t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)},t.prototype.isCompletelyInFrustum=function(e){var t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)},t.prototype.render=function(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this},t.prototype._getLinesIndexBuffer=function(e,t){if(!this._linesIndexBuffer){for(var i=[],n=this.indexStart;n<this.indexStart+this.indexCount;n+=3)i.push(e[n],e[n+1],e[n+1],e[n+2],e[n+2],e[n]);this._linesIndexBuffer=t.createIndexBuffer(i),this._linesIndexCount=i.length}return this._linesIndexBuffer},t.prototype.canIntersects=function(e){var t=this.getBoundingInfo();return!!t&&e.intersectsBox(t.boundingBox)},t.prototype.intersects=function(e,t,i,n,r){var o=this.getMaterial();if(!o)return null;var a=3,c=!1;switch(o.fillMode){case s.a.MATERIAL_PointListDrawMode:case s.a.MATERIAL_LineListDrawMode:case s.a.MATERIAL_LineLoopDrawMode:case s.a.MATERIAL_LineStripDrawMode:case s.a.MATERIAL_TriangleFanDrawMode:return null;case s.a.MATERIAL_TriangleStripDrawMode:a=1,c=!0}return"InstancedLinesMesh"===this._mesh.getClassName()||"LinesMesh"===this._mesh.getClassName()?i.length?this._intersectLines(e,t,i,this._mesh.intersectionThreshold,n):this._intersectUnIndexedLines(e,t,i,this._mesh.intersectionThreshold,n):!i.length&&this._mesh._unIndexed?this._intersectUnIndexedTriangles(e,t,i,n,r):this._intersectTriangles(e,t,i,a,c,n,r)},t.prototype._intersectLines=function(e,t,i,n,r){for(var a=null,s=this.indexStart;s<this.indexStart+this.indexCount;s+=2){var c=t[i[s]],l=t[i[s+1]],u=e.intersectionSegment(c,l,n);if(!(u<0)&&((r||!a||u<a.distance)&&((a=new o.a(null,null,u)).faceId=s/2,r)))break}return a},t.prototype._intersectUnIndexedLines=function(e,t,i,n,r){for(var a=null,s=this.verticesStart;s<this.verticesStart+this.verticesCount;s+=2){var c=t[s],l=t[s+1],u=e.intersectionSegment(c,l,n);if(!(u<0)&&((r||!a||u<a.distance)&&((a=new o.a(null,null,u)).faceId=s/2,r)))break}return a},t.prototype._intersectTriangles=function(e,t,i,n,r,o,a){for(var s=null,c=-1,l=this.indexStart;l<this.indexStart+this.indexCount;l+=n){c++;var u=i[l],h=i[l+1],d=i[l+2];if(r&&4294967295===d)l+=2;else{var f=t[u],p=t[h],_=t[d];if(!a||a(f,p,_,e)){var m=e.intersectsTriangle(f,p,_);if(m){if(m.distance<0)continue;if((o||!s||m.distance<s.distance)&&((s=m).faceId=c,o))break}}}}return s},t.prototype._intersectUnIndexedTriangles=function(e,t,i,n,r){for(var o=null,a=this.verticesStart;a<this.verticesStart+this.verticesCount;a+=3){var s=t[a],c=t[a+1],l=t[a+2];if(!r||r(s,c,l,e)){var u=e.intersectsTriangle(s,c,l);if(u){if(u.distance<0)continue;if((n||!o||u.distance<o.distance)&&((o=u).faceId=a/3,n))break}}}return o},t.prototype._rebuild=function(){this._linesIndexBuffer&&(this._linesIndexBuffer=null)},t.prototype.clone=function(e,i){var n=new t(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,e,i,!1);if(!this.IsGlobal){var r=this.getBoundingInfo();if(!r)return n;n._boundingInfo=new a.a(r.minimum,r.maximum)}return n},t.prototype.dispose=function(){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);var e=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(e,1)},t.prototype.getClassName=function(){return"SubMesh"},t.CreateFromIndices=function(e,i,n,r,o){for(var a=Number.MAX_VALUE,s=-Number.MAX_VALUE,c=(o||r).getIndices(),l=i;l<i+n;l++){var u=c[l];u<a&&(a=u),u>s&&(s=u)}return new t(e,a,s-a+1,i,n,r,o)},t}(l)},function(e,t,i){"use strict";var n="helperFunctions",r="const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nconst float Epsilon=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\n#define absEps(x) abs(x)+Epsilon\n#define maxEps(x) max(x,Epsilon)\n#define saturateEps(x) clamp(x,Epsilon,1.0)\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat toGammaSpace(float color)\n{\nreturn pow(color,GammaEncodePowerApprox);\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat pow5(float value) {\nfloat sq=value*value;\nreturn sq*sq*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=maxEps(max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D);\n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}\n";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";i.d(t,"a",function(){return l});var n=i(0),r=i(10),o=i(5),a=i(15),s=i(18),c=i(22);a.a.CreateCylinder=function(e){var t=e.height||2,i=0===e.diameterTop?0:e.diameterTop||e.diameter||1,s=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;i=i||1e-5,s=s||1e-5;var l,u=e.tessellation||24,h=e.subdivisions||1,d=!!e.hasRings,f=!!e.enclose,p=0===e.cap?0:e.cap||o.a.CAP_ALL,_=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,m=0===e.sideOrientation?0:e.sideOrientation||a.a.DEFAULTSIDE,g=e.faceUV||new Array(3),v=e.faceColors,y=2+(1+(1!==_&&f?2:0))*(d?h:1);for(l=0;l<y;l++)v&&void 0===v[l]&&(v[l]=new r.b(1,1,1,1));for(l=0;l<y;l++)g&&void 0===g[l]&&(g[l]=new n.f(0,0,1,1));var b,T,E,x,P,A,S=new Array,C=new Array,R=new Array,O=new Array,M=new Array,I=2*Math.PI*_/u,D=(s-i)/2/t,w=n.e.Zero(),L=n.e.Zero(),N=n.e.Zero(),F=n.e.Zero(),B=n.e.Zero(),U=c.a.Y,V=1,k=1,z=0,G=0;for(x=0;x<=h;x++)for(E=((T=x/h)*(i-s)+s)/2,V=d&&0!==x&&x!==h?2:1,A=0;A<V;A++){for(d&&(k+=A),f&&(k+=2*A),P=0;P<=u;P++)b=P*I,w.x=Math.cos(-b)*E,w.y=-t/2+T*t,w.z=Math.sin(-b)*E,0===i&&x===h?(L.x=R[R.length-3*(u+1)],L.y=R[R.length-3*(u+1)+1],L.z=R[R.length-3*(u+1)+2]):(L.x=w.x,L.z=w.z,L.y=Math.sqrt(L.x*L.x+L.z*L.z)*D,L.normalize()),0===P&&(N.copyFrom(w),F.copyFrom(L)),C.push(w.x,w.y,w.z),R.push(L.x,L.y,L.z),G=d?z!==k?g[k].y:g[k].w:g[k].y+(g[k].w-g[k].y)*T,O.push(g[k].x+(g[k].z-g[k].x)*P/u,G),v&&M.push(v[k].r,v[k].g,v[k].b,v[k].a);1!==_&&f&&(C.push(w.x,w.y,w.z),C.push(0,w.y,0),C.push(0,w.y,0),C.push(N.x,N.y,N.z),n.e.CrossToRef(U,L,B),B.normalize(),R.push(B.x,B.y,B.z,B.x,B.y,B.z),n.e.CrossToRef(F,U,B),B.normalize(),R.push(B.x,B.y,B.z,B.x,B.y,B.z),G=d?z!==k?g[k+1].y:g[k+1].w:g[k+1].y+(g[k+1].w-g[k+1].y)*T,O.push(g[k+1].x,G),O.push(g[k+1].z,G),G=d?z!==k?g[k+2].y:g[k+2].w:g[k+2].y+(g[k+2].w-g[k+2].y)*T,O.push(g[k+2].x,G),O.push(g[k+2].z,G),v&&(M.push(v[k+1].r,v[k+1].g,v[k+1].b,v[k+1].a),M.push(v[k+1].r,v[k+1].g,v[k+1].b,v[k+1].a),M.push(v[k+2].r,v[k+2].g,v[k+2].b,v[k+2].a),M.push(v[k+2].r,v[k+2].g,v[k+2].b,v[k+2].a))),z!==k&&(z=k)}var j=1!==_&&f?u+4:u;for(x=0,k=0;k<h;k++){var W=0,X=0,H=0,Y=0;for(P=0;P<u;P++)W=x*(j+1)+P,X=(x+1)*(j+1)+P,H=x*(j+1)+(P+1),Y=(x+1)*(j+1)+(P+1),S.push(W,X,H),S.push(Y,H,X);1!==_&&f&&(S.push(W+2,X+2,H+2),S.push(Y+2,H+2,X+2),S.push(W+4,X+4,H+4),S.push(Y+4,H+4,X+4)),x=d?x+2:x+1}var K=function(e){var r=e?i/2:s/2;if(0!==r){var o,a,c,l=e?g[y-1]:g[0],h=null;v&&(h=e?v[y-1]:v[0]);var d=C.length/3,f=e?t/2:-t/2,p=new n.e(0,f,0);C.push(p.x,p.y,p.z),R.push(0,e?1:-1,0),O.push(l.x+.5*(l.z-l.x),l.y+.5*(l.w-l.y)),h&&M.push(h.r,h.g,h.b,h.a);var m=new n.d(.5,.5);for(c=0;c<=u;c++){o=2*Math.PI*c*_/u;var b=Math.cos(-o),T=Math.sin(-o);a=new n.e(b*r,f,T*r);var E=new n.d(b*m.x+.5,T*m.y+.5);C.push(a.x,a.y,a.z),R.push(0,e?1:-1,0),O.push(l.x+(l.z-l.x)*E.x,l.y+(l.w-l.y)*E.y),h&&M.push(h.r,h.g,h.b,h.a)}for(c=0;c<u;c++)e?(S.push(d),S.push(d+(c+2)),S.push(d+(c+1))):(S.push(d),S.push(d+(c+1)),S.push(d+(c+2)))}};p!==o.a.CAP_START&&p!==o.a.CAP_ALL||K(!1),p!==o.a.CAP_END&&p!==o.a.CAP_ALL||K(!0),a.a._ComputeSides(m,C,S,R,O,e.frontUVs,e.backUVs);var Q=new a.a;return Q.indices=S,Q.positions=C,Q.normals=R,Q.uvs=O,v&&(Q.colors=M),Q},o.a.CreateCylinder=function(e,t,i,n,r,a,c,u,h){void 0!==c&&c instanceof s.a||(void 0!==c&&(h=u||o.a.DEFAULTSIDE,u=c),c=a,a=1);var d={height:t,diameterTop:i,diameterBottom:n,tessellation:r,subdivisions:a,sideOrientation:h,updatable:u};return l.CreateCylinder(e,d,c)};var l=function(){function e(){}return e.CreateCylinder=function(e,t,i){var n=new o.a(e,i);return t.sideOrientation=o.a._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,a.a.CreateCylinder(t).applyToMesh(n,t.updatable),n},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r});var n=i(0),r=function(){function e(e,t,i,r){this.normal=new n.e(e,t,i),this.d=r}return e.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},e.prototype.clone=function(){return new e(this.normal.x,this.normal.y,this.normal.z,this.d)},e.prototype.getClassName=function(){return"Plane"},e.prototype.getHashCode=function(){var e=this.normal.getHashCode();return e=397*e^(0|this.d)},e.prototype.normalize=function(){var e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this},e.prototype.transform=function(t){var i=e._TmpMatrix;n.a.TransposeToRef(t,i);var r=i.m,o=this.normal.x,a=this.normal.y,s=this.normal.z,c=this.d;return new e(o*r[0]+a*r[1]+s*r[2]+c*r[3],o*r[4]+a*r[5]+s*r[6]+c*r[7],o*r[8]+a*r[9]+s*r[10]+c*r[11],o*r[12]+a*r[13]+s*r[14]+c*r[15])},e.prototype.dotCoordinate=function(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d},e.prototype.copyFromPoints=function(e,t,i){var n,r=t.x-e.x,o=t.y-e.y,a=t.z-e.z,s=i.x-e.x,c=i.y-e.y,l=i.z-e.z,u=o*l-a*c,h=a*s-r*l,d=r*c-o*s,f=Math.sqrt(u*u+h*h+d*d);return n=0!==f?1/f:0,this.normal.x=u*n,this.normal.y=h*n,this.normal.z=d*n,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this},e.prototype.isFrontFacingTo=function(e,t){return n.e.Dot(this.normal,e)<=t},e.prototype.signedDistanceTo=function(e){return n.e.Dot(e,this.normal)+this.d},e.FromArray=function(t){return new e(t[0],t[1],t[2],t[3])},e.FromPoints=function(t,i,n){var r=new e(0,0,0,0);return r.copyFromPoints(t,i,n),r},e.FromPositionAndNormal=function(t,i){var n=new e(0,0,0,0);return i.normalize(),n.normal=i,n.d=-(i.x*t.x+i.y*t.y+i.z*t.z),n},e.SignedDistanceToPlaneFromPositionAndNormal=function(e,t,i){var r=-(t.x*e.x+t.y*e.y+t.z*e.z);return n.e.Dot(i,t)+r},e._TmpMatrix=n.a.Identity(),e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(e,t,i,n){this.x=e,this.y=t,this.width=i,this.height=n}return e.prototype.toGlobal=function(t,i){return new e(this.x*t,this.y*i,this.width*t,this.height*i)},e.prototype.toGlobalToRef=function(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},e.prototype.clone=function(){return new e(this.x,this.y,this.width,this.height)},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return u});var n=i(5),r=i(18),o=i(6),a=i(0),s=i(20),c=i(39),l=i(55),u=(i(79),function(){function e(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this.maxDragAngle=0,this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerID=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new o.c,this.onDragStartObservable=new o.c,this.onDragEndObservable=new o.c,this.moveAttached=!0,this.enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=function(e){return!0},this._tmpVector=new a.e(0,0,0),this._alternatePickedPoint=new a.e(0,0,0),this._worldDragAxis=new a.e(0,0,0),this._targetPosition=new a.e(0,0,0),this._attachedElement=null,this._startDragRay=new c.a(new a.e,new a.e),this._lastPointerRay={},this._dragDelta=new a.e,this._pointA=new a.e(0,0,0),this._pointB=new a.e(0,0,0),this._pointC=new a.e(0,0,0),this._lineA=new a.e(0,0,0),this._lineB=new a.e(0,0,0),this._localAxis=new a.e(0,0,0),this._lookAt=new a.e(0,0,0),this._options=e||{};var t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}return Object.defineProperty(e.prototype,"options",{get:function(){return this._options},set:function(e){this._options=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"name",{get:function(){return"PointerDrag"},enumerable:!0,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(t,i){var o=this;this._scene=t.getScene(),this.attachedNode=t,e._planeScene||(this._debugMode?e._planeScene=this._scene:(e._planeScene=new r.a(this._scene.getEngine(),{virtual:!0}),e._planeScene.detachControl(),this._scene.onDisposeObservable.addOnce(function(){e._planeScene.dispose(),e._planeScene=null}))),this._dragPlane=n.a.CreatePlane("pointerDragPlane",this._debugMode?1:1e4,e._planeScene,!1,n.a.DOUBLESIDE),this.lastDragPosition=new a.e(0,0,0);var u=i||function(e){return o.attachedNode==e||e.isDescendantOf(o.attachedNode)};this._pointerObserver=this._scene.onPointerObservable.add(function(t,i){if(o.enabled)if(t.type==s.a.POINTERDOWN)o.startAndReleaseDragOnPointerEvents&&!o.dragging&&t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh&&t.pickInfo.pickedPoint&&t.pickInfo.ray&&u(t.pickInfo.pickedMesh)&&o._startDrag(t.event.pointerId,t.pickInfo.ray,t.pickInfo.pickedPoint);else if(t.type==s.a.POINTERUP)o.startAndReleaseDragOnPointerEvents&&o.currentDraggingPointerID==t.event.pointerId&&o.releaseDrag();else if(t.type==s.a.POINTERMOVE){var n=t.event.pointerId;o.currentDraggingPointerID===e._AnyMouseID&&n!==e._AnyMouseID&&"mouse"==t.event.pointerType&&(o._lastPointerRay[o.currentDraggingPointerID]&&(o._lastPointerRay[n]=o._lastPointerRay[o.currentDraggingPointerID],delete o._lastPointerRay[o.currentDraggingPointerID]),o.currentDraggingPointerID=n),o._lastPointerRay[n]||(o._lastPointerRay[n]=new c.a(new a.e,new a.e)),t.pickInfo&&t.pickInfo.ray&&(o._lastPointerRay[n].origin.copyFrom(t.pickInfo.ray.origin),o._lastPointerRay[n].direction.copyFrom(t.pickInfo.ray.direction),o.currentDraggingPointerID==n&&o.dragging&&o._moveDrag(t.pickInfo.ray))}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(function(){o._moving&&o.moveAttached&&(l.a._RemoveAndStorePivotPoint(o.attachedNode),o._targetPosition.subtractToRef(o.attachedNode.absolutePosition,o._tmpVector),o._tmpVector.scaleInPlace(o.dragDeltaRatio),o.attachedNode.getAbsolutePosition().addToRef(o._tmpVector,o._tmpVector),o.validateDrag(o._tmpVector)&&o.attachedNode.setAbsolutePosition(o._tmpVector),l.a._RestorePivotPoint(o.attachedNode))})},e.prototype.releaseDrag=function(){this.dragging&&(this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerID}),this.dragging=!1),this.currentDraggingPointerID=-1,this._moving=!1,this.detachCameraControls&&this._attachedElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera&&this._scene.activeCamera.attachControl(this._attachedElement,!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault)},e.prototype.startDrag=function(t,i,n){void 0===t&&(t=e._AnyMouseID),this._startDrag(t,i,n);var r=this._lastPointerRay[t];t===e._AnyMouseID&&(r=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),r&&this._moveDrag(r)},e.prototype._startDrag=function(e,t,i){if(this._scene.activeCamera&&!this.dragging&&this.attachedNode){l.a._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);var n=this._pickWithRayOnDragPlane(this._startDragRay);n&&(this.dragging=!0,this.currentDraggingPointerID=e,this.lastDragPosition.copyFrom(n),this.onDragStartObservable.notifyObservers({dragPlanePoint:n,pointerId:this.currentDraggingPointerID}),this._targetPosition.copyFrom(this.attachedNode.absolutePosition),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedElement?(this._attachedElement=this._scene.activeCamera.inputs.attachedElement,this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement)):this._attachedElement=null)),l.a._RestorePivotPoint(this.attachedNode)}},e.prototype._moveDrag=function(e){this._moving=!0;var t=this._pickWithRayOnDragPlane(e);if(t){this.updateDragPlane&&this._updateDragPlanePosition(e,t);var i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?a.e.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=a.e.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerID}),this.lastDragPosition.copyFrom(t)}},e.prototype._pickWithRayOnDragPlane=function(t){var i=this;if(!t)return null;var n=Math.acos(a.e.Dot(this._dragPlane.forward,t.direction));if(n>Math.PI/2&&(n=Math.PI-n),this.maxDragAngle>0&&n>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(t.direction),this.attachedNode.absolutePosition.subtractToRef(t.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*a.e.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);var r=a.e.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-r,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}return null}var o=e._planeScene.pickWithRay(t,function(e){return e==i._dragPlane});return o&&o.hit&&o.pickedMesh&&o.pickedPoint?o.pickedPoint:null},e.prototype._updateDragPlanePosition=function(e,t){this._pointA.copyFrom(t),this._options.dragAxis?(this.useObjectOrientationForDragging?a.e.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragAxis),this._pointA.addToRef(this._localAxis,this._pointB),e.origin.subtractToRef(this._pointA,this._pointC),this._pointA.addToRef(this._pointC.normalize(),this._pointC),this._pointB.subtractToRef(this._pointA,this._lineA),this._pointC.subtractToRef(this._pointA,this._lineB),a.e.CrossToRef(this._lineA,this._lineB,this._lookAt),a.e.CrossToRef(this._lineA,this._lookAt,this._lookAt),this._lookAt.normalize(),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?a.e.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.absolutePosition),this._dragPlane.computeWorldMatrix(!0)},e.prototype.detach=function(){this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this.releaseDrag()},e._AnyMouseID=-2,e}())},function(e,t,i){"use strict";i.d(t,"a",function(){return r}),i.d(t,"b",function(){return o}),i.d(t,"c",function(){return a});var n=i(1),r=function(){function e(){}return e.KEYDOWN=1,e.KEYUP=2,e}(),o=function(e,t){this.type=e,this.event=t},a=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.type=t,n.event=i,n.skipOnPointerObservable=!1,n}return Object(n.d)(t,e),t}(o)},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}return e.prototype.unBindMesh=function(){this._mesh=null},e.prototype.addFallback=function(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)},e.prototype.addCPUSkinningFallback=function(e,t){this._mesh=t,e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e)},Object.defineProperty(e.prototype,"hasMoreFallbacks",{get:function(){return this._currentRank<=this._maxRank},enumerable:!0,configurable:!0}),e.prototype.reduce=function(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;for(var i=this._mesh.getScene(),n=0;n<i.meshes.length;n++){var r=i.meshes[n];if(r.material){if(r.computeBonesUsingShaders&&0!==r.numBoneInfluencers)if(r.material.getEffect()===t)r.computeBonesUsingShaders=!1;else if(r.subMeshes)for(var o=0,a=r.subMeshes;o<a.length;o++){if(a[o].effect===t){r.computeBonesUsingShaders=!1;break}}}else!this._mesh.material&&r.computeBonesUsingShaders&&r.numBoneInfluencers>0&&(r.computeBonesUsingShaders=!1)}}else{var s=this._defines[this._currentRank];if(s)for(n=0;n<s.length;n++)e=e.replace("#define "+s[n],"");this._currentRank++}return e},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){this._xhr=new XMLHttpRequest}return e.prototype._injectCustomRequestHeaders=function(){for(var t in e.CustomRequestHeaders){var i=e.CustomRequestHeaders[t];i&&this._xhr.setRequestHeader(t,i)}},Object.defineProperty(e.prototype,"onprogress",{get:function(){return this._xhr.onprogress},set:function(e){this._xhr.onprogress=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"readyState",{get:function(){return this._xhr.readyState},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"status",{get:function(){return this._xhr.status},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"statusText",{get:function(){return this._xhr.statusText},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"response",{get:function(){return this._xhr.response},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"responseURL",{get:function(){return this._xhr.responseURL},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"responseText",{get:function(){return this._xhr.responseText},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"responseType",{get:function(){return this._xhr.responseType},set:function(e){this._xhr.responseType=e},enumerable:!0,configurable:!0}),e.prototype.addEventListener=function(e,t,i){this._xhr.addEventListener(e,t,i)},e.prototype.removeEventListener=function(e,t,i){this._xhr.removeEventListener(e,t,i)},e.prototype.abort=function(){this._xhr.abort()},e.prototype.send=function(t){e.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(t)},e.prototype.open=function(t,i){for(var n=0,r=e.CustomRequestModifiers;n<r.length;n++){(0,r[n])(this._xhr,i)}return i=(i=i.replace("file:http:","http:")).replace("file:https:","https:"),this._xhr.open(t,i,!0)},e.prototype.setRequestHeader=function(e,t){this._xhr.setRequestHeader(e,t)},e.prototype.getResponseHeader=function(e){return this._xhr.getResponseHeader(e)},e.CustomRequestHeaders={},e.CustomRequestModifiers=new Array,e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return s});var n=i(0),r=i(10),o=i(5),a=i(15);a.a.CreateBox=function(e){var t,i=[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],o=[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=[],c=e.width||e.size||1,l=e.height||e.size||1,u=e.depth||e.size||1,h=e.wrap||!1,d=void 0===e.topBaseAt?1:e.topBaseAt,f=void 0===e.bottomBaseAt?0:e.bottomBaseAt,p=[2,0,3,1][d=(d+4)%4],_=[2,0,1,3][f=(f+4)%4],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){i=[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];for(var g=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],v=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]],y=[17,18,19,16],b=[22,23,20,21];p>0;)g.unshift(g.pop()),y.unshift(y.pop()),p--;for(;_>0;)v.unshift(v.pop()),b.unshift(b.pop()),_--;g=g.flat(),v=v.flat(),m=m.concat(g).concat(v),i.push(y[0],y[2],y[3],y[0],y[1],y[2]),i.push(b[0],b[2],b[3],b[0],b[1],b[2])}var T=[c/2,l/2,u/2];t=m.reduce(function(e,t,i){return e.concat(t*T[i%3])},[]);for(var E=0===e.sideOrientation?0:e.sideOrientation||a.a.DEFAULTSIDE,x=e.faceUV||new Array(6),P=e.faceColors,A=[],S=0;S<6;S++)void 0===x[S]&&(x[S]=new n.f(0,0,1,1)),P&&void 0===P[S]&&(P[S]=new r.b(1,1,1,1));for(var C=0;C<6;C++)if(s.push(x[C].z,x[C].w),s.push(x[C].x,x[C].w),s.push(x[C].x,x[C].y),s.push(x[C].z,x[C].y),P)for(var R=0;R<4;R++)A.push(P[C].r,P[C].g,P[C].b,P[C].a);a.a._ComputeSides(E,t,i,o,s,e.frontUVs,e.backUVs);var O=new a.a;if(O.indices=i,O.positions=t,O.normals=o,O.uvs=s,P){var M=E===a.a.DOUBLESIDE?A.concat(A):A;O.colors=M}return O},o.a.CreateBox=function(e,t,i,n,r){void 0===i&&(i=null);var o={size:t,sideOrientation:r,updatable:n};return s.CreateBox(e,o,i)};var s=function(){function e(){}return e.CreateBox=function(e,t,i){void 0===i&&(i=null);var n=new o.a(e,i);return t.sideOrientation=o.a._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,a.a.CreateBox(t).applyToMesh(n,t.updatable),n},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r});var n=i(2),r=function(){function e(){}return Object.defineProperty(e,"ForceFullSceneLoadingForIncremental",{get:function(){return e._ForceFullSceneLoadingForIncremental},set:function(t){e._ForceFullSceneLoadingForIncremental=t},enumerable:!0,configurable:!0}),Object.defineProperty(e,"ShowLoadingScreen",{get:function(){return e._ShowLoadingScreen},set:function(t){e._ShowLoadingScreen=t},enumerable:!0,configurable:!0}),Object.defineProperty(e,"loggingLevel",{get:function(){return e._loggingLevel},set:function(t){e._loggingLevel=t},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CleanBoneMatrixWeights",{get:function(){return e._CleanBoneMatrixWeights},set:function(t){e._CleanBoneMatrixWeights=t},enumerable:!0,configurable:!0}),e._ForceFullSceneLoadingForIncremental=!1,e._ShowLoadingScreen=!0,e._CleanBoneMatrixWeights=!1,e._loggingLevel=n.a.SCENELOADER_NO_LOGGING,e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(e,t){this.width=e,this.height=t}return e.prototype.toString=function(){return"{W: "+this.width+", H: "+this.height+"}"},e.prototype.getClassName=function(){return"Size"},e.prototype.getHashCode=function(){var e=0|this.width;return e=397*e^(0|this.height)},e.prototype.copyFrom=function(e){this.width=e.width,this.height=e.height},e.prototype.copyFromFloats=function(e,t){return this.width=e,this.height=t,this},e.prototype.set=function(e,t){return this.copyFromFloats(e,t)},e.prototype.multiplyByFloats=function(t,i){return new e(this.width*t,this.height*i)},e.prototype.clone=function(){return new e(this.width,this.height)},e.prototype.equals=function(e){return!!e&&(this.width===e.width&&this.height===e.height)},Object.defineProperty(e.prototype,"surface",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),e.Zero=function(){return new e(0,0)},e.prototype.add=function(t){return new e(this.width+t.width,this.height+t.height)},e.prototype.subtract=function(t){return new e(this.width-t.width,this.height-t.height)},e.Lerp=function(t,i,n){return new e(t.width+(i.width-t.width)*n,t.height+(i.height-t.height)*n)},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return p});var n=i(0),r=i(10),o=i(15),a=i(4),s=i(57),c=i(67),l=i(44),u=i(2),h=i(13),d=i(35),f=i(110),p=function(){function e(e,t,i,n,r){void 0===n&&(n=!1),void 0===r&&(r=null),this.delayLoadState=u.a.DELAYLOADSTATE_NONE,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this.id=e,this.uniqueId=t.getUniqueId(),this._engine=t.getEngine(),this._meshes=[],this._scene=t,this._vertexBuffers={},this._indices=[],this._updatable=n,i?this.setAllVerticesData(i,n):(this._totalVertices=0,this._indices=[]),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.computeWorldMatrix(!0))}return Object.defineProperty(e.prototype,"boundingBias",{get:function(){return this._boundingBias},set:function(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)},enumerable:!0,configurable:!0}),e.CreateGeometryForMesh=function(t){var i=new e(e.RandomId(),t.getScene());return i.applyToMesh(t),i},Object.defineProperty(e.prototype,"extend",{get:function(){return this._extend},enumerable:!0,configurable:!0}),e.prototype.getScene=function(){return this._scene},e.prototype.getEngine=function(){return this._engine},e.prototype.isReady=function(){return this.delayLoadState===u.a.DELAYLOADSTATE_LOADED||this.delayLoadState===u.a.DELAYLOADSTATE_NONE},Object.defineProperty(e.prototype,"doNotSerialize",{get:function(){for(var e=0;e<this._meshes.length;e++)if(!this._meshes[e].doNotSerialize)return!1;return!0},enumerable:!0,configurable:!0}),e.prototype._rebuild=function(){for(var e in this._vertexArrayObjects&&(this._vertexArrayObjects={}),0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices)),this._vertexBuffers){this._vertexBuffers[e]._rebuild()}},e.prototype.setAllVerticesData=function(e,t){e.applyToGeometry(this,t),this.notifyUpdate()},e.prototype.setVerticesData=function(e,t,i,n){void 0===i&&(i=!1);var r=new a.b(this._engine,t,e,i,0===this._meshes.length,n);this.setVerticesBuffer(r)},e.prototype.removeVerticesData=function(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e])},e.prototype.setVerticesBuffer=function(e,t){void 0===t&&(t=null);var i=e.getKind();if(this._vertexBuffers[i]&&this._vertexBuffers[i].dispose(),this._vertexBuffers[i]=e,i===a.b.PositionKind){var n=e.getData();null!=t?this._totalVertices=t:null!=n&&(this._totalVertices=n.length/(e.byteStride/4)),this._updateExtend(n),this._resetPointsArrayCache();for(var r=this._meshes,o=r.length,s=0;s<o;s++){var c=r[s];c._boundingInfo=new l.a(this._extend.minimum,this._extend.maximum),c._createGlobalSubMesh(!1),c.computeWorldMatrix(!0)}}this.notifyUpdate(i),this._vertexArrayObjects&&(this._disposeVertexArrayObjects(),this._vertexArrayObjects={})},e.prototype.updateVerticesDataDirectly=function(e,t,i,n){void 0===n&&(n=!1);var r=this.getVertexBuffer(e);r&&(r.updateDirectly(t,i,n),this.notifyUpdate(e))},e.prototype.updateVerticesData=function(e,t,i){void 0===i&&(i=!1);var n=this.getVertexBuffer(e);n&&(n.update(t),e===a.b.PositionKind&&this._updateBoundingInfo(i,t),this.notifyUpdate(e))},e.prototype._updateBoundingInfo=function(e,t){if(e&&this._updateExtend(t),this._resetPointsArrayCache(),e)for(var i=0,n=this._meshes;i<n.length;i++){var r=n[i];r._boundingInfo?r._boundingInfo.reConstruct(this._extend.minimum,this._extend.maximum):r._boundingInfo=new l.a(this._extend.minimum,this._extend.maximum);for(var o=0,a=r.subMeshes;o<a.length;o++){a[o].refreshBoundingInfo()}}},e.prototype._bind=function(e,t){if(e){void 0===t&&(t=this._indexBuffer);var i=this.getVertexBuffers();i&&(t==this._indexBuffer&&this._vertexArrayObjects?(this._vertexArrayObjects[e.key]||(this._vertexArrayObjects[e.key]=this._engine.recordVertexArrayObject(i,t,e)),this._engine.bindVertexArrayObject(this._vertexArrayObjects[e.key],t)):this._engine.bindBuffers(i,t,e))}},e.prototype.getTotalVertices=function(){return this.isReady()?this._totalVertices:0},e.prototype.getVerticesData=function(e,t,i){var n=this.getVertexBuffer(e);if(!n)return null;var r=n.getData();if(!r)return null;var o=n.getSize()*a.b.GetTypeByteLength(n.type),s=this._totalVertices*n.getSize();if(n.type!==a.b.FLOAT||n.byteStride!==o){var c=[];return n.forEach(s,function(e){return c.push(e)}),c}if(!(r instanceof Array||r instanceof Float32Array)||0!==n.byteOffset||r.length!==s){if(r instanceof Array){var l=n.byteOffset/4;return h.b.Slice(r,l,l+s)}if(r instanceof ArrayBuffer)return new Float32Array(r,n.byteOffset,s);l=r.byteOffset+n.byteOffset;if(i||t&&1!==this._meshes.length){var u=new Float32Array(s),d=new Float32Array(r.buffer,l,s);return u.set(d),u}return new Float32Array(r.buffer,l,s)}return i||t&&1!==this._meshes.length?h.b.Slice(r):r},e.prototype.isVertexBufferUpdatable=function(e){var t=this._vertexBuffers[e];return!!t&&t.isUpdatable()},e.prototype.getVertexBuffer=function(e){return this.isReady()?this._vertexBuffers[e]:null},e.prototype.getVertexBuffers=function(){return this.isReady()?this._vertexBuffers:null},e.prototype.isVerticesDataPresent=function(e){return this._vertexBuffers?void 0!==this._vertexBuffers[e]:!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)},e.prototype.getVerticesDataKinds=function(){var e,t=[];if(!this._vertexBuffers&&this._delayInfo)for(e in this._delayInfo)t.push(e);else for(e in this._vertexBuffers)t.push(e);return t},e.prototype.updateIndices=function(e,t,i){if(void 0===i&&(i=!1),this._indexBuffer)if(this._indexBufferIsUpdatable){var n=e.length!==this._indices.length;if(i||(this._indices=e.slice()),this._engine.updateDynamicIndexBuffer(this._indexBuffer,e,t),n)for(var r=0,o=this._meshes;r<o.length;r++){o[r]._createGlobalSubMesh(!0)}}else this.setIndices(e,null,!0)},e.prototype.setIndices=function(e,t,i){void 0===t&&(t=null),void 0===i&&(i=!1),this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._disposeVertexArrayObjects(),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i)),null!=t&&(this._totalVertices=t);for(var n=0,r=this._meshes;n<r.length;n++){r[n]._createGlobalSubMesh(!0)}this.notifyUpdate()},e.prototype.getTotalIndices=function(){return this.isReady()?this._indices.length:0},e.prototype.getIndices=function(e,t){if(!this.isReady())return null;var i=this._indices;if(t||e&&1!==this._meshes.length){for(var n=i.length,r=[],o=0;o<n;o++)r.push(i[o]);return r}return i},e.prototype.getIndexBuffer=function(){return this.isReady()?this._indexBuffer:null},e.prototype._releaseVertexArrayObject=function(e){void 0===e&&(e=null),e&&this._vertexArrayObjects&&this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])},e.prototype.releaseForMesh=function(e,t){var i=this._meshes,n=i.indexOf(e);-1!==n&&(i.splice(n,1),e._geometry=null,0===i.length&&t&&this.dispose())},e.prototype.applyToMesh=function(e){if(e._geometry!==this){var t=e._geometry;t&&t.releaseForMesh(e);var i=this._meshes;e._geometry=this,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):e._boundingInfo=this._boundingInfo}},e.prototype._updateExtend=function(e){void 0===e&&(e=null),e||(e=this.getVerticesData(a.b.PositionKind)),this._extend=Object(f.a)(e,0,this._totalVertices,this.boundingBias,3)},e.prototype._applyToMesh=function(e){var t=this._meshes.length;for(var i in this._vertexBuffers){1===t&&this._vertexBuffers[i].create();var n=this._vertexBuffers[i].getBuffer();n&&(n.references=t),i===a.b.PositionKind&&(this._extend||this._updateExtend(),e._boundingInfo=new l.a(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(!1),e._updateBoundingInfo())}1===t&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices)),this._indexBuffer&&(this._indexBuffer.references=t),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()},e.prototype.notifyUpdate=function(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e);for(var t=0,i=this._meshes;t<i.length;t++){i[t]._markSubMeshesAsAttributesDirty()}},e.prototype.load=function(e,t){this.delayLoadState!==u.a.DELAYLOADSTATE_LOADING&&(this.isReady()?t&&t():(this.delayLoadState=u.a.DELAYLOADSTATE_LOADING,this._queueLoad(e,t)))},e.prototype._queueLoad=function(e,t){var i=this;this.delayLoadingFile&&(e._addPendingData(this),e._loadFile(this.delayLoadingFile,function(n){if(i._delayLoadingFunction){i._delayLoadingFunction(JSON.parse(n),i),i.delayLoadState=u.a.DELAYLOADSTATE_LOADED,i._delayInfo=[],e._removePendingData(i);for(var r=i._meshes,o=r.length,a=0;a<o;a++)i._applyToMesh(r[a]);t&&t()}},void 0,!0))},e.prototype.toLeftHanded=function(){var e=this.getIndices(!1);if(null!=e&&e.length>0){for(var t=0;t<e.length;t+=3){var i=e[t+0];e[t+0]=e[t+2],e[t+2]=i}this.setIndices(e)}var n=this.getVerticesData(a.b.PositionKind,!1);if(null!=n&&n.length>0){for(t=0;t<n.length;t+=3)n[t+2]=-n[t+2];this.setVerticesData(a.b.PositionKind,n,!1)}var r=this.getVerticesData(a.b.NormalKind,!1);if(null!=r&&r.length>0){for(t=0;t<r.length;t+=3)r[t+2]=-r[t+2];this.setVerticesData(a.b.NormalKind,r,!1)}},e.prototype._resetPointsArrayCache=function(){this._positions=null},e.prototype._generatePointsArray=function(){if(this._positions)return!0;var e=this.getVerticesData(a.b.PositionKind);if(!e||0===e.length)return!1;this._positions=[];for(var t=0;t<e.length;t+=3)this._positions.push(n.e.FromArray(e,t));return!0},e.prototype.isDisposed=function(){return this._isDisposed},e.prototype._disposeVertexArrayObjects=function(){if(this._vertexArrayObjects){for(var e in this._vertexArrayObjects)this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e]);this._vertexArrayObjects={}}},e.prototype.dispose=function(){var e,t=this._meshes,i=t.length;for(e=0;e<i;e++)this.releaseForMesh(t[e]);for(var n in this._meshes=[],this._disposeVertexArrayObjects(),this._vertexBuffers)this._vertexBuffers[n].dispose();this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=u.a.DELAYLOADSTATE_NONE,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._isDisposed=!0},e.prototype.copy=function(t){var i=new o.a;i.indices=[];var n=this.getIndices();if(n)for(var r=0;r<n.length;r++)i.indices.push(n[r]);var a,s=!1,c=!1;for(a in this._vertexBuffers){var u=this.getVerticesData(a);if(u&&(u instanceof Float32Array?i.set(new Float32Array(u),a):i.set(u.slice(0),a),!c)){var h=this.getVertexBuffer(a);h&&(c=!(s=h.isUpdatable()))}}var d=new e(t,this._scene,i,s);for(a in d.delayLoadState=this.delayLoadState,d.delayLoadingFile=this.delayLoadingFile,d._delayLoadingFunction=this._delayLoadingFunction,this._delayInfo)d._delayInfo=d._delayInfo||[],d._delayInfo.push(a);return d._boundingInfo=new l.a(this._extend.minimum,this._extend.maximum),d},e.prototype.serialize=function(){var e={};return e.id=this.id,e.updatable=this._updatable,d.a&&d.a.HasTags(this)&&(e.tags=d.a.GetTags(this)),e},e.prototype.toNumberArray=function(e){return Array.isArray(e)?e:Array.prototype.slice.call(e)},e.prototype.serializeVerticeData=function(){var e=this.serialize();return this.isVerticesDataPresent(a.b.PositionKind)&&(e.positions=this.toNumberArray(this.getVerticesData(a.b.PositionKind)),this.isVertexBufferUpdatable(a.b.PositionKind)&&(e.positions._updatable=!0)),this.isVerticesDataPresent(a.b.NormalKind)&&(e.normals=this.toNumberArray(this.getVerticesData(a.b.NormalKind)),this.isVertexBufferUpdatable(a.b.NormalKind)&&(e.normals._updatable=!0)),this.isVerticesDataPresent(a.b.TangentKind)&&(e.tangets=this.toNumberArray(this.getVerticesData(a.b.TangentKind)),this.isVertexBufferUpdatable(a.b.TangentKind)&&(e.tangets._updatable=!0)),this.isVerticesDataPresent(a.b.UVKind)&&(e.uvs=this.toNumberArray(this.getVerticesData(a.b.UVKind)),this.isVertexBufferUpdatable(a.b.UVKind)&&(e.uvs._updatable=!0)),this.isVerticesDataPresent(a.b.UV2Kind)&&(e.uv2s=this.toNumberArray(this.getVerticesData(a.b.UV2Kind)),this.isVertexBufferUpdatable(a.b.UV2Kind)&&(e.uv2s._updatable=!0)),this.isVerticesDataPresent(a.b.UV3Kind)&&(e.uv3s=this.toNumberArray(this.getVerticesData(a.b.UV3Kind)),this.isVertexBufferUpdatable(a.b.UV3Kind)&&(e.uv3s._updatable=!0)),this.isVerticesDataPresent(a.b.UV4Kind)&&(e.uv4s=this.toNumberArray(this.getVerticesData(a.b.UV4Kind)),this.isVertexBufferUpdatable(a.b.UV4Kind)&&(e.uv4s._updatable=!0)),this.isVerticesDataPresent(a.b.UV5Kind)&&(e.uv5s=this.toNumberArray(this.getVerticesData(a.b.UV5Kind)),this.isVertexBufferUpdatable(a.b.UV5Kind)&&(e.uv5s._updatable=!0)),this.isVerticesDataPresent(a.b.UV6Kind)&&(e.uv6s=this.toNumberArray(this.getVerticesData(a.b.UV6Kind)),this.isVertexBufferUpdatable(a.b.UV6Kind)&&(e.uv6s._updatable=!0)),this.isVerticesDataPresent(a.b.ColorKind)&&(e.colors=this.toNumberArray(this.getVerticesData(a.b.ColorKind)),this.isVertexBufferUpdatable(a.b.ColorKind)&&(e.colors._updatable=!0)),this.isVerticesDataPresent(a.b.MatricesIndicesKind)&&(e.matricesIndices=this.toNumberArray(this.getVerticesData(a.b.MatricesIndicesKind)),e.matricesIndices._isExpanded=!0,this.isVertexBufferUpdatable(a.b.MatricesIndicesKind)&&(e.matricesIndices._updatable=!0)),this.isVerticesDataPresent(a.b.MatricesWeightsKind)&&(e.matricesWeights=this.toNumberArray(this.getVerticesData(a.b.MatricesWeightsKind)),this.isVertexBufferUpdatable(a.b.MatricesWeightsKind)&&(e.matricesWeights._updatable=!0)),e.indices=this.toNumberArray(this.getIndices()),e},e.ExtractFromMesh=function(e,t){var i=e._geometry;return i?i.copy(t):null},e.RandomId=function(){return h.b.RandomId()},e._ImportGeometry=function(t,i){var n=i.getScene(),o=t.geometryId;if(o){var c=n.getGeometryByID(o);c&&c.applyToMesh(i)}else if(t instanceof ArrayBuffer){var l=i._binaryInfo;if(l.positionsAttrDesc&&l.positionsAttrDesc.count>0){var u=new Float32Array(t,l.positionsAttrDesc.offset,l.positionsAttrDesc.count);i.setVerticesData(a.b.PositionKind,u,!1)}if(l.normalsAttrDesc&&l.normalsAttrDesc.count>0){var h=new Float32Array(t,l.normalsAttrDesc.offset,l.normalsAttrDesc.count);i.setVerticesData(a.b.NormalKind,h,!1)}if(l.tangetsAttrDesc&&l.tangetsAttrDesc.count>0){var d=new Float32Array(t,l.tangetsAttrDesc.offset,l.tangetsAttrDesc.count);i.setVerticesData(a.b.TangentKind,d,!1)}if(l.uvsAttrDesc&&l.uvsAttrDesc.count>0){var f=new Float32Array(t,l.uvsAttrDesc.offset,l.uvsAttrDesc.count);i.setVerticesData(a.b.UVKind,f,!1)}if(l.uvs2AttrDesc&&l.uvs2AttrDesc.count>0){var p=new Float32Array(t,l.uvs2AttrDesc.offset,l.uvs2AttrDesc.count);i.setVerticesData(a.b.UV2Kind,p,!1)}if(l.uvs3AttrDesc&&l.uvs3AttrDesc.count>0){var _=new Float32Array(t,l.uvs3AttrDesc.offset,l.uvs3AttrDesc.count);i.setVerticesData(a.b.UV3Kind,_,!1)}if(l.uvs4AttrDesc&&l.uvs4AttrDesc.count>0){var m=new Float32Array(t,l.uvs4AttrDesc.offset,l.uvs4AttrDesc.count);i.setVerticesData(a.b.UV4Kind,m,!1)}if(l.uvs5AttrDesc&&l.uvs5AttrDesc.count>0){var g=new Float32Array(t,l.uvs5AttrDesc.offset,l.uvs5AttrDesc.count);i.setVerticesData(a.b.UV5Kind,g,!1)}if(l.uvs6AttrDesc&&l.uvs6AttrDesc.count>0){var v=new Float32Array(t,l.uvs6AttrDesc.offset,l.uvs6AttrDesc.count);i.setVerticesData(a.b.UV6Kind,v,!1)}if(l.colorsAttrDesc&&l.colorsAttrDesc.count>0){var y=new Float32Array(t,l.colorsAttrDesc.offset,l.colorsAttrDesc.count);i.setVerticesData(a.b.ColorKind,y,!1,l.colorsAttrDesc.stride)}if(l.matricesIndicesAttrDesc&&l.matricesIndicesAttrDesc.count>0){for(var b=new Int32Array(t,l.matricesIndicesAttrDesc.offset,l.matricesIndicesAttrDesc.count),T=[],E=0;E<b.length;E++){var x=b[E];T.push(255&x),T.push((65280&x)>>8),T.push((16711680&x)>>16),T.push(x>>24)}i.setVerticesData(a.b.MatricesIndicesKind,T,!1)}if(l.matricesWeightsAttrDesc&&l.matricesWeightsAttrDesc.count>0){var P=new Float32Array(t,l.matricesWeightsAttrDesc.offset,l.matricesWeightsAttrDesc.count);i.setVerticesData(a.b.MatricesWeightsKind,P,!1)}if(l.indicesAttrDesc&&l.indicesAttrDesc.count>0){var A=new Int32Array(t,l.indicesAttrDesc.offset,l.indicesAttrDesc.count);i.setIndices(A,null)}if(l.subMeshesAttrDesc&&l.subMeshesAttrDesc.count>0){var S=new Int32Array(t,l.subMeshesAttrDesc.offset,5*l.subMeshesAttrDesc.count);i.subMeshes=[];for(E=0;E<l.subMeshesAttrDesc.count;E++){var C=S[5*E+0],R=S[5*E+1],O=S[5*E+2],M=S[5*E+3],I=S[5*E+4];s.b.AddToMesh(C,R,O,M,I,i)}}}else if(t.positions&&t.normals&&t.indices){if(i.setVerticesData(a.b.PositionKind,t.positions,t.positions._updatable),i.setVerticesData(a.b.NormalKind,t.normals,t.normals._updatable),t.tangents&&i.setVerticesData(a.b.TangentKind,t.tangents,t.tangents._updatable),t.uvs&&i.setVerticesData(a.b.UVKind,t.uvs,t.uvs._updatable),t.uvs2&&i.setVerticesData(a.b.UV2Kind,t.uvs2,t.uvs2._updatable),t.uvs3&&i.setVerticesData(a.b.UV3Kind,t.uvs3,t.uvs3._updatable),t.uvs4&&i.setVerticesData(a.b.UV4Kind,t.uvs4,t.uvs4._updatable),t.uvs5&&i.setVerticesData(a.b.UV5Kind,t.uvs5,t.uvs5._updatable),t.uvs6&&i.setVerticesData(a.b.UV6Kind,t.uvs6,t.uvs6._updatable),t.colors&&i.setVerticesData(a.b.ColorKind,r.b.CheckColors4(t.colors,t.positions.length/3),t.colors._updatable),t.matricesIndices)if(t.matricesIndices._isExpanded)delete t.matricesIndices._isExpanded,i.setVerticesData(a.b.MatricesIndicesKind,t.matricesIndices,t.matricesIndices._updatable);else{for(T=[],E=0;E<t.matricesIndices.length;E++){var D=t.matricesIndices[E];T.push(255&D),T.push((65280&D)>>8),T.push((16711680&D)>>16),T.push(D>>24)}i.setVerticesData(a.b.MatricesIndicesKind,T,t.matricesIndices._updatable)}if(t.matricesIndicesExtra)if(t.matricesIndicesExtra._isExpanded)delete t.matricesIndices._isExpanded,i.setVerticesData(a.b.MatricesIndicesExtraKind,t.matricesIndicesExtra,t.matricesIndicesExtra._updatable);else{for(T=[],E=0;E<t.matricesIndicesExtra.length;E++){D=t.matricesIndicesExtra[E];T.push(255&D),T.push((65280&D)>>8),T.push((16711680&D)>>16),T.push(D>>24)}i.setVerticesData(a.b.MatricesIndicesExtraKind,T,t.matricesIndicesExtra._updatable)}t.matricesWeights&&(e._CleanMatricesWeights(t,i),i.setVerticesData(a.b.MatricesWeightsKind,t.matricesWeights,t.matricesWeights._updatable)),t.matricesWeightsExtra&&i.setVerticesData(a.b.MatricesWeightsExtraKind,t.matricesWeightsExtra,t.matricesWeights._updatable),i.setIndices(t.indices,null)}if(t.subMeshes){i.subMeshes=[];for(var w=0;w<t.subMeshes.length;w++){var L=t.subMeshes[w];s.b.AddToMesh(L.materialIndex,L.verticesStart,L.verticesCount,L.indexStart,L.indexCount,i)}}i._shouldGenerateFlatShading&&(i.convertToFlatShadedMesh(),delete i._shouldGenerateFlatShading),i.computeWorldMatrix(!0),n.onMeshImportedObservable.notifyObservers(i)},e._CleanMatricesWeights=function(e,t){if(c.a.CleanBoneMatrixWeights){var i=0;if(e.skeletonId>-1){var n=t.getScene().getLastSkeletonByID(e.skeletonId);if(n){i=n.bones.length;for(var r=t.getVerticesData(a.b.MatricesIndicesKind),o=t.getVerticesData(a.b.MatricesIndicesExtraKind),s=e.matricesWeights,l=e.matricesWeightsExtra,u=e.numBoneInfluencer,h=s.length,d=0;d<h;d+=4){for(var f=0,p=-1,_=0;_<4;_++){f+=m=s[d+_],m<.001&&p<0&&(p=_)}if(l)for(_=0;_<4;_++){var m;f+=m=l[d+_],m<.001&&p<0&&(p=_+4)}if((p<0||p>u-1)&&(p=u-1),f>.001){var g=1/f;for(_=0;_<4;_++)s[d+_]*=g;if(l)for(_=0;_<4;_++)l[d+_]*=g}else p>=4?(l[d+p-4]=1-f,o[d+p-4]=i):(s[d+p]=1-f,r[d+p]=i)}t.setVerticesData(a.b.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(a.b.MatricesIndicesExtraKind,o)}}}},e.Parse=function(t,i,r){if(i.getGeometryByID(t.id))return null;var s=new e(t.id,i,void 0,t.updatable);return d.a&&d.a.AddTagsTo(s,t.tags),t.delayLoadingFile?(s.delayLoadState=u.a.DELAYLOADSTATE_NOTLOADED,s.delayLoadingFile=r+t.delayLoadingFile,s._boundingInfo=new l.a(n.e.FromArray(t.boundingBoxMinimum),n.e.FromArray(t.boundingBoxMaximum)),s._delayInfo=[],t.hasUVs&&s._delayInfo.push(a.b.UVKind),t.hasUVs2&&s._delayInfo.push(a.b.UV2Kind),t.hasUVs3&&s._delayInfo.push(a.b.UV3Kind),t.hasUVs4&&s._delayInfo.push(a.b.UV4Kind),t.hasUVs5&&s._delayInfo.push(a.b.UV5Kind),t.hasUVs6&&s._delayInfo.push(a.b.UV6Kind),t.hasColors&&s._delayInfo.push(a.b.ColorKind),t.hasMatricesIndices&&s._delayInfo.push(a.b.MatricesIndicesKind),t.hasMatricesWeights&&s._delayInfo.push(a.b.MatricesWeightsKind),s._delayLoadingFunction=o.a.ImportVertexData):o.a.ImportVertexData(t,s),i.pushGeometry(s,!0),s},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return e.CreateCanvas=function(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);var i=document.createElement("canvas");return i.width=e,i.height=t,i},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return s});var n=i(1),r=i(29),o=i(35),a=i(12),s=function(e){function t(t,i){var n=e.call(this,t,i,!0)||this;return i.multiMaterials.push(n),n.subMaterials=new Array,n._storeEffectOnSubMeshes=!0,n}return Object(n.d)(t,e),Object.defineProperty(t.prototype,"subMaterials",{get:function(){return this._subMaterials},set:function(e){this._subMaterials=e,this._hookArray(e)},enumerable:!0,configurable:!0}),t.prototype.getChildren=function(){return this.subMaterials},t.prototype._hookArray=function(e){var t=this,i=e.push;e.push=function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var o=i.apply(e,n);return t._markAllSubMeshesAsTexturesDirty(),o};var n=e.splice;e.splice=function(i,r){var o=n.apply(e,[i,r]);return t._markAllSubMeshesAsTexturesDirty(),o}},t.prototype.getSubMaterial=function(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]},t.prototype.getActiveTextures=function(){var t;return(t=e.prototype.getActiveTextures.call(this)).concat.apply(t,this.subMaterials.map(function(e){return e?e.getActiveTextures():[]}))},t.prototype.getClassName=function(){return"MultiMaterial"},t.prototype.isReadyForSubMesh=function(e,t,i){for(var n=0;n<this.subMaterials.length;n++){var r=this.subMaterials[n];if(r){if(r._storeEffectOnSubMeshes){if(!r.isReadyForSubMesh(e,t,i))return!1;continue}if(!r.isReady(e))return!1}}return!0},t.prototype.clone=function(e,i){for(var n=new t(e,this.getScene()),r=0;r<this.subMaterials.length;r++){var o=null,a=this.subMaterials[r];o=i&&a?a.clone(e+"-"+a.name):this.subMaterials[r],n.subMaterials.push(o)}return n},t.prototype.serialize=function(){var e={};e.name=this.name,e.id=this.id,o.a&&(e.tags=o.a.GetTags(this)),e.materials=[];for(var t=0;t<this.subMaterials.length;t++){var i=this.subMaterials[t];i?e.materials.push(i.id):e.materials.push(null)}return e},t.prototype.dispose=function(t,i,n){var r=this.getScene();if(r){if(n)for(var o=0;o<this.subMaterials.length;o++){var a=this.subMaterials[o];a&&a.dispose(t,i)}(o=r.multiMaterials.indexOf(this))>=0&&r.multiMaterials.splice(o,1),e.prototype.dispose.call(this,t,i)}},t.ParseMultiMaterial=function(e,i){var n=new t(e.name,i);n.id=e.id,o.a&&o.a.AddTagsTo(n,e.tags);for(var r=0;r<e.materials.length;r++){var a=e.materials[r];a?n.subMaterials.push(i.getLastMaterialByID(a)):n.subMaterials.push(null)}return n},t}(r.a);a.a.RegisteredTypes["BABYLON.MultiMaterial"]=s},function(e,t,i){"use strict";i.d(t,"a",function(){return f});var n=i(1),r=i(6),o=i(0),a=i(43),s=i(59),c=i(62),l=i(56),u=i(41),h=i(32),d=i(10),f=function(e){function t(i,n,a,s){void 0===n&&(n=d.a.Gray()),void 0===a&&(a=u.a.DefaultUtilityLayer),void 0===s&&(s=null);var l=e.call(this,a)||this;l._pointerObserver=null,l.snapDistance=0,l.onSnapObservable=new r.c,l._isEnabled=!0,l._parent=null,l._parent=s,l._coloredMaterial=new h.a("",a.utilityLayerScene),l._coloredMaterial.diffuseColor=n,l._coloredMaterial.specularColor=n.subtract(new d.a(.1,.1,.1)),l._hoverMaterial=new h.a("",a.utilityLayerScene),l._hoverMaterial.diffuseColor=n.add(new d.a(.3,.3,.3)),l._arrow=t._CreateArrow(a.utilityLayerScene,l._coloredMaterial),l._arrow.lookAt(l._rootMesh.position.add(i)),l._arrow.scaling.scaleInPlace(1/3),l._arrow.parent=l._rootMesh;var f=0,p=new o.e,_={snapDistance:0};l.dragBehavior=new c.a({dragAxis:i}),l.dragBehavior.moveAttached=!1,l._rootMesh.addBehavior(l.dragBehavior);var m=new o.e,g=new o.a;l.dragBehavior.onDragObservable.add(function(e){if(l.attachedMesh)if(l.attachedMesh.parent?(l.attachedMesh.parent.computeWorldMatrix().invertToRef(g),g.setTranslationFromFloats(0,0,0),o.e.TransformCoordinatesToRef(e.delta,g,m)):m.copyFrom(e.delta),0==l.snapDistance)l.attachedMesh.position.addInPlace(m);else if(f+=e.dragDistance,Math.abs(f)>l.snapDistance){var t=Math.floor(Math.abs(f)/l.snapDistance);f%=l.snapDistance,m.normalizeToRef(p),p.scaleInPlace(l.snapDistance*t),l.attachedMesh.position.addInPlace(p),_.snapDistance=l.snapDistance*t,l.onSnapObservable.notifyObservers(_)}}),l._pointerObserver=a.utilityLayerScene.onPointerObservable.add(function(e){if(!l._customMeshSet){var t=e.pickInfo&&-1!=l._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)?l._hoverMaterial:l._coloredMaterial;l._rootMesh.getChildMeshes().forEach(function(e){e.material=t,e.color&&(e.color=t.diffuseColor)})}});var v=a._getSharedGizmoLight();return v.includedOnlyMeshes=v.includedOnlyMeshes.concat(l._rootMesh.getChildMeshes(!1)),l}return Object(n.d)(t,e),t._CreateArrow=function(e,t){var i=new a.a("arrow",e),n=s.a.CreateCylinder("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375,tessellation:96},e),r=s.a.CreateCylinder("cylinder",{diameterTop:.005,height:.275,diameterBottom:.005,tessellation:96},e);return r.material=t,n.parent=i,r.parent=i,n.material=t,n.rotation.x=Math.PI/2,n.position.z+=.3,r.position.z+=.1375,r.rotation.x=Math.PI/2,i},t._CreateArrowInstance=function(e,t){for(var i=new a.a("arrow",e),n=0,r=t.getChildMeshes();n<r.length;n++){var o=r[n];o.createInstance(o.name).parent=i}return i},t.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._arrow&&this._arrow.dispose(),[this._coloredMaterial,this._hoverMaterial].forEach(function(e){e&&e.dispose()}),e.prototype.dispose.call(this)},t}(l.a)},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1}return Object.defineProperty(e.prototype,"isDirty",{get:function(){return this._isDirty},enumerable:!0,configurable:!0}),e.prototype.markAsProcessed=function(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._areImageProcessingDirty=!1},e.prototype.markAsUnprocessed=function(){this._isDirty=!0},e.prototype.markAllAsDirty=function(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._areImageProcessingDirty=!0,this._isDirty=!0},e.prototype.markAsImageProcessingDirty=function(){this._areImageProcessingDirty=!0,this._isDirty=!0},e.prototype.markAsLightDirty=function(e){void 0===e&&(e=!1),this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0},e.prototype.markAsAttributesDirty=function(){this._areAttributesDirty=!0,this._isDirty=!0},e.prototype.markAsTexturesDirty=function(){this._areTexturesDirty=!0,this._isDirty=!0},e.prototype.markAsFresnelDirty=function(){this._areFresnelDirty=!0,this._isDirty=!0},e.prototype.markAsMiscDirty=function(){this._areMiscDirty=!0,this._isDirty=!0},e.prototype.rebuild=function(){this._keys&&delete this._keys,this._keys=[];for(var e=0,t=Object.keys(this);e<t.length;e++){var i=t[e];"_"!==i[0]&&this._keys.push(i)}},e.prototype.isEqual=function(e){if(this._keys.length!==e._keys.length)return!1;for(var t=0;t<this._keys.length;t++){var i=this._keys[t];if(this[i]!==e[i])return!1}return!0},e.prototype.cloneTo=function(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(var t=0;t<this._keys.length;t++){var i=this._keys[t];e[i]=this[i]}},e.prototype.reset=function(){for(var e=0;e<this._keys.length;e++){var t=this._keys[e];switch(typeof this[t]){case"number":this[t]=0;break;case"string":this[t]="";break;default:this[t]=!1}}},e.prototype.toString=function(){for(var e="",t=0;t<this._keys.length;t++){var i=this._keys[t],n=this[i];switch(typeof n){case"number":case"string":e+="#define "+i+" "+n+"\n";break;default:n&&(e+="#define "+i+"\n")}}return e},e}()},function(e,t,i){"use strict";var n="bonesDeclaration",r="#if NUM_BONE_INFLUENCERS>0\n#ifdef BONETEXTURE\nuniform sampler2D boneSampler;\nuniform float boneTextureWidth;\n#else\nuniform mat4 mBones[BonesPerMesh];\n#endif\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#ifdef BONETEXTURE\nmat4 readMatrixFromRawSampler(sampler2D smp,float index)\n{\nfloat offset=index*4.0;\nfloat dx=1.0/boneTextureWidth;\nvec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));\nvec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));\nvec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));\nvec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));\nreturn mat4(m0,m1,m2,m3);\n}\n#endif\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];\n#endif\n#else\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\n#endif\nfinalWorld=finalWorld*influence;\n#endif";i(8).a.IncludesShadersStore.bonesVertex=n},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return e.FilesToLoad={},e}()},function(e,t,i){"use strict";var n="instancesDeclaration",r="#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="instancesVertex",r="#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";i.d(t,"a",function(){return o});var n=i(5),r=i(15);r.a.CreatePlane=function(e){var t=[],i=[],n=[],o=[],a=e.width||e.size||1,s=e.height||e.size||1,c=0===e.sideOrientation?0:e.sideOrientation||r.a.DEFAULTSIDE,l=a/2,u=s/2;i.push(-l,-u,0),n.push(0,0,-1),o.push(0,0),i.push(l,-u,0),n.push(0,0,-1),o.push(1,0),i.push(l,u,0),n.push(0,0,-1),o.push(1,1),i.push(-l,u,0),n.push(0,0,-1),o.push(0,1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),r.a._ComputeSides(c,i,t,n,o,e.frontUVs,e.backUVs);var h=new r.a;return h.indices=t,h.positions=i,h.normals=n,h.uvs=o,h},n.a.CreatePlane=function(e,t,i,n,r){var a={size:t,width:t,height:t,sideOrientation:r,updatable:n};return o.CreatePlane(e,a,i)};var o=function(){function e(){}return e.CreatePlane=function(e,t,i){void 0===i&&(i=null);var o=new n.a(e,i);return t.sideOrientation=n.a._GetDefaultSideOrientation(t.sideOrientation),o._originalBuilderSideOrientation=t.sideOrientation,r.a.CreatePlane(t).applyToMesh(o,t.updatable),t.sourcePlane&&(o.translate(t.sourcePlane.normal,-t.sourcePlane.d),o.setDirection(t.sourcePlane.normal.scale(-1))),o},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return l});var n=i(1),r=i(3),o=i(0),a=i(10),s=i(26),c=i(50);s.a.AddNodeConstructor("Light_Type_3",function(e,t){return function(){return new l(e,o.e.Zero(),t)}});var l=function(e){function t(t,i,n){var r=e.call(this,t,n)||this;return r.groundColor=new a.a(0,0,0),r.direction=i||o.e.Up(),r}return Object(n.d)(t,e),t.prototype._buildUniformLayout=function(){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()},t.prototype.getClassName=function(){return"HemisphericLight"},t.prototype.setDirectionToTarget=function(e){return this.direction=o.e.Normalize(e.subtract(o.e.Zero())),this.direction},t.prototype.getShadowGenerator=function(){return null},t.prototype.transferToEffect=function(e,t){var i=o.e.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},t.prototype.transferToNodeMaterialEffect=function(e,t){var i=o.e.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this},t.prototype.computeWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=o.a.Identity()),this._worldMatrix},t.prototype.getTypeID=function(){return c.a.LIGHTTYPEID_HEMISPHERICLIGHT},t.prototype.prepareLightSpecificDefines=function(e,t){e["HEMILIGHT"+t]=!0},Object(n.c)([Object(r.e)()],t.prototype,"groundColor",void 0),Object(n.c)([Object(r.o)()],t.prototype,"direction",void 0),t}(c.a)},function(e,t,i){"use strict";i.d(t,"a",function(){return o});var n=i(1),r=i(0),o=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n._normalMatrix=new r.a,n.allowShaderHotSwapping=!0,n._storeEffectOnSubMeshes=!0,n}return Object(n.d)(t,e),t.prototype.getEffect=function(){return this._activeEffect},t.prototype.isReady=function(e,t){return!!e&&(!e.subMeshes||0===e.subMeshes.length||this.isReadyForSubMesh(e,e.subMeshes[0],t))},t.prototype.bindOnlyWorldMatrix=function(e){this._activeEffect.setMatrix("world",e)},t.prototype.bindOnlyNormalMatrix=function(e){this._activeEffect.setMatrix("normalMatrix",e)},t.prototype.bind=function(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])},t.prototype._afterBind=function(t,i){void 0===i&&(i=null),e.prototype._afterBind.call(this,t),this.getScene()._cachedEffect=i},t.prototype._mustRebind=function(e,t,i){return void 0===i&&(i=1),e.isCachedMaterialInvalid(this,t,i)},t}(i(29).a)},function(e,t,i){"use strict";i.d(t,"a",function(){return f});var n=i(1),r=i(3),o=i(0),a=i(4),s=i(9),c=i(16),l=i(29),u=i(12),h=i(10),d=i(64),f=function(e){function t(t,i,r,a){void 0===a&&(a={});var s=e.call(this,t,i)||this;return s._textures={},s._textureArrays={},s._floats={},s._ints={},s._floatsArrays={},s._colors3={},s._colors3Arrays={},s._colors4={},s._colors4Arrays={},s._vectors2={},s._vectors3={},s._vectors4={},s._matrices={},s._matrixArrays={},s._matrices3x3={},s._matrices2x2={},s._vectors2Arrays={},s._vectors3Arrays={},s._vectors4Arrays={},s._cachedWorldViewMatrix=new o.a,s._cachedWorldViewProjectionMatrix=new o.a,s._multiview=!1,s._shaderPath=r,s._options=Object(n.a)({needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],defines:[]},a),s}return Object(n.d)(t,e),Object.defineProperty(t.prototype,"shaderPath",{get:function(){return this._shaderPath},set:function(e){this._shaderPath=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"options",{get:function(){return this._options},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"ShaderMaterial"},t.prototype.needAlphaBlending=function(){return this.alpha<1||this._options.needAlphaBlending},t.prototype.needAlphaTesting=function(){return this._options.needAlphaTesting},t.prototype._checkUniform=function(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)},t.prototype.setTexture=function(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this},t.prototype.setTextureArray=function(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this},t.prototype.setFloat=function(e,t){return this._checkUniform(e),this._floats[e]=t,this},t.prototype.setInt=function(e,t){return this._checkUniform(e),this._ints[e]=t,this},t.prototype.setFloats=function(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this},t.prototype.setColor3=function(e,t){return this._checkUniform(e),this._colors3[e]=t,this},t.prototype.setColor3Array=function(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce(function(e,t){return t.toArray(e,e.length),e},[]),this},t.prototype.setColor4=function(e,t){return this._checkUniform(e),this._colors4[e]=t,this},t.prototype.setColor4Array=function(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce(function(e,t){return t.toArray(e,e.length),e},[]),this},t.prototype.setVector2=function(e,t){return this._checkUniform(e),this._vectors2[e]=t,this},t.prototype.setVector3=function(e,t){return this._checkUniform(e),this._vectors3[e]=t,this},t.prototype.setVector4=function(e,t){return this._checkUniform(e),this._vectors4[e]=t,this},t.prototype.setMatrix=function(e,t){return this._checkUniform(e),this._matrices[e]=t,this},t.prototype.setMatrices=function(e,t){this._checkUniform(e);for(var i=new Float32Array(16*t.length),n=0;n<t.length;n++){t[n].copyToArray(i,16*n)}return this._matrixArrays[e]=i,this},t.prototype.setMatrix3x3=function(e,t){return this._checkUniform(e),this._matrices3x3[e]=t,this},t.prototype.setMatrix2x2=function(e,t){return this._checkUniform(e),this._matrices2x2[e]=t,this},t.prototype.setArray2=function(e,t){return this._checkUniform(e),this._vectors2Arrays[e]=t,this},t.prototype.setArray3=function(e,t){return this._checkUniform(e),this._vectors3Arrays[e]=t,this},t.prototype.setArray4=function(e,t){return this._checkUniform(e),this._vectors4Arrays[e]=t,this},t.prototype._checkCache=function(e,t){return!e||(!this._effect||-1!==this._effect.defines.indexOf("#define INSTANCES")===t)},t.prototype.isReadyForSubMesh=function(e,t,i){return this.isReady(e,i)},t.prototype.isReady=function(e,t){if(this._effect&&this.isFrozen&&this._effect._wasPreviouslyReady)return!0;var i=this.getScene(),n=i.getEngine();if(!this.checkReadyOnEveryCall&&this._renderId===i.getRenderId()&&this._checkCache(e,t))return!0;var r=[],o=[],s=new d.a;n.getCaps().multiview&&i.activeCamera&&i.activeCamera.outputRenderTarget&&i.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,r.push("#define MULTIVIEW"),-1!==this._options.uniforms.indexOf("viewProjection")&&-1===this._options.uniforms.push("viewProjectionR")&&this._options.uniforms.push("viewProjectionR"));for(var l=0;l<this._options.defines.length;l++)r.push(this._options.defines[l]);for(l=0;l<this._options.attributes.length;l++)o.push(this._options.attributes[l]);if(e&&e.isVerticesDataPresent(a.b.ColorKind)&&(o.push(a.b.ColorKind),r.push("#define VERTEXCOLOR")),t&&(r.push("#define INSTANCES"),c.a.PushAttributesForInstances(o)),e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton){o.push(a.b.MatricesIndicesKind),o.push(a.b.MatricesWeightsKind),e.numBoneInfluencers>4&&(o.push(a.b.MatricesIndicesExtraKind),o.push(a.b.MatricesWeightsExtraKind));var u=e.skeleton;r.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),s.addCPUSkinningFallback(0,e),u.isUsingTextureForMatrices?(r.push("#define BONETEXTURE"),-1===this._options.uniforms.indexOf("boneTextureWidth")&&this._options.uniforms.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(r.push("#define BonesPerMesh "+(u.bones.length+1)),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones"))}else r.push("#define NUM_BONE_INFLUENCERS 0");for(var h in this._textures)if(!this._textures[h].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&r.push("#define ALPHATEST");var f=this._effect,p=r.join("\n");return this._effect=n.createEffect(this._shaderPath,{attributes:o,uniformsNames:this._options.uniforms,uniformBuffersNames:this._options.uniformBuffers,samplers:this._options.samplers,defines:p,fallbacks:s,onCompiled:this.onCompiled,onError:this.onError},n),!!this._effect.isReady()&&(f!==this._effect&&i.resetCachedMaterial(),this._renderId=i.getRenderId(),this._effect._wasPreviouslyReady=!0,!0)},t.prototype.bindOnlyWorldMatrix=function(e){var t=this.getScene();this._effect&&(-1!==this._options.uniforms.indexOf("world")&&this._effect.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),this._effect.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),this._effect.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))},t.prototype.bind=function(e,t){if(this.bindOnlyWorldMatrix(e),this._effect&&this.getScene().getCachedMaterial()!==this){var i;for(i in-1!==this._options.uniforms.indexOf("view")&&this._effect.setMatrix("view",this.getScene().getViewMatrix()),-1!==this._options.uniforms.indexOf("projection")&&this._effect.setMatrix("projection",this.getScene().getProjectionMatrix()),-1!==this._options.uniforms.indexOf("viewProjection")&&(this._effect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._multiview&&this._effect.setMatrix("viewProjectionR",this.getScene()._transformMatrixR)),this.getScene().activeCamera&&-1!==this._options.uniforms.indexOf("cameraPosition")&&this._effect.setVector3("cameraPosition",this.getScene().activeCamera.globalPosition),c.a.BindBonesParameters(t,this._effect),this._textures)this._effect.setTexture(i,this._textures[i]);for(i in this._textureArrays)this._effect.setTextureArray(i,this._textureArrays[i]);for(i in this._ints)this._effect.setInt(i,this._ints[i]);for(i in this._floats)this._effect.setFloat(i,this._floats[i]);for(i in this._floatsArrays)this._effect.setArray(i,this._floatsArrays[i]);for(i in this._colors3)this._effect.setColor3(i,this._colors3[i]);for(i in this._colors3Arrays)this._effect.setArray3(i,this._colors3Arrays[i]);for(i in this._colors4){var n=this._colors4[i];this._effect.setFloat4(i,n.r,n.g,n.b,n.a)}for(i in this._colors4Arrays)this._effect.setArray4(i,this._colors4Arrays[i]);for(i in this._vectors2)this._effect.setVector2(i,this._vectors2[i]);for(i in this._vectors3)this._effect.setVector3(i,this._vectors3[i]);for(i in this._vectors4)this._effect.setVector4(i,this._vectors4[i]);for(i in this._matrices)this._effect.setMatrix(i,this._matrices[i]);for(i in this._matrixArrays)this._effect.setMatrices(i,this._matrixArrays[i]);for(i in this._matrices3x3)this._effect.setMatrix3x3(i,this._matrices3x3[i]);for(i in this._matrices2x2)this._effect.setMatrix2x2(i,this._matrices2x2[i]);for(i in this._vectors2Arrays)this._effect.setArray2(i,this._vectors2Arrays[i]);for(i in this._vectors3Arrays)this._effect.setArray3(i,this._vectors3Arrays[i]);for(i in this._vectors4Arrays)this._effect.setArray4(i,this._vectors4Arrays[i])}this._afterBind(t)},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);for(var i in this._textures)t.push(this._textures[i]);for(var i in this._textureArrays)for(var n=this._textureArrays[i],r=0;r<n.length;r++)t.push(n[r]);return t},t.prototype.hasTexture=function(t){if(e.prototype.hasTexture.call(this,t))return!0;for(var i in this._textures)if(this._textures[i]===t)return!0;for(var i in this._textureArrays)for(var n=this._textureArrays[i],r=0;r<n.length;r++)if(n[r]===t)return!0;return!1},t.prototype.clone=function(e){var i=this,o=r.a.Clone(function(){return new t(e,i.getScene(),i._shaderPath,i._options)},this);for(var a in o.name=e,o.id=e,"object"==typeof o._shaderPath&&(o._shaderPath=Object(n.a)({},o._shaderPath)),this._options=Object(n.a)({},this._options),Object.keys(this._options).forEach(function(e){var t=i._options[e];Array.isArray(t)&&(i._options[e]=t.slice(0))}),this._textures)o.setTexture(a,this._textures[a]);for(var a in this._floats)o.setFloat(a,this._floats[a]);for(var a in this._floatsArrays)o.setFloats(a,this._floatsArrays[a]);for(var a in this._colors3)o.setColor3(a,this._colors3[a]);for(var a in this._colors4)o.setColor4(a,this._colors4[a]);for(var a in this._vectors2)o.setVector2(a,this._vectors2[a]);for(var a in this._vectors3)o.setVector3(a,this._vectors3[a]);for(var a in this._vectors4)o.setVector4(a,this._vectors4[a]);for(var a in this._matrices)o.setMatrix(a,this._matrices[a]);for(var a in this._matrices3x3)o.setMatrix3x3(a,this._matrices3x3[a]);for(var a in this._matrices2x2)o.setMatrix2x2(a,this._matrices2x2[a]);return o},t.prototype.dispose=function(t,i,n){if(i){var r;for(r in this._textures)this._textures[r].dispose();for(r in this._textureArrays)for(var o=this._textureArrays[r],a=0;a<o.length;a++)o[a].dispose()}this._textures={},e.prototype.dispose.call(this,t,i,n)},t.prototype.serialize=function(){var e,t=r.a.Serialize(this);for(e in t.customType="BABYLON.ShaderMaterial",t.options=this._options,t.shaderPath=this._shaderPath,t.textures={},this._textures)t.textures[e]=this._textures[e].serialize();for(e in t.textureArrays={},this._textureArrays){t.textureArrays[e]=[];for(var i=this._textureArrays[e],n=0;n<i.length;n++)t.textureArrays[e].push(i[n].serialize())}for(e in t.floats={},this._floats)t.floats[e]=this._floats[e];for(e in t.FloatArrays={},this._floatsArrays)t.FloatArrays[e]=this._floatsArrays[e];for(e in t.colors3={},this._colors3)t.colors3[e]=this._colors3[e].asArray();for(e in t.colors3Arrays={},this._colors3Arrays)t.colors3Arrays[e]=this._colors3Arrays[e];for(e in t.colors4={},this._colors4)t.colors4[e]=this._colors4[e].asArray();for(e in t.colors4Arrays={},this._colors4Arrays)t.colors4Arrays[e]=this._colors4Arrays[e];for(e in t.vectors2={},this._vectors2)t.vectors2[e]=this._vectors2[e].asArray();for(e in t.vectors3={},this._vectors3)t.vectors3[e]=this._vectors3[e].asArray();for(e in t.vectors4={},this._vectors4)t.vectors4[e]=this._vectors4[e].asArray();for(e in t.matrices={},this._matrices)t.matrices[e]=this._matrices[e].asArray();for(e in t.matrixArray={},this._matrixArrays)t.matrixArray[e]=this._matrixArrays[e];for(e in t.matrices3x3={},this._matrices3x3)t.matrices3x3[e]=this._matrices3x3[e];for(e in t.matrices2x2={},this._matrices2x2)t.matrices2x2[e]=this._matrices2x2[e];for(e in t.vectors2Arrays={},this._vectors2Arrays)t.vectors2Arrays[e]=this._vectors2Arrays[e];for(e in t.vectors3Arrays={},this._vectors3Arrays)t.vectors3Arrays[e]=this._vectors3Arrays[e];for(e in t.vectors4Arrays={},this._vectors4Arrays)t.vectors4Arrays[e]=this._vectors4Arrays[e];return t},t.Parse=function(e,i,n){var a,c=r.a.Parse(function(){return new t(e.name,i,e.shaderPath,e.options)},e,i,n);for(a in e.textures)c.setTexture(a,s.a.Parse(e.textures[a],i,n));for(a in e.textureArrays){for(var l=e.textureArrays[a],u=new Array,d=0;d<l.length;d++)u.push(s.a.Parse(l[d],i,n));c.setTextureArray(a,u)}for(a in e.floats)c.setFloat(a,e.floats[a]);for(a in e.floatsArrays)c.setFloats(a,e.floatsArrays[a]);for(a in e.colors3)c.setColor3(a,h.a.FromArray(e.colors3[a]));for(a in e.colors3Arrays){var f=e.colors3Arrays[a].reduce(function(e,t,i){return i%3==0?e.push([t]):e[e.length-1].push(t),e},[]).map(function(e){return h.a.FromArray(e)});c.setColor3Array(a,f)}for(a in e.colors4)c.setColor4(a,h.b.FromArray(e.colors4[a]));for(a in e.colors4Arrays){f=e.colors4Arrays[a].reduce(function(e,t,i){return i%4==0?e.push([t]):e[e.length-1].push(t),e},[]).map(function(e){return h.b.FromArray(e)});c.setColor4Array(a,f)}for(a in e.vectors2)c.setVector2(a,o.d.FromArray(e.vectors2[a]));for(a in e.vectors3)c.setVector3(a,o.e.FromArray(e.vectors3[a]));for(a in e.vectors4)c.setVector4(a,o.f.FromArray(e.vectors4[a]));for(a in e.matrices)c.setMatrix(a,o.a.FromArray(e.matrices[a]));for(a in e.matrixArray)c._matrixArrays[a]=new Float32Array(e.matrixArray[a]);for(a in e.matrices3x3)c.setMatrix3x3(a,e.matrices3x3[a]);for(a in e.matrices2x2)c.setMatrix2x2(a,e.matrices2x2[a]);for(a in e.vectors2Arrays)c.setArray2(a,e.vectors2Arrays[a]);for(a in e.vectors3Arrays)c.setArray3(a,e.vectors3Arrays[a]);for(a in e.vectors4Arrays)c.setArray4(a,e.vectors4Arrays[a]);return c},t}(l.a);u.a.RegisteredTypes["BABYLON.ShaderMaterial"]=f},function(e,t,i){"use strict";var n=i(7),r=i(31),o=i(84);r.a.prototype.createUniformBuffer=function(e){var t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");var i=new o.a(t);return this.bindUniformBuffer(i),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),i.references=1,i},r.a.prototype.createDynamicUniformBuffer=function(e){var t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");var i=new o.a(t);return this.bindUniformBuffer(i),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),i.references=1,i},r.a.prototype.updateUniformBuffer=function(e,t,i,n){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===n?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+n)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+n)),this.bindUniformBuffer(null)},r.a.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},r.a.prototype.bindUniformBufferBase=function(e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},r.a.prototype.bindUniformBlock=function(e,t,i){var n=e.program,r=this._gl.getUniformBlockIndex(n,t);this._gl.uniformBlockBinding(n,r,i)},i.d(t,"a",function(){return a});var a=function(){function e(e,t,i){this._alreadyBound=!1,this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers,this._dynamic=i,this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformLocationPointer=0,this._needSync=!1,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.updateMatrix=this._updateMatrixForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect):(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.updateMatrix=this._updateMatrixForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform)}return Object.defineProperty(e.prototype,"useUbo",{get:function(){return!this._noUBO},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isSync",{get:function(){return!this._needSync},enumerable:!0,configurable:!0}),e.prototype.isDynamic=function(){return void 0!==this._dynamic},e.prototype.getData=function(){return this._bufferData},e.prototype.getBuffer=function(){return this._buffer},e.prototype._fillAlignment=function(e){var t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){var i=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;for(var n=this._uniformLocationPointer-i,r=0;r<n;r++)this._data.push(0)}},e.prototype.addUniform=function(e,t){if(!this._noUBO&&void 0===this._uniformLocations[e]){var i;if(t instanceof Array)t=(i=t).length;else{t=t,i=[];for(var n=0;n<t;n++)i.push(0)}this._fillAlignment(t),this._uniformSizes[e]=t,this._uniformLocations[e]=this._uniformLocationPointer,this._uniformLocationPointer+=t;for(n=0;n<t;n++)this._data.push(i[n]);this._needSync=!0}},e.prototype.addMatrix=function(e,t){this.addUniform(e,Array.prototype.slice.call(t.toArray()))},e.prototype.addFloat2=function(e,t,i){var n=[t,i];this.addUniform(e,n)},e.prototype.addFloat3=function(e,t,i,n){var r=[t,i,n];this.addUniform(e,r)},e.prototype.addColor3=function(e,t){var i=new Array;t.toArray(i),this.addUniform(e,i)},e.prototype.addColor4=function(e,t,i){var n=new Array;t.toArray(n),n.push(i),this.addUniform(e,n)},e.prototype.addVector3=function(e,t){var i=new Array;t.toArray(i),this.addUniform(e,i)},e.prototype.addMatrix3x3=function(e){this.addUniform(e,12)},e.prototype.addMatrix2x2=function(e){this.addUniform(e,8)},e.prototype.create=function(){this._noUBO||this._buffer||(this._fillAlignment(4),this._bufferData=new Float32Array(this._data),this._rebuild(),this._needSync=!0)},e.prototype._rebuild=function(){!this._noUBO&&this._bufferData&&(this._dynamic?this._buffer=this._engine.createDynamicUniformBuffer(this._bufferData):this._buffer=this._engine.createUniformBuffer(this._bufferData))},e.prototype.update=function(){this._buffer?(this._dynamic||this._needSync)&&(this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._needSync=!1):this.create()},e.prototype.updateUniform=function(e,t,i){var r=this._uniformLocations[e];if(void 0===r){if(this._buffer)return void n.a.Error("Cannot add an uniform after UBO has been created.");this.addUniform(e,i),r=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(a=0;a<i;a++)this._bufferData[r+a]=t[a];else{for(var o=!1,a=0;a<i;a++)16!==i&&this._bufferData[r+a]===t[a]||(o=!0,this._bufferData[r+a]=t[a]);this._needSync=this._needSync||o}},e.prototype._cacheMatrix=function(e,t){var i=this._valueCache[e],n=t.updateFlag;return(void 0===i||i!==n)&&(this._valueCache[e]=n,!0)},e.prototype._updateMatrix3x3ForUniform=function(t,i){for(var n=0;n<3;n++)e._tempBuffer[4*n]=i[3*n],e._tempBuffer[4*n+1]=i[3*n+1],e._tempBuffer[4*n+2]=i[3*n+2],e._tempBuffer[4*n+3]=0;this.updateUniform(t,e._tempBuffer,12)},e.prototype._updateMatrix3x3ForEffect=function(e,t){this._currentEffect.setMatrix3x3(e,t)},e.prototype._updateMatrix2x2ForEffect=function(e,t){this._currentEffect.setMatrix2x2(e,t)},e.prototype._updateMatrix2x2ForUniform=function(t,i){for(var n=0;n<2;n++)e._tempBuffer[4*n]=i[2*n],e._tempBuffer[4*n+1]=i[2*n+1],e._tempBuffer[4*n+2]=0,e._tempBuffer[4*n+3]=0;this.updateUniform(t,e._tempBuffer,8)},e.prototype._updateFloatForEffect=function(e,t){this._currentEffect.setFloat(e,t)},e.prototype._updateFloatForUniform=function(t,i){e._tempBuffer[0]=i,this.updateUniform(t,e._tempBuffer,1)},e.prototype._updateFloat2ForEffect=function(e,t,i,n){void 0===n&&(n=""),this._currentEffect.setFloat2(e+n,t,i)},e.prototype._updateFloat2ForUniform=function(t,i,n){e._tempBuffer[0]=i,e._tempBuffer[1]=n,this.updateUniform(t,e._tempBuffer,2)},e.prototype._updateFloat3ForEffect=function(e,t,i,n,r){void 0===r&&(r=""),this._currentEffect.setFloat3(e+r,t,i,n)},e.prototype._updateFloat3ForUniform=function(t,i,n,r){e._tempBuffer[0]=i,e._tempBuffer[1]=n,e._tempBuffer[2]=r,this.updateUniform(t,e._tempBuffer,3)},e.prototype._updateFloat4ForEffect=function(e,t,i,n,r,o){void 0===o&&(o=""),this._currentEffect.setFloat4(e+o,t,i,n,r)},e.prototype._updateFloat4ForUniform=function(t,i,n,r,o){e._tempBuffer[0]=i,e._tempBuffer[1]=n,e._tempBuffer[2]=r,e._tempBuffer[3]=o,this.updateUniform(t,e._tempBuffer,4)},e.prototype._updateMatrixForEffect=function(e,t){this._currentEffect.setMatrix(e,t)},e.prototype._updateMatrixForUniform=function(e,t){this._cacheMatrix(e,t)&&this.updateUniform(e,t.toArray(),16)},e.prototype._updateVector3ForEffect=function(e,t){this._currentEffect.setVector3(e,t)},e.prototype._updateVector3ForUniform=function(t,i){i.toArray(e._tempBuffer),this.updateUniform(t,e._tempBuffer,3)},e.prototype._updateVector4ForEffect=function(e,t){this._currentEffect.setVector4(e,t)},e.prototype._updateVector4ForUniform=function(t,i){i.toArray(e._tempBuffer),this.updateUniform(t,e._tempBuffer,4)},e.prototype._updateColor3ForEffect=function(e,t,i){void 0===i&&(i=""),this._currentEffect.setColor3(e+i,t)},e.prototype._updateColor3ForUniform=function(t,i){i.toArray(e._tempBuffer),this.updateUniform(t,e._tempBuffer,3)},e.prototype._updateColor4ForEffect=function(e,t,i,n){void 0===n&&(n=""),this._currentEffect.setColor4(e+n,t,i)},e.prototype._updateColor4ForUniform=function(t,i,n){i.toArray(e._tempBuffer),e._tempBuffer[3]=n,this.updateUniform(t,e._tempBuffer,4)},e.prototype.setTexture=function(e,t){this._currentEffect.setTexture(e,t)},e.prototype.updateUniformDirectly=function(e,t){this.updateUniform(e,t,t.length),this.update()},e.prototype.bindToEffect=function(e,t){this._currentEffect=e,!this._noUBO&&this._buffer&&(this._alreadyBound=!0,e.bindUniformBuffer(this._buffer,t))},e.prototype.dispose=function(){if(!this._noUBO){var e=this._engine._uniformBuffers,t=e.indexOf(this);-1!==t&&(e[t]=e[e.length-1],e.pop()),this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)}},e._MAX_UNIFORM_SIZE=256,e._tempBuffer=new Float32Array(e._MAX_UNIFORM_SIZE),e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r});var n=i(1),r=function(e){function t(t){var i=e.call(this)||this;return i._buffer=t,i}return Object(n.d)(t,e),Object.defineProperty(t.prototype,"underlyingResource",{get:function(){return this._buffer},enumerable:!0,configurable:!0}),t}(i(85).a)},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){this.references=0,this.capacity=0,this.is32Bits=!1}return Object.defineProperty(e.prototype,"underlyingResource",{get:function(){return null},enumerable:!0,configurable:!0}),e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r});var n=i(60),r=function(){function e(){}return e.GetPlanes=function(t){for(var i=[],r=0;r<6;r++)i.push(new n.a(0,0,0,0));return e.GetPlanesToRef(t,i),i},e.GetNearPlaneToRef=function(e,t){var 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()},e.GetFarPlaneToRef=function(e,t){var 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()},e.GetLeftPlaneToRef=function(e,t){var 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()},e.GetRightPlaneToRef=function(e,t){var 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()},e.GetTopPlaneToRef=function(e,t){var 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()},e.GetBottomPlaneToRef=function(e,t){var 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()},e.GetPlanesToRef=function(t,i){e.GetNearPlaneToRef(t,i[0]),e.GetFarPlaneToRef(t,i[1]),e.GetLeftPlaneToRef(t,i[2]),e.GetRightPlaneToRef(t,i[3]),e.GetTopPlaneToRef(t,i[4]),e.GetBottomPlaneToRef(t,i[5])},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r});var n=i(2),r=function(){function e(){this.hoverCursor="",this.actions=new Array,this.isRecursive=!1}return Object.defineProperty(e,"HasTriggers",{get:function(){for(var t in e.Triggers)if(e.Triggers.hasOwnProperty(t))return!0;return!1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"HasPickTriggers",{get:function(){for(var t in e.Triggers)if(e.Triggers.hasOwnProperty(t)){var i=parseInt(t);if(i>=n.a.ACTION_OnPickTrigger&&i<=n.a.ACTION_OnPickUpTrigger)return!0}return!1},enumerable:!0,configurable:!0}),e.HasSpecificTrigger=function(t){for(var i in e.Triggers){if(e.Triggers.hasOwnProperty(i))if(parseInt(i)===t)return!0}return!1},e.Triggers={},e}()},function(e,t,i){"use strict";var n="morphTargetsVertexGlobalDeclaration",r="#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="morphTargetsVertexDeclaration",r="#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#ifdef MORPHTARGETS_UV\nattribute vec2 uv_{X};\n#endif\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";i.d(t,"a",function(){return a});var n=i(29),r=i(4),o=i(2),a=function(){function e(e){this._vertexBuffers={},this._scene=e}return e.prototype._prepareBuffers=function(){if(!this._vertexBuffers[r.b.PositionKind]){var e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[r.b.PositionKind]=new r.b(this._scene.getEngine(),e,r.b.PositionKind,!1,!1,2),this._buildIndexBuffer()}},e.prototype._buildIndexBuffer=function(){var 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)},e.prototype._rebuild=function(){var e=this._vertexBuffers[r.b.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())},e.prototype._prepareFrame=function(e,t){void 0===e&&(e=null),void 0===t&&(t=null);var i=this._scene.activeCamera;return!!i&&(!(!(t=t||i._postProcesses.filter(function(e){return null!=e}))||0===t.length||!this._scene.postProcessesEnabled)&&(t[0].activate(i,e,null!=t),!0))},e.prototype.directRender=function(e,t,i,r,o){void 0===t&&(t=null),void 0===i&&(i=!1),void 0===r&&(r=0),void 0===o&&(o=0);for(var a=this._scene.getEngine(),s=0;s<e.length;s++){s<e.length-1?e[s+1].activate(this._scene.activeCamera,t):t?a.bindFramebuffer(t,r,void 0,void 0,i,o):a.restoreDefaultFramebuffer();var c=e[s],l=c.apply();l&&(c.onBeforeRenderObservable.notifyObservers(l),this._prepareBuffers(),a.bindBuffers(this._vertexBuffers,this._indexBuffer,l),a.drawElementsType(n.a.TriangleFillMode,0,6),c.onAfterRenderObservable.notifyObservers(l))}a.setDepthBuffer(!0),a.setDepthWrite(!0)},e.prototype._finalizeFrame=function(e,t,i,r,a){void 0===a&&(a=!1);var s=this._scene.activeCamera;if(s&&0!==(r=r||s._postProcesses.filter(function(e){return null!=e})).length&&this._scene.postProcessesEnabled){for(var c=this._scene.getEngine(),l=0,u=r.length;l<u;l++){var h=r[l];if(l<u-1?h._outputTexture=r[l+1].activate(s,t):t?(c.bindFramebuffer(t,i,void 0,void 0,a),h._outputTexture=t):(c.restoreDefaultFramebuffer(),h._outputTexture=null),e)break;var d=h.apply();d&&(h.onBeforeRenderObservable.notifyObservers(d),this._prepareBuffers(),c.bindBuffers(this._vertexBuffers,this._indexBuffer,d),c.drawElementsType(n.a.TriangleFillMode,0,6),h.onAfterRenderObservable.notifyObservers(d))}c.setDepthBuffer(!0),c.setDepthWrite(!0),c.setAlphaMode(o.a.ALPHA_DISABLE)}},e.prototype.dispose=function(){var e=this._vertexBuffers[r.b.PositionKind];e&&(e.dispose(),this._vertexBuffers[r.b.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r}),i.d(t,"b",function(){return o});var n=i(134),r=function(){},o=function(){function e(t){this._useSceneAutoClearSetup=!1,this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new r,this._scene=t;for(var i=e.MIN_RENDERINGGROUPS;i<e.MAX_RENDERINGGROUPS;i++)this._autoClearDepthStencil[i]={autoClear:!0,depth:!0,stencil:!0}}return e.prototype._clearDepthStencilBuffer=function(e,t){void 0===e&&(e=!0),void 0===t&&(t=!0),this._depthStencilBufferAlreadyCleaned||(this._scene.getEngine().clear(null,!1,e,t),this._depthStencilBufferAlreadyCleaned=!0)},e.prototype.render=function(t,i,n,r){var o=this._renderingGroupInfo;if(o.scene=this._scene,o.camera=this._scene.activeCamera,this._scene.spriteManagers&&r)for(var a=0;a<this._scene.spriteManagers.length;a++){var s=this._scene.spriteManagers[a];this.dispatchSprites(s)}for(a=e.MIN_RENDERINGGROUPS;a<e.MAX_RENDERINGGROUPS;a++){this._depthStencilBufferAlreadyCleaned=a===e.MIN_RENDERINGGROUPS;var c=this._renderingGroups[a];if(c){var l=Math.pow(2,a);if(o.renderingGroupId=a,this._scene.onBeforeRenderingGroupObservable.notifyObservers(o,l),e.AUTOCLEAR){var u=this._useSceneAutoClearSetup?this._scene.getAutoClearDepthStencilSetup(a):this._autoClearDepthStencil[a];u&&u.autoClear&&this._clearDepthStencilBuffer(u.depth,u.stencil)}for(var h=0,d=this._scene._beforeRenderingGroupDrawStage;h<d.length;h++){d[h].action(a)}c.render(t,r,n,i);for(var f=0,p=this._scene._afterRenderingGroupDrawStage;f<p.length;f++){p[f].action(a)}this._scene.onAfterRenderingGroupObservable.notifyObservers(o,l)}}},e.prototype.reset=function(){for(var t=e.MIN_RENDERINGGROUPS;t<e.MAX_RENDERINGGROUPS;t++){var i=this._renderingGroups[t];i&&i.prepare()}},e.prototype.dispose=function(){this.freeRenderingGroups(),this._renderingGroups.length=0,this._renderingGroupInfo=null},e.prototype.freeRenderingGroups=function(){for(var t=e.MIN_RENDERINGGROUPS;t<e.MAX_RENDERINGGROUPS;t++){var i=this._renderingGroups[t];i&&i.dispose()}},e.prototype._prepareRenderingGroup=function(e){void 0===this._renderingGroups[e]&&(this._renderingGroups[e]=new n.a(e,this._scene,this._customOpaqueSortCompareFn[e],this._customAlphaTestSortCompareFn[e],this._customTransparentSortCompareFn[e]))},e.prototype.dispatchSprites=function(e){var t=e.renderingGroupId||0;this._prepareRenderingGroup(t),this._renderingGroups[t].dispatchSprites(e)},e.prototype.dispatchParticles=function(e){var t=e.renderingGroupId||0;this._prepareRenderingGroup(t),this._renderingGroups[t].dispatchParticles(e)},e.prototype.dispatch=function(e,t,i){void 0===t&&(t=e.getMesh());var n=t.renderingGroupId||0;this._prepareRenderingGroup(n),this._renderingGroups[n].dispatch(e,t,i)},e.prototype.setRenderingOrder=function(e,t,i,n){if(void 0===t&&(t=null),void 0===i&&(i=null),void 0===n&&(n=null),this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=i,this._customTransparentSortCompareFn[e]=n,this._renderingGroups[e]){var r=this._renderingGroups[e];r.opaqueSortCompareFn=this._customOpaqueSortCompareFn[e],r.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[e],r.transparentSortCompareFn=this._customTransparentSortCompareFn[e]}},e.prototype.setRenderingAutoClearDepthStencil=function(e,t,i,n){void 0===i&&(i=!0),void 0===n&&(n=!0),this._autoClearDepthStencil[e]={autoClear:t,depth:i,stencil:n}},e.prototype.getAutoClearDepthStencilSetup=function(e){return this._autoClearDepthStencil[e]},e.MAX_RENDERINGGROUPS=4,e.MIN_RENDERINGGROUPS=0,e.AUTOCLEAR=!0,e}()},function(e,t,i){"use strict";i.d(t,"b",function(){return h}),i.d(t,"a",function(){return d});var n=i(1),r=i(10),o=i(4),a=i(5),s=i(136),c=i(29),l=i(82),u=i(16),h=(i(148),i(149),function(e){function t(t,i,n,a,s,c,u){void 0===i&&(i=null),void 0===n&&(n=null),void 0===a&&(a=null);var h=e.call(this,t,i,n,a,s)||this;h.useVertexColor=c,h.useVertexAlpha=u,h.color=new r.a(1,1,1),h.alpha=1,a&&(h.color=a.color.clone(),h.alpha=a.alpha,h.useVertexColor=a.useVertexColor,h.useVertexAlpha=a.useVertexAlpha),h.intersectionThreshold=.1;var d={attributes:[o.b.PositionKind,"world0","world1","world2","world3"],uniforms:["vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","world","viewProjection"],needAlphaBlending:!0,defines:[]};return!1===u&&(d.needAlphaBlending=!1),c?(d.defines.push("#define VERTEXCOLOR"),d.attributes.push(o.b.ColorKind)):(d.uniforms.push("color"),h.color4=new r.b),h._colorShader=new l.a("colorShader",h.getScene(),"color",d),h}return Object(n.d)(t,e),t.prototype._addClipPlaneDefine=function(e){var t="#define "+e;-1===this._colorShader.options.defines.indexOf(t)&&this._colorShader.options.defines.push(t)},t.prototype._removeClipPlaneDefine=function(e){var t="#define "+e,i=this._colorShader.options.defines.indexOf(t);-1!==i&&this._colorShader.options.defines.splice(i,1)},t.prototype.isReady=function(){var t=this.getScene();return t.clipPlane?this._addClipPlaneDefine("CLIPPLANE"):this._removeClipPlaneDefine("CLIPPLANE"),t.clipPlane2?this._addClipPlaneDefine("CLIPPLANE2"):this._removeClipPlaneDefine("CLIPPLANE2"),t.clipPlane3?this._addClipPlaneDefine("CLIPPLANE3"):this._removeClipPlaneDefine("CLIPPLANE3"),t.clipPlane4?this._addClipPlaneDefine("CLIPPLANE4"):this._removeClipPlaneDefine("CLIPPLANE4"),t.clipPlane5?this._addClipPlaneDefine("CLIPPLANE5"):this._removeClipPlaneDefine("CLIPPLANE5"),t.clipPlane6?this._addClipPlaneDefine("CLIPPLANE6"):this._removeClipPlaneDefine("CLIPPLANE6"),!!this._colorShader.isReady()&&e.prototype.isReady.call(this)},t.prototype.getClassName=function(){return"LinesMesh"},Object.defineProperty(t.prototype,"material",{get:function(){return this._colorShader},set:function(e){},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"checkCollisions",{get:function(){return!1},enumerable:!0,configurable:!0}),t.prototype._bind=function(e,t,i){if(!this._geometry)return this;var n=this._colorShader.getEffect(),r=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(this._geometry._bind(n,r),!this.useVertexColor){var o=this.color,a=o.r,s=o.g,c=o.b;this.color4.set(a,s,c,this.alpha),this._colorShader.setColor4("color",this.color4)}return u.a.BindClipPlane(n,this.getScene()),this},t.prototype._draw=function(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;var n=this.getScene().getEngine();return this._unIndexed?n.drawArraysType(c.a.LineListDrawMode,e.verticesStart,e.verticesCount,i):n.drawElementsType(c.a.LineListDrawMode,e.indexStart,e.indexCount,i),this},t.prototype.dispose=function(t){this._colorShader.dispose(!1,!1,!0),e.prototype.dispose.call(this,t)},t.prototype.clone=function(e,i,n){return void 0===i&&(i=null),new t(e,this.getScene(),i,this,n)},t.prototype.createInstance=function(e){return new d(e,this)},t}(a.a)),d=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.intersectionThreshold=i.intersectionThreshold,n}return Object(n.d)(t,e),t.prototype.getClassName=function(){return"InstancedLinesMesh"},t}(s.a)},function(e,t,i){"use strict";i.r(t);var n,r=i(0),o=i(32),a=i(72),s=i(10),c=function(){function e(t,i,n,c,l,u){if(void 0===i&&(i=1),void 0===n&&(n=2),this._scaleLinesFactor=4,this._instanced=!1,this.scaleLines=1,this.scaleLines=i,!c){var h=new o.a("",t);h.disableLighting=!0,h.emissiveColor=s.a.Red().scale(.5),c=a.a._CreateArrow(t,h)}if(!l){var d=new o.a("",t);d.disableLighting=!0,d.emissiveColor=s.a.Green().scale(.5),l=a.a._CreateArrow(t,d)}if(!u){var f=new o.a("",t);f.disableLighting=!0,f.emissiveColor=s.a.Blue().scale(.5),u=a.a._CreateArrow(t,f)}this._xAxis=c,this._xAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._yAxis=l,this._yAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._zAxis=u,this._zAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),null!=n&&(e._SetRenderingGroupId(this._xAxis,n),e._SetRenderingGroupId(this._yAxis,n),e._SetRenderingGroupId(this._zAxis,n)),this.scene=t,this.update(new r.e,r.e.Right(),r.e.Up(),r.e.Forward())}return Object.defineProperty(e.prototype,"xAxis",{get:function(){return this._xAxis},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"yAxis",{get:function(){return this._yAxis},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"zAxis",{get:function(){return this._zAxis},enumerable:!0,configurable:!0}),e.prototype.update=function(e,t,i,n){this._xAxis.position.copyFrom(e),this._xAxis.setDirection(t),this._xAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._yAxis.position.copyFrom(e),this._yAxis.setDirection(i),this._yAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._zAxis.position.copyFrom(e),this._zAxis.setDirection(n),this._zAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor)},e.prototype.createInstance=function(){var t=a.a._CreateArrowInstance(this.scene,this._xAxis),i=a.a._CreateArrowInstance(this.scene,this._yAxis),n=a.a._CreateArrowInstance(this.scene,this._zAxis),r=new e(this.scene,this.scaleLines,null,t,i,n);return r._instanced=!0,r},e.prototype.dispose=function(){this._xAxis&&(this._xAxis.dispose(!1,!this._instanced),delete this._xAxis),this._yAxis&&(this._yAxis.dispose(!1,!this._instanced),delete this._yAxis),this._zAxis&&(this._zAxis.dispose(!1,!this._instanced),delete this._zAxis),delete this.scene},e._SetRenderingGroupId=function(e,t){e.getChildMeshes().forEach(function(e){e.renderingGroupId=t})},e}(),l=i(1),u=i(22),h=function(e){function t(t,i,n,o){void 0===o&&(o=1);var a=e.call(this,t,o)||this;return a.pos=r.e.Zero(),a.xaxis=r.e.Zero(),a.yaxis=r.e.Zero(),a.zaxis=r.e.Zero(),a.mesh=n,a.bone=i,a}return Object(l.d)(t,e),t.prototype.update=function(){if(this.mesh&&this.bone){var t=this.bone;t._markAsDirtyAndCompose(),t.getAbsolutePositionToRef(this.mesh,this.pos),t.getDirectionToRef(u.a.X,this.mesh,this.xaxis),t.getDirectionToRef(u.a.Y,this.mesh,this.yaxis),t.getDirectionToRef(u.a.Z,this.mesh,this.zaxis),e.prototype.update.call(this,this.pos,this.xaxis,this.yaxis,this.zaxis)}},t.prototype.dispose=function(){this.mesh&&(this.mesh=null,this.bone=null,e.prototype.dispose.call(this))},t}(c),d=i(13),f=i(6),p=i(18),_=i(11);Object.defineProperty(p.a.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new m(this)),this._debugLayer},enumerable:!0,configurable:!0}),function(e){e[e.Properties=0]="Properties",e[e.Debug=1]="Debug",e[e.Statistics=2]="Statistics",e[e.Tools=3]="Tools",e[e.Settings=4]="Settings"}(n||(n={}));var m=function(){function e(e){var t=this;this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e,this._scene.onDisposeObservable.add(function(){t._scene._debugLayer&&t._scene._debugLayer.hide()})}return Object.defineProperty(e.prototype,"onPropertyChangedObservable",{get:function(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new f.c),this._onPropertyChangedObservable)},enumerable:!0,configurable:!0}),e.prototype._createInspector=function(e){if(!this.isVisible()){if(this._onPropertyChangedObservable){for(var t=0,i=this._onPropertyChangedObservable.observers;t<i.length;t++){var n=i[t];this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(n)}this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}var r=Object(l.a)({overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0},e);this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,r)}},e.prototype.select=function(e,t){this.BJSINSPECTOR&&(this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))},e.prototype._getGlobalInspector=function(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0},e.prototype.isVisible=function(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible},e.prototype.hide=function(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()},e.prototype.show=function(t){var i=this;return new Promise(function(n,r){if(void 0===i.BJSINSPECTOR){var o=t&&t.inspectorURL?t.inspectorURL:e.InspectorURL;d.b.LoadScript(o,function(){i._createInspector(t),n(i)})}else i._createInspector(t),n(i)})},e.InspectorURL="https://unpkg.com/babylonjs-inspector@"+_.a.Version+"/babylon.inspector.bundle.js",e}(),g=i(5),v=i(66),y=i(48),b=i(23),T=i(30),E=i(41),x=i(59),P=function(){function e(e){this._impostors=[],this._meshes=[],this._numMeshes=0,this._debugMeshMeshes=new Array,this._scene=e||b.a.LastCreatedScene;var t=this._scene.getPhysicsEngine();t&&(this._physicsEnginePlugin=t.getPhysicsPlugin()),this._utilityLayer=new E.a(this._scene,!1),this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!0}return e.prototype._updateDebugMeshes=function(){for(var e=this._physicsEnginePlugin,t=0;t<this._numMeshes;t++){var i=this._impostors[t];if(i)if(i.isDisposed)this.hideImpostor(this._impostors[t--]);else{if(i.type===T.a.MeshImpostor)continue;var n=this._meshes[t];n&&e&&e.syncMeshWithImpostor(n,i)}}},e.prototype.showImpostor=function(e,t){if(!this._scene)return null;for(var i=0;i<this._numMeshes;i++)if(this._impostors[i]==e)return null;var n=this._getDebugMesh(e,t);return n&&(this._impostors[this._numMeshes]=e,this._meshes[this._numMeshes]=n,0===this._numMeshes&&(this._renderFunction=this._updateDebugMeshes.bind(this),this._scene.registerBeforeRender(this._renderFunction)),this._numMeshes++),n},e.prototype.hideImpostor=function(e){if(e&&this._scene&&this._utilityLayer){for(var t=!1,i=this._utilityLayer.utilityLayerScene,n=0;n<this._numMeshes;n++)if(this._impostors[n]==e){var r=this._meshes[n];if(!r)continue;i.removeMesh(r),r.dispose();var o=this._debugMeshMeshes.indexOf(r);o>-1&&this._debugMeshMeshes.splice(o,1),this._numMeshes--,this._numMeshes>0?(this._meshes[n]=this._meshes[this._numMeshes],this._impostors[n]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&0===this._numMeshes&&this._scene.unregisterBeforeRender(this._renderFunction)}},e.prototype._getDebugMaterial=function(e){return this._debugMaterial||(this._debugMaterial=new o.a("",e),this._debugMaterial.wireframe=!0,this._debugMaterial.emissiveColor=s.a.White(),this._debugMaterial.disableLighting=!0),this._debugMaterial},e.prototype._getDebugBoxMesh=function(e){return this._debugBoxMesh||(this._debugBoxMesh=v.a.CreateBox("physicsBodyBoxViewMesh",{size:1},e),this._debugBoxMesh.rotationQuaternion=r.b.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(e),this._debugBoxMesh.setEnabled(!1)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")},e.prototype._getDebugSphereMesh=function(e){return this._debugSphereMesh||(this._debugSphereMesh=y.a.CreateSphere("physicsBodySphereViewMesh",{diameter:1},e),this._debugSphereMesh.rotationQuaternion=r.b.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(e),this._debugSphereMesh.setEnabled(!1)),this._debugSphereMesh.createInstance("physicsBodyBoxViewInstance")},e.prototype._getDebugCylinderMesh=function(e){return this._debugCylinderMesh||(this._debugCylinderMesh=x.a.CreateCylinder("physicsBodyCylinderViewMesh",{diameterTop:1,diameterBottom:1,height:1},e),this._debugCylinderMesh.rotationQuaternion=r.b.Identity(),this._debugCylinderMesh.material=this._getDebugMaterial(e),this._debugCylinderMesh.setEnabled(!1)),this._debugCylinderMesh.createInstance("physicsBodyBoxViewInstance")},e.prototype._getDebugMeshMesh=function(e,t){var i=new g.a(e.name,t,null,e);return i.position=r.e.Zero(),i.setParent(e),i.material=this._getDebugMaterial(t),this._debugMeshMeshes.push(i),i},e.prototype._getDebugMesh=function(e,t){var i=this;if(!this._utilityLayer)return null;if(t&&t.parent&&t.parent.physicsImpostor)return null;var n=null,r=this._utilityLayer.utilityLayerScene;switch(e.type){case T.a.BoxImpostor:n=this._getDebugBoxMesh(r),e.getBoxSizeToRef(n.scaling);break;case T.a.SphereImpostor:n=this._getDebugSphereMesh(r);var o=e.getRadius();n.scaling.x=2*o,n.scaling.y=2*o,n.scaling.z=2*o;break;case T.a.MeshImpostor:t&&(n=this._getDebugMeshMesh(t,r));break;case T.a.NoImpostor:if(t)t.getChildMeshes().filter(function(e){return e.physicsImpostor?1:0}).forEach(function(e){i._getDebugBoxMesh(r).parent=e});break;case T.a.CylinderImpostor:n=this._getDebugCylinderMesh(r);var a=e.object.getBoundingInfo();n.scaling.x=a.boundingBox.maximum.x-a.boundingBox.minimum.x,n.scaling.y=a.boundingBox.maximum.y-a.boundingBox.minimum.y,n.scaling.z=a.boundingBox.maximum.z-a.boundingBox.minimum.z}return n},e.prototype.dispose=function(){for(var e=this._numMeshes,t=0;t<e;t++)this.hideImpostor(this._impostors[0]);this._debugBoxMesh&&this._debugBoxMesh.dispose(),this._debugSphereMesh&&this._debugSphereMesh.dispose(),this._debugCylinderMesh&&this._debugCylinderMesh.dispose(),this._debugMaterial&&this._debugMaterial.dispose(),this._impostors.length=0,this._scene=null,this._physicsEnginePlugin=null,this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null)},e}(),A=i(46),S=function(){function e(e){this.ray=e}return e.CreateAndShow=function(t,i,n){var r=new e(t);return r.show(i,n),r},e.prototype.show=function(e,t){if(!this._renderFunction&&this.ray){var i=this.ray;this._renderFunction=this._render.bind(this),this._scene=e,this._renderPoints=[i.origin,i.origin.add(i.direction.scale(i.length))],this._renderLine=g.a.CreateLines("ray",this._renderPoints,e,!0),this._renderFunction&&this._scene.registerBeforeRender(this._renderFunction)}t&&this._renderLine&&this._renderLine.color.copyFrom(t)},e.prototype.hide=function(){this._renderFunction&&this._scene&&(this._scene.unregisterBeforeRender(this._renderFunction),this._scene=null,this._renderFunction=null,this._renderLine&&(this._renderLine.dispose(),this._renderLine=null),this._renderPoints=[])},e.prototype._render=function(){var e=this.ray;if(e){var t=this._renderPoints[1],i=Math.min(e.length,1e6);t.copyFrom(e.direction),t.scaleInPlace(i),t.addInPlace(e.origin),g.a.CreateLines("ray",this._renderPoints,this._scene,!0,this._renderLine)}},e.prototype.attachToMesh=function(e,t,i,n){this._attachedToMesh=e;var o=this.ray;o&&(o.direction||(o.direction=r.e.Zero()),o.origin||(o.origin=r.e.Zero()),n&&(o.length=n),i||(i=r.e.Zero()),t||(t=new r.e(0,0,-1)),this._meshSpaceDirection?(this._meshSpaceDirection.copyFrom(t),this._meshSpaceOrigin.copyFrom(i)):(this._meshSpaceDirection=t.clone(),this._meshSpaceOrigin=i.clone()),this._updateToMeshFunction||(this._updateToMeshFunction=this._updateToMesh.bind(this),this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction)),this._updateToMesh())},e.prototype.detachFromMesh=function(){this._attachedToMesh&&(this._updateToMeshFunction&&this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction),this._attachedToMesh=null,this._updateToMeshFunction=null)},e.prototype._updateToMesh=function(){var e=this.ray;this._attachedToMesh&&e&&(this._attachedToMesh._isDisposed?this.detachFromMesh():(this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection,e.direction),r.e.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),e.origin)))},e.prototype.dispose=function(){this.hide(),this.detachFromMesh(),this.ray=null},e}(),C=function(){function e(e,t,i,n,r){void 0===n&&(n=!0),void 0===r&&(r=1),this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=n,this.renderingGroupId=r,this.color=s.a.White(),this._debugLines=new Array,this._isEnabled=!1,this._scene=i,this._utilityLayer=new E.a(this._scene,!1),this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!0,this.update(),this._renderFunction=this.update.bind(this)}return Object.defineProperty(e.prototype,"debugMesh",{get:function(){return this._debugMesh},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled!==e&&(this._isEnabled=e,e?this._scene.registerBeforeRender(this._renderFunction):this._scene.unregisterBeforeRender(this._renderFunction))},enumerable:!0,configurable:!0}),e.prototype._getBonePosition=function(e,t,i,n,o,a){void 0===n&&(n=0),void 0===o&&(o=0),void 0===a&&(a=0);var s=r.c.Matrix[0],c=t.getParent();if(s.copyFrom(t.getLocalMatrix()),0!==n||0!==o||0!==a){var l=r.c.Matrix[1];r.a.IdentityToRef(l),l.setTranslationFromFloats(n,o,a),l.multiplyToRef(s,s)}c&&s.multiplyToRef(c.getAbsoluteTransform(),s),s.multiplyToRef(i,s),e.x=s.m[12],e.y=s.m[13],e.z=s.m[14]},e.prototype._getLinesForBonesWithLength=function(e,t){for(var i=e.length,n=this.mesh._effectiveMesh.position,o=0;o<i;o++){var a=e[o],s=this._debugLines[o];s||(s=[r.e.Zero(),r.e.Zero()],this._debugLines[o]=s),this._getBonePosition(s[0],a,t),this._getBonePosition(s[1],a,t,0,a.length,0),s[0].subtractInPlace(n),s[1].subtractInPlace(n)}},e.prototype._getLinesForBonesNoLength=function(e,t){for(var i=e.length,n=0,o=this.mesh._effectiveMesh,a=o.position,s=i-1;s>=0;s--){var c=e[s],l=c.getParent();if(l){var u=this._debugLines[n];u||(u=[r.e.Zero(),r.e.Zero()],this._debugLines[n]=u),c.getAbsolutePositionToRef(o,u[0]),l.getAbsolutePositionToRef(o,u[1]),u[0].subtractInPlace(a),u[1].subtractInPlace(a),n++}}},e.prototype.update=function(){if(this._utilityLayer){this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteTransforms();var e=this.mesh._effectiveMesh;void 0===this.skeleton.bones[0].length?this._getLinesForBonesNoLength(this.skeleton.bones,e.getWorldMatrix()):this._getLinesForBonesWithLength(this.skeleton.bones,e.getWorldMatrix());var t=this._utilityLayer.utilityLayerScene;this._debugMesh?A.a.CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:this._debugMesh},t):(this._debugMesh=A.a.CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:null},t),this._debugMesh.renderingGroupId=this.renderingGroupId),this._debugMesh.position.copyFrom(this.mesh.position),this._debugMesh.color=this.color}},e.prototype.dispose=function(){this.isEnabled=!1,this._debugMesh&&(this.isEnabled=!1,this._debugMesh.dispose(),this._debugMesh=null),this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null)},e}();i.d(t,"AxesViewer",function(){return c}),i.d(t,"BoneAxesViewer",function(){return h}),i.d(t,"DebugLayerTab",function(){return n}),i.d(t,"DebugLayer",function(){return m}),i.d(t,"PhysicsViewer",function(){return P}),i.d(t,"RayHelper",function(){return S}),i.d(t,"SkeletonViewer",function(){return C})},function(e,t,i){"use strict";var n="morphTargetsVertex",r="#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}];\n#endif\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){}},function(e,t,i){"use strict";i.d(t,"a",function(){return a});var n=i(42),r=i(0),o=i(28),a=function(){function e(e,t,i){this.vectors=n.a.BuildArray(8,r.e.Zero),this.center=r.e.Zero(),this.centerWorld=r.e.Zero(),this.extendSize=r.e.Zero(),this.extendSizeWorld=r.e.Zero(),this.directions=n.a.BuildArray(3,r.e.Zero),this.vectorsWorld=n.a.BuildArray(8,r.e.Zero),this.minimumWorld=r.e.Zero(),this.maximumWorld=r.e.Zero(),this.minimum=r.e.Zero(),this.maximum=r.e.Zero(),this.reConstruct(e,t,i)}return e.prototype.reConstruct=function(e,t,i){var n=e.x,o=e.y,a=e.z,s=t.x,c=t.y,l=t.z,u=this.vectors;this.minimum.copyFromFloats(n,o,a),this.maximum.copyFromFloats(s,c,l),u[0].copyFromFloats(n,o,a),u[1].copyFromFloats(s,c,l),u[2].copyFromFloats(s,o,a),u[3].copyFromFloats(n,c,a),u[4].copyFromFloats(n,o,l),u[5].copyFromFloats(s,c,a),u[6].copyFromFloats(n,c,l),u[7].copyFromFloats(s,o,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||r.a.IdentityReadOnly,this._update(this._worldMatrix)},e.prototype.scale=function(t){var i=e.TmpVector3,n=this.maximum.subtractToRef(this.minimum,i[0]),r=n.length();n.normalizeFromLength(r);var o=r*t,a=n.scaleInPlace(.5*o),s=this.center.subtractToRef(a,i[1]),c=this.center.addToRef(a,i[2]);return this.reConstruct(s,c,this._worldMatrix),this},e.prototype.getWorldMatrix=function(){return this._worldMatrix},e.prototype._update=function(e){var t=this.minimumWorld,i=this.maximumWorld,n=this.directions,o=this.vectorsWorld,a=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(s=0;s<8;++s)o[s].copyFrom(a[s]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(var s=0;s<8;++s){var c=o[s];r.e.TransformCoordinatesToRef(a[s],e,c),t.minimizeInPlace(c),i.maximizeInPlace(c)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}r.e.FromArrayToRef(e.m,0,n[0]),r.e.FromArrayToRef(e.m,4,n[1]),r.e.FromArrayToRef(e.m,8,n[2]),this._worldMatrix=e},e.prototype.isInFrustum=function(t){return e.IsInFrustum(this.vectorsWorld,t)},e.prototype.isCompletelyInFrustum=function(t){return e.IsCompletelyInFrustum(this.vectorsWorld,t)},e.prototype.intersectsPoint=function(e){var t=this.minimumWorld,i=this.maximumWorld,n=t.x,r=t.y,a=t.z,s=i.x,c=i.y,l=i.z,u=e.x,h=e.y,d=e.z,f=-o.a;return!(s-u<f||f>u-n)&&(!(c-h<f||f>h-r)&&!(l-d<f||f>d-a))},e.prototype.intersectsSphere=function(t){return e.IntersectsSphere(this.minimumWorld,this.maximumWorld,t.centerWorld,t.radiusWorld)},e.prototype.intersectsMinMax=function(e,t){var i=this.minimumWorld,n=this.maximumWorld,r=i.x,o=i.y,a=i.z,s=n.x,c=n.y,l=n.z,u=e.x,h=e.y,d=e.z,f=t.x,p=t.y,_=t.z;return!(s<u||r>f)&&(!(c<h||o>p)&&!(l<d||a>_))},e.Intersects=function(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)},e.IntersectsSphere=function(t,i,n,o){var a=e.TmpVector3[0];return r.e.ClampToRef(n,t,i,a),r.e.DistanceSquared(n,a)<=o*o},e.IsCompletelyInFrustum=function(e,t){for(var i=0;i<6;++i)for(var n=t[i],r=0;r<8;++r)if(n.dotCoordinate(e[r])<0)return!1;return!0},e.IsInFrustum=function(e,t){for(var i=0;i<6;++i){for(var n=!0,r=t[i],o=0;o<8;++o)if(r.dotCoordinate(e[o])>=0){n=!1;break}if(n)return!1}return!0},e.TmpVector3=n.a.BuildArray(3,r.e.Zero),e}()},function(e,t,i){"use strict";var n="lightFragmentDeclaration",r="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float cascadeBlendFactor{X};\nvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\nuniform highp sampler2DArray depthSampler{X};\nuniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\n#else\nuniform highp sampler2DArray shadowSampler{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);\nvec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="lightUboDeclaration",r="#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float cascadeBlendFactor{X};\nvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\nuniform highp sampler2DArray depthSampler{X};\nuniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\n#else\nuniform highp sampler2DArray shadowSampler{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);\nvec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="imageProcessingDeclaration",r="#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="imageProcessingFunctions",r="#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x;\n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=saturate(sliceUV);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=saturate(sliceUV);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=saturate(color);\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=saturate(result.rgb);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=result.rgb*result.rgb*(3.0-2.0*result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="clipPlaneFragment",r="#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE5\nif (fClipDistance5>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE6\nif (fClipDistance6>0.0)\n{\ndiscard;\n}\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="clipPlaneVertex",r="#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nfClipDistance5=dot(worldPos,vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nfClipDistance6=dot(worldPos,vClipPlane6);\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){this._count=0,this._data={}}return e.prototype.copyFrom=function(e){var t=this;this.clear(),e.forEach(function(e,i){return t.add(e,i)})},e.prototype.get=function(e){var t=this._data[e];if(void 0!==t)return t},e.prototype.getOrAddWithFactory=function(e,t){var i=this.get(e);return void 0!==i?i:((i=t(e))&&this.add(e,i),i)},e.prototype.getOrAdd=function(e,t){var i=this.get(e);return void 0!==i?i:(this.add(e,t),t)},e.prototype.contains=function(e){return void 0!==this._data[e]},e.prototype.add=function(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)},e.prototype.set=function(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)},e.prototype.getAndRemove=function(e){var t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null},e.prototype.remove=function(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)},e.prototype.clear=function(){this._data={},this._count=0},Object.defineProperty(e.prototype,"count",{get:function(){return this._count},enumerable:!0,configurable:!0}),e.prototype.forEach=function(e){for(var t in this._data){e(t,this._data[t])}},e.prototype.first=function(e){for(var t in this._data){var i=e(t,this._data[t]);if(i)return i}return null},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return o});var n=i(42),r=i(0),o=function(){function e(e,t,i){this.center=r.e.Zero(),this.centerWorld=r.e.Zero(),this.minimum=r.e.Zero(),this.maximum=r.e.Zero(),this.reConstruct(e,t,i)}return e.prototype.reConstruct=function(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);var n=r.e.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*n,this._update(i||r.a.IdentityReadOnly)},e.prototype.scale=function(t){var i=this.radius*t,n=e.TmpVector3,r=n[0].setAll(i),o=this.center.subtractToRef(r,n[1]),a=this.center.addToRef(r,n[2]);return this.reConstruct(o,a,this._worldMatrix),this},e.prototype.getWorldMatrix=function(){return this._worldMatrix},e.prototype._update=function(t){if(t.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{r.e.TransformCoordinatesToRef(this.center,t,this.centerWorld);var i=e.TmpVector3[0];r.e.TransformNormalFromFloatsToRef(1,1,1,t,i),this.radiusWorld=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z))*this.radius}},e.prototype.isInFrustum=function(e){for(var t=this.centerWorld,i=this.radiusWorld,n=0;n<6;n++)if(e[n].dotCoordinate(t)<=-i)return!1;return!0},e.prototype.isCenterInFrustum=function(e){for(var t=this.centerWorld,i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0},e.prototype.intersectsPoint=function(e){var t=r.e.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld<t)},e.Intersects=function(e,t){var i=r.e.DistanceSquared(e.centerWorld,t.centerWorld),n=e.radiusWorld+t.radiusWorld;return!(n*n<i)},e.TmpVector3=n.a.BuildArray(3,r.e.Zero),e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}},function(e,t,i){"use strict";var n="clipPlaneFragmentDeclaration",r="#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nvarying float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nvarying float fClipDistance6;\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="logDepthDeclaration",r="#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="clipPlaneVertexDeclaration",r="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;\nvarying float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;\nvarying float fClipDistance6;\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return e.prototype.attributeProcessor=function(e){return e.replace("attribute","in")},e.prototype.varyingProcessor=function(e,t){return e.replace("varying",t?"in":"out")},e.prototype.postProcessor=function(e,t,i){var n=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i)e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(n?"":"out vec4 glFragColor;\n")+"void main(");else if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e},e}()},function(e,t,i){"use strict";i.d(t,"b",function(){return r}),i.d(t,"a",function(){return o});var n=i(0);function r(e,t,i,r,o){void 0===o&&(o=null);for(var a=new n.e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new n.e(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),c=i;c<i+r;c++){var l=3*t[c],u=e[l],h=e[l+1],d=e[l+2];a.minimizeInPlaceFromFloats(u,h,d),s.maximizeInPlaceFromFloats(u,h,d)}return o&&(a.x-=a.x*o.x+o.y,a.y-=a.y*o.x+o.y,a.z-=a.z*o.x+o.y,s.x+=s.x*o.x+o.y,s.y+=s.y*o.x+o.y,s.z+=s.z*o.x+o.y),{minimum:a,maximum:s}}function o(e,t,i,r,o){void 0===r&&(r=null);var a=new n.e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new n.e(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);o||(o=3);for(var c=t,l=t*o;c<t+i;c++,l+=o){var u=e[l],h=e[l+1],d=e[l+2];a.minimizeInPlaceFromFloats(u,h,d),s.maximizeInPlaceFromFloats(u,h,d)}return r&&(a.x-=a.x*r.x+r.y,a.y-=a.y*r.x+r.y,a.z-=a.z*r.x+r.y,s.x+=s.x*r.x+r.y,s.y+=s.y*r.x+r.y,s.z+=s.z*r.x+r.y),{minimum:a,maximum:s}}},function(e,t,i){"use strict";i.d(t,"a",function(){return a});var n=i(1),r=i(3),o=i(10),a=function(){function e(){this._dirty=!0,this._tempColor=new o.b(0,0,0,0),this._globalCurve=new o.b(0,0,0,0),this._highlightsCurve=new o.b(0,0,0,0),this._midtonesCurve=new o.b(0,0,0,0),this._shadowsCurve=new o.b(0,0,0,0),this._positiveCurve=new o.b(0,0,0,0),this._negativeCurve=new o.b(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}return Object.defineProperty(e.prototype,"globalHue",{get:function(){return this._globalHue},set:function(e){this._globalHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"globalDensity",{get:function(){return this._globalDensity},set:function(e){this._globalDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"globalSaturation",{get:function(){return this._globalSaturation},set:function(e){this._globalSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"globalExposure",{get:function(){return this._globalExposure},set:function(e){this._globalExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"highlightsHue",{get:function(){return this._highlightsHue},set:function(e){this._highlightsHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"highlightsDensity",{get:function(){return this._highlightsDensity},set:function(e){this._highlightsDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"highlightsSaturation",{get:function(){return this._highlightsSaturation},set:function(e){this._highlightsSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"highlightsExposure",{get:function(){return this._highlightsExposure},set:function(e){this._highlightsExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"midtonesHue",{get:function(){return this._midtonesHue},set:function(e){this._midtonesHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"midtonesDensity",{get:function(){return this._midtonesDensity},set:function(e){this._midtonesDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"midtonesSaturation",{get:function(){return this._midtonesSaturation},set:function(e){this._midtonesSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"midtonesExposure",{get:function(){return this._midtonesExposure},set:function(e){this._midtonesExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"shadowsHue",{get:function(){return this._shadowsHue},set:function(e){this._shadowsHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"shadowsDensity",{get:function(){return this._shadowsDensity},set:function(e){this._shadowsDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"shadowsSaturation",{get:function(){return this._shadowsSaturation},set:function(e){this._shadowsSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"shadowsExposure",{get:function(){return this._shadowsExposure},set:function(e){this._shadowsExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),e.prototype.getClassName=function(){return"ColorCurves"},e.Bind=function(e,t,i,n,r){void 0===i&&(i="vCameraColorCurvePositive"),void 0===n&&(n="vCameraColorCurveNeutral"),void 0===r&&(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(n,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))},e.PrepareUniforms=function(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")},e.prototype.getColorGradingDataToRef=function(t,i,n,r,o){null!=t&&(t=e.clamp(t,0,360),i=e.clamp(i,-100,100),n=e.clamp(n,-100,100),r=e.clamp(r,-100,100),i=e.applyColorGradingSliderNonlinear(i),i*=.5,r=e.applyColorGradingSliderNonlinear(r),i<0&&(i*=-1,t=(t+180)%360),e.fromHSBToRef(t,i,50+.25*r,o),o.scaleToRef(2,o),o.a=1+.01*n)},e.applyColorGradingSliderNonlinear=function(e){e/=100;var t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100},e.fromHSBToRef=function(t,i,n,r){var o=e.clamp(t,0,360),a=e.clamp(i/100,0,1),s=e.clamp(n/100,0,1);if(0===a)r.r=s,r.g=s,r.b=s;else{o/=60;var c=Math.floor(o),l=o-c,u=s*(1-a),h=s*(1-a*l),d=s*(1-a*(1-l));switch(c){case 0:r.r=s,r.g=d,r.b=u;break;case 1:r.r=h,r.g=s,r.b=u;break;case 2:r.r=u,r.g=s,r.b=d;break;case 3:r.r=u,r.g=h,r.b=s;break;case 4:r.r=d,r.g=u,r.b=s;break;default:r.r=s,r.g=u,r.b=h}}r.a=1},e.clamp=function(e,t,i){return Math.min(Math.max(e,t),i)},e.prototype.clone=function(){return r.a.Clone(function(){return new e},this)},e.prototype.serialize=function(){return r.a.Serialize(this)},e.Parse=function(t){return r.a.Parse(function(){return new e},t,null,null)},Object(n.c)([Object(r.c)()],e.prototype,"_globalHue",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_globalDensity",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_globalSaturation",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_globalExposure",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_highlightsHue",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_highlightsDensity",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_highlightsSaturation",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_highlightsExposure",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_midtonesHue",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_midtonesDensity",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_midtonesSaturation",void 0),Object(n.c)([Object(r.c)()],e.prototype,"_midtonesExposure",void 0),e}();r.a._ColorCurvesParser=a.Parse},function(e,t,i){"use strict";i.d(t,"a",function(){return o});var n=i(7),r=i(12),o=function(){function e(){}return e.Instantiate=function(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];var t=r.a.GetClass(e);if(t)return t;n.a.Warn(e+" not found, you may have missed an import.");for(var i=e.split("."),o=window||this,a=0,s=i.length;a<s;a++)o=o[i[a]];return"function"!=typeof o?null:o},e.RegisteredExternalClasses={},e}()},function(e,t,i){"use strict";var n="fogFragmentDeclaration",r="#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";i.r(t);var n=i(37),r=i(87),o=i(6),a=i(0),s=i(10),c=i(12),l=function(){function e(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new o.c,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}return e.prototype._prepare=function(){},e.prototype.getTriggerParameter=function(){return this._triggerParameter},e.prototype._executeCurrent=function(e){if(this._nextActiveAction._condition){var t=this._nextActiveAction._condition,i=this._actionManager.getScene().getRenderId();if(t._evaluationId===i){if(!t._currentResult)return}else{if(t._evaluationId=i,!t.isValid())return void(t._currentResult=!1);t._currentResult=!0}}this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction()},e.prototype.execute=function(e){},e.prototype.skipToNextActiveAction=function(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this},e.prototype.then=function(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e},e.prototype._getProperty=function(e){return this._actionManager._getProperty(e)},e.prototype._getEffectiveTarget=function(e,t){return this._actionManager._getEffectiveTarget(e,t)},e.prototype.serialize=function(e){},e.prototype._serialize=function(e,t){var i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){var n=this._condition.serialize();return n.children.push(i),t&&t.children.push(n),n}return t&&t.children.push(i),i},e._SerializeValueAsString=function(e){return"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof a.d?e.x+", "+e.y:e instanceof a.e?e.x+", "+e.y+", "+e.z:e instanceof s.a?e.r+", "+e.g+", "+e.b:e instanceof s.b?e.r+", "+e.g+", "+e.b+", "+e.a:e},e._GetTargetProperty=function(e){return{name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":"SceneProperties",value:e._isScene?"Scene":e.name}},e}();c.a.RegisteredTypes["BABYLON.Action"]=l;var u=i(45),h=i(1),d=function(){function e(e){this._actionManager=e}return e.prototype.isValid=function(){return!0},e.prototype._getProperty=function(e){return this._actionManager._getProperty(e)},e.prototype._getEffectiveTarget=function(e,t){return this._actionManager._getEffectiveTarget(e,t)},e.prototype.serialize=function(){},e.prototype._serialize=function(e){return{type:2,children:[],name:e.name,properties:e.properties}},e}(),f=function(e){function t(i,n,r,o,a){void 0===a&&(a=t.IsEqual);var s=e.call(this,i)||this;return s.propertyPath=r,s.value=o,s.operator=a,s._target=n,s._effectiveTarget=s._getEffectiveTarget(n,s.propertyPath),s._property=s._getProperty(s.propertyPath),s}return Object(h.d)(t,e),Object.defineProperty(t,"IsEqual",{get:function(){return t._IsEqual},enumerable:!0,configurable:!0}),Object.defineProperty(t,"IsDifferent",{get:function(){return t._IsDifferent},enumerable:!0,configurable:!0}),Object.defineProperty(t,"IsGreater",{get:function(){return t._IsGreater},enumerable:!0,configurable:!0}),Object.defineProperty(t,"IsLesser",{get:function(){return t._IsLesser},enumerable:!0,configurable:!0}),t.prototype.isValid=function(){switch(this.operator){case t.IsGreater:return this._effectiveTarget[this._property]>this.value;case t.IsLesser:return this._effectiveTarget[this._property]<this.value;case t.IsEqual:case t.IsDifferent:var e;return e=this.value.equals?this.value.equals(this._effectiveTarget[this._property]):this.value===this._effectiveTarget[this._property],this.operator===t.IsEqual?e:!e}return!1},t.prototype.serialize=function(){return this._serialize({name:"ValueCondition",properties:[l._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:l._SerializeValueAsString(this.value)},{name:"operator",value:t.GetOperatorName(this.operator)}]})},t.GetOperatorName=function(e){switch(e){case t._IsEqual:return"IsEqual";case t._IsDifferent:return"IsDifferent";case t._IsGreater:return"IsGreater";case t._IsLesser:return"IsLesser";default:return""}},t._IsEqual=0,t._IsDifferent=1,t._IsGreater=2,t._IsLesser=3,t}(d),p=function(e){function t(t,i){var n=e.call(this,t)||this;return n.predicate=i,n}return Object(h.d)(t,e),t.prototype.isValid=function(){return this.predicate()},t}(d),_=function(e){function t(t,i,n){var r=e.call(this,t)||this;return r.value=n,r._target=i,r}return Object(h.d)(t,e),t.prototype.isValid=function(){return this._target.state===this.value},t.prototype.serialize=function(){return this._serialize({name:"StateCondition",properties:[l._GetTargetProperty(this._target),{name:"value",value:this.value}]})},t}(d);c.a.RegisteredTypes["BABYLON.ValueCondition"]=f,c.a.RegisteredTypes["BABYLON.PredicateCondition"]=p,c.a.RegisteredTypes["BABYLON.StateCondition"]=_;var m=i(7),g=i(2),v=function(e){function t(t,i,n,r){var o=e.call(this,t,r)||this;return o.propertyPath=n,o._target=o._effectiveTarget=i,o}return Object(h.d)(t,e),t.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},t.prototype.execute=function(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"SwitchBooleanAction",properties:[l._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},t)},t}(l),y=function(e){function t(t,i,n,r){var o=e.call(this,t,r)||this;return o.value=n,o._target=i,o}return Object(h.d)(t,e),t.prototype.execute=function(){this._target.state=this.value},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"SetStateAction",properties:[l._GetTargetProperty(this._target),{name:"value",value:this.value}]},t)},t}(l),b=function(e){function t(t,i,n,r,o){var a=e.call(this,t,o)||this;return a.propertyPath=n,a.value=r,a._target=a._effectiveTarget=i,a}return Object(h.d)(t,e),t.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},t.prototype.execute=function(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"SetValueAction",properties:[l._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:l._SerializeValueAsString(this.value)}]},t)},t}(l),T=function(e){function t(t,i,n,r,o){var a=e.call(this,t,o)||this;return a.propertyPath=n,a.value=r,a._target=a._effectiveTarget=i,a}return Object(h.d)(t,e),t.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&m.a.Warn("Warning: IncrementValueAction can only be used with number values")},t.prototype.execute=function(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"IncrementValueAction",properties:[l._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:l._SerializeValueAsString(this.value)}]},t)},t}(l),E=function(e){function t(t,i,n,r,o,a){var s=e.call(this,t,a)||this;return s.from=n,s.to=r,s.loop=o,s._target=i,s}return Object(h.d)(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){this._actionManager.getScene().beginAnimation(this._target,this.from,this.to,this.loop)},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"PlayAnimationAction",properties:[l._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:l._SerializeValueAsString(this.loop)||!1}]},t)},t}(l),x=function(e){function t(t,i,n){var r=e.call(this,t,n)||this;return r._target=i,r}return Object(h.d)(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){this._actionManager.getScene().stopAnimation(this._target)},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"StopAnimationAction",properties:[l._GetTargetProperty(this._target)]},t)},t}(l),P=function(e){function t(t,i){return void 0===t&&(t=g.a.ACTION_NothingTrigger),e.call(this,t,i)||this}return Object(h.d)(t,e),t.prototype.execute=function(){},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"DoNothingAction",properties:[]},t)},t}(l),A=function(e){function t(t,i,n){var r=e.call(this,t,n)||this;return r.children=i,r}return Object(h.d)(t,e),t.prototype._prepare=function(){for(var e=0;e<this.children.length;e++)this.children[e]._actionManager=this._actionManager,this.children[e]._prepare()},t.prototype.execute=function(e){for(var t=0;t<this.children.length;t++)this.children[t].execute(e)},t.prototype.serialize=function(t){for(var i=e.prototype._serialize.call(this,{name:"CombineAction",properties:[],combine:[]},t),n=0;n<this.children.length;n++)i.combine.push(this.children[n].serialize(null));return i},t}(l),S=function(e){function t(t,i,n){var r=e.call(this,t,n)||this;return r.func=i,r}return Object(h.d)(t,e),t.prototype.execute=function(e){this.func(e)},t}(l),C=function(e){function t(t,i,n,r){var o=e.call(this,t,r)||this;return o._target=i,o._parent=n,o}return Object(h.d)(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){if(this._target.parent!==this._parent){var e=this._parent.getWorldMatrix().clone();e.invert(),this._target.position=a.e.TransformCoordinates(this._target.position,e),this._target.parent=this._parent}},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"SetParentAction",properties:[l._GetTargetProperty(this._target),l._GetTargetProperty(this._parent)]},t)},t}(l);c.a.RegisteredTypes["BABYLON.SetParentAction"]=C,c.a.RegisteredTypes["BABYLON.ExecuteCodeAction"]=S,c.a.RegisteredTypes["BABYLON.DoNothingAction"]=P,c.a.RegisteredTypes["BABYLON.StopAnimationAction"]=x,c.a.RegisteredTypes["BABYLON.PlayAnimationAction"]=E,c.a.RegisteredTypes["BABYLON.IncrementValueAction"]=T,c.a.RegisteredTypes["BABYLON.SetValueAction"]=b,c.a.RegisteredTypes["BABYLON.SetStateAction"]=y,c.a.RegisteredTypes["BABYLON.SetParentAction"]=C;var R=i(23),O=i(33),M=function(e){function t(t){var i=e.call(this)||this;return i._scene=t||R.a.LastCreatedScene,t.actionManagers.push(i),i}return Object(h.d)(t,e),t.prototype.dispose=function(){for(var e=this._scene.actionManagers.indexOf(this),i=0;i<this.actions.length;i++){var n=this.actions[i];t.Triggers[n.trigger]--,0===t.Triggers[n.trigger]&&delete t.Triggers[n.trigger]}e>-1&&this._scene.actionManagers.splice(e,1)},t.prototype.getScene=function(){return this._scene},t.prototype.hasSpecificTriggers=function(e){for(var t=0;t<this.actions.length;t++){var i=this.actions[t];if(e.indexOf(i.trigger)>-1)return!0}return!1},t.prototype.hasSpecificTriggers2=function(e,t){for(var i=0;i<this.actions.length;i++){var n=this.actions[i];if(e==n.trigger||t==n.trigger)return!0}return!1},t.prototype.hasSpecificTrigger=function(e,t){for(var i=0;i<this.actions.length;i++){var n=this.actions[i];if(n.trigger===e){if(!t)return!0;if(t(n.getTriggerParameter()))return!0}}return!1},Object.defineProperty(t.prototype,"hasPointerTriggers",{get:function(){for(var e=0;e<this.actions.length;e++){var i=this.actions[e];if(i.trigger>=t.OnPickTrigger&&i.trigger<=t.OnPointerOutTrigger)return!0}return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasPickTriggers",{get:function(){for(var e=0;e<this.actions.length;e++){var i=this.actions[e];if(i.trigger>=t.OnPickTrigger&&i.trigger<=t.OnPickUpTrigger)return!0}return!1},enumerable:!0,configurable:!0}),t.prototype.registerAction=function(e){return e.trigger===t.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(m.a.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),t.Triggers[e.trigger]?t.Triggers[e.trigger]++:t.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)},t.prototype.unregisterAction=function(e){var i=this.actions.indexOf(e);return-1!==i&&(this.actions.splice(i,1),t.Triggers[e.trigger]-=1,0===t.Triggers[e.trigger]&&delete t.Triggers[e.trigger],delete e._actionManager,!0)},t.prototype.processTrigger=function(e,i){for(var n=0;n<this.actions.length;n++){var r=this.actions[n];if(r.trigger===e){if(i&&(e===t.OnKeyUpTrigger||e===t.OnKeyDownTrigger)){var o=r.getTriggerParameter();if(o&&o!==i.sourceEvent.keyCode){if(!o.toLowerCase)continue;var a=o.toLowerCase();if(a!==i.sourceEvent.key){var s=i.sourceEvent.charCode?i.sourceEvent.charCode:i.sourceEvent.keyCode;if(String.fromCharCode(s).toLowerCase()!==a)continue}}}r._executeCurrent(i)}}},t.prototype._getEffectiveTarget=function(e,t){for(var i=t.split("."),n=0;n<i.length-1;n++)e=e[i[n]];return e},t.prototype._getProperty=function(e){var t=e.split(".");return t[t.length-1]},t.prototype.serialize=function(e){for(var i={children:new Array,name:e,type:3,properties:new Array},n=0;n<this.actions.length;n++){var r={type:0,children:new Array,name:t.GetTriggerName(this.actions[n].trigger),properties:new Array},o=this.actions[n].triggerOptions;if(o&&"number"!=typeof o)if(o.parameter instanceof Node)r.properties.push(l._GetTargetProperty(o.parameter));else{var a={};O.a.DeepCopy(o.parameter,a,["mesh"]),o.parameter&&o.parameter.mesh&&(a._meshId=o.parameter.mesh.id),r.properties.push({name:"parameter",targetType:null,value:a})}this.actions[n].serialize(r),i.children.push(r)}return i},t.Parse=function(e,i,n){var r=new t(n);null===i?n.actionManager=r:i.actionManager=r;for(var o=function(e,t,i,n){if(null===n){var r=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(r)?t:r}for(var o=n.split("."),c=t.split(","),l=0;l<o.length;l++)i=i[o[l]];if("boolean"==typeof i)return"true"===c[0];if("string"==typeof i)return c[0];var u=new Array;for(l=0;l<c.length;l++)u.push(parseFloat(c[l]));return i instanceof a.e?a.e.FromArray(u):i instanceof a.f?a.f.FromArray(u):i instanceof s.a?s.a.FromArray(u):i instanceof s.b?s.b.FromArray(u):parseFloat(c[0])},l=function(e,i,a,s,u){if(void 0===u&&(u=null),!e.detached){var h=new Array,p=null,_=null,m=e.combine&&e.combine.length>0;if(2===e.type?h.push(r):h.push(i),m){for(var g=new Array,v=0;v<e.combine.length;v++)l(e.combine[v],t.NothingTrigger,a,s,g);h.push(g)}else for(var y=0;y<e.properties.length;y++){var b=e.properties[y].value,T=e.properties[y].name,E=e.properties[y].targetType;"target"===T?b=p=null!==E&&"SceneProperties"===E?n:n.getNodeByName(b):"parent"===T?b=n.getNodeByName(b):"sound"===T?n.getSoundByName&&(b=n.getSoundByName(b)):"propertyPath"!==T?b=2===e.type&&"operator"===T?f[b]:o(0,b,p,"value"===T?_:null):_=b,h.push(b)}if(null===u?h.push(a):h.push(null),"InterpolateValueAction"===e.name){var x=h[h.length-2];h[h.length-1]=x,h[h.length-2]=a}var A=function(e,t){var i=c.a.GetClass("BABYLON."+e);if(i){var n=Object.create(i.prototype);return n.constructor.apply(n,t),n}}(e.name,h);if(A instanceof d&&null!==a){var S=new P(i,a);s?s.then(S):r.registerAction(S),s=S}null===u?A instanceof d?(a=A,A=s):(a=null,s?s.then(A):r.registerAction(A)):u.push(A);for(y=0;y<e.children.length;y++)l(e.children[y],i,a,A,null)}},u=0;u<e.children.length;u++){var h,p=e.children[u];if(p.properties.length>0){var _=p.properties[0].value,m=null===p.properties[0].targetType?_:n.getMeshByName(_);m._meshId&&(m.mesh=n.getMeshByID(m._meshId)),h={trigger:t[p.name],parameter:m}}else h=t[p.name];for(var g=0;g<p.children.length;g++)p.detached||l(p.children[g],h,null,null)}},t.GetTriggerName=function(e){switch(e){case 0:return"NothingTrigger";case 1:return"OnPickTrigger";case 2:return"OnLeftPickTrigger";case 3:return"OnRightPickTrigger";case 4:return"OnCenterPickTrigger";case 5:return"OnPickDownTrigger";case 6:return"OnPickUpTrigger";case 7:return"OnLongPressTrigger";case 8:return"OnPointerOverTrigger";case 9:return"OnPointerOutTrigger";case 10:return"OnEveryFrameTrigger";case 11:return"OnIntersectionEnterTrigger";case 12:return"OnIntersectionExitTrigger";case 13:return"OnKeyDownTrigger";case 14:return"OnKeyUpTrigger";case 15:return"OnPickOutTrigger";default:return""}},t.NothingTrigger=g.a.ACTION_NothingTrigger,t.OnPickTrigger=g.a.ACTION_OnPickTrigger,t.OnLeftPickTrigger=g.a.ACTION_OnLeftPickTrigger,t.OnRightPickTrigger=g.a.ACTION_OnRightPickTrigger,t.OnCenterPickTrigger=g.a.ACTION_OnCenterPickTrigger,t.OnPickDownTrigger=g.a.ACTION_OnPickDownTrigger,t.OnDoublePickTrigger=g.a.ACTION_OnDoublePickTrigger,t.OnPickUpTrigger=g.a.ACTION_OnPickUpTrigger,t.OnPickOutTrigger=g.a.ACTION_OnPickOutTrigger,t.OnLongPressTrigger=g.a.ACTION_OnLongPressTrigger,t.OnPointerOverTrigger=g.a.ACTION_OnPointerOverTrigger,t.OnPointerOutTrigger=g.a.ACTION_OnPointerOutTrigger,t.OnEveryFrameTrigger=g.a.ACTION_OnEveryFrameTrigger,t.OnIntersectionEnterTrigger=g.a.ACTION_OnIntersectionEnterTrigger,t.OnIntersectionExitTrigger=g.a.ACTION_OnIntersectionExitTrigger,t.OnKeyDownTrigger=g.a.ACTION_OnKeyDownTrigger,t.OnKeyUpTrigger=15,t}(r.a),I=function(e){function t(t,i,n){var r=e.call(this,t,n)||this;return r._sound=i,r}return Object(h.d)(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){void 0!==this._sound&&this._sound.play()},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"PlaySoundAction",properties:[{name:"sound",value:this._sound.name}]},t)},t}(l),D=function(e){function t(t,i,n){var r=e.call(this,t,n)||this;return r._sound=i,r}return Object(h.d)(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){void 0!==this._sound&&this._sound.stop()},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"StopSoundAction",properties:[{name:"sound",value:this._sound.name}]},t)},t}(l);c.a.RegisteredTypes["BABYLON.PlaySoundAction"]=D,c.a.RegisteredTypes["BABYLON.StopSoundAction"]=D;var w,L=i(14),N=i(3);!function(e){e[e.STEP=1]="STEP"}(w||(w={}));var F=function(){function e(e,t,i){this.name=e,this.from=t,this.to=i}return e.prototype.clone=function(){return new e(this.name,this.from,this.to)},e}(),B=i(26),U=i(68),V=function(){},k=function(){function e(t,i,n,r,o,a){this.name=t,this.targetProperty=i,this.framePerSecond=n,this.dataType=r,this.loopMode=o,this.enableBlending=a,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=i.split("."),this.dataType=r,this.loopMode=void 0===o?e.ANIMATIONLOOPMODE_CYCLE:o}return e._PrepareAnimation=function(t,i,n,r,o,c,l,u){var h=void 0;if(!isNaN(parseFloat(o))&&isFinite(o)?h=e.ANIMATIONTYPE_FLOAT:o instanceof a.b?h=e.ANIMATIONTYPE_QUATERNION:o instanceof a.e?h=e.ANIMATIONTYPE_VECTOR3:o instanceof a.d?h=e.ANIMATIONTYPE_VECTOR2:o instanceof s.a?h=e.ANIMATIONTYPE_COLOR3:o instanceof s.b?h=e.ANIMATIONTYPE_COLOR4:o instanceof U.a&&(h=e.ANIMATIONTYPE_SIZE),null==h)return null;var d=new e(t,i,n,h,l),f=[{frame:0,value:o},{frame:r,value:c}];return d.setKeys(f),void 0!==u&&d.setEasingFunction(u),d},e.CreateAnimation=function(t,i,n,r){var o=new e(t+"Animation",t,n,i,e.ANIMATIONLOOPMODE_CONSTANT);return o.setEasingFunction(r),o},e.CreateAndStartAnimation=function(t,i,n,r,o,a,s,c,l,u){var h=e._PrepareAnimation(t,n,r,o,a,s,c,l);return h?i.getScene().beginDirectAnimation(i,[h],0,o,1===h.loopMode,1,u):null},e.CreateAndStartHierarchyAnimation=function(t,i,n,r,o,a,s,c,l,u,h){var d=e._PrepareAnimation(t,r,o,a,s,c,l,u);return d?i.getScene().beginDirectHierarchyAnimation(i,n,[d],0,a,1===d.loopMode,1,h):null},e.CreateMergeAndStartAnimation=function(t,i,n,r,o,a,s,c,l,u){var h=e._PrepareAnimation(t,n,r,o,a,s,c,l);return h?(i.animations.push(h),i.getScene().beginAnimation(i,0,o,1===h.loopMode,1,u)):null},e.TransitionTo=function(e,t,i,n,r,o,a,s){if(void 0===s&&(s=null),a<=0)return i[e]=t,s&&s(),null;var c=r*(a/1e3);o.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:c,value:t}]),i.animations||(i.animations=[]),i.animations.push(o);var l=n.beginAnimation(i,0,c,!1);return l.onAnimationEnd=s,l},Object.defineProperty(e.prototype,"runtimeAnimations",{get:function(){return this._runtimeAnimations},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasRunningRuntimeAnimations",{get:function(){for(var e=0,t=this._runtimeAnimations;e<t.length;e++){if(!t[e].isStopped)return!0}return!1},enumerable:!0,configurable:!0}),e.prototype.toString=function(e){var t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";var i=!0;for(var n in this._ranges)i&&(t+=", ",i=!1),t+=n;t+="}"}return t},e.prototype.addEvent=function(e){this._events.push(e)},e.prototype.removeEvents=function(e){for(var t=0;t<this._events.length;t++)this._events[t].frame===e&&(this._events.splice(t,1),t--)},e.prototype.getEvents=function(){return this._events},e.prototype.createRange=function(e,t,i){this._ranges[e]||(this._ranges[e]=new F(e,t,i))},e.prototype.deleteRange=function(e,t){void 0===t&&(t=!0);var i=this._ranges[e];if(i){if(t)for(var n=i.from,r=i.to,o=this._keys.length-1;o>=0;o--)this._keys[o].frame>=n&&this._keys[o].frame<=r&&this._keys.splice(o,1);this._ranges[e]=null}},e.prototype.getRange=function(e){return this._ranges[e]},e.prototype.getKeys=function(){return this._keys},e.prototype.getHighestFrame=function(){for(var e=0,t=0,i=this._keys.length;t<i;t++)e<this._keys[t].frame&&(e=this._keys[t].frame);return e},e.prototype.getEasingFunction=function(){return this._easingFunction},e.prototype.setEasingFunction=function(e){this._easingFunction=e},e.prototype.floatInterpolateFunction=function(e,t,i){return L.a.Lerp(e,t,i)},e.prototype.floatInterpolateFunctionWithTangents=function(e,t,i,n,r){return L.a.Hermite(e,t,i,n,r)},e.prototype.quaternionInterpolateFunction=function(e,t,i){return a.b.Slerp(e,t,i)},e.prototype.quaternionInterpolateFunctionWithTangents=function(e,t,i,n,r){return a.b.Hermite(e,t,i,n,r).normalize()},e.prototype.vector3InterpolateFunction=function(e,t,i){return a.e.Lerp(e,t,i)},e.prototype.vector3InterpolateFunctionWithTangents=function(e,t,i,n,r){return a.e.Hermite(e,t,i,n,r)},e.prototype.vector2InterpolateFunction=function(e,t,i){return a.d.Lerp(e,t,i)},e.prototype.vector2InterpolateFunctionWithTangents=function(e,t,i,n,r){return a.d.Hermite(e,t,i,n,r)},e.prototype.sizeInterpolateFunction=function(e,t,i){return U.a.Lerp(e,t,i)},e.prototype.color3InterpolateFunction=function(e,t,i){return s.a.Lerp(e,t,i)},e.prototype.color4InterpolateFunction=function(e,t,i){return s.b.Lerp(e,t,i)},e.prototype._getKeyValue=function(e){return"function"==typeof e?e():e},e.prototype._interpolate=function(t,i){if(i.loopMode===e.ANIMATIONLOOPMODE_CONSTANT&&i.repeatCount>0)return i.highLimitValue.clone?i.highLimitValue.clone():i.highLimitValue;var n=this._keys;if(1===n.length)return this._getKeyValue(n[0].value);var r=i.key;if(n[r].frame>=t)for(;r-1>=0&&n[r].frame>=t;)r--;for(var o=r;o<n.length;o++){var a=n[o+1];if(a.frame>=t){i.key=o;var s=n[o],c=this._getKeyValue(s.value);if(s.interpolation===w.STEP)return c;var l=this._getKeyValue(a.value),u=void 0!==s.outTangent&&void 0!==a.inTangent,h=a.frame-s.frame,d=(t-s.frame)/h,f=this.getEasingFunction();switch(null!=f&&(d=f.ease(d)),this.dataType){case e.ANIMATIONTYPE_FLOAT:var p=u?this.floatInterpolateFunctionWithTangents(c,s.outTangent*h,l,a.inTangent*h,d):this.floatInterpolateFunction(c,l,d);switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:return p;case e.ANIMATIONLOOPMODE_RELATIVE:return i.offsetValue*i.repeatCount+p}break;case e.ANIMATIONTYPE_QUATERNION:var _=u?this.quaternionInterpolateFunctionWithTangents(c,s.outTangent.scale(h),l,a.inTangent.scale(h),d):this.quaternionInterpolateFunction(c,l,d);switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:return _;case e.ANIMATIONLOOPMODE_RELATIVE:return _.addInPlace(i.offsetValue.scale(i.repeatCount))}return _;case e.ANIMATIONTYPE_VECTOR3:var m=u?this.vector3InterpolateFunctionWithTangents(c,s.outTangent.scale(h),l,a.inTangent.scale(h),d):this.vector3InterpolateFunction(c,l,d);switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:return m;case e.ANIMATIONLOOPMODE_RELATIVE:return m.add(i.offsetValue.scale(i.repeatCount))}case e.ANIMATIONTYPE_VECTOR2:var g=u?this.vector2InterpolateFunctionWithTangents(c,s.outTangent.scale(h),l,a.inTangent.scale(h),d):this.vector2InterpolateFunction(c,l,d);switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:return g;case e.ANIMATIONLOOPMODE_RELATIVE:return g.add(i.offsetValue.scale(i.repeatCount))}case e.ANIMATIONTYPE_SIZE:switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:return this.sizeInterpolateFunction(c,l,d);case e.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(c,l,d).add(i.offsetValue.scale(i.repeatCount))}case e.ANIMATIONTYPE_COLOR3:switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:return this.color3InterpolateFunction(c,l,d);case e.ANIMATIONLOOPMODE_RELATIVE:return this.color3InterpolateFunction(c,l,d).add(i.offsetValue.scale(i.repeatCount))}case e.ANIMATIONTYPE_COLOR4:switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:return this.color4InterpolateFunction(c,l,d);case e.ANIMATIONLOOPMODE_RELATIVE:return this.color4InterpolateFunction(c,l,d).add(i.offsetValue.scale(i.repeatCount))}case e.ANIMATIONTYPE_MATRIX:switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:if(e.AllowMatricesInterpolation)return this.matrixInterpolateFunction(c,l,d,i.workValue);case e.ANIMATIONLOOPMODE_RELATIVE:return c}}break}}return this._getKeyValue(n[n.length-1].value)},e.prototype.matrixInterpolateFunction=function(t,i,n,r){return e.AllowMatrixDecomposeForInterpolation?r?(a.a.DecomposeLerpToRef(t,i,n,r),r):a.a.DecomposeLerp(t,i,n):r?(a.a.LerpToRef(t,i,n,r),r):a.a.Lerp(t,i,n)},e.prototype.clone=function(){var t=new e(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(t.enableBlending=this.enableBlending,t.blendingSpeed=this.blendingSpeed,this._keys&&t.setKeys(this._keys),this._ranges)for(var i in t._ranges={},this._ranges){var n=this._ranges[i];n&&(t._ranges[i]=n.clone())}return t},e.prototype.setKeys=function(e){this._keys=e.slice(0)},e.prototype.serialize=function(){var t={};t.name=this.name,t.property=this.targetProperty,t.framePerSecond=this.framePerSecond,t.dataType=this.dataType,t.loopBehavior=this.loopMode,t.enableBlending=this.enableBlending,t.blendingSpeed=this.blendingSpeed;var i=this.dataType;t.keys=[];for(var n=this.getKeys(),r=0;r<n.length;r++){var o=n[r],a={};switch(a.frame=o.frame,i){case e.ANIMATIONTYPE_FLOAT:a.values=[o.value];break;case e.ANIMATIONTYPE_QUATERNION:case e.ANIMATIONTYPE_MATRIX:case e.ANIMATIONTYPE_VECTOR3:case e.ANIMATIONTYPE_COLOR3:case e.ANIMATIONTYPE_COLOR4:a.values=o.value.asArray()}t.keys.push(a)}for(var s in t.ranges=[],this._ranges){var c=this._ranges[s];if(c){var l={};l.name=s,l.from=c.from,l.to=c.to,t.ranges.push(l)}}return t},e._UniversalLerp=function(e,t,i){var n=e.constructor;return n.Lerp?n.Lerp(e,t,i):n.Slerp?n.Slerp(e,t,i):e.toFixed?e*(1-i)+i*t:t},e.Parse=function(t){var i,n,r=new e(t.name,t.property,t.framePerSecond,t.dataType,t.loopBehavior),o=t.dataType,c=[];for(t.enableBlending&&(r.enableBlending=t.enableBlending),t.blendingSpeed&&(r.blendingSpeed=t.blendingSpeed),n=0;n<t.keys.length;n++){var l,u,h=t.keys[n];switch(o){case e.ANIMATIONTYPE_FLOAT:i=h.values[0],h.values.length>=1&&(l=h.values[1]),h.values.length>=2&&(u=h.values[2]);break;case e.ANIMATIONTYPE_QUATERNION:if(i=a.b.FromArray(h.values),h.values.length>=8){var d=a.b.FromArray(h.values.slice(4,8));d.equals(a.b.Zero())||(l=d)}if(h.values.length>=12){var f=a.b.FromArray(h.values.slice(8,12));f.equals(a.b.Zero())||(u=f)}break;case e.ANIMATIONTYPE_MATRIX:i=a.a.FromArray(h.values);break;case e.ANIMATIONTYPE_COLOR3:i=s.a.FromArray(h.values);break;case e.ANIMATIONTYPE_COLOR4:i=s.b.FromArray(h.values);break;case e.ANIMATIONTYPE_VECTOR3:default:i=a.e.FromArray(h.values)}var p={};p.frame=h.frame,p.value=i,null!=l&&(p.inTangent=l),null!=u&&(p.outTangent=u),c.push(p)}if(r.setKeys(c),t.ranges)for(n=0;n<t.ranges.length;n++)i=t.ranges[n],r.createRange(i.name,i.from,i.to);return r},e.AppendSerializedAnimations=function(e,t){N.a.AppendSerializedAnimations(e,t)},e.AllowMatricesInterpolation=!1,e.AllowMatrixDecomposeForInterpolation=!0,e.ANIMATIONTYPE_FLOAT=0,e.ANIMATIONTYPE_VECTOR3=1,e.ANIMATIONTYPE_QUATERNION=2,e.ANIMATIONTYPE_MATRIX=3,e.ANIMATIONTYPE_COLOR3=4,e.ANIMATIONTYPE_COLOR4=7,e.ANIMATIONTYPE_VECTOR2=5,e.ANIMATIONTYPE_SIZE=6,e.ANIMATIONLOOPMODE_RELATIVE=0,e.ANIMATIONLOOPMODE_CYCLE=1,e.ANIMATIONLOOPMODE_CONSTANT=2,e}();c.a.RegisteredTypes["BABYLON.Animation"]=k,B.a._AnimationRangeFactory=function(e,t,i){return new F(e,t,i)};var z=function(e){function t(t,i,n,r,a,s,c,l){void 0===a&&(a=1e3);var u=e.call(this,t,s)||this;return u.duration=1e3,u.onInterpolationDoneObservable=new o.c,u.propertyPath=n,u.value=r,u.duration=a,u.stopOtherAnimations=c,u.onInterpolationDone=l,u._target=u._effectiveTarget=i,u}return Object(h.d)(t,e),t.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},t.prototype.execute=function(){var e,t=this,i=this._actionManager.getScene(),n=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];if("number"==typeof this.value)e=k.ANIMATIONTYPE_FLOAT;else if(this.value instanceof s.a)e=k.ANIMATIONTYPE_COLOR3;else if(this.value instanceof a.e)e=k.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof a.a)e=k.ANIMATIONTYPE_MATRIX;else{if(!(this.value instanceof a.b))return void m.a.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");e=k.ANIMATIONTYPE_QUATERNION}var r=new k("InterpolateValueAction",this._property,1e3/this.duration*100,e,k.ANIMATIONLOOPMODE_CONSTANT);r.setKeys(n),this.stopOtherAnimations&&i.stopAnimation(this._effectiveTarget);i.beginDirectAnimation(this._effectiveTarget,[r],0,100,!1,1,function(){t.onInterpolationDoneObservable.notifyObservers(t),t.onInterpolationDone&&t.onInterpolationDone()})},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"InterpolateValueAction",properties:[l._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:l._SerializeValueAsString(this.value)},{name:"duration",value:l._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:l._SerializeValueAsString(this.stopOtherAnimations)||!1}]},t)},t}(l);c.a.RegisteredTypes["BABYLON.InterpolateValueAction"]=z;var G=Object.freeze(new a.b(0,0,0,0)),j=Object.freeze(a.e.Zero()),W=Object.freeze(a.d.Zero()),X=Object.freeze(U.a.Zero()),H=Object.freeze(s.a.Black()),Y=function(){function e(e,t,i,n){var r=this;if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._ratioOffset=0,this._previousDelay=0,this._previousRatio=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=n,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===k.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=a.a.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,0!==this._minFrame){var o={frame:0,value:this._minValue};this._keys.splice(0,0,o)}if(this._target instanceof Array){for(var s=0,c=0,l=this._target;c<l.length;c++){var u=l[c];this._preparePath(u,s),this._getOriginalValues(s),s++}this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];var h=t.getEvents();h&&h.length>0&&h.forEach(function(e){r._events.push(e._clone())}),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}return Object.defineProperty(e.prototype,"currentFrame",{get:function(){return this._currentFrame},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weight",{get:function(){return this._weight},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentValue",{get:function(){return this._currentValue},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"targetPath",{get:function(){return this._targetPath},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"target",{get:function(){return this._currentActiveTarget},enumerable:!0,configurable:!0}),e.prototype._preparePath=function(e,t){void 0===t&&(t=0);var i=this._animation.targetPropertyPath;if(i.length>1){for(var n=e[i[0]],r=1;r<i.length-1;r++)n=n[i[r]];this._targetPath=i[i.length-1],this._activeTargets[t]=n}else this._targetPath=i[0],this._activeTargets[t]=e},Object.defineProperty(e.prototype,"animation",{get:function(){return this._animation},enumerable:!0,configurable:!0}),e.prototype.reset=function(e){if(void 0===e&&(e=!1),e)if(this._target instanceof Array)for(var t=0,i=0,n=this._target;i<n.length;i++){var r=n[i];void 0!==this._originalValue[t]&&this._setValue(r,this._activeTargets[t],this._originalValue[t],-1,t),t++}else void 0!==this._originalValue[0]&&this._setValue(this._target,this._directTarget,this._originalValue[0],-1,0);this._offsetsCache={},this._highLimitsCache={},this._currentFrame=0,this._blendingFactor=0;for(t=0;t<this._events.length;t++)this._events[t].isDone=!1},e.prototype.isStopped=function(){return this._stopped},e.prototype.dispose=function(){var e=this._animation.runtimeAnimations.indexOf(this);e>-1&&this._animation.runtimeAnimations.splice(e,1)},e.prototype.setValue=function(e,t){if(this._targetIsArray)for(var i=0;i<this._target.length;i++){var n=this._target[i];this._setValue(n,this._activeTargets[i],e,t,i)}else this._setValue(this._target,this._directTarget,e,t,0)},e.prototype._getOriginalValues=function(e){var t;void 0===e&&(e=0);var i=this._activeTargets[e];(t=i.getRestPose&&"_matrix"===this._targetPath?i.getRestPose():i[this._targetPath])&&t.clone?this._originalValue[e]=t.clone():this._originalValue[e]=t},e.prototype._setValue=function(e,t,i,n,r){if(this._currentActiveTarget=t,this._weight=n,this._enableBlending&&this._blendingFactor<=1){if(!this._originalBlendValue){var o=t[this._targetPath];o.clone?this._originalBlendValue=o.clone():this._originalBlendValue=o}this._originalBlendValue.m?k.AllowMatrixDecomposeForInterpolation?this._currentValue?a.a.DecomposeLerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=a.a.DecomposeLerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue?a.a.LerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=a.a.Lerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue=k._UniversalLerp(this._originalBlendValue,i,this._blendingFactor);var s=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.blendingSpeed:this._animation.blendingSpeed;this._blendingFactor+=s}else this._currentValue=i;-1!==n?this._scene._registerTargetForLateAnimationBinding(this,this._originalValue[r]):t[this._targetPath]=this._currentValue,e.markAsDirty&&e.markAsDirty(this._animation.targetProperty)},e.prototype._getCorrectLoopMode=function(){return this._target&&this._target.animationPropertiesOverride?this._target.animationPropertiesOverride.loopMode:this._animation.loopMode},e.prototype.goToFrame=function(e){var t=this._animation.getKeys();e<t[0].frame?e=t[0].frame:e>t[t.length-1].frame&&(e=t[t.length-1].frame);var i=this._events;if(i.length)for(var n=0;n<i.length;n++)i[n].onlyOnce||(i[n].isDone=i[n].frame<e);this._currentFrame=e;var r=this._animation._interpolate(e,this._animationState);this.setValue(r,-1)},e.prototype._prepareForSpeedRatioChange=function(e){var t=this._previousDelay*(this._animation.framePerSecond*e)/1e3;this._ratioOffset=this._previousRatio-t},e.prototype.animate=function(e,t,i,n,r,o){void 0===o&&(o=-1);var a=this._animation,s=a.targetPropertyPath;if(!s||s.length<1)return this._stopped=!0,!1;var c=!0;(t<this._minFrame||t>this._maxFrame)&&(t=this._minFrame),(i<this._minFrame||i>this._maxFrame)&&(i=this._maxFrame);var l,u,h=i-t,d=e*(a.framePerSecond*r)/1e3+this._ratioOffset,f=0;if(this._previousDelay=e,this._previousRatio=d,!n&&i>=t&&d>=h)c=!1,f=a._getKeyValue(this._maxValue);else if(!n&&t>=i&&d<=h)c=!1,f=a._getKeyValue(this._minValue);else if(this._animationState.loopMode!==k.ANIMATIONLOOPMODE_CYCLE){var p=i.toString()+t.toString();if(!this._offsetsCache[p]){this._animationState.repeatCount=0,this._animationState.loopMode=k.ANIMATIONLOOPMODE_CYCLE;var _=a._interpolate(t,this._animationState),m=a._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),a.dataType){case k.ANIMATIONTYPE_FLOAT:this._offsetsCache[p]=m-_;break;case k.ANIMATIONTYPE_QUATERNION:this._offsetsCache[p]=m.subtract(_);break;case k.ANIMATIONTYPE_VECTOR3:this._offsetsCache[p]=m.subtract(_);case k.ANIMATIONTYPE_VECTOR2:this._offsetsCache[p]=m.subtract(_);case k.ANIMATIONTYPE_SIZE:this._offsetsCache[p]=m.subtract(_);case k.ANIMATIONTYPE_COLOR3:this._offsetsCache[p]=m.subtract(_)}this._highLimitsCache[p]=m}f=this._highLimitsCache[p],l=this._offsetsCache[p]}if(void 0===l)switch(a.dataType){case k.ANIMATIONTYPE_FLOAT:l=0;break;case k.ANIMATIONTYPE_QUATERNION:l=G;break;case k.ANIMATIONTYPE_VECTOR3:l=j;break;case k.ANIMATIONTYPE_VECTOR2:l=W;break;case k.ANIMATIONTYPE_SIZE:l=X;break;case k.ANIMATIONTYPE_COLOR3:l=H}if(this._host&&this._host.syncRoot){var g=this._host.syncRoot;u=t+(i-t)*((g.masterFrame-g.fromFrame)/(g.toFrame-g.fromFrame))}else u=c&&0!==h?t+d%h:i;var v=this._events;if((h>0&&this.currentFrame>u||h<0&&this.currentFrame<u)&&(this._onLoop(),v.length))for(var y=0;y<v.length;y++)v[y].onlyOnce||(v[y].isDone=!1);this._currentFrame=u,this._animationState.repeatCount=0===h?0:d/h>>0,this._animationState.highLimitValue=f,this._animationState.offsetValue=l;var b=a._interpolate(u,this._animationState);if(this.setValue(b,o),v.length)for(y=0;y<v.length;y++)if(h>0&&u>=v[y].frame&&v[y].frame>=t||h<0&&u<=v[y].frame&&v[y].frame<=t){var T=v[y];T.isDone||(T.onlyOnce&&(v.splice(y,1),y--),T.isDone=!0,T.action(u))}return c||(this._stopped=!0),c},e}(),K=i(18),Q=i(52),q=i(42),Z=i(22),J=function(e){function t(t,i,n,r,o,s,c){void 0===n&&(n=null),void 0===r&&(r=null),void 0===o&&(o=null),void 0===s&&(s=null),void 0===c&&(c=null);var l=e.call(this,t,i.getScene())||this;return l.name=t,l.children=new Array,l.animations=new Array,l._index=null,l._absoluteTransform=new a.a,l._invertedAbsoluteTransform=new a.a,l._scalingDeterminant=1,l._worldTransform=new a.a,l._needToDecompose=!0,l._needToCompose=!1,l._linkedTransformNode=null,l._waitingTransformNodeId=null,l._skeleton=i,l._localMatrix=r?r.clone():a.a.Identity(),l._restPose=o||l._localMatrix.clone(),l._baseMatrix=s||l._localMatrix.clone(),l._index=c,i.bones.push(l),l.setParent(n,!1),(s||r)&&l._updateDifferenceMatrix(),l}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"_matrix",{get:function(){return this._compose(),this._localMatrix},set:function(e){this._localMatrix.copyFrom(e),this._needToDecompose=!0},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"Bone"},t.prototype.getSkeleton=function(){return this._skeleton},t.prototype.getParent=function(){return this._parent},t.prototype.getChildren=function(){return this.children},t.prototype.getIndex=function(){return null===this._index?this.getSkeleton().bones.indexOf(this):this._index},t.prototype.setParent=function(e,t){if(void 0===t&&(t=!0),this._parent!==e){if(this._parent){var i=this._parent.children.indexOf(this);-1!==i&&this._parent.children.splice(i,1)}this._parent=e,this._parent&&this._parent.children.push(this),t&&this._updateDifferenceMatrix(),this.markAsDirty()}},t.prototype.getLocalMatrix=function(){return this._compose(),this._localMatrix},t.prototype.getBaseMatrix=function(){return this._baseMatrix},t.prototype.getRestPose=function(){return this._restPose},t.prototype.getWorldMatrix=function(){return this._worldTransform},t.prototype.returnToRest=function(){this.updateMatrix(this._restPose.clone())},t.prototype.getInvertedAbsoluteTransform=function(){return this._invertedAbsoluteTransform},t.prototype.getAbsoluteTransform=function(){return this._absoluteTransform},t.prototype.linkTransformNode=function(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++},t.prototype.getTransformNode=function(){return this._linkedTransformNode},Object.defineProperty(t.prototype,"position",{get:function(){return this._decompose(),this._localPosition},set:function(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return this.getRotation()},set:function(e){this.setRotation(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationQuaternion",{get:function(){return this._decompose(),this._localRotation},set:function(e){this.setRotationQuaternion(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this.getScale()},set:function(e){this.setScale(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationPropertiesOverride",{get:function(){return this._skeleton.animationPropertiesOverride},enumerable:!0,configurable:!0}),t.prototype._decompose=function(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=a.e.Zero(),this._localRotation=a.b.Zero(),this._localPosition=a.e.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))},t.prototype._compose=function(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,a.a.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)},t.prototype.updateMatrix=function(e,t,i){void 0===t&&(t=!0),void 0===i&&(i=!0),this._baseMatrix.copyFrom(e),t&&this._updateDifferenceMatrix(),i?(this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose()):this.markAsDirty()},t.prototype._updateDifferenceMatrix=function(e,t){if(void 0===t&&(t=!0),e||(e=this._baseMatrix),this._parent?e.multiplyToRef(this._parent._absoluteTransform,this._absoluteTransform):this._absoluteTransform.copyFrom(e),this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform),t)for(var i=0;i<this.children.length;i++)this.children[i]._updateDifferenceMatrix();this._scalingDeterminant=this._absoluteTransform.determinant()<0?-1:1},t.prototype.markAsDirty=function(){this._currentRenderId++,this._childUpdateId++,this._skeleton._markAsDirty()},t.prototype._markAsDirtyAndCompose=function(){this.markAsDirty(),this._needToCompose=!0},t.prototype._markAsDirtyAndDecompose=function(){this.markAsDirty(),this._needToDecompose=!0},t.prototype.translate=function(e,i,n){void 0===i&&(i=Z.b.LOCAL);var r=this.getLocalMatrix();if(i==Z.b.LOCAL)r.addAtIndex(12,e.x),r.addAtIndex(13,e.y),r.addAtIndex(14,e.z);else{var o=null;n&&(o=n.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var s=t._tmpMats[0],c=t._tmpVecs[0];this._parent&&(n&&o?(s.copyFrom(this._parent.getAbsoluteTransform()),s.multiplyToRef(o,s)):s.copyFrom(this._parent.getAbsoluteTransform())),s.setTranslationFromFloats(0,0,0),s.invert(),a.e.TransformCoordinatesToRef(e,s,c),r.addAtIndex(12,c.x),r.addAtIndex(13,c.y),r.addAtIndex(14,c.z)}this._markAsDirtyAndDecompose()},t.prototype.setPosition=function(e,i,n){void 0===i&&(i=Z.b.LOCAL);var r=this.getLocalMatrix();if(i==Z.b.LOCAL)r.setTranslationFromFloats(e.x,e.y,e.z);else{var o=null;n&&(o=n.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var s=t._tmpMats[0],c=t._tmpVecs[0];this._parent&&(n&&o?(s.copyFrom(this._parent.getAbsoluteTransform()),s.multiplyToRef(o,s)):s.copyFrom(this._parent.getAbsoluteTransform())),s.invert(),a.e.TransformCoordinatesToRef(e,s,c),r.setTranslationFromFloats(c.x,c.y,c.z)}this._markAsDirtyAndDecompose()},t.prototype.setAbsolutePosition=function(e,t){this.setPosition(e,Z.b.WORLD,t)},t.prototype.scale=function(e,i,n,r){void 0===r&&(r=!1);var o=this.getLocalMatrix(),s=t._tmpMats[0];a.a.ScalingToRef(e,i,n,s),s.multiplyToRef(o,o),s.invert();for(var c=0,l=this.children;c<l.length;c++){var u=(f=l[c]).getLocalMatrix();u.multiplyToRef(s,u),u.multiplyAtIndex(12,e),u.multiplyAtIndex(13,i),u.multiplyAtIndex(14,n),f._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),r)for(var h=0,d=this.children;h<d.length;h++){var f;(f=d[h]).scale(e,i,n,r)}},t.prototype.setScale=function(e){this._decompose(),this._localScaling.copyFrom(e),this._markAsDirtyAndCompose()},t.prototype.getScale=function(){return this._decompose(),this._localScaling},t.prototype.getScaleToRef=function(e){this._decompose(),e.copyFrom(this._localScaling)},t.prototype.setYawPitchRoll=function(e,i,n,r,o){if(void 0===r&&(r=Z.b.LOCAL),r===Z.b.LOCAL){var s=t._tmpQuat;return a.b.RotationYawPitchRollToRef(e,i,n,s),void this.setRotationQuaternion(s,r,o)}var c=t._tmpMats[0];if(this._getNegativeRotationToRef(c,o)){var l=t._tmpMats[1];a.a.RotationYawPitchRollToRef(e,i,n,l),c.multiplyToRef(l,l),this._rotateWithMatrix(l,r,o)}},t.prototype.rotate=function(e,i,n,r){void 0===n&&(n=Z.b.LOCAL);var o=t._tmpMats[0];o.setTranslationFromFloats(0,0,0),a.a.RotationAxisToRef(e,i,o),this._rotateWithMatrix(o,n,r)},t.prototype.setAxisAngle=function(e,i,n,r){if(void 0===n&&(n=Z.b.LOCAL),n===Z.b.LOCAL){var o=t._tmpQuat;return a.b.RotationAxisToRef(e,i,o),void this.setRotationQuaternion(o,n,r)}var s=t._tmpMats[0];if(this._getNegativeRotationToRef(s,r)){var c=t._tmpMats[1];a.a.RotationAxisToRef(e,i,c),s.multiplyToRef(c,c),this._rotateWithMatrix(c,n,r)}},t.prototype.setRotation=function(e,t,i){void 0===t&&(t=Z.b.LOCAL),this.setYawPitchRoll(e.y,e.x,e.z,t,i)},t.prototype.setRotationQuaternion=function(e,i,n){if(void 0===i&&(i=Z.b.LOCAL),i===Z.b.LOCAL)return this._decompose(),this._localRotation.copyFrom(e),void this._markAsDirtyAndCompose();var r=t._tmpMats[0];if(this._getNegativeRotationToRef(r,n)){var o=t._tmpMats[1];a.a.FromQuaternionToRef(e,o),r.multiplyToRef(o,o),this._rotateWithMatrix(o,i,n)}},t.prototype.setRotationMatrix=function(e,i,n){if(void 0===i&&(i=Z.b.LOCAL),i===Z.b.LOCAL){var r=t._tmpQuat;return a.b.FromRotationMatrixToRef(e,r),void this.setRotationQuaternion(r,i,n)}var o=t._tmpMats[0];if(this._getNegativeRotationToRef(o,n)){var s=t._tmpMats[1];s.copyFrom(e),o.multiplyToRef(e,s),this._rotateWithMatrix(s,i,n)}},t.prototype._rotateWithMatrix=function(e,i,n){void 0===i&&(i=Z.b.LOCAL);var r=this.getLocalMatrix(),o=r.m[12],a=r.m[13],s=r.m[14],c=this.getParent(),l=t._tmpMats[3],u=t._tmpMats[4];c&&i==Z.b.WORLD?(n?(l.copyFrom(n.getWorldMatrix()),c.getAbsoluteTransform().multiplyToRef(l,l)):l.copyFrom(c.getAbsoluteTransform()),u.copyFrom(l),u.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(u,r)):i==Z.b.WORLD&&n?(l.copyFrom(n.getWorldMatrix()),u.copyFrom(l),u.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(u,r)):r.multiplyToRef(e,r),r.setTranslationFromFloats(o,a,s),this.computeAbsoluteTransforms(),this._markAsDirtyAndDecompose()},t.prototype._getNegativeRotationToRef=function(e,i){var n=t._tmpMats[2];return e.copyFrom(this.getAbsoluteTransform()),i&&(e.multiplyToRef(i.getWorldMatrix(),e),a.a.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,n)),e.invert(),!isNaN(e.m[0])&&(n.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(n,e),!0)},t.prototype.getPosition=function(e,t){void 0===e&&(e=Z.b.LOCAL),void 0===t&&(t=null);var i=a.e.Zero();return this.getPositionToRef(e,t,i),i},t.prototype.getPositionToRef=function(e,i,n){if(void 0===e&&(e=Z.b.LOCAL),e==Z.b.LOCAL){var r=this.getLocalMatrix();n.x=r.m[12],n.y=r.m[13],n.z=r.m[14]}else{var o=null;i&&(o=i.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var a=t._tmpMats[0];i&&o?(a.copyFrom(this.getAbsoluteTransform()),a.multiplyToRef(o,a)):a=this.getAbsoluteTransform(),n.x=a.m[12],n.y=a.m[13],n.z=a.m[14]}},t.prototype.getAbsolutePosition=function(e){void 0===e&&(e=null);var t=a.e.Zero();return this.getPositionToRef(Z.b.WORLD,e,t),t},t.prototype.getAbsolutePositionToRef=function(e,t){this.getPositionToRef(Z.b.WORLD,e,t)},t.prototype.computeAbsoluteTransforms=function(){if(this._compose(),this._parent)this._localMatrix.multiplyToRef(this._parent._absoluteTransform,this._absoluteTransform);else{this._absoluteTransform.copyFrom(this._localMatrix);var e=this._skeleton.getPoseMatrix();e&&this._absoluteTransform.multiplyToRef(e,this._absoluteTransform)}for(var t=this.children,i=t.length,n=0;n<i;n++)t[n].computeAbsoluteTransforms()},t.prototype.getDirection=function(e,t){void 0===t&&(t=null);var i=a.e.Zero();return this.getDirectionToRef(e,t,i),i},t.prototype.getDirectionToRef=function(e,i,n){void 0===i&&(i=null);var r=null;i&&(r=i.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var o=t._tmpMats[0];o.copyFrom(this.getAbsoluteTransform()),i&&r&&o.multiplyToRef(r,o),a.e.TransformNormalToRef(e,o,n),n.normalize()},t.prototype.getRotation=function(e,t){void 0===e&&(e=Z.b.LOCAL),void 0===t&&(t=null);var i=a.e.Zero();return this.getRotationToRef(e,t,i),i},t.prototype.getRotationToRef=function(e,i,n){void 0===e&&(e=Z.b.LOCAL),void 0===i&&(i=null);var r=t._tmpQuat;this.getRotationQuaternionToRef(e,i,r),r.toEulerAnglesToRef(n)},t.prototype.getRotationQuaternion=function(e,t){void 0===e&&(e=Z.b.LOCAL),void 0===t&&(t=null);var i=a.b.Identity();return this.getRotationQuaternionToRef(e,t,i),i},t.prototype.getRotationQuaternionToRef=function(e,i,n){if(void 0===e&&(e=Z.b.LOCAL),void 0===i&&(i=null),e==Z.b.LOCAL)this._decompose(),n.copyFrom(this._localRotation);else{var r=t._tmpMats[0],o=this.getAbsoluteTransform();i?o.multiplyToRef(i.getWorldMatrix(),r):r.copyFrom(o),r.multiplyAtIndex(0,this._scalingDeterminant),r.multiplyAtIndex(1,this._scalingDeterminant),r.multiplyAtIndex(2,this._scalingDeterminant),r.decompose(void 0,n,void 0)}},t.prototype.getRotationMatrix=function(e,t){void 0===e&&(e=Z.b.LOCAL);var i=a.a.Identity();return this.getRotationMatrixToRef(e,t,i),i},t.prototype.getRotationMatrixToRef=function(e,i,n){if(void 0===e&&(e=Z.b.LOCAL),e==Z.b.LOCAL)this.getLocalMatrix().getRotationMatrixToRef(n);else{var r=t._tmpMats[0],o=this.getAbsoluteTransform();i?o.multiplyToRef(i.getWorldMatrix(),r):r.copyFrom(o),r.multiplyAtIndex(0,this._scalingDeterminant),r.multiplyAtIndex(1,this._scalingDeterminant),r.multiplyAtIndex(2,this._scalingDeterminant),r.getRotationMatrixToRef(n)}},t.prototype.getAbsolutePositionFromLocal=function(e,t){void 0===t&&(t=null);var i=a.e.Zero();return this.getAbsolutePositionFromLocalToRef(e,t,i),i},t.prototype.getAbsolutePositionFromLocalToRef=function(e,i,n){void 0===i&&(i=null);var r=null;i&&(r=i.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var o=t._tmpMats[0];i&&r?(o.copyFrom(this.getAbsoluteTransform()),o.multiplyToRef(r,o)):o=this.getAbsoluteTransform(),a.e.TransformCoordinatesToRef(e,o,n)},t.prototype.getLocalPositionFromAbsolute=function(e,t){void 0===t&&(t=null);var i=a.e.Zero();return this.getLocalPositionFromAbsoluteToRef(e,t,i),i},t.prototype.getLocalPositionFromAbsoluteToRef=function(e,i,n){void 0===i&&(i=null);var r=null;i&&(r=i.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var o=t._tmpMats[0];o.copyFrom(this.getAbsoluteTransform()),i&&r&&o.multiplyToRef(r,o),o.invert(),a.e.TransformCoordinatesToRef(e,o,n)},t._tmpVecs=q.a.BuildArray(2,a.e.Zero),t._tmpQuat=a.b.Identity(),t._tmpMats=q.a.BuildArray(5,a.a.Identity),t}(B.a),$=function(){function e(e,t,i,n,r,a,s,c,l){void 0===i&&(i=0),void 0===n&&(n=100),void 0===r&&(r=!1),void 0===a&&(a=1),this.target=t,this.fromFrame=i,this.toFrame=n,this.loopAnimation=r,this.onAnimationEnd=s,this.onAnimationLoop=l,this._localDelayOffset=null,this._pausedDelay=null,this._runtimeAnimations=new Array,this._paused=!1,this._speedRatio=1,this._weight=-1,this._syncRoot=null,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new o.c,this.onAnimationLoopObservable=new o.c,this._scene=e,c&&this.appendAnimations(t,c),this._speedRatio=a,e._activeAnimatables.push(this)}return Object.defineProperty(e.prototype,"syncRoot",{get:function(){return this._syncRoot},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"masterFrame",{get:function(){return 0===this._runtimeAnimations.length?0:this._runtimeAnimations[0].currentFrame},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weight",{get:function(){return this._weight},set:function(e){this._weight=-1!==e?Math.min(Math.max(e,0),1):-1},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"speedRatio",{get:function(){return this._speedRatio},set:function(e){for(var t=0;t<this._runtimeAnimations.length;t++){this._runtimeAnimations[t]._prepareForSpeedRatioChange(e)}this._speedRatio=e},enumerable:!0,configurable:!0}),e.prototype.syncWith=function(e){if(this._syncRoot=e,e){var t=this._scene._activeAnimatables.indexOf(this);t>-1&&(this._scene._activeAnimatables.splice(t,1),this._scene._activeAnimatables.push(this))}return this},e.prototype.getAnimations=function(){return this._runtimeAnimations},e.prototype.appendAnimations=function(e,t){for(var i=this,n=0;n<t.length;n++){var r=t[n],o=new Y(e,r,this._scene,this);o._onLoop=function(){i.onAnimationLoopObservable.notifyObservers(i),i.onAnimationLoop&&i.onAnimationLoop()},this._runtimeAnimations.push(o)}},e.prototype.getAnimationByTargetProperty=function(e){for(var t=this._runtimeAnimations,i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i].animation;return null},e.prototype.getRuntimeAnimationByTargetProperty=function(e){for(var t=this._runtimeAnimations,i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i];return null},e.prototype.reset=function(){for(var e=this._runtimeAnimations,t=0;t<e.length;t++)e[t].reset(!0);this._localDelayOffset=null,this._pausedDelay=null},e.prototype.enableBlending=function(e){for(var t=this._runtimeAnimations,i=0;i<t.length;i++)t[i].animation.enableBlending=!0,t[i].animation.blendingSpeed=e},e.prototype.disableBlending=function(){for(var e=this._runtimeAnimations,t=0;t<e.length;t++)e[t].animation.enableBlending=!1},e.prototype.goToFrame=function(e){var t=this._runtimeAnimations;if(t[0]){var i=t[0].animation.framePerSecond,n=e-t[0].currentFrame,r=0!==this.speedRatio?1e3*n/(i*this.speedRatio):0;null===this._localDelayOffset&&(this._localDelayOffset=0),this._localDelayOffset-=r}for(var o=0;o<t.length;o++)t[o].goToFrame(e)},e.prototype.pause=function(){this._paused||(this._paused=!0)},e.prototype.restart=function(){this._paused=!1},e.prototype._raiseOnAnimationEnd=function(){this.onAnimationEnd&&this.onAnimationEnd(),this.onAnimationEndObservable.notifyObservers(this)},e.prototype.stop=function(e,t){if(e||t){var i=this._scene._activeAnimatables.indexOf(this);if(i>-1){for(var n=(o=this._runtimeAnimations).length-1;n>=0;n--){var r=o[n];e&&r.animation.name!=e||(t&&!t(r.target)||(r.dispose(),o.splice(n,1)))}0==o.length&&(this._scene._activeAnimatables.splice(i,1),this._raiseOnAnimationEnd())}}else{if((n=this._scene._activeAnimatables.indexOf(this))>-1){this._scene._activeAnimatables.splice(n,1);var o=this._runtimeAnimations;for(n=0;n<o.length;n++)o[n].dispose();this._raiseOnAnimationEnd()}}},e.prototype.waitAsync=function(){var e=this;return new Promise(function(t,i){e.onAnimationEndObservable.add(function(){t(e)},void 0,void 0,e,!0)})},e.prototype._animate=function(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),0===this._weight)return!0;var t,i=!1,n=this._runtimeAnimations;for(t=0;t<n.length;t++){var r=n[t].animate(e-this._localDelayOffset,this.fromFrame,this.toFrame,this.loopAnimation,this._speedRatio,this._weight);i=i||r}if(this.animationStarted=i,!i){if(this.disposeOnEnd)for(t=this._scene._activeAnimatables.indexOf(this),this._scene._activeAnimatables.splice(t,1),t=0;t<n.length;t++)n[t].dispose();this._raiseOnAnimationEnd(),this.disposeOnEnd&&(this.onAnimationEnd=null,this.onAnimationLoop=null,this.onAnimationLoopObservable.clear(),this.onAnimationEndObservable.clear())}return i},e}();K.a.prototype._animate=function(){if(this.animationsEnabled){var e=Q.a.Now;if(!this._animationTimeLast){if(this._pendingData.length>0)return;this._animationTimeLast=e}this.deltaTime=this.useConstantAnimationDeltaTime?16:(e-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=e;var t=this._activeAnimatables;if(0!==t.length){this._animationTime+=this.deltaTime;for(var i=this._animationTime,n=0;n<t.length;n++){var r=t[n];!r._animate(i)&&r.disposeOnEnd&&n--}this._processLateAnimationBindings()}}},K.a.prototype.beginWeightedAnimation=function(e,t,i,n,r,o,a,s,c,l){void 0===n&&(n=1),void 0===o&&(o=1);var u=this.beginAnimation(e,t,i,r,o,a,s,!1,c,l);return u.weight=n,u},K.a.prototype.beginAnimation=function(e,t,i,n,r,o,a,s,c,l){void 0===r&&(r=1),void 0===s&&(s=!0),t>i&&r>0&&(r*=-1),s&&this.stopAnimation(e,void 0,c),a||(a=new $(this,e,t,i,n,r,o,void 0,l));var u=!c||c(e);if(e.animations&&u&&a.appendAnimations(e,e.animations),e.getAnimatables)for(var h=e.getAnimatables(),d=0;d<h.length;d++)this.beginAnimation(h[d],t,i,n,r,o,a,s,c,l);return a.reset(),a},K.a.prototype.beginHierarchyAnimation=function(e,t,i,n,r,o,a,s,c,l,u){void 0===o&&(o=1),void 0===c&&(c=!0);var h=e.getDescendants(t),d=[];d.push(this.beginAnimation(e,i,n,r,o,a,s,c,l));for(var f=0,p=h;f<p.length;f++){var _=p[f];d.push(this.beginAnimation(_,i,n,r,o,a,s,c,l))}return d},K.a.prototype.beginDirectAnimation=function(e,t,i,n,r,o,a,s){return void 0===o&&(o=1),i>n&&o>0&&(o*=-1),new $(this,e,i,n,r,o,a,t,s)},K.a.prototype.beginDirectHierarchyAnimation=function(e,t,i,n,r,o,a,s,c){var l=e.getDescendants(t),u=[];u.push(this.beginDirectAnimation(e,i,n,r,o,a,s,c));for(var h=0,d=l;h<d.length;h++){var f=d[h];u.push(this.beginDirectAnimation(f,i,n,r,o,a,s,c))}return u},K.a.prototype.getAnimatableByTarget=function(e){for(var t=0;t<this._activeAnimatables.length;t++)if(this._activeAnimatables[t].target===e)return this._activeAnimatables[t];return null},K.a.prototype.getAllAnimatablesByTarget=function(e){for(var t=[],i=0;i<this._activeAnimatables.length;i++)this._activeAnimatables[i].target===e&&t.push(this._activeAnimatables[i]);return t},K.a.prototype.stopAnimation=function(e,t,i){for(var n=0,r=this.getAllAnimatablesByTarget(e);n<r.length;n++){r[n].stop(t,i)}},K.a.prototype.stopAllAnimations=function(){if(this._activeAnimatables){for(var e=0;e<this._activeAnimatables.length;e++)this._activeAnimatables[e].stop();this._activeAnimatables=[]}for(var t=0,i=this.animationGroups;t<i.length;t++){i[t].stop()}},K.a.prototype._registerTargetForLateAnimationBinding=function(e,t){var i=e.target;this._registeredForLateAnimationBindings.pushNoDuplicate(i),i._lateAnimationHolders||(i._lateAnimationHolders={}),i._lateAnimationHolders[e.targetPath]||(i._lateAnimationHolders[e.targetPath]={totalWeight:0,animations:[],originalValue:t}),i._lateAnimationHolders[e.targetPath].animations.push(e),i._lateAnimationHolders[e.targetPath].totalWeight+=e.weight},K.a.prototype._processLateAnimationBindingsForMatrices=function(e){var t=1,i=a.c.Vector3[0],n=a.c.Vector3[1],r=a.c.Quaternion[0],o=0,s=e.animations[0],c=e.originalValue,l=1;if(e.totalWeight<1)c.decompose(n,r,i),l=1-e.totalWeight;else if(o=1,t=e.totalWeight,s.currentValue.decompose(n,r,i),1==(l=s.weight/t))return s.currentValue;n.scaleInPlace(l),i.scaleInPlace(l),r.scaleInPlace(l);for(var u=o;u<e.animations.length;u++){var h=e.animations[u],d=(l=h.weight/t,a.c.Vector3[2]),f=a.c.Vector3[3],p=a.c.Quaternion[1];h.currentValue.decompose(f,p,d),f.scaleAndAddToRef(l,n),p.scaleAndAddToRef(l,r),d.scaleAndAddToRef(l,i)}var _=s._animationState.workValue;return a.a.ComposeToRef(n,r,i,_),_},K.a.prototype._processLateAnimationBindingsForQuaternions=function(e,t){var i=e.animations[0],n=e.originalValue;if(1===e.animations.length)return a.b.SlerpToRef(n,i.currentValue,Math.min(1,e.totalWeight),t),t;var r,o,s=1;if(e.totalWeight<1){var c=1-e.totalWeight;o=[],(r=[]).push(n),o.push(c)}else{if(2===e.animations.length)return a.b.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),t;r=[],o=[],s=e.totalWeight}for(var l=0;l<e.animations.length;l++){var u=e.animations[l];r.push(u.currentValue),o.push(u.weight/s)}for(var h=0,d=null,f=0;f<r.length;)d?(h+=o[f],a.b.SlerpToRef(d,r[f],o[f]/h,d),f++):(a.b.SlerpToRef(r[f],r[f+1],o[f+1]/(o[f]+o[f+1]),t),d=t,h=o[f]+o[f+1],f+=2);return d},K.a.prototype._processLateAnimationBindings=function(){if(this._registeredForLateAnimationBindings.length){for(var e=0;e<this._registeredForLateAnimationBindings.length;e++){var t=this._registeredForLateAnimationBindings.data[e];for(var i in t._lateAnimationHolders){var n=t._lateAnimationHolders[i],r=n.animations[0],o=n.originalValue,s=k.AllowMatrixDecomposeForInterpolation&&o.m,c=t[i];if(s)c=this._processLateAnimationBindingsForMatrices(n);else if(void 0!==o.w)c=this._processLateAnimationBindingsForQuaternions(n,c||a.b.Identity());else{var l=0,u=1;if(n.totalWeight<1)c=o.scale?o.scale(1-n.totalWeight):o*(1-n.totalWeight);else{u=n.totalWeight;var h=r.weight/u;c=1!==h?r.currentValue.scale?r.currentValue.scale(h):r.currentValue*h:r.currentValue,l=1}for(var d=l;d<n.animations.length;d++){var f=n.animations[d],p=f.weight/u;f.currentValue.scaleAndAddToRef?f.currentValue.scaleAndAddToRef(p,c):c+=f.currentValue*p}}t[i]=c}t._lateAnimationHolders={}}this._registeredForLateAnimationBindings.reset()}},J.prototype.copyAnimationRange=function(e,t,i,n,r){void 0===n&&(n=!1),void 0===r&&(r=null),0===this.animations.length&&(this.animations.push(new k(this.name,"_matrix",e.animations[0].framePerSecond,k.ANIMATIONTYPE_MATRIX,0)),this.animations[0].setKeys([]));var o=e.animations[0].getRange(t);if(!o)return!1;for(var a,s,c,l=o.from,u=o.to,h=e.animations[0].getKeys(),d=e.length,f=e.getParent(),p=this.getParent(),_=n&&f&&d&&this.length&&d!==this.length,m=_&&p&&f?p.length/f.length:1,g=n&&!p&&r&&(1!==r.x||1!==r.y||1!==r.z),v=this.animations[0].getKeys(),y=0,b=h.length;y<b;y++)(a=h[y]).frame>=l&&a.frame<=u&&(n?(c=a.value.clone(),_?(s=c.getTranslation(),c.setTranslation(s.scaleInPlace(m))):g&&r?(s=c.getTranslation(),c.setTranslation(s.multiplyInPlace(r))):c=a.value):c=a.value,v.push({frame:a.frame+i,value:c}));return this.animations[0].createRange(t,l+i,u+i),!0};var ee,te=function(){function e(){}return e.prototype.serialize=function(){var e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e},e}(),ie=function(){function e(e,t){void 0===t&&(t=null),this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this.onAnimationEndObservable=new o.c,this.onAnimationLoopObservable=new o.c,this.onAnimationGroupLoopObservable=new o.c,this.onAnimationGroupEndObservable=new o.c,this.onAnimationGroupPauseObservable=new o.c,this.onAnimationGroupPlayObservable=new o.c,this._scene=t||R.a.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._scene.animationGroups.push(this)}return Object.defineProperty(e.prototype,"from",{get:function(){return this._from},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"to",{get:function(){return this._to},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isStarted",{get:function(){return this._isStarted},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isPlaying",{get:function(){return this._isStarted&&!this._isPaused},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"speedRatio",{get:function(){return this._speedRatio},set:function(e){if(this._speedRatio!==e){this._speedRatio=e;for(var t=0;t<this._animatables.length;t++){this._animatables[t].speedRatio=this._speedRatio}}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"loopAnimation",{get:function(){return this._loopAnimation},set:function(e){if(this._loopAnimation!==e){this._loopAnimation=e;for(var t=0;t<this._animatables.length;t++){this._animatables[t].loopAnimation=this._loopAnimation}}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"targetedAnimations",{get:function(){return this._targetedAnimations},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"animatables",{get:function(){return this._animatables},enumerable:!0,configurable:!0}),e.prototype.addTargetedAnimation=function(e,t){var i=new te;i.animation=e,i.target=t;var n=e.getKeys();return this._from>n[0].frame&&(this._from=n[0].frame),this._to<n[n.length-1].frame&&(this._to=n[n.length-1].frame),this._targetedAnimations.push(i),i},e.prototype.normalize=function(e,t){void 0===e&&(e=null),void 0===t&&(t=null),null==e&&(e=this._from),null==t&&(t=this._to);for(var i=0;i<this._targetedAnimations.length;i++){var n=this._targetedAnimations[i].animation.getKeys(),r=n[0],o=n[n.length-1];if(r.frame>e){var a={frame:e,value:r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation};n.splice(0,0,a)}if(o.frame<t){a={frame:t,value:o.value,inTangent:o.outTangent,outTangent:o.outTangent,interpolation:o.interpolation};n.push(a)}}return this._from=e,this._to=t,this},e.prototype._processLoop=function(e,t,i){var n=this;e.onAnimationLoop=function(){n.onAnimationLoopObservable.notifyObservers(t),n._animationLoopFlags[i]||(n._animationLoopFlags[i]=!0,n._animationLoopCount++,n._animationLoopCount===n._targetedAnimations.length&&(n.onAnimationGroupLoopObservable.notifyObservers(n),n._animationLoopCount=0,n._animationLoopFlags=[]))}},e.prototype.start=function(e,t,i,n){var r=this;if(void 0===e&&(e=!1),void 0===t&&(t=1),this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags=[];for(var o=function(){var o=a._targetedAnimations[s],c=a._scene.beginDirectAnimation(o.target,[o.animation],void 0!==i?i:a._from,void 0!==n?n:a._to,e,t);c.onAnimationEnd=function(){r.onAnimationEndObservable.notifyObservers(o),r._checkAnimationGroupEnded(c)},a._processLoop(c,o,s),a._animatables.push(c)},a=this,s=0;s<this._targetedAnimations.length;s++)o();if(this._speedRatio=t,void 0!==i&&void 0!==n)if(i<n&&this._speedRatio<0){var c=n;n=i,i=c}else i>n&&this._speedRatio>0&&(this._speedRatio=-t);return this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this},e.prototype.pause=function(){if(!this._isStarted)return this;this._isPaused=!0;for(var e=0;e<this._animatables.length;e++){this._animatables[e].pause()}return this.onAnimationGroupPauseObservable.notifyObservers(this),this},e.prototype.play=function(e){return this.isStarted&&this._animatables.length===this._targetedAnimations.length?(void 0!==e&&(this.loopAnimation=e),this.restart()):(this.stop(),this.start(e,this._speedRatio)),this._isPaused=!1,this},e.prototype.reset=function(){if(!this._isStarted)return this;for(var e=0;e<this._animatables.length;e++){this._animatables[e].reset()}return this},e.prototype.restart=function(){if(!this._isStarted)return this;for(var e=0;e<this._animatables.length;e++){this._animatables[e].restart()}return this.onAnimationGroupPlayObservable.notifyObservers(this),this},e.prototype.stop=function(){if(!this._isStarted)return this;for(var e=this._animatables.slice(),t=0;t<e.length;t++)e[t].stop();return this._isStarted=!1,this},e.prototype.setWeightForAllAnimatables=function(e){for(var t=0;t<this._animatables.length;t++){this._animatables[t].weight=e}return this},e.prototype.syncAllAnimationsWith=function(e){for(var t=0;t<this._animatables.length;t++){this._animatables[t].syncWith(e)}return this},e.prototype.goToFrame=function(e){if(!this._isStarted)return this;for(var t=0;t<this._animatables.length;t++){this._animatables[t].goToFrame(e)}return this},e.prototype.dispose=function(){this._targetedAnimations=[],this._animatables=[];var e=this._scene.animationGroups.indexOf(this);e>-1&&this._scene.animationGroups.splice(e,1),this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()},e.prototype._checkAnimationGroupEnded=function(e){var t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))},e.prototype.clone=function(t,i){for(var n=new e(t||this.name,this._scene),r=0,o=this._targetedAnimations;r<o.length;r++){var a=o[r];n.addTargetedAnimation(a.animation.clone(),i?i(a.target):a.target)}return n},e.prototype.serialize=function(){var e={};e.name=this.name,e.from=this.from,e.to=this.to,e.targetedAnimations=[];for(var t=0;t<this.targetedAnimations.length;t++){var i=this.targetedAnimations[t];e.targetedAnimations[t]=i.serialize()}return e},e.Parse=function(t,i){for(var n=new e(t.name,i),r=0;r<t.targetedAnimations.length;r++){var o=t.targetedAnimations[r],a=k.Parse(o.animation),s=o.targetId;if("influence"===o.animation.property){var c=i.getMorphTargetById(s);c&&n.addTargetedAnimation(a,c)}else{var l=i.getNodeByID(s);null!=l&&n.addTargetedAnimation(a,l)}}return null!==t.from&&null!==t.to&&n.normalize(t.from,t.to),n},e.prototype.getClassName=function(){return"AnimationGroup"},e.prototype.toString=function(e){var t="Name: "+this.name;return t+=", type: "+this.getClassName(),e&&(t+=", from: "+this._from,t+=", to: "+this._to,t+=", isStarted: "+this._isStarted,t+=", speedRatio: "+this._speedRatio,t+=", targetedAnimations length: "+this._targetedAnimations.length,t+=", animatables length: "+this._animatables),t},e}(),ne=function(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=k.ANIMATIONLOOPMODE_CYCLE},re=i(28);!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(ee||(ee={}));var oe=function(){function e(){}return e.Interpolate=function(e,t,i,n,r){for(var o=1-3*n+3*t,a=3*n-6*t,s=3*t,c=e,l=0;l<5;l++){var u=c*c;c-=(o*(u*c)+a*u+s*c-e)*(1/(3*o*u+2*a*c+s)),c=Math.min(1,Math.max(0,c))}return 3*Math.pow(1-c,2)*c*i+3*(1-c)*Math.pow(c,2)*r+Math.pow(c,3)},e}(),ae=function(){function e(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}return e.prototype.degrees=function(){return 180*this._radians/Math.PI},e.prototype.radians=function(){return this._radians},e.BetweenTwoPoints=function(t,i){var n=i.subtract(t);return new e(Math.atan2(n.y,n.x))},e.FromRadians=function(t){return new e(t)},e.FromDegrees=function(t){return new e(t*Math.PI/180)},e}(),se=function(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;var n=Math.pow(t.x,2)+Math.pow(t.y,2),r=(Math.pow(e.x,2)+Math.pow(e.y,2)-n)/2,o=(n-Math.pow(i.x,2)-Math.pow(i.y,2))/2,s=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new a.d((r*(t.y-i.y)-o*(e.y-t.y))/s,((e.x-t.x)*o-(t.x-i.x)*r)/s),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=ae.BetweenTwoPoints(this.centerPoint,this.startPoint);var c=this.startAngle.degrees(),l=ae.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),u=ae.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-c>180&&(l-=360),l-c<-180&&(l+=360),u-l>180&&(u-=360),u-l<-180&&(u+=360),this.orientation=l-c<0?ee.CW:ee.CCW,this.angle=ae.FromDegrees(this.orientation===ee.CW?c-u:u-c)},ce=function(){function e(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new a.d(e,t))}return e.prototype.addLineTo=function(e,t){if(this.closed)return this;var i=new a.d(e,t),n=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(n).length(),this},e.prototype.addArcTo=function(e,t,i,n,r){if(void 0===r&&(r=36),this.closed)return this;var o=this._points[this._points.length-1],s=new a.d(e,t),c=new a.d(i,n),l=new se(o,s,c),u=l.angle.radians()/r;l.orientation===ee.CW&&(u*=-1);for(var h=l.startAngle.radians()+u,d=0;d<r;d++){var f=Math.cos(h)*l.radius+l.centerPoint.x,p=Math.sin(h)*l.radius+l.centerPoint.y;this.addLineTo(f,p),h+=u}return this},e.prototype.close=function(){return this.closed=!0,this},e.prototype.length=function(){var e=this._length;if(this.closed){var t=this._points[this._points.length-1];e+=this._points[0].subtract(t).length()}return e},e.prototype.getPoints=function(){return this._points},e.prototype.getPointAtLengthPosition=function(e){if(e<0||e>1)return a.d.Zero();for(var t=e*this.length(),i=0,n=0;n<this._points.length;n++){var r=(n+1)%this._points.length,o=this._points[n],s=this._points[r].subtract(o),c=s.length()+i;if(t>=i&&t<=c){var l=s.normalize(),u=t-i;return new a.d(o.x+l.x*u,o.y+l.y*u)}i=c}return a.d.Zero()},e.StartingAt=function(t,i){return new e(t,i)},e}(),le=function(){function e(e,t,i,n){void 0===t&&(t=null),void 0===n&&(n=!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:a.e.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:a.a.Identity()};for(var r=0;r<e.length;r++)this._curve[r]=e[r].clone();this._raw=i||!1,this._alignTangentsWithPath=n,this._compute(t,n)}return e.prototype.getCurve=function(){return this._curve},e.prototype.getPoints=function(){return this._curve},e.prototype.length=function(){return this._distances[this._distances.length-1]},e.prototype.getTangents=function(){return this._tangents},e.prototype.getNormals=function(){return this._normals},e.prototype.getBinormals=function(){return this._binormals},e.prototype.getDistances=function(){return this._distances},e.prototype.getPointAt=function(e){return this._updatePointAtData(e).point},e.prototype.getTangentAt=function(e,t){return void 0===t&&(t=!1),this._updatePointAtData(e,t),t?a.e.TransformCoordinates(a.e.Forward(),this._pointAtData.interpolationMatrix):this._tangents[this._pointAtData.previousPointArrayIndex]},e.prototype.getNormalAt=function(e,t){return void 0===t&&(t=!1),this._updatePointAtData(e,t),t?a.e.TransformCoordinates(a.e.Right(),this._pointAtData.interpolationMatrix):this._normals[this._pointAtData.previousPointArrayIndex]},e.prototype.getBinormalAt=function(e,t){return void 0===t&&(t=!1),this._updatePointAtData(e,t),t?a.e.TransformCoordinates(a.e.UpReadOnly,this._pointAtData.interpolationMatrix):this._binormals[this._pointAtData.previousPointArrayIndex]},e.prototype.getDistanceAt=function(e){return this.length()*e},e.prototype.getPreviousPointIndexAt=function(e){return this._updatePointAtData(e),this._pointAtData.previousPointArrayIndex},e.prototype.getSubPositionAt=function(e){return this._updatePointAtData(e),this._pointAtData.subPosition},e.prototype.getClosestPositionTo=function(e){for(var t=Number.MAX_VALUE,i=0,n=0;n<this._curve.length-1;n++){var r=this._curve[n+0],o=this._curve[n+1].subtract(r).normalize(),s=this._distances[n+1]-this._distances[n+0],c=Math.min(Math.max(a.e.Dot(o,e.subtract(r).normalize()),0)*a.e.Distance(r,e)/s,1),l=a.e.Distance(r.add(o.scale(c*s)),e);l<t&&(t=l,i=(this._distances[n+0]+s*c)/this.length())}return i},e.prototype.slice=function(t,i){if(void 0===t&&(t=0),void 0===i&&(i=1),t<0&&(t=1- -1*t%1),i<0&&(i=1- -1*i%1),t>i){var n=t;t=i,i=n}var r=this.getCurve(),o=this.getPointAt(t),a=this.getPreviousPointIndexAt(t),s=this.getPointAt(i),c=this.getPreviousPointIndexAt(i)+1,l=[];return 0!==t&&(a++,l.push(o)),l.push.apply(l,r.slice(a,c)),1===i&&1!==t||l.push(s),new e(l,this.getNormalAt(t),this._raw,this._alignTangentsWithPath)},e.prototype.update=function(e,t,i){void 0===t&&(t=null),void 0===i&&(i=!1);for(var n=0;n<e.length;n++)this._curve[n].x=e[n].x,this._curve[n].y=e[n].y,this._curve[n].z=e[n].z;return this._compute(t,i),this},e.prototype._compute=function(e,t){void 0===t&&(t=!1);var i=this._curve.length;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();var n,r,o,s,c,l=this._tangents[0],u=this._normalVector(l,e);this._normals[0]=u,this._raw||this._normals[0].normalize(),this._binormals[0]=a.e.Cross(l,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var h=1;h<i;h++)n=this._getLastNonNullVector(h),h<i-1&&(r=this._getFirstNonNullVector(h),this._tangents[h]=t?r:n.add(r),this._tangents[h].normalize()),this._distances[h]=this._distances[h-1]+n.length(),o=this._tangents[h],c=this._binormals[h-1],this._normals[h]=a.e.Cross(c,o),this._raw||(0===this._normals[h].length()?(s=this._normals[h-1],this._normals[h]=s.clone()):this._normals[h].normalize()),this._binormals[h]=a.e.Cross(o,this._normals[h]),this._raw||this._binormals[h].normalize();this._pointAtData.id=NaN},e.prototype._getFirstNonNullVector=function(e){for(var t=1,i=this._curve[e+t].subtract(this._curve[e]);0===i.length()&&e+t+1<this._curve.length;)t++,i=this._curve[e+t].subtract(this._curve[e]);return i},e.prototype._getLastNonNullVector=function(e){for(var t=1,i=this._curve[e].subtract(this._curve[e-t]);0===i.length()&&e>t+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i},e.prototype._normalVector=function(e,t){var i,n,r=e.length();(0===r&&(r=1),null==t)?(n=L.a.WithinEpsilon(Math.abs(e.y)/r,1,re.a)?L.a.WithinEpsilon(Math.abs(e.x)/r,1,re.a)?L.a.WithinEpsilon(Math.abs(e.z)/r,1,re.a)?a.e.Zero():new a.e(0,0,1):new a.e(1,0,0):new a.e(0,-1,0),i=a.e.Cross(e,n)):(i=a.e.Cross(e,t),a.e.CrossToRef(i,e,i));return i.normalize(),i},e.prototype._updatePointAtData=function(e,t){if(void 0===t&&(t=!1),this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;var 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);for(var n,r=i[0],o=0,s=e*this.length(),c=1;c<i.length;c++){n=i[c];var l=a.e.Distance(r,n);if((o+=l)===s)return this._setPointAtData(e,1,n,c,t);if(o>s){var u=(o-s)/l,h=r.subtract(n),d=n.add(h.scaleInPlace(u));return this._setPointAtData(e,1-u,d,c-1,t)}r=n}return this._pointAtData},e.prototype._setPointAtData=function(e,t,i,n,r){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=n,this._pointAtData.interpolateReady=r,r&&this._updateInterpolationMatrix(),this._pointAtData},e.prototype._updateInterpolationMatrix=function(){this._pointAtData.interpolationMatrix=a.a.Identity();var e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){var t=e+1,i=this._tangents[e].clone(),n=this._normals[e].clone(),r=this._binormals[e].clone(),o=this._tangents[t].clone(),s=this._normals[t].clone(),c=this._binormals[t].clone(),l=a.b.RotationQuaternionFromAxis(n,r,i),u=a.b.RotationQuaternionFromAxis(s,c,o);a.b.Slerp(l,u,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}},e}(),ue=function(){function e(e){this._length=0,this._points=e,this._length=this._computeLength(e)}return e.CreateQuadraticBezier=function(t,i,n,r){r=r>2?r:3;for(var o=new Array,s=function(e,t,i,n){return(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*n},c=0;c<=r;c++)o.push(new a.e(s(c/r,t.x,i.x,n.x),s(c/r,t.y,i.y,n.y),s(c/r,t.z,i.z,n.z)));return new e(o)},e.CreateCubicBezier=function(t,i,n,r,o){o=o>3?o:4;for(var s=new Array,c=function(e,t,i,n,r){return(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*n+e*e*e*r},l=0;l<=o;l++)s.push(new a.e(c(l/o,t.x,i.x,n.x,r.x),c(l/o,t.y,i.y,n.y,r.y),c(l/o,t.z,i.z,n.z,r.z)));return new e(s)},e.CreateHermiteSpline=function(t,i,n,r,o){for(var s=new Array,c=1/o,l=0;l<=o;l++)s.push(a.e.Hermite(t,i,n,r,l*c));return new e(s)},e.CreateCatmullRomSpline=function(t,i,n){var r=new Array,o=1/i,s=0;if(n){for(var c=t.length,l=0;l<c;l++){s=0;for(var u=0;u<i;u++)r.push(a.e.CatmullRom(t[l%c],t[(l+1)%c],t[(l+2)%c],t[(l+3)%c],s)),s+=o}r.push(r[0])}else{var h=new Array;h.push(t[0].clone()),Array.prototype.push.apply(h,t),h.push(t[t.length-1].clone());for(l=0;l<h.length-3;l++){s=0;for(u=0;u<i;u++)r.push(a.e.CatmullRom(h[l],h[l+1],h[l+2],h[l+3],s)),s+=o}l--,r.push(a.e.CatmullRom(h[l],h[l+1],h[l+2],h[l+3],s))}return new e(r)},e.prototype.getPoints=function(){return this._points},e.prototype.length=function(){return this._length},e.prototype.continue=function(t){for(var i=this._points[this._points.length-1],n=this._points.slice(),r=t.getPoints(),o=1;o<r.length;o++)n.push(r[o].subtract(r[0]).add(i));return new e(n)},e.prototype._computeLength=function(e){for(var t=0,i=1;i<e.length;i++)t+=e[i].subtract(e[i-1]).length();return t},e}(),he=function(){function e(){this._easingMode=e.EASINGMODE_EASEIN}return e.prototype.setEasingMode=function(e){var t=Math.min(Math.max(e,0),2);this._easingMode=t},e.prototype.getEasingMode=function(){return this._easingMode},e.prototype.easeInCore=function(e){throw new Error("You must implement this method")},e.prototype.ease=function(t){switch(this._easingMode){case e.EASINGMODE_EASEIN:return this.easeInCore(t);case e.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-t)}return t>=.5?.5*(1-this.easeInCore(2*(1-t)))+.5:.5*this.easeInCore(2*t)},e.EASINGMODE_EASEIN=0,e.EASINGMODE_EASEOUT=1,e.EASINGMODE_EASEINOUT=2,e}(),de=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t.prototype.easeInCore=function(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)},t}(he),fe=function(e){function t(t){void 0===t&&(t=1);var i=e.call(this)||this;return i.amplitude=t,i}return Object(h.d)(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)},t}(he),pe=function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=2);var n=e.call(this)||this;return n.bounces=t,n.bounciness=i,n}return Object(h.d)(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.bounces),i=this.bounciness;i<=1&&(i=1.001);var n=Math.pow(i,t),r=1-i,o=(1-n)/r+.5*n,a=e*o,s=Math.log(-a*(1-i)+1)/Math.log(i),c=Math.floor(s),l=c+1,u=(1-Math.pow(i,c))/(r*o),h=.5*(u+(1-Math.pow(i,l))/(r*o)),d=e-h,f=h-u;return-Math.pow(1/i,t-c)/(f*f)*(d-f)*(d+f)},t}(he),_e=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t.prototype.easeInCore=function(e){return e*e*e},t}(he),me=function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=3);var n=e.call(this)||this;return n.oscillations=t,n.springiness=i,n}return Object(h.d)(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.oscillations),i=Math.max(0,this.springiness);return(0==i?e:(Math.exp(i*e)-1)/(Math.exp(i)-1))*Math.sin((6.283185307179586*t+1.5707963267948966)*e)},t}(he),ge=function(e){function t(t){void 0===t&&(t=2);var i=e.call(this)||this;return i.exponent=t,i}return Object(h.d)(t,e),t.prototype.easeInCore=function(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)},t}(he),ve=function(e){function t(t){void 0===t&&(t=2);var i=e.call(this)||this;return i.power=t,i}return Object(h.d)(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.power);return Math.pow(e,t)},t}(he),ye=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t.prototype.easeInCore=function(e){return e*e},t}(he),be=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t.prototype.easeInCore=function(e){return e*e*e*e},t}(he),Te=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t.prototype.easeInCore=function(e){return e*e*e*e*e},t}(he),Ee=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t.prototype.easeInCore=function(e){return 1-Math.sin(1.5707963267948966*(1-e))},t}(he),xe=function(e){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=1),void 0===r&&(r=1);var o=e.call(this)||this;return o.x1=t,o.y1=i,o.x2=n,o.y2=r,o}return Object(h.d)(t,e),t.prototype.easeInCore=function(e){return oe.Interpolate(e,this.x1,this.y1,this.x2,this.y2)},t}(he),Pe=function(){function e(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}return e.prototype._clone=function(){return new e(this.frame,this.action,this.onlyOnce)},e}(),Ae=i(5),Se=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t}(n.a),Ce=function(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]},Re=function(e){function t(t){var i=e.call(this)||this;return i._wasAddedToScene=!1,i.scene=t,i.sounds=[],i.effectLayers=[],i.layers=[],i.lensFlareSystems=[],i.proceduralTextures=[],i.reflectionProbes=[],t.onDisposeObservable.add(function(){i._wasAddedToScene||i.dispose()}),i}return Object(h.d)(t,e),t.prototype.instantiateModelsToScene=function(e,t){var i=this;void 0===t&&(t=!1);var n={},r={},o=new Ce,a=[],s=[],c={doNotInstantiate:!0},l=function(t,i){if(n[t.uniqueId]=i.uniqueId,r[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof Ae.a){var o=i;if(o.morphTargetManager){var a=t.morphTargetManager;o.morphTargetManager=a.clone();for(var s=0;s<a.numTargets;s++){var c=a.getTarget(s),l=o.morphTargetManager.getTarget(s);n[c.uniqueId]=l.uniqueId,r[l.uniqueId]=l}}}};return this.transformNodes.forEach(function(e){if(!e.parent){var t=e.instantiateHierarchy(null,c,function(e,t){l(e,t)});t&&o.rootNodes.push(t)}}),this.meshes.forEach(function(a){if(!a.parent){var u=a.instantiateHierarchy(null,c,function(o,a){if(l(o,a),a.material){var c=a;if(c.material)if(t){var u=o.material;if(-1===s.indexOf(u)){var h=u.clone(e?e(u.name):"Clone of "+u.name);if(s.push(u),n[u.uniqueId]=h.uniqueId,r[h.uniqueId]=h,"MultiMaterial"===u.getClassName())for(var d=0,f=u.subMaterials;d<f.length;d++){var p=f[d];p&&(h=p.clone(e?e(p.name):"Clone of "+p.name),s.push(p),n[p.uniqueId]=h.uniqueId,r[h.uniqueId]=h)}}c.material=r[n[u.uniqueId]]}else"MultiMaterial"===c.material.getClassName()?-1===i.scene.multiMaterials.indexOf(c.material)&&i.scene.addMultiMaterial(c.material):-1===i.scene.materials.indexOf(c.material)&&i.scene.addMaterial(c.material)}});u&&o.rootNodes.push(u)}}),this.skeletons.forEach(function(t){var s=t.clone(e?e(t.name):"Clone of "+t.name);t.overrideMesh&&(s.overrideMesh=r[n[t.overrideMesh.uniqueId]]);for(var c=0,l=i.meshes;c<l.length;c++){var u=l[c];if(u.skeleton===t&&!u.isAnInstance){if(r[n[u.uniqueId]].skeleton=s,-1!==a.indexOf(s))continue;a.push(s);for(var h=0,d=s.bones;h<d.length;h++){var f=d[h];f._linkedTransformNode&&(f._linkedTransformNode=r[n[f._linkedTransformNode.uniqueId]])}}}o.skeletons.push(s)}),this.animationGroups.forEach(function(e){var t=e.clone(e.name,function(e){return r[n[e.uniqueId]]||e});o.animationGroups.push(t)}),o},t.prototype.addAllToScene=function(){var e=this;this._wasAddedToScene=!0,this.cameras.forEach(function(t){e.scene.addCamera(t)}),this.lights.forEach(function(t){e.scene.addLight(t)}),this.meshes.forEach(function(t){e.scene.addMesh(t)}),this.skeletons.forEach(function(t){e.scene.addSkeleton(t)}),this.animations.forEach(function(t){e.scene.addAnimation(t)}),this.animationGroups.forEach(function(t){e.scene.addAnimationGroup(t)}),this.multiMaterials.forEach(function(t){e.scene.addMultiMaterial(t)}),this.materials.forEach(function(t){e.scene.addMaterial(t)}),this.morphTargetManagers.forEach(function(t){e.scene.addMorphTargetManager(t)}),this.geometries.forEach(function(t){e.scene.addGeometry(t)}),this.transformNodes.forEach(function(t){e.scene.addTransformNode(t)}),this.actionManagers.forEach(function(t){e.scene.addActionManager(t)}),this.textures.forEach(function(t){e.scene.addTexture(t)}),this.reflectionProbes.forEach(function(t){e.scene.addReflectionProbe(t)}),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(var t=0,i=this.scene._serializableComponents;t<i.length;t++){i[t].addFromContainer(this)}},t.prototype.removeAllFromScene=function(){var e=this;this._wasAddedToScene=!1,this.cameras.forEach(function(t){e.scene.removeCamera(t)}),this.lights.forEach(function(t){e.scene.removeLight(t)}),this.meshes.forEach(function(t){e.scene.removeMesh(t)}),this.skeletons.forEach(function(t){e.scene.removeSkeleton(t)}),this.animations.forEach(function(t){e.scene.removeAnimation(t)}),this.animationGroups.forEach(function(t){e.scene.removeAnimationGroup(t)}),this.multiMaterials.forEach(function(t){e.scene.removeMultiMaterial(t)}),this.materials.forEach(function(t){e.scene.removeMaterial(t)}),this.morphTargetManagers.forEach(function(t){e.scene.removeMorphTargetManager(t)}),this.geometries.forEach(function(t){e.scene.removeGeometry(t)}),this.transformNodes.forEach(function(t){e.scene.removeTransformNode(t)}),this.actionManagers.forEach(function(t){e.scene.removeActionManager(t)}),this.textures.forEach(function(t){e.scene.removeTexture(t)}),this.reflectionProbes.forEach(function(t){e.scene.removeReflectionProbe(t)}),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(var t=0,i=this.scene._serializableComponents;t<i.length;t++){i[t].removeFromContainer(this)}},t.prototype.dispose=function(){this.cameras.forEach(function(e){e.dispose()}),this.cameras=[],this.lights.forEach(function(e){e.dispose()}),this.lights=[],this.meshes.forEach(function(e){e.dispose()}),this.meshes=[],this.skeletons.forEach(function(e){e.dispose()}),this.skeletons=[],this.animationGroups.forEach(function(e){e.dispose()}),this.animationGroups=[],this.multiMaterials.forEach(function(e){e.dispose()}),this.multiMaterials=[],this.materials.forEach(function(e){e.dispose()}),this.materials=[],this.geometries.forEach(function(e){e.dispose()}),this.geometries=[],this.transformNodes.forEach(function(e){e.dispose()}),this.transformNodes=[],this.actionManagers.forEach(function(e){e.dispose()}),this.actionManagers=[],this.textures.forEach(function(e){e.dispose()}),this.textures=[],this.reflectionProbes.forEach(function(e){e.dispose()}),this.reflectionProbes=[],this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(var e=0,t=this.scene._serializableComponents;e<t.length;e++){t[e].removeFromContainer(this,!0)}},t.prototype._moveAssets=function(e,t,i){if(e)for(var n=0,r=e;n<r.length;n++){var o=r[n],a=!0;if(i)for(var s=0,c=i;s<c.length;s++){if(o===c[s]){a=!1;break}}a&&t.push(o)}},t.prototype.moveAllFromScene=function(e){for(var t in this._wasAddedToScene=!1,void 0===e&&(e=new Se),this)this.hasOwnProperty(t)&&(this[t]=this[t]||("environmentTexture"===t?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.removeAllFromScene()},t.prototype.createRootMesh=function(){var e=new Ae.a("assetContainerRootMesh",this.scene);return this.meshes.forEach(function(t){t.parent||e.addChild(t)}),this.meshes.unshift(e),e},t.prototype.mergeAnimationsTo=function(e,t,i){if(void 0===e&&(e=R.a.LastCreatedScene),void 0===i&&(i=null),e){var n=i||function(t){return e.getBoneByName(t.name)||e.getNodeByName(t.name)};this.getNodes().forEach(function(e){var t=n(e);if(null!==t){for(var i=function(e){for(var i=0,n=t.animations.filter(function(t){return t.targetProperty===e.targetProperty});i<n.length;i++){var r=n[i],o=t.animations.indexOf(r,0);o>-1&&t.animations.splice(o,1)}},r=0,o=e.animations;r<o.length;r++){i(o[r])}t.animations=t.animations.concat(e.animations)}}),this.animationGroups.slice().forEach(function(e){e.clone(e.name,n),e.animatables.forEach(function(e){e.stop()})}),t.forEach(function(t){var i=n(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))})}else m.a.Error("No scene available to merge animations to")},t}(n.a),Oe=i(11),Me=function(){function e(e){this.SMOOTHING=.75,this.FFT_SIZE=512,this.BARGRAPHAMPLITUDE=256,this.DEBUGCANVASPOS={x:20,y:20},this.DEBUGCANVASSIZE={width:320,height:200},this._scene=e,this._audioEngine=Oe.a.audioEngine,this._audioEngine.canUseWebAudio&&this._audioEngine.audioContext&&(this._webAudioAnalyser=this._audioEngine.audioContext.createAnalyser(),this._webAudioAnalyser.minDecibels=-140,this._webAudioAnalyser.maxDecibels=0,this._byteFreqs=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._byteTime=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._floatFreqs=new Float32Array(this._webAudioAnalyser.frequencyBinCount))}return e.prototype.getFrequencyBinCount=function(){return this._audioEngine.canUseWebAudio?this._webAudioAnalyser.frequencyBinCount:0},e.prototype.getByteFrequencyData=function(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs)),this._byteFreqs},e.prototype.getByteTimeDomainData=function(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteTimeDomainData(this._byteTime)),this._byteTime},e.prototype.getFloatFrequencyData=function(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs)),this._floatFreqs},e.prototype.drawDebugCanvas=function(){var e=this;if(this._audioEngine.canUseWebAudio&&(this._debugCanvas||(this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=this.DEBUGCANVASSIZE.width,this._debugCanvas.height=this.DEBUGCANVASSIZE.height,this._debugCanvas.style.position="absolute",this._debugCanvas.style.top=this.DEBUGCANVASPOS.y+"px",this._debugCanvas.style.left=this.DEBUGCANVASPOS.x+"px",this._debugCanvasContext=this._debugCanvas.getContext("2d"),document.body.appendChild(this._debugCanvas),this._registerFunc=function(){e.drawDebugCanvas()},this._scene.registerBeforeRender(this._registerFunc)),this._registerFunc&&this._debugCanvasContext)){var t=this.getByteFrequencyData();this._debugCanvasContext.fillStyle="rgb(0, 0, 0)",this._debugCanvasContext.fillRect(0,0,this.DEBUGCANVASSIZE.width,this.DEBUGCANVASSIZE.height);for(var i=0;i<this.getFrequencyBinCount();i++){var n=t[i]/this.BARGRAPHAMPLITUDE,r=this.DEBUGCANVASSIZE.height*n,o=this.DEBUGCANVASSIZE.height-r-1,a=this.DEBUGCANVASSIZE.width/this.getFrequencyBinCount(),s=i/this.getFrequencyBinCount()*360;this._debugCanvasContext.fillStyle="hsl("+s+", 100%, 50%)",this._debugCanvasContext.fillRect(i*a,o,a,r)}}},e.prototype.stopDebugCanvas=function(){this._debugCanvas&&(this._registerFunc&&(this._scene.unregisterBeforeRender(this._registerFunc),this._registerFunc=null),document.body.removeChild(this._debugCanvas),this._debugCanvas=null,this._debugCanvasContext=null)},e.prototype.connectAudioNodes=function(e,t){this._audioEngine.canUseWebAudio&&(e.connect(this._webAudioAnalyser),this._webAudioAnalyser.connect(t))},e.prototype.dispose=function(){this._audioEngine.canUseWebAudio&&this._webAudioAnalyser.disconnect()},e}();Oe.a.AudioEngineFactory=function(e){return new Ie(e)};var Ie=function(){function e(e){var t=this;void 0===e&&(e=null),this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!0,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new o.c,this.onAudioLockedObservable=new o.c,this._tryToRun=!1,this._onResize=function(){t._moveButtonToTopLeft()},void 0===window.AudioContext&&void 0===window.webkitAudioContext||(window.AudioContext=window.AudioContext||window.webkitAudioContext,this.canUseWebAudio=!0);var i=document.createElement("audio");this._hostElement=e;try{i&&i.canPlayType&&i.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")&&(this.isMP3supported=!0)}catch(e){}try{i&&i.canPlayType&&i.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}return Object.defineProperty(e.prototype,"audioContext",{get:function(){return this._audioContextInitialized?this.unlocked||this._muteButton||this._displayMuteButton():this._initializeAudioContext(),this._audioContext},enumerable:!0,configurable:!0}),e.prototype.lock=function(){this._triggerSuspendedState()},e.prototype.unlock=function(){this._triggerRunningState()},e.prototype._resumeAudioContext=function(){var e;return this._audioContext.resume&&(e=this._audioContext.resume()),e||Promise.resolve()},e.prototype._initializeAudioContext=function(){try{this.canUseWebAudio&&(this._audioContext=new AudioContext,this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this._audioContext.destination),this._audioContextInitialized=!0,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,m.a.Error("Web Audio: "+e.message)}},e.prototype._triggerRunningState=function(){var e=this;this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then(function(){e._tryToRun=!1,e._muteButton&&e._hideMuteButton()}).catch(function(){e._tryToRun=!1,e.unlocked=!1}),this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this))},e.prototype._triggerSuspendedState=function(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()},e.prototype._displayMuteButton=function(){var e=this;if(!this.useCustomUnlockedButton&&!this._muteButton){this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";var t=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png")+");  background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",i=document.createElement("style");i.appendChild(document.createTextNode(t)),document.getElementsByTagName("head")[0].appendChild(i),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",function(){e._triggerRunningState()},!0),this._muteButton.addEventListener("click",function(){e._triggerRunningState()},!0),window.addEventListener("resize",this._onResize)}},e.prototype._moveButtonToTopLeft=function(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")},e.prototype._hideMuteButton=function(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)},e.prototype.dispose=function(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()},e.prototype.getGlobalVolume=function(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1},e.prototype.setGlobalVolume=function(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)},e.prototype.connectToAnalyser=function(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))},e}(),De=i(13),we=i(19),Le=function(){function e(t,i,n,r,s){var c=this;if(void 0===r&&(r=null),this.autoplay=!1,this.loop=!1,this.useCustomAttenuation=!1,this.isPlaying=!1,this.isPaused=!1,this.spatialSound=!1,this.refDistance=1,this.rolloffFactor=1,this.maxDistance=100,this.distanceModel="linear",this.onEndedObservable=new o.c,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._startOffset=0,this._position=a.e.Zero(),this._positionInEmitterSpace=!1,this._localDirection=new a.e(1,0,0),this._volume=1,this._isReadyToPlay=!1,this._isDirectional=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._coneOuterGain=0,this._isOutputConnected=!1,this._urlType="Unknown",this.name=t,this._scene=n,e._SceneComponentInitialization(n),this._readyToPlayCallback=r,this._customAttenuationFunction=function(e,t,i,n,r){return t<i?e*(1-t/i):0},s&&(this.autoplay=s.autoplay||!1,this.loop=s.loop||!1,void 0!==s.volume&&(this._volume=s.volume),this.spatialSound=s.spatialSound||!1,this.maxDistance=s.maxDistance||100,this.useCustomAttenuation=s.useCustomAttenuation||!1,this.rolloffFactor=s.rolloffFactor||1,this.refDistance=s.refDistance||1,this.distanceModel=s.distanceModel||"linear",this._playbackRate=s.playbackRate||1,this._streaming=s.streaming||!1,this._length=s.length,this._offset=s.offset),Oe.a.audioEngine.canUseWebAudio&&Oe.a.audioEngine.audioContext){this._soundGain=Oe.a.audioEngine.audioContext.createGain(),this._soundGain.gain.value=this._volume,this._inputAudioNode=this._soundGain,this._outputAudioNode=this._soundGain,this.spatialSound&&this._createSpatialParameters(),this._scene.mainSoundTrack.AddSound(this);var l=!0;if(i)try{"string"==typeof i?this._urlType="String":i instanceof ArrayBuffer?this._urlType="ArrayBuffer":i instanceof MediaStream?this._urlType="MediaStream":Array.isArray(i)&&(this._urlType="Array");var u=[],h=!1;switch(this._urlType){case"MediaStream":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=Oe.a.audioEngine.audioContext.createMediaStreamSource(i),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"ArrayBuffer":i.byteLength>0&&(h=!0,this._soundLoaded(i));break;case"String":u.push(i);case"Array":0===u.length&&(u=i);for(var d=0;d<u.length;d++){var f=u[d];if(h=s&&s.skipCodecCheck||-1!==f.indexOf(".mp3",f.length-4)&&Oe.a.audioEngine.isMP3supported||-1!==f.indexOf(".ogg",f.length-4)&&Oe.a.audioEngine.isOGGsupported||-1!==f.indexOf(".wav",f.length-4)||-1!==f.indexOf("blob:")){this._streaming?(this._htmlAudioElement=new Audio(f),this._htmlAudioElement.controls=!1,this._htmlAudioElement.loop=this.loop,De.b.SetCorsBehavior(f,this._htmlAudioElement),this._htmlAudioElement.preload="auto",this._htmlAudioElement.addEventListener("canplaythrough",function(){c._isReadyToPlay=!0,c.autoplay&&c.play(0,c._offset,c._length),c._readyToPlayCallback&&c._readyToPlayCallback()}),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(f,function(e){c._soundLoaded(e)},void 0,!0,!0,function(e){e&&m.a.Error("XHR "+e.status+" error on: "+f+"."),m.a.Error("Sound creation aborted."),c._scene.mainSoundTrack.RemoveSound(c)});break}}break;default:l=!1}l?h||(this._isReadyToPlay=!0,this._readyToPlayCallback&&window.setTimeout(function(){c._readyToPlayCallback&&c._readyToPlayCallback()},1e3)):m.a.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){m.a.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.RemoveSound(this)}}else this._scene.mainSoundTrack.AddSound(this),Oe.a.audioEngine.WarnedWebAudioUnsupported||(m.a.Error("Web Audio is not supported by your browser."),Oe.a.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&window.setTimeout(function(){c._readyToPlayCallback&&c._readyToPlayCallback()},1e3)}return e.prototype.dispose=function(){Oe.a.audioEngine.canUseWebAudio&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,-1===this.soundTrackId?this._scene.mainSoundTrack.RemoveSound(this):this._scene.soundTracks&&this._scene.soundTracks[this.soundTrackId].RemoveSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._streamingSource&&this._streamingSource.disconnect(),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null))},e.prototype.isReady=function(){return this._isReadyToPlay},e.prototype._soundLoaded=function(e){var t=this;Oe.a.audioEngine.audioContext&&Oe.a.audioEngine.audioContext.decodeAudioData(e,function(e){t._audioBuffer=e,t._isReadyToPlay=!0,t.autoplay&&t.play(0,t._offset,t._length),t._readyToPlayCallback&&t._readyToPlayCallback()},function(e){m.a.Error("Error while decoding audio data for: "+t.name+" / Error: "+e)})},e.prototype.setAudioBuffer=function(e){Oe.a.audioEngine.canUseWebAudio&&(this._audioBuffer=e,this._isReadyToPlay=!0)},e.prototype.updateOptions=function(e){e&&(this.loop=e.loop||this.loop,this.maxDistance=e.maxDistance||this.maxDistance,this.useCustomAttenuation=e.useCustomAttenuation||this.useCustomAttenuation,this.rolloffFactor=e.rolloffFactor||this.rolloffFactor,this.refDistance=e.refDistance||this.refDistance,this.distanceModel=e.distanceModel||this.distanceModel,this._playbackRate=e.playbackRate||this._playbackRate,this._length=e.length?e.length/1e3:void 0,this._offset=e.offset?e.offset/1e3:void 0,this._updateSpatialParameters(),this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate)))},e.prototype._createSpatialParameters=function(){Oe.a.audioEngine.canUseWebAudio&&Oe.a.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=Oe.a.audioEngine.audioContext.createPanner(),this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner)},e.prototype._updateSpatialParameters=function(){this.spatialSound&&this._soundPanner&&(this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel))},e.prototype.switchPanningModelToHRTF=function(){this._panningModel="HRTF",this._switchPanningModel()},e.prototype.switchPanningModelToEqualPower=function(){this._panningModel="equalpower",this._switchPanningModel()},e.prototype._switchPanningModel=function(){Oe.a.audioEngine.canUseWebAudio&&this.spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)},e.prototype.connectToSoundTrackAudioNode=function(e){Oe.a.audioEngine.canUseWebAudio&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)},e.prototype.setDirectionalCone=function(e,t,i){t<e?m.a.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."):(this._coneInnerAngle=e,this._coneOuterAngle=t,this._coneOuterGain=i,this._isDirectional=!0,this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length)))},Object.defineProperty(e.prototype,"directionalConeInnerAngle",{get:function(){return this._coneInnerAngle},set:function(e){if(e!=this._coneInnerAngle){if(this._coneOuterAngle<e)return void m.a.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneInnerAngle=e,Oe.a.audioEngine.canUseWebAudio&&this.spatialSound&&this._soundPanner&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle)}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"directionalConeOuterAngle",{get:function(){return this._coneOuterAngle},set:function(e){if(e!=this._coneOuterAngle){if(e<this._coneInnerAngle)return void m.a.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneOuterAngle=e,Oe.a.audioEngine.canUseWebAudio&&this.spatialSound&&this._soundPanner&&(this._soundPanner.coneOuterAngle=this._coneOuterAngle)}},enumerable:!0,configurable:!0}),e.prototype.setPosition=function(e){this._position=e,Oe.a.audioEngine.canUseWebAudio&&this.spatialSound&&this._soundPanner&&!isNaN(this._position.x)&&!isNaN(this._position.y)&&!isNaN(this._position.z)&&this._soundPanner.setPosition(this._position.x,this._position.y,this._position.z)},e.prototype.setLocalDirectionToMesh=function(e){this._localDirection=e,Oe.a.audioEngine.canUseWebAudio&&this._connectedTransformNode&&this.isPlaying&&this._updateDirection()},e.prototype._updateDirection=function(){if(this._connectedTransformNode&&this._soundPanner){var e=this._connectedTransformNode.getWorldMatrix(),t=a.e.TransformNormal(this._localDirection,e);t.normalize(),this._soundPanner.setOrientation(t.x,t.y,t.z)}},e.prototype.updateDistanceFromListener=function(){if(Oe.a.audioEngine.canUseWebAudio&&this._connectedTransformNode&&this.useCustomAttenuation&&this._soundGain&&this._scene.activeCamera){var e=this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);this._soundGain.gain.value=this._customAttenuationFunction(this._volume,e,this.maxDistance,this.refDistance,this.rolloffFactor)}},e.prototype.setAttenuationFunction=function(e){this._customAttenuationFunction=e},e.prototype.play=function(e,t,i){var n=this;if(this._isReadyToPlay&&this._scene.audioEnabled&&Oe.a.audioEngine.audioContext)try{this._startOffset<0&&(e=-this._startOffset,this._startOffset=0);var r=e?Oe.a.audioEngine.audioContext.currentTime+e:Oe.a.audioEngine.audioContext.currentTime;if(this._soundSource&&this._streamingSource||this.spatialSound&&this._soundPanner&&(isNaN(this._position.x)||isNaN(this._position.y)||isNaN(this._position.z)||this._soundPanner.setPosition(this._position.x,this._position.y,this._position.z),this._isDirectional&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle,this._soundPanner.coneOuterAngle=this._coneOuterAngle,this._soundPanner.coneOuterGain=this._coneOuterGain,this._connectedTransformNode?this._updateDirection():this._soundPanner.setOrientation(this._localDirection.x,this._localDirection.y,this._localDirection.z))),this._streaming){if(this._streamingSource||(this._streamingSource=Oe.a.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement),this._htmlAudioElement.onended=function(){n._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement)(o=function(){if(Oe.a.audioEngine.unlocked){var e=n._htmlAudioElement.play();void 0!==e&&e.catch(function(e){Oe.a.audioEngine.lock(),(n.loop||n.autoplay)&&Oe.a.audioEngine.onAudioUnlockedObservable.addOnce(function(){o()})})}else(n.loop||n.autoplay)&&Oe.a.audioEngine.onAudioUnlockedObservable.addOnce(function(){o()})})()}else{var o=function(){if(Oe.a.audioEngine.audioContext){i=i||n._length,t=t||n._offset,n._soundSource=Oe.a.audioEngine.audioContext.createBufferSource(),n._soundSource.buffer=n._audioBuffer,n._soundSource.connect(n._inputAudioNode),n._soundSource.loop=n.loop,void 0!==t&&(n._soundSource.loopStart=t),void 0!==i&&(n._soundSource.loopEnd=(0|t)+i),n._soundSource.playbackRate.value=n._playbackRate,n._soundSource.onended=function(){n._onended()},r=e?Oe.a.audioEngine.audioContext.currentTime+e:Oe.a.audioEngine.audioContext.currentTime;var o=n.isPaused?n._startOffset%n._soundSource.buffer.duration:t||0;n._soundSource.start(r,o,n.loop?void 0:i)}};"suspended"===Oe.a.audioEngine.audioContext.state?setTimeout(function(){"suspended"===Oe.a.audioEngine.audioContext.state?(Oe.a.audioEngine.lock(),(n.loop||n.autoplay)&&Oe.a.audioEngine.onAudioUnlockedObservable.addOnce(function(){o()})):o()},500):o()}this._startTime=r,this.isPlaying=!0,this.isPaused=!1}catch(e){m.a.Error("Error while trying to play audio: "+this.name+", "+e.message)}},e.prototype._onended=function(){this.isPlaying=!1,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)},e.prototype.stop=function(e){var t=this;if(this.isPlaying)if(this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if(Oe.a.audioEngine.audioContext&&this._soundSource){var i=e?Oe.a.audioEngine.audioContext.currentTime+e:Oe.a.audioEngine.audioContext.currentTime;this._soundSource.stop(i),this._soundSource.onended=function(){t.isPlaying=!1},this.isPaused||(this._startOffset=0)}},e.prototype.pause=function(){this.isPlaying&&(this.isPaused=!0,this._streaming?this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect():Oe.a.audioEngine.audioContext&&(this.stop(0),this._startOffset+=Oe.a.audioEngine.audioContext.currentTime-this._startTime))},e.prototype.setVolume=function(e,t){Oe.a.audioEngine.canUseWebAudio&&this._soundGain&&(t&&Oe.a.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(Oe.a.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,Oe.a.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,Oe.a.audioEngine.audioContext.currentTime+t)):this._soundGain.gain.value=e),this._volume=e},e.prototype.setPlaybackRate=function(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))},e.prototype.getVolume=function(){return this._volume},e.prototype.attachToMesh=function(e){var t=this;this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=e,this.spatialSound||(this.spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=function(e){return t._onRegisterAfterWorldMatrixUpdate(e)},this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)},e.prototype.detachFromMesh=function(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)},e.prototype._onRegisterAfterWorldMatrixUpdate=function(e){if(e.getBoundingInfo){var t=e;if(this._positionInEmitterSpace)t.worldMatrixFromCache.invertToRef(a.c.Matrix[0]),this.setPosition(a.c.Matrix[0].getTranslation());else{var i=t.getBoundingInfo();this.setPosition(i.boundingSphere.centerWorld)}Oe.a.audioEngine.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}},e.prototype.clone=function(){var t=this;if(this._streaming)return null;var i=function(){t._isReadyToPlay?(r._audioBuffer=t.getAudioBuffer(),r._isReadyToPlay=!0,r.autoplay&&r.play(0,t._offset,t._length)):window.setTimeout(i,300)},n={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},r=new e(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,n);return this.useCustomAttenuation&&r.setAttenuationFunction(this._customAttenuationFunction),r.setPosition(this._position),r.setPlaybackRate(this._playbackRate),i(),r},e.prototype.getAudioBuffer=function(){return this._audioBuffer},e.prototype.serialize=function(){var e={name:this.name,url:this.name,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId};return this.spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e},e.Parse=function(t,i,n,r){var o,s=t.name;o=t.url?n+t.url:n+s;var c,l={autoplay:t.autoplay,loop:t.loop,volume:t.volume,spatialSound:t.spatialSound,maxDistance:t.maxDistance,rolloffFactor:t.rolloffFactor,refDistance:t.refDistance,distanceModel:t.distanceModel,playbackRate:t.playbackRate};if(r){var u=function(){r._isReadyToPlay?(c._audioBuffer=r.getAudioBuffer(),c._isReadyToPlay=!0,c.autoplay&&c.play(0,c._offset,c._length)):window.setTimeout(u,300)};c=new e(s,new ArrayBuffer(0),i,null,l),u()}else c=new e(s,o,i,function(){i._removePendingData(c)},l),i._addPendingData(c);if(t.position){var h=a.e.FromArray(t.position);c.setPosition(h)}if(t.isDirectional&&(c.setDirectionalCone(t.coneInnerAngle||360,t.coneOuterAngle||360,t.coneOuterGain||0),t.localDirectionToMesh)){var d=a.e.FromArray(t.localDirectionToMesh);c.setLocalDirectionToMesh(d)}if(t.connectedMeshId){var f=i.getMeshByID(t.connectedMeshId);f&&c.attachToMesh(f)}return c},e._SceneComponentInitialization=function(e){throw we.a.WarnImport("AudioSceneComponent")},e}(),Ne=function(){function e(e,t){void 0===t&&(t={}),this.id=-1,this._isInitialized=!1,this._scene=e,this.soundCollection=new Array,this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}return e.prototype._initializeSoundTrackAudioGraph=function(){Oe.a.audioEngine.canUseWebAudio&&Oe.a.audioEngine.audioContext&&(this._outputAudioNode=Oe.a.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(Oe.a.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)},e.prototype.dispose=function(){if(Oe.a.audioEngine&&Oe.a.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}},e.prototype.AddSound=function(e){this._isInitialized||this._initializeSoundTrackAudioGraph(),Oe.a.audioEngine.canUseWebAudio&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.RemoveSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].RemoveSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id},e.prototype.RemoveSound=function(e){var t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)},e.prototype.setVolume=function(e){Oe.a.audioEngine.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)},e.prototype.switchPanningModelToHRTF=function(){if(Oe.a.audioEngine.canUseWebAudio)for(var e=0;e<this.soundCollection.length;e++)this.soundCollection[e].switchPanningModelToHRTF()},e.prototype.switchPanningModelToEqualPower=function(){if(Oe.a.audioEngine.canUseWebAudio)for(var e=0;e<this.soundCollection.length;e++)this.soundCollection[e].switchPanningModelToEqualPower()},e.prototype.connectToAnalyser=function(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser=e,Oe.a.audioEngine.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.disconnect(),this._connectedAnalyser.connectAudioNodes(this._outputAudioNode,Oe.a.audioEngine.masterGain))},e}(),Fe=i(17);n.a.AddParser(Fe.a.NAME_AUDIO,function(e,t,i,n){var r,o=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(var a=0,s=e.sounds.length;a<s;a++){var c=e.sounds[a];Oe.a.audioEngine.canUseWebAudio?(c.url||(c.url=c.name),o[c.url]?i.sounds.push(Le.Parse(c,t,n,o[c.url])):(r=Le.Parse(c,t,n),o[c.url]=r,i.sounds.push(r))):i.sounds.push(new Le(c.name,null,t))}o=[]}),Object.defineProperty(K.a.prototype,"mainSoundTrack",{get:function(){var e=this._getComponent(Fe.a.NAME_AUDIO);return e||(e=new Be(this),this._addComponent(e)),this._mainSoundTrack||(this._mainSoundTrack=new Ne(this,{mainTrack:!0})),this._mainSoundTrack},enumerable:!0,configurable:!0}),K.a.prototype.getSoundByName=function(e){var t;for(t=0;t<this.mainSoundTrack.soundCollection.length;t++)if(this.mainSoundTrack.soundCollection[t].name===e)return this.mainSoundTrack.soundCollection[t];if(this.soundTracks)for(var i=0;i<this.soundTracks.length;i++)for(t=0;t<this.soundTracks[i].soundCollection.length;t++)if(this.soundTracks[i].soundCollection[t].name===e)return this.soundTracks[i].soundCollection[t];return null},Object.defineProperty(K.a.prototype,"audioEnabled",{get:function(){var e=this._getComponent(Fe.a.NAME_AUDIO);return e||(e=new Be(this),this._addComponent(e)),e.audioEnabled},set:function(e){var t=this._getComponent(Fe.a.NAME_AUDIO);t||(t=new Be(this),this._addComponent(t)),e?t.enableAudio():t.disableAudio()},enumerable:!0,configurable:!0}),Object.defineProperty(K.a.prototype,"headphone",{get:function(){var e=this._getComponent(Fe.a.NAME_AUDIO);return e||(e=new Be(this),this._addComponent(e)),e.headphone},set:function(e){var t=this._getComponent(Fe.a.NAME_AUDIO);t||(t=new Be(this),this._addComponent(t)),e?t.switchAudioModeForHeadphones():t.switchAudioModeForNormalSpeakers()},enumerable:!0,configurable:!0}),Object.defineProperty(K.a.prototype,"audioListenerPositionProvider",{get:function(){var e=this._getComponent(Fe.a.NAME_AUDIO);return e||(e=new Be(this),this._addComponent(e)),e.audioListenerPositionProvider},set:function(e){var t=this._getComponent(Fe.a.NAME_AUDIO);if(t||(t=new Be(this),this._addComponent(t)),"function"!=typeof e)throw new Error("The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3");t.audioListenerPositionProvider=e},enumerable:!0,configurable:!0}),Object.defineProperty(K.a.prototype,"audioPositioningRefreshRate",{get:function(){var e=this._getComponent(Fe.a.NAME_AUDIO);return e||(e=new Be(this),this._addComponent(e)),e.audioPositioningRefreshRate},set:function(e){var t=this._getComponent(Fe.a.NAME_AUDIO);t||(t=new Be(this),this._addComponent(t)),t.audioPositioningRefreshRate=e},enumerable:!0,configurable:!0});var Be=function(){function e(e){this.name=Fe.a.NAME_AUDIO,this._audioEnabled=!0,this._headphone=!1,this.audioPositioningRefreshRate=500,this._audioListenerPositionProvider=null,this._cachedCameraDirection=new a.e,this._cachedCameraPosition=new a.e,this._lastCheck=0,this.scene=e,e.soundTracks=new Array,e.sounds=new Array}return Object.defineProperty(e.prototype,"audioEnabled",{get:function(){return this._audioEnabled},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"headphone",{get:function(){return this._headphone},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"audioListenerPositionProvider",{get:function(){return this._audioListenerPositionProvider},set:function(e){this._audioListenerPositionProvider=e},enumerable:!0,configurable:!0}),e.prototype.register=function(){this.scene._afterRenderStage.registerStep(Fe.a.STEP_AFTERRENDER_AUDIO,this,this._afterRender)},e.prototype.rebuild=function(){},e.prototype.serialize=function(e){if(e.sounds=[],this.scene.soundTracks)for(var t=0;t<this.scene.soundTracks.length;t++)for(var i=this.scene.soundTracks[t],n=0;n<i.soundCollection.length;n++)e.sounds.push(i.soundCollection[n].serialize())},e.prototype.addFromContainer=function(e){var t=this;e.sounds&&e.sounds.forEach(function(e){e.play(),e.autoplay=!0,t.scene.mainSoundTrack.AddSound(e)})},e.prototype.removeFromContainer=function(e,t){var i=this;void 0===t&&(t=!1),e.sounds&&e.sounds.forEach(function(e){e.stop(),e.autoplay=!1,i.scene.mainSoundTrack.RemoveSound(e),t&&e.dispose()})},e.prototype.dispose=function(){var e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(var t=0;t<e.soundTracks.length;t++)e.soundTracks[t].dispose()},e.prototype.disableAudio=function(){var e,t=this.scene;for(this._audioEnabled=!1,Oe.a.audioEngine&&Oe.a.audioEngine.audioContext&&Oe.a.audioEngine.audioContext.suspend(),e=0;e<t.mainSoundTrack.soundCollection.length;e++)t.mainSoundTrack.soundCollection[e].pause();if(t.soundTracks)for(e=0;e<t.soundTracks.length;e++)for(var i=0;i<t.soundTracks[e].soundCollection.length;i++)t.soundTracks[e].soundCollection[i].pause()},e.prototype.enableAudio=function(){var e,t=this.scene;for(this._audioEnabled=!0,Oe.a.audioEngine&&Oe.a.audioEngine.audioContext&&Oe.a.audioEngine.audioContext.resume(),e=0;e<t.mainSoundTrack.soundCollection.length;e++)t.mainSoundTrack.soundCollection[e].isPaused&&t.mainSoundTrack.soundCollection[e].play();if(t.soundTracks)for(e=0;e<t.soundTracks.length;e++)for(var i=0;i<t.soundTracks[e].soundCollection.length;i++)t.soundTracks[e].soundCollection[i].isPaused&&t.soundTracks[e].soundCollection[i].play()},e.prototype.switchAudioModeForHeadphones=function(){var e=this.scene;if(this._headphone=!0,e.mainSoundTrack.switchPanningModelToHRTF(),e.soundTracks)for(var t=0;t<e.soundTracks.length;t++)e.soundTracks[t].switchPanningModelToHRTF()},e.prototype.switchAudioModeForNormalSpeakers=function(){var e=this.scene;if(this._headphone=!1,e.mainSoundTrack.switchPanningModelToEqualPower(),e.soundTracks)for(var t=0;t<e.soundTracks.length;t++)e.soundTracks[t].switchPanningModelToEqualPower()},e.prototype._afterRender=function(){var e=Q.a.Now;if(!(this._lastCheck&&e-this._lastCheck<this.audioPositioningRefreshRate)){this._lastCheck=e;var t=this.scene;if(this._audioEnabled&&t._mainSoundTrack&&t.soundTracks&&(0!==t._mainSoundTrack.soundCollection.length||1!==t.soundTracks.length)){var i=Oe.a.audioEngine;if(i.audioContext){if(this._audioListenerPositionProvider){var n=this._audioListenerPositionProvider();n.x=n.x||0,n.y=n.y||0,n.z=n.z||0,i.audioContext.listener.setPosition(n.x,n.y,n.z)}else{var r;if(r=t.activeCameras.length>0?t.activeCameras[0]:t.activeCamera){this._cachedCameraPosition.equals(r.globalPosition)||(this._cachedCameraPosition.copyFrom(r.globalPosition),i.audioContext.listener.setPosition(r.globalPosition.x,r.globalPosition.y,r.globalPosition.z)),r.rigCameras&&r.rigCameras.length>0&&(r=r.rigCameras[0]);var o=a.a.Invert(r.getViewMatrix()),s=a.e.TransformNormal(new a.e(0,0,-1),o);s.normalize(),isNaN(s.x)||isNaN(s.y)||isNaN(s.z)||this._cachedCameraDirection.equals(s)||(this._cachedCameraDirection.copyFrom(s),i.audioContext.listener.setOrientation(s.x,s.y,s.z,0,1,0))}else i.audioContext.listener.setPosition(0,0,0)}var c;for(c=0;c<t.mainSoundTrack.soundCollection.length;c++){var l=t.mainSoundTrack.soundCollection[c];l.useCustomAttenuation&&l.updateDistanceFromListener()}if(t.soundTracks)for(c=0;c<t.soundTracks.length;c++)for(var u=0;u<t.soundTracks[c].soundCollection.length;u++)(l=t.soundTracks[c].soundCollection[u]).useCustomAttenuation&&l.updateDistanceFromListener()}}}},e}();Le._SceneComponentInitialization=function(e){var t=e._getComponent(Fe.a.NAME_AUDIO);t||(t=new Be(e),e._addComponent(t))};var Ue=function(){function e(e,t,i){var n=this;if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],t.length!==i.length)throw new Error("Sounds length does not equal weights length");this.loop=e,this._weights=i;for(var r=0,o=0,a=i;o<a.length;o++){r+=a[o]}for(var s=r>0?1/r:0,c=0;c<this._weights.length;c++)this._weights[c]*=s;this._sounds=t;for(var l=0,u=this._sounds;l<u.length;l++){u[l].onEndedObservable.add(function(){n._onended()})}}return Object.defineProperty(e.prototype,"directionalConeInnerAngle",{get:function(){return this._coneInnerAngle},set:function(e){if(e!==this._coneInnerAngle){if(this._coneOuterAngle<e)return void m.a.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneInnerAngle=e;for(var t=0,i=this._sounds;t<i.length;t++){i[t].directionalConeInnerAngle=e}}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"directionalConeOuterAngle",{get:function(){return this._coneOuterAngle},set:function(e){if(e!==this._coneOuterAngle){if(e<this._coneInnerAngle)return void m.a.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneOuterAngle=e;for(var t=0,i=this._sounds;t<i.length;t++){i[t].directionalConeOuterAngle=e}}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"volume",{get:function(){return this._volume},set:function(e){if(e!==this._volume)for(var t=0,i=this._sounds;t<i.length;t++){i[t].setVolume(e)}},enumerable:!0,configurable:!0}),e.prototype._onended=function(){void 0!==this._currentIndex&&(this._sounds[this._currentIndex].autoplay=!1),this.loop&&this.isPlaying?this.play():this.isPlaying=!1},e.prototype.pause=function(){this.isPaused=!0,void 0!==this._currentIndex&&this._sounds[this._currentIndex].pause()},e.prototype.stop=function(){this.isPlaying=!1,void 0!==this._currentIndex&&this._sounds[this._currentIndex].stop()},e.prototype.play=function(e){if(!this.isPaused){this.stop();for(var t=Math.random(),i=0,n=0;n<this._weights.length;n++)if(t<=(i+=this._weights[n])){this._currentIndex=n;break}}var r=this._sounds[this._currentIndex];r.isReady()?r.play(0,this.isPaused?void 0:e):r.autoplay=!0,this.isPlaying=!0,this.isPaused=!1},e}(),Ve=i(20),ke=function(){function e(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}return Object.defineProperty(e.prototype,"name",{get:function(){return"AutoRotation"},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"zoomStopsAnimation",{get:function(){return this._zoomStopsAnimation},set:function(e){this._zoomStopsAnimation=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"idleRotationSpeed",{get:function(){return this._idleRotationSpeed},set:function(e){this._idleRotationSpeed=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"idleRotationWaitTime",{get:function(){return this._idleRotationWaitTime},set:function(e){this._idleRotationWaitTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"idleRotationSpinupTime",{get:function(){return this._idleRotationSpinupTime},set:function(e){this._idleRotationSpinupTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rotationInProgress",{get:function(){return Math.abs(this._cameraRotationSpeed)>0},enumerable:!0,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(e){var t=this;this._attachedCamera=e;var i=this._attachedCamera.getScene();this._onPrePointerObservableObserver=i.onPrePointerObservable.add(function(e){e.type!==Ve.a.POINTERDOWN?e.type===Ve.a.POINTERUP&&(t._isPointerDown=!1):t._isPointerDown=!0}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(function(){var e=Q.a.Now,i=0;null!=t._lastFrameTime&&(i=e-t._lastFrameTime),t._lastFrameTime=e,t._applyUserInteraction();var n=e-t._lastInteractionTime-t._idleRotationWaitTime,r=Math.max(Math.min(n/t._idleRotationSpinupTime,1),0);t._cameraRotationSpeed=t._idleRotationSpeed*r,t._attachedCamera&&(t._attachedCamera.alpha-=t._cameraRotationSpeed*(i/1e3))})},e.prototype.detach=function(){if(this._attachedCamera){var e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}},e.prototype._userIsZooming=function(){return!!this._attachedCamera&&0!==this._attachedCamera.inertialRadiusOffset},e.prototype._shouldAnimationStopForInteraction=function(){if(!this._attachedCamera)return!1;var e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&0!==this._attachedCamera.inertialRadiusOffset&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()},e.prototype._applyUserInteraction=function(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=Q.a.Now)},e.prototype._userIsMoving=function(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)},e}(),ze=function(){function e(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}return Object.defineProperty(e.prototype,"name",{get:function(){return"Bouncing"},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"autoTransitionRange",{get:function(){return this._autoTransitionRange},set:function(e){var t=this;if(this._autoTransitionRange!==e){this._autoTransitionRange=e;var i=this._attachedCamera;i&&(e?this._onMeshTargetChangedObserver=i.onMeshTargetChangedObservable.add(function(e){if(e){e.computeWorldMatrix(!0);var i=e.getBoundingInfo().diagonalLength;t.lowerRadiusTransitionRange=.05*i,t.upperRadiusTransitionRange=.05*i}}):this._onMeshTargetChangedObserver&&i.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}},enumerable:!0,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(e){var t=this;this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(function(){t._attachedCamera&&(t._isRadiusAtLimit(t._attachedCamera.lowerRadiusLimit)&&t._applyBoundRadiusAnimation(t.lowerRadiusTransitionRange),t._isRadiusAtLimit(t._attachedCamera.upperRadiusLimit)&&t._applyBoundRadiusAnimation(t.upperRadiusTransitionRange))})},e.prototype.detach=function(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)},e.prototype._isRadiusAtLimit=function(e){return!!this._attachedCamera&&(this._attachedCamera.radius===e&&!this._radiusIsAnimating)},e.prototype._applyBoundRadiusAnimation=function(t){var i=this;if(this._attachedCamera){this._radiusBounceTransition||(e.EasingFunction.setEasingMode(e.EasingMode),this._radiusBounceTransition=k.CreateAnimation("radius",k.ANIMATIONTYPE_FLOAT,60,e.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;var n=k.TransitionTo("radius",this._attachedCamera.radius+t,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,function(){return i._clearAnimationLocks()});n&&this._animatables.push(n)}},e.prototype._clearAnimationLocks=function(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)},e.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()},e.EasingFunction=new fe(.3),e.EasingMode=he.EASINGMODE_EASEOUT,e}(),Ge=function(){function e(){this._mode=e.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}return Object.defineProperty(e.prototype,"name",{get:function(){return"Framing"},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"mode",{get:function(){return this._mode},set:function(e){this._mode=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"radiusScale",{get:function(){return this._radiusScale},set:function(e){this._radiusScale=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"positionScale",{get:function(){return this._positionScale},set:function(e){this._positionScale=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"defaultElevation",{get:function(){return this._defaultElevation},set:function(e){this._defaultElevation=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"elevationReturnTime",{get:function(){return this._elevationReturnTime},set:function(e){this._elevationReturnTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"elevationReturnWaitTime",{get:function(){return this._elevationReturnWaitTime},set:function(e){this._elevationReturnWaitTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"zoomStopsAnimation",{get:function(){return this._zoomStopsAnimation},set:function(e){this._zoomStopsAnimation=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"framingTime",{get:function(){return this._framingTime},set:function(e){this._framingTime=e},enumerable:!0,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(t){var i=this;this._attachedCamera=t;var n=this._attachedCamera.getScene();e.EasingFunction.setEasingMode(e.EasingMode),this._onPrePointerObservableObserver=n.onPrePointerObservable.add(function(e){e.type!==Ve.a.POINTERDOWN?e.type===Ve.a.POINTERUP&&(i._isPointerDown=!1):i._isPointerDown=!0}),this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add(function(e){e&&i.zoomOnMesh(e)}),this._onAfterCheckInputsObserver=t.onAfterCheckInputsObservable.add(function(){i._applyUserInteraction(),i._maintainCameraAboveGround()})},e.prototype.detach=function(){if(this._attachedCamera){var e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}},e.prototype.zoomOnMesh=function(e,t,i){void 0===t&&(t=!1),void 0===i&&(i=null),e.computeWorldMatrix(!0);var n=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(n.minimumWorld,n.maximumWorld,t,i)},e.prototype.zoomOnMeshHierarchy=function(e,t,i){void 0===t&&(t=!1),void 0===i&&(i=null),e.computeWorldMatrix(!0);var n=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(n.min,n.max,t,i)},e.prototype.zoomOnMeshesHierarchy=function(e,t,i){void 0===t&&(t=!1),void 0===i&&(i=null);for(var n=new a.e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new a.e(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),o=0;o<e.length;o++){var s=e[o].getHierarchyBoundingVectors(!0);a.e.CheckExtends(s.min,n,r),a.e.CheckExtends(s.max,n,r)}this.zoomOnBoundingInfo(n,r,t,i)},e.prototype.zoomOnBoundingInfo=function(t,i,n,r){var o,s=this;if(void 0===n&&(n=!1),void 0===r&&(r=null),this._attachedCamera){var c=t.y,l=c+(i.y-c)*this._positionScale,u=i.subtract(t).scale(.5);if(n)o=new a.e(0,l,0);else{var h=t.add(u);o=new a.e(h.x,l,h.z)}this._vectorTransition||(this._vectorTransition=k.CreateAnimation("target",k.ANIMATIONTYPE_VECTOR3,60,e.EasingFunction)),this._betaIsAnimating=!0;var d=k.TransitionTo("target",o,this._attachedCamera,this._attachedCamera.getScene(),60,this._vectorTransition,this._framingTime);d&&this._animatables.push(d);var f=0;if(this._mode===e.FitFrustumSidesMode){var p=this._calculateLowerRadiusFromModelBoundingSphere(t,i);this.autoCorrectCameraLimitsAndSensibility&&(this._attachedCamera.lowerRadiusLimit=u.length()+this._attachedCamera.minZ),f=p}else this._mode===e.IgnoreBoundsSizeMode&&(f=this._calculateLowerRadiusFromModelBoundingSphere(t,i),this.autoCorrectCameraLimitsAndSensibility&&null===this._attachedCamera.lowerRadiusLimit&&(this._attachedCamera.lowerRadiusLimit=this._attachedCamera.minZ));if(this.autoCorrectCameraLimitsAndSensibility){var _=i.subtract(t).length();this._attachedCamera.panningSensibility=5e3/_,this._attachedCamera.wheelPrecision=100/f}this._radiusTransition||(this._radiusTransition=k.CreateAnimation("radius",k.ANIMATIONTYPE_FLOAT,60,e.EasingFunction)),(d=k.TransitionTo("radius",f,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusTransition,this._framingTime,function(){s.stopAllAnimations(),r&&r(),s._attachedCamera&&s._attachedCamera.useInputToRestoreState&&s._attachedCamera.storeState()}))&&this._animatables.push(d)}},e.prototype._calculateLowerRadiusFromModelBoundingSphere=function(t,i){var n=i.subtract(t).length(),r=this._getFrustumSlope(),o=.5*n*this._radiusScale,a=o*Math.sqrt(1+1/(r.x*r.x)),s=o*Math.sqrt(1+1/(r.y*r.y)),c=Math.max(a,s),l=this._attachedCamera;return l?(l.lowerRadiusLimit&&this._mode===e.IgnoreBoundsSizeMode&&(c=c<l.lowerRadiusLimit?l.lowerRadiusLimit:c),l.upperRadiusLimit&&(c=c>l.upperRadiusLimit?l.upperRadiusLimit:c),c):0},e.prototype._maintainCameraAboveGround=function(){var t=this;if(!(this._elevationReturnTime<0)){var i=Q.a.Now-this._lastInteractionTime,n=.5*Math.PI-this._defaultElevation,r=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>r&&i>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=k.CreateAnimation("beta",k.ANIMATIONTYPE_FLOAT,60,e.EasingFunction));var o=k.TransitionTo("beta",n,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,function(){t._clearAnimationLocks(),t.stopAllAnimations()});o&&this._animatables.push(o)}}},e.prototype._getFrustumSlope=function(){var e=this._attachedCamera;if(!e)return a.d.Zero();var t=e.getScene().getEngine().getAspectRatio(e),i=Math.tan(e.fov/2),n=i*t;return new a.d(n,i)},e.prototype._clearAnimationLocks=function(){this._betaIsAnimating=!1},e.prototype._applyUserInteraction=function(){this.isUserIsMoving&&(this._lastInteractionTime=Q.a.Now,this.stopAllAnimations(),this._clearAnimationLocks())},e.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()},Object.defineProperty(e.prototype,"isUserIsMoving",{get:function(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)},enumerable:!0,configurable:!0}),e.EasingFunction=new ge,e.EasingMode=he.EASINGMODE_EASEINOUT,e.IgnoreBoundsSizeMode=0,e.FitFrustumSidesMode=1,e}(),je=function(e,t,i,n){void 0===t&&(t=new a.e),void 0===i&&(i=0),void 0===n&&(n=!1),this.direction=e,this.rotatedDirection=t,this.diff=i,this.ignore=n},We=function(){function e(e){this.ui=e,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new je(a.e.Up()),new je(a.e.Down()),new je(a.e.Left()),new je(a.e.Right()),new je(a.e.Forward()),new je(a.e.Forward().scaleInPlace(-1))],this._tmpMatrix=new a.a,this._tmpVector=new a.e,this._zeroVector=a.e.Zero(),this._lookAtTmpMatrix=new a.a}return e.prototype.init=function(){},e.prototype._closestFace=function(e){var t=this;return this._faceVectors.forEach(function(i){t._target.rotationQuaternion||(t._target.rotationQuaternion=a.b.RotationYawPitchRoll(t._target.rotation.y,t._target.rotation.x,t._target.rotation.z)),t._target.rotationQuaternion.toRotationMatrix(t._tmpMatrix),a.e.TransformCoordinatesToRef(i.direction,t._tmpMatrix,i.rotatedDirection),i.diff=a.e.GetAngleBetweenVectors(i.rotatedDirection,e,a.e.Cross(i.rotatedDirection,e))}),this._faceVectors.reduce(function(e,t){return e.ignore?t:t.ignore?e:e.diff<t.diff?e:t},this._faceVectors[0])},e.prototype._lookAtToRef=function(e,t,i){void 0===t&&(t=new a.e(0,1,0)),a.a.LookAtLHToRef(this._zeroVector,e,t,this._lookAtTmpMatrix),this._lookAtTmpMatrix.invert(),a.b.FromRotationMatrixToRef(this._lookAtTmpMatrix,i)},e.prototype.attach=function(e){var t=this;this._target=e,this._scene=this._target.getScene(),this._onRenderObserver=this._scene.onBeforeRenderObservable.add(function(){if(t._scene.activeCamera){var i=t._scene.activeCamera.position;t._scene.activeCamera.devicePosition&&(i=t._scene.activeCamera.devicePosition);var n=t._closestFace(i.subtract(e.position));t._scene.activeCamera.leftCamera?t._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(t._tmpMatrix):t._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(t._tmpMatrix),a.e.TransformCoordinatesToRef(a.e.Up(),t._tmpMatrix,t._tmpVector),t._faceVectors.forEach(function(e){n.direction.x&&e.direction.x&&(e.ignore=!0),n.direction.y&&e.direction.y&&(e.ignore=!0),n.direction.z&&e.direction.z&&(e.ignore=!0)});var r=t._closestFace(t._tmpVector);t._faceVectors.forEach(function(e){e.ignore=!1}),t.ui.position.copyFrom(e.position),n.direction.x&&(n.rotatedDirection.scaleToRef(e.scaling.x/2+t.distanceAwayFromFace,t._tmpVector),t.ui.position.addInPlace(t._tmpVector)),n.direction.y&&(n.rotatedDirection.scaleToRef(e.scaling.y/2+t.distanceAwayFromFace,t._tmpVector),t.ui.position.addInPlace(t._tmpVector)),n.direction.z&&(n.rotatedDirection.scaleToRef(e.scaling.z/2+t.distanceAwayFromFace,t._tmpVector),t.ui.position.addInPlace(t._tmpVector)),t.ui.rotationQuaternion||(t.ui.rotationQuaternion=a.b.RotationYawPitchRoll(t.ui.rotation.y,t.ui.rotation.x,t.ui.rotation.z)),n.rotatedDirection.scaleToRef(-1,t._tmpVector),t._lookAtToRef(t._tmpVector,r.rotatedDirection,t.ui.rotationQuaternion),r.direction.x&&t.ui.up.scaleToRef(t.distanceAwayFromBottomOfFace-e.scaling.x/2,t._tmpVector),r.direction.y&&t.ui.up.scaleToRef(t.distanceAwayFromBottomOfFace-e.scaling.y/2,t._tmpVector),r.direction.z&&t.ui.up.scaleToRef(t.distanceAwayFromBottomOfFace-e.scaling.z/2,t._tmpVector),t.ui.position.addInPlace(t._tmpVector)}})},e.prototype.detach=function(){this._scene.onBeforeRenderObservable.remove(this._onRenderObserver)},e}(),Xe=function(){function e(){var e=this;this.delay=0,this.fadeInTime=300,this._millisecondsPerFrame=1e3/60,this._hovered=!1,this._hoverValue=0,this._ownerNode=null,this._update=function(){if(e._ownerNode){if(e._hoverValue+=e._hovered?e._millisecondsPerFrame:-e._millisecondsPerFrame,e._setAllVisibility(e._ownerNode,(e._hoverValue-e.delay)/e.fadeInTime),e._ownerNode.visibility>1)return e._setAllVisibility(e._ownerNode,1),void(e._hoverValue=e.fadeInTime+e.delay);if(e._ownerNode.visibility<0&&(e._setAllVisibility(e._ownerNode,0),e._hoverValue<0))return void(e._hoverValue=0);setTimeout(e._update,e._millisecondsPerFrame)}}}return Object.defineProperty(e.prototype,"name",{get:function(){return"FadeInOut"},enumerable:!0,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(e){this._ownerNode=e,this._setAllVisibility(this._ownerNode,0)},e.prototype.detach=function(){this._ownerNode=null},e.prototype.fadeIn=function(e){this._hovered=e,this._update()},e.prototype._setAllVisibility=function(e,t){var i=this;e.visibility=t,e.getChildMeshes().forEach(function(e){i._setAllVisibility(e,t)})},e}(),He=i(62),Ye=function(){function e(){this._startDistance=0,this._initialScale=new a.e(0,0,0),this._targetScale=new a.e(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new He.a({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new He.a({}),this._dragBehaviorB.moveAttached=!1}return Object.defineProperty(e.prototype,"name",{get:function(){return"MultiPointerScale"},enumerable:!0,configurable:!0}),e.prototype.init=function(){},e.prototype._getCurrentDistance=function(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()},e.prototype.attach=function(e){var t=this;this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add(function(i){t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging&&(t._dragBehaviorA.currentDraggingPointerID==t._dragBehaviorB.currentDraggingPointerID?t._dragBehaviorA.releaseDrag():(t._initialScale.copyFrom(e.scaling),t._startDistance=t._getCurrentDistance()))}),this._dragBehaviorB.onDragStartObservable.add(function(i){t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging&&(t._dragBehaviorA.currentDraggingPointerID==t._dragBehaviorB.currentDraggingPointerID?t._dragBehaviorB.releaseDrag():(t._initialScale.copyFrom(e.scaling),t._startDistance=t._getCurrentDistance()))}),[this._dragBehaviorA,this._dragBehaviorB].forEach(function(e){e.onDragObservable.add(function(){if(t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging){var e=t._getCurrentDistance()/t._startDistance;t._initialScale.scaleToRef(e,t._targetScale)}})}),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add(function(){if(t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging){var i=t._targetScale.subtract(e.scaling).scaleInPlace(.1);i.length()>.01&&e.scaling.addInPlace(i)}})},e.prototype.detach=function(){var e=this;this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach(function(t){t.onDragStartObservable.clear(),t.onDragObservable.clear(),e._ownerNode.removeBehavior(t)})},e}(),Ke=i(27),Qe=i(24),qe=i(55),Ze=function(){function e(){this._sceneRenderObserver=null,this._targetPosition=new a.e(0,0,0),this._moving=!1,this._startingOrientation=new a.b,this.zDragFactor=3,this.rotateDraggedObject=!0,this.dragging=!1,this.dragDeltaRatio=.2,this.currentDraggingPointerID=-1,this.detachCameraControls=!0,this.onDragStartObservable=new o.c,this.onDragEndObservable=new o.c}return Object.defineProperty(e.prototype,"name",{get:function(){return"SixDofDrag"},enumerable:!0,configurable:!0}),e.prototype.init=function(){},Object.defineProperty(e.prototype,"_pointerCamera",{get:function(){return this._scene.cameraToUseForPointers?this._scene.cameraToUseForPointers:this._scene.activeCamera},enumerable:!0,configurable:!0}),e.prototype.attach=function(t){var i=this;this._ownerNode=t,this._scene=this._ownerNode.getScene(),e._virtualScene||(e._virtualScene=new K.a(this._scene.getEngine()),e._virtualScene.detachControl(),this._scene.getEngine().scenes.pop());var n=null,r=new a.e(0,0,0);this._virtualOriginMesh=new Ke.a("",e._virtualScene),this._virtualOriginMesh.rotationQuaternion=new a.b,this._virtualDragMesh=new Ke.a("",e._virtualScene),this._virtualDragMesh.rotationQuaternion=new a.b;var o=null;this._pointerObserver=this._scene.onPointerObservable.add(function(e,t){if(e.type==Ve.a.POINTERDOWN){if(!i.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.ray&&(h=e.pickInfo.pickedMesh,i._ownerNode==h||h.isDescendantOf(i._ownerNode))){i._pointerCamera&&i._pointerCamera.cameraRigMode==Qe.a.RIG_MODE_NONE&&e.pickInfo.ray.origin.copyFrom(i._pointerCamera.globalPosition),n=i._ownerNode,qe.a._RemoveAndStorePivotPoint(n),r.copyFrom(e.pickInfo.ray.origin),i._virtualOriginMesh.position.copyFrom(e.pickInfo.ray.origin),i._virtualOriginMesh.lookAt(e.pickInfo.ray.origin.add(e.pickInfo.ray.direction)),i._virtualOriginMesh.removeChild(i._virtualDragMesh),n.computeWorldMatrix(),i._virtualDragMesh.position.copyFrom(n.absolutePosition),n.rotationQuaternion||(n.rotationQuaternion=a.b.RotationYawPitchRoll(n.rotation.y,n.rotation.x,n.rotation.z));var s=n.parent;n.setParent(null),i._virtualDragMesh.rotationQuaternion.copyFrom(n.rotationQuaternion),n.setParent(s),i._virtualOriginMesh.addChild(i._virtualDragMesh),i._targetPosition.copyFrom(i._virtualDragMesh.absolutePosition),i.dragging=!0,i.currentDraggingPointerID=e.event.pointerId,i.detachCameraControls&&i._pointerCamera&&!i._pointerCamera.leftCamera&&(i._pointerCamera.inputs.attachedElement?(o=i._pointerCamera.inputs.attachedElement,i._pointerCamera.detachControl(i._pointerCamera.inputs.attachedElement)):o=null),qe.a._RestorePivotPoint(n),i.onDragStartObservable.notifyObservers({})}}else if(e.type==Ve.a.POINTERUP)i.currentDraggingPointerID==e.event.pointerId&&(i.dragging=!1,i._moving=!1,i.currentDraggingPointerID=-1,n=null,i._virtualOriginMesh.removeChild(i._virtualDragMesh),i.detachCameraControls&&o&&i._pointerCamera&&!i._pointerCamera.leftCamera&&i._pointerCamera.attachControl(o,!0),i.onDragEndObservable.notifyObservers({}));else if(e.type==Ve.a.POINTERMOVE&&i.currentDraggingPointerID==e.event.pointerId&&i.dragging&&e.pickInfo&&e.pickInfo.ray&&n){var c=i.zDragFactor;i._pointerCamera&&i._pointerCamera.cameraRigMode==Qe.a.RIG_MODE_NONE&&(e.pickInfo.ray.origin.copyFrom(i._pointerCamera.globalPosition),c=0);var l=e.pickInfo.ray.origin.subtract(r);r.copyFrom(e.pickInfo.ray.origin);var u=-a.e.Dot(l,e.pickInfo.ray.direction);i._virtualOriginMesh.addChild(i._virtualDragMesh),i._virtualDragMesh.position.z-=i._virtualDragMesh.position.z<1?u*i.zDragFactor:u*c*i._virtualDragMesh.position.z,i._virtualDragMesh.position.z<0&&(i._virtualDragMesh.position.z=0),i._virtualOriginMesh.position.copyFrom(e.pickInfo.ray.origin),i._virtualOriginMesh.lookAt(e.pickInfo.ray.origin.add(e.pickInfo.ray.direction)),i._virtualOriginMesh.removeChild(i._virtualDragMesh),i._targetPosition.copyFrom(i._virtualDragMesh.absolutePosition),n.parent&&a.e.TransformCoordinatesToRef(i._targetPosition,a.a.Invert(n.parent.getWorldMatrix()),i._targetPosition),i._moving||i._startingOrientation.copyFrom(i._virtualDragMesh.rotationQuaternion),i._moving=!0}var h});var s=new a.b;this._sceneRenderObserver=t.getScene().onBeforeRenderObservable.add(function(){if(i.dragging&&i._moving&&n){if(qe.a._RemoveAndStorePivotPoint(n),n.position.addInPlace(i._targetPosition.subtract(n.position).scale(i.dragDeltaRatio)),i.rotateDraggedObject){s.copyFrom(i._startingOrientation),s.x=-s.x,s.y=-s.y,s.z=-s.z,i._virtualDragMesh.rotationQuaternion.multiplyToRef(s,s),a.b.RotationYawPitchRollToRef(s.toEulerAngles("xyz").y,0,0,s),s.multiplyToRef(i._startingOrientation,s);var e=n.parent;(!e||e.scaling&&!e.scaling.isNonUniformWithinEpsilon(.001))&&(n.setParent(null),a.b.SlerpToRef(n.rotationQuaternion,s,i.dragDeltaRatio,n.rotationQuaternion),n.setParent(e))}qe.a._RestorePivotPoint(n)}})},e.prototype.detach=function(){this._scene&&this._scene.onPointerObservable.remove(this._pointerObserver),this._ownerNode&&this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),this._virtualOriginMesh&&this._virtualOriginMesh.dispose(),this._virtualDragMesh&&this._virtualDragMesh.dispose(),this.onDragEndObservable.clear(),this.onDragStartObservable.clear()},e}(),Je=function(){function e(e,t,i){if(this.targetPosition=a.e.Zero(),this.poleTargetPosition=a.e.Zero(),this.poleTargetLocalOffset=a.e.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=a.b.Identity(),this._bone1Mat=a.a.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=a.e.Right(),this._slerping=!1,this._adjustRoll=0,this._bone2=t,this._bone1=t.getParent(),this._bone1){this.mesh=e;var n=t.getPosition();if(t.getAbsoluteTransform().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,n.x>n.y&&n.x>n.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length){var r=this._bone1.getScale(),o=this._bone2.getScale();this._bone1Length=this._bone1.length*r.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*o.y*this.mesh.scaling.y}else if(this._bone1.children[0]){e.computeWorldMatrix(!0);var s=this._bone2.children[0].getAbsolutePosition(e),c=this._bone2.getAbsolutePosition(e),l=this._bone1.getAbsolutePosition(e);this._bone1Length=a.e.Distance(s,c),this._bone2Length=a.e.Distance(c,l)}this._bone1.getRotationMatrixToRef(Z.b.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}}return Object.defineProperty(e.prototype,"maxAngle",{get:function(){return this._maxAngle},set:function(e){this._setMaxAngle(e)},enumerable:!0,configurable:!0}),e.prototype._setMaxAngle=function(e){e<0&&(e=0),(e>Math.PI||null==e)&&(e=Math.PI),this._maxAngle=e;var t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))},e.prototype.update=function(){var t=this._bone1;if(t){var i=this.targetPosition,n=this.poleTargetPosition,r=e._tmpMats[0],o=e._tmpMats[1];this.targetMesh&&i.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,n):this.poleTargetMesh&&a.e.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),n);var s=e._tmpVecs[0],c=e._tmpVecs[1],l=e._tmpVecs[2],u=e._tmpVecs[3],h=e._tmpVecs[4],d=e._tmpQuat;t.getAbsolutePositionToRef(this.mesh,s),n.subtractToRef(s,h),0==h.x&&0==h.y&&0==h.z?h.y=1:h.normalize(),i.subtractToRef(s,u),u.normalize(),a.e.CrossToRef(u,h,c),c.normalize(),a.e.CrossToRef(u,c,l),l.normalize(),a.a.FromXYZAxesToRef(l,u,c,r);var f=this._bone1Length,p=this._bone2Length,_=a.e.Distance(s,i);this._maxReach>0&&(_=Math.min(this._maxReach,_));var m=(p*p+_*_-f*f)/(2*p*_),g=(_*_+f*f-p*p)/(2*_*f);m>1&&(m=1),g>1&&(g=1),m<-1&&(m=-1),g<-1&&(g=-1);var v=Math.acos(m),y=Math.acos(g),b=-v-y;if(this._rightHandedSystem)a.a.RotationYawPitchRollToRef(0,0,this._adjustRoll,o),o.multiplyToRef(r,r),a.a.RotationAxisToRef(this._bendAxis,y,o),o.multiplyToRef(r,r);else{var T=e._tmpVecs[5];T.copyFrom(this._bendAxis),T.x*=-1,a.a.RotationAxisToRef(T,-y,o),o.multiplyToRef(r,r)}this.poleAngle&&(a.a.RotationAxisToRef(u,this.poleAngle,o),r.multiplyToRef(o,r)),this._bone1&&(this.slerpAmount<1?(this._slerping||a.b.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),a.b.FromRotationMatrixToRef(r,d),a.b.SlerpToRef(this._bone1Quat,d,this.slerpAmount,this._bone1Quat),b=this._bone2Ang*(1-this.slerpAmount)+b*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,Z.b.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(r,Z.b.WORLD,this.mesh),this._bone1Mat.copyFrom(r),this._slerping=!1)),this._bone2.setAxisAngle(this._bendAxis,b,Z.b.LOCAL),this._bone2Ang=b}},e._tmpVecs=[a.e.Zero(),a.e.Zero(),a.e.Zero(),a.e.Zero(),a.e.Zero(),a.e.Zero()],e._tmpQuat=a.b.Identity(),e._tmpMats=[a.a.Identity(),a.a.Identity()],e}(),$e=function(){function e(e,t,i,n){if(this.upAxis=a.e.Up(),this.upAxisSpace=Z.b.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=a.b.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=a.e.Forward(),this.mesh=e,this.bone=t,this.target=i,n&&(n.adjustYaw&&(this.adjustYaw=n.adjustYaw),n.adjustPitch&&(this.adjustPitch=n.adjustPitch),n.adjustRoll&&(this.adjustRoll=n.adjustRoll),null!=n.maxYaw?this.maxYaw=n.maxYaw:this.maxYaw=Math.PI,null!=n.minYaw?this.minYaw=n.minYaw:this.minYaw=-Math.PI,null!=n.maxPitch?this.maxPitch=n.maxPitch:this.maxPitch=Math.PI,null!=n.minPitch?this.minPitch=n.minPitch:this.minPitch=-Math.PI,null!=n.slerpAmount&&(this.slerpAmount=n.slerpAmount),null!=n.upAxis&&(this.upAxis=n.upAxis),null!=n.upAxisSpace&&(this.upAxisSpace=n.upAxisSpace),null!=n.yawAxis||null!=n.pitchAxis)){var r=Z.a.Y,o=Z.a.X;null!=n.yawAxis&&(r=n.yawAxis.clone()).normalize(),null!=n.pitchAxis&&(o=n.pitchAxis.clone()).normalize();var s=a.e.Cross(o,r);this._transformYawPitch=a.a.Identity(),a.a.FromXYZAxesToRef(o,r,s,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}t.getParent()||this.upAxisSpace!=Z.b.BONE||(this.upAxisSpace=Z.b.LOCAL)}return Object.defineProperty(e.prototype,"minYaw",{get:function(){return this._minYaw},set:function(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maxYaw",{get:function(){return this._maxYaw},set:function(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"minPitch",{get:function(){return this._minPitch},set:function(e){this._minPitch=e,this._minPitchTan=Math.tan(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maxPitch",{get:function(){return this._maxPitch},set:function(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)},enumerable:!0,configurable:!0}),e.prototype.update=function(){if(this.slerpAmount<1&&!this._firstFrameSkipped)this._firstFrameSkipped=!0;else{var t=this.bone,i=e._tmpVecs[0];t.getAbsolutePositionToRef(this.mesh,i);var n=this.target,r=e._tmpMats[0],o=e._tmpMats[1],s=this.mesh,c=t.getParent(),l=e._tmpVecs[1];l.copyFrom(this.upAxis),this.upAxisSpace==Z.b.BONE&&c?(this._transformYawPitch&&a.e.TransformCoordinatesToRef(l,this._transformYawPitchInv,l),c.getDirectionToRef(l,this.mesh,l)):this.upAxisSpace==Z.b.LOCAL&&(s.getDirectionToRef(l,l),1==s.scaling.x&&1==s.scaling.y&&1==s.scaling.z||l.normalize());var u=!1,h=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(u=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(h=!0),u||h){var d=e._tmpMats[2],f=e._tmpMats[3];if(this.upAxisSpace==Z.b.BONE&&1==l.y&&c)c.getRotationMatrixToRef(Z.b.WORLD,this.mesh,d);else if(this.upAxisSpace!=Z.b.LOCAL||1!=l.y||c){(_=e._tmpVecs[2]).copyFrom(this._fowardAxis),this._transformYawPitch&&a.e.TransformCoordinatesToRef(_,this._transformYawPitchInv,_),c?c.getDirectionToRef(_,this.mesh,_):s.getDirectionToRef(_,_);var p=a.e.Cross(l,_);p.normalize();var _=a.e.Cross(p,l);a.a.FromXYZAxesToRef(p,l,_,d)}else d.copyFrom(s.getWorldMatrix());d.invertToRef(f);var m=null;if(h){var g=e._tmpVecs[3];n.subtractToRef(i,g),a.e.TransformCoordinatesToRef(g,f,g),m=Math.sqrt(g.x*g.x+g.z*g.z);var v=Math.atan2(g.y,m),y=v;v>this._maxPitch?(g.y=this._maxPitchTan*m,y=this._maxPitch):v<this._minPitch&&(g.y=this._minPitchTan*m,y=this._minPitch),v!=y&&(a.e.TransformCoordinatesToRef(g,d,g),g.addInPlace(i),n=g)}if(u){g=e._tmpVecs[4];n.subtractToRef(i,g),a.e.TransformCoordinatesToRef(g,f,g);var b=Math.atan2(g.x,g.z),T=b;if((b>this._maxYaw||b<this._minYaw)&&(null==m&&(m=Math.sqrt(g.x*g.x+g.z*g.z)),this._yawRange>Math.PI?this._isAngleBetween(b,this._maxYaw,this._midYawConstraint)?(g.z=this._maxYawCos*m,g.x=this._maxYawSin*m,T=this._maxYaw):this._isAngleBetween(b,this._midYawConstraint,this._minYaw)&&(g.z=this._minYawCos*m,g.x=this._minYawSin*m,T=this._minYaw):b>this._maxYaw?(g.z=this._maxYawCos*m,g.x=this._maxYawSin*m,T=this._maxYaw):b<this._minYaw&&(g.z=this._minYawCos*m,g.x=this._minYawSin*m,T=this._minYaw)),this._slerping&&this._yawRange>Math.PI){var E=e._tmpVecs[8];E.copyFrom(Z.a.Z),this._transformYawPitch&&a.e.TransformCoordinatesToRef(E,this._transformYawPitchInv,E);var x=e._tmpMats[4];this._boneQuat.toRotationMatrix(x),this.mesh.getWorldMatrix().multiplyToRef(x,x),a.e.TransformCoordinatesToRef(E,x,E),a.e.TransformCoordinatesToRef(E,f,E);var P=Math.atan2(E.x,E.z);if(this._getAngleBetween(P,b)>this._getAngleBetween(P,this._midYawConstraint)){null==m&&(m=Math.sqrt(g.x*g.x+g.z*g.z));var A=this._getAngleBetween(P,this._maxYaw);this._getAngleBetween(P,this._minYaw)<A?(T=P+.75*Math.PI,g.z=Math.cos(T)*m,g.x=Math.sin(T)*m):(T=P-.75*Math.PI,g.z=Math.cos(T)*m,g.x=Math.sin(T)*m)}}b!=T&&(a.e.TransformCoordinatesToRef(g,d,g),g.addInPlace(i),n=g)}}var S=e._tmpVecs[5],C=e._tmpVecs[6],R=e._tmpVecs[7],O=e._tmpQuat;n.subtractToRef(i,S),S.normalize(),a.e.CrossToRef(l,S,C),C.normalize(),a.e.CrossToRef(S,C,R),R.normalize(),a.a.FromXYZAxesToRef(C,R,S,r),0===C.x&&0===C.y&&0===C.z||0===R.x&&0===R.y&&0===R.z||0===S.x&&0===S.y&&0===S.z||((this.adjustYaw||this.adjustPitch||this.adjustRoll)&&(a.a.RotationYawPitchRollToRef(this.adjustYaw,this.adjustPitch,this.adjustRoll,o),o.multiplyToRef(r,r)),this.slerpAmount<1?(this._slerping||this.bone.getRotationQuaternionToRef(Z.b.WORLD,this.mesh,this._boneQuat),this._transformYawPitch&&this._transformYawPitch.multiplyToRef(r,r),a.b.FromRotationMatrixToRef(r,O),a.b.SlerpToRef(this._boneQuat,O,this.slerpAmount,this._boneQuat),this.bone.setRotationQuaternion(this._boneQuat,Z.b.WORLD,this.mesh),this._slerping=!0):(this._transformYawPitch&&this._transformYawPitch.multiplyToRef(r,r),this.bone.setRotationMatrix(r,Z.b.WORLD,this.mesh),this._slerping=!1))}},e.prototype._getAngleDiff=function(e,t){var i=t-e;return(i%=2*Math.PI)>Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i},e.prototype._getAngleBetween=function(e,t){var i=0;return(i=(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)<(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)?t-e:e-t)>Math.PI&&(i=2*Math.PI-i),i},e.prototype._isAngleBetween=function(e,t,i){if(e=(e%=2*Math.PI)<0?e+2*Math.PI:e,(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)<(i=(i%=2*Math.PI)<0?i+2*Math.PI:i)){if(e>t&&e<i)return!0}else if(e>i&&e<t)return!0;return!1},e._tmpVecs=q.a.BuildArray(10,a.e.Zero),e._tmpQuat=a.b.Identity(),e._tmpMats=q.a.BuildArray(5,a.a.Identity),e}(),et=i(9),tt=i(25);function it(e){return function(t,i,n,r,o,a,s,c,l,u){void 0===l&&(l=null),void 0===u&&(u=g.a.TEXTURETYPE_UNSIGNED_INT);var h=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,d=e?tt.b.Raw3D:tt.b.Raw2DArray,f=new tt.a(this,d);f.baseWidth=i,f.baseHeight=n,f.baseDepth=r,f.width=i,f.height=n,f.depth=r,f.format=o,f.type=u,f.generateMipMaps=a,f.samplingMode=c,e?f.is3D=!0:f.is2DArray=!0,this._doNotHandleContextLost||(f._bufferView=t),e?this.updateRawTexture3D(f,t,o,s,l,u):this.updateRawTexture2DArray(f,t,o,s,l,u),this._bindTextureDirectly(h,f,!0);var p=this._getSamplingParameters(c,a);return this._gl.texParameteri(h,this._gl.TEXTURE_MAG_FILTER,p.mag),this._gl.texParameteri(h,this._gl.TEXTURE_MIN_FILTER,p.min),a&&this._gl.generateMipmap(h),this._bindTextureDirectly(h,null),this._internalTexturesCache.push(f),f}}function nt(e){return function(t,i,n,r,o,a){void 0===o&&(o=null),void 0===a&&(a=g.a.TEXTURETYPE_UNSIGNED_INT);var s=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,c=this._getWebGLTextureType(a),l=this._getInternalFormat(n),u=this._getRGBABufferInternalSizedFormat(a,n);this._bindTextureDirectly(s,t,!0),this._unpackFlipY(void 0===r||!!r),this._doNotHandleContextLost||(t._bufferView=i,t.format=n,t.invertY=r,t._compression=o),t.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),o&&i?this._gl.compressedTexImage3D(s,0,this.getCaps().s3tc[o],t.width,t.height,t.depth,0,i):this._gl.texImage3D(s,0,u,t.width,t.height,t.depth,0,l,c,i),t.generateMipMaps&&this._gl.generateMipmap(s),this._bindTextureDirectly(s,null),t.isReady=!0}}Oe.a.prototype.updateRawTexture=function(e,t,i,n,r,o){if(void 0===r&&(r=null),void 0===o&&(o=g.a.TEXTURETYPE_UNSIGNED_INT),e){var a=this._getRGBABufferInternalSizedFormat(o,i),s=this._getInternalFormat(i),c=this._getWebGLTextureType(o);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===n||!!n),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=o,e.invertY=n,e._compression=r),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[r],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,e.width,e.height,0,s,c,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}},Oe.a.prototype.createRawTexture=function(e,t,i,n,r,o,a,s,c){void 0===s&&(s=null),void 0===c&&(c=g.a.TEXTURETYPE_UNSIGNED_INT);var l=new tt.a(this,tt.b.Raw);l.baseWidth=t,l.baseHeight=i,l.width=t,l.height=i,l.format=n,l.generateMipMaps=r,l.samplingMode=a,l.invertY=o,l._compression=s,l.type=c,this._doNotHandleContextLost||(l._bufferView=e),this.updateRawTexture(l,e,n,o,s,c),this._bindTextureDirectly(this._gl.TEXTURE_2D,l,!0);var u=this._getSamplingParameters(a,r);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,u.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,u.min),r&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(l),l},Oe.a.prototype.createRawCubeTexture=function(e,t,i,n,r,o,a,s){void 0===s&&(s=null);var c=this._gl,l=new tt.a(this,tt.b.CubeRaw);l.isCube=!0,l.format=i,l.type=n,this._doNotHandleContextLost||(l._bufferViewArray=e);var u=this._getWebGLTextureType(n),h=this._getInternalFormat(i);h===c.RGB&&(h=c.RGBA),u!==c.FLOAT||this._caps.textureFloatLinearFiltering?u!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?u!==c.FLOAT||this._caps.textureFloatRender?u!==c.HALF_FLOAT||this._caps.colorBufferFloat||(r=!1,m.a.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(r=!1,m.a.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(r=!1,a=g.a.TEXTURE_NEAREST_SAMPLINGMODE,m.a.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(r=!1,a=g.a.TEXTURE_NEAREST_SAMPLINGMODE,m.a.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."));var d=t,f=d;l.width=d,l.height=f,!this.needPOTTextures||De.b.IsExponentOfTwo(l.width)&&De.b.IsExponentOfTwo(l.height)||(r=!1),e&&this.updateRawCubeTexture(l,e,i,n,o,s),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,l,!0),e&&r&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);var p=this._getSamplingParameters(a,r);return c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MAG_FILTER,p.mag),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MIN_FILTER,p.min),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this._bindTextureDirectly(c.TEXTURE_CUBE_MAP,null),l.generateMipMaps=r,l},Oe.a.prototype.updateRawCubeTexture=function(e,t,i,n,r,o,a){void 0===o&&(o=null),void 0===a&&(a=0),e._bufferViewArray=t,e.format=i,e.type=n,e.invertY=r,e._compression=o;var s=this._gl,c=this._getWebGLTextureType(n),l=this._getInternalFormat(i),u=this._getRGBABufferInternalSizedFormat(n),h=!1;l===s.RGB&&(l=s.RGBA,h=!0),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===r||!!r),e.width%4!=0&&s.pixelStorei(s.UNPACK_ALIGNMENT,1);for(var d=0;d<6;d++){var f=t[d];o?s.compressedTexImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+d,a,this.getCaps().s3tc[o],e.width,e.height,0,f):(h&&(f=this._convertRGBtoRGBATextureData(f,e.width,e.height,n)),s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+d,a,u,e.width,e.height,0,l,c,f))}(!this.needPOTTextures||De.b.IsExponentOfTwo(e.width)&&De.b.IsExponentOfTwo(e.height))&&e.generateMipMaps&&0===a&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},Oe.a.prototype.createRawCubeTextureFromUrl=function(e,t,i,n,r,o,a,s,c,l,u,h){var d=this;void 0===c&&(c=null),void 0===l&&(l=null),void 0===u&&(u=g.a.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===h&&(h=!1);var f=this._gl,p=this.createRawCubeTexture(null,i,n,r,!o,h,u,null);t._addPendingData(p),p.url=e,this._internalTexturesCache.push(p);return this._loadFile(e,function(e){!function(e){var i=p.width,o=a(e);if(o){if(s){var l=d._getWebGLTextureType(r),u=d._getInternalFormat(n),_=d._getRGBABufferInternalSizedFormat(r),m=!1;u===f.RGB&&(u=f.RGBA,m=!0),d._bindTextureDirectly(f.TEXTURE_CUBE_MAP,p,!0),d._unpackFlipY(!1);for(var g=s(o),v=0;v<g.length;v++)for(var y=i>>v,b=0;b<6;b++){var T=g[v][b];m&&(T=d._convertRGBtoRGBATextureData(T,y,y,r)),f.texImage2D(b,v,_,y,y,0,u,l,T)}d._bindTextureDirectly(f.TEXTURE_CUBE_MAP,null)}else d.updateRawCubeTexture(p,o,n,r,h);p.isReady=!0,t._removePendingData(p),c&&c()}}(e)},void 0,t.offlineProvider,!0,function(e,i){t._removePendingData(p),l&&e&&l(e.status+" "+e.statusText,i)}),p},Oe.a.prototype.createRawTexture2DArray=it(!1),Oe.a.prototype.createRawTexture3D=it(!0),Oe.a.prototype.updateRawTexture2DArray=nt(!1),Oe.a.prototype.updateRawTexture3D=nt(!0);var rt=function(e){function t(t,i,n,r,o,a,s,c,l){void 0===a&&(a=!0),void 0===s&&(s=!1),void 0===c&&(c=g.a.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===l&&(l=g.a.TEXTURETYPE_UNSIGNED_INT);var u=e.call(this,null,o,!a,s)||this;return u.format=r,u._engine=o.getEngine(),u._texture=o.getEngine().createRawTexture(t,i,n,r,a,s,c,null,l),u.wrapU=et.a.CLAMP_ADDRESSMODE,u.wrapV=et.a.CLAMP_ADDRESSMODE,u}return Object(h.d)(t,e),t.prototype.update=function(e){this._engine.updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)},t.CreateLuminanceTexture=function(e,i,n,r,o,a,s){return void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=g.a.TEXTURE_TRILINEAR_SAMPLINGMODE),new t(e,i,n,g.a.TEXTUREFORMAT_LUMINANCE,r,o,a,s)},t.CreateLuminanceAlphaTexture=function(e,i,n,r,o,a,s){return void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=g.a.TEXTURE_TRILINEAR_SAMPLINGMODE),new t(e,i,n,g.a.TEXTUREFORMAT_LUMINANCE_ALPHA,r,o,a,s)},t.CreateAlphaTexture=function(e,i,n,r,o,a,s){return void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=g.a.TEXTURE_TRILINEAR_SAMPLINGMODE),new t(e,i,n,g.a.TEXTUREFORMAT_ALPHA,r,o,a,s)},t.CreateRGBTexture=function(e,i,n,r,o,a,s,c){return void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=g.a.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===c&&(c=g.a.TEXTURETYPE_UNSIGNED_INT),new t(e,i,n,g.a.TEXTUREFORMAT_RGB,r,o,a,s,c)},t.CreateRGBATexture=function(e,i,n,r,o,a,s,c){return void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=g.a.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===c&&(c=g.a.TEXTURETYPE_UNSIGNED_INT),new t(e,i,n,g.a.TEXTUREFORMAT_RGBA,r,o,a,s,c)},t.CreateRTexture=function(e,i,n,r,o,a,s,c){return void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=et.a.TRILINEAR_SAMPLINGMODE),void 0===c&&(c=g.a.TEXTURETYPE_FLOAT),new t(e,i,n,g.a.TEXTUREFORMAT_R,r,o,a,s,c)},t}(et.a),ot=function(){function e(e,t,i){this.name=e,this.id=t,this.bones=new Array,this.needInitialSkinMatrix=!1,this.overrideMesh=null,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=a.a.Identity(),this._ranges={},this._lastAbsoluteTransformsUpdateId=-1,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new o.c,this.bones=[],this._scene=i||R.a.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;var n=this._scene.getEngine().getCaps();this._canUseTextureForBones=n.textureFloat&&n.maxVertexTextureImageUnits>0}return Object.defineProperty(e.prototype,"useTextureToStoreBoneMatrices",{get:function(){return this._useTextureToStoreBoneMatrices},set:function(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isUsingTextureForMatrices",{get:function(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!0,configurable:!0}),e.prototype.getClassName=function(){return"Skeleton"},e.prototype.getChildren=function(){return this.bones.filter(function(e){return!e.getParent()})},e.prototype.getTransformMatrices=function(e){return this.needInitialSkinMatrix&&e._bonesTransformMatrices?e._bonesTransformMatrices:(this._transformMatrices||this.prepare(),this._transformMatrices)},e.prototype.getTransformMatrixTexture=function(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture},e.prototype.getScene=function(){return this._scene},e.prototype.toString=function(e){var t="Name: "+this.name+", nBones: "+this.bones.length;if(t+=", nAnimationRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";var i=!0;for(var n in this._ranges)i&&(t+=", ",i=!1),t+=n;t+="}"}return t},e.prototype.getBoneIndexByName=function(e){for(var t=0,i=this.bones.length;t<i;t++)if(this.bones[t].name===e)return t;return-1},e.prototype.createAnimationRange=function(e,t,i){if(!this._ranges[e]){this._ranges[e]=new F(e,t,i);for(var n=0,r=this.bones.length;n<r;n++)this.bones[n].animations[0]&&this.bones[n].animations[0].createRange(e,t,i)}},e.prototype.deleteAnimationRange=function(e,t){void 0===t&&(t=!0);for(var i=0,n=this.bones.length;i<n;i++)this.bones[i].animations[0]&&this.bones[i].animations[0].deleteRange(e,t);this._ranges[e]=null},e.prototype.getAnimationRange=function(e){return this._ranges[e]},e.prototype.getAnimationRanges=function(){var e,t=[];for(e in this._ranges)t.push(this._ranges[e]);return t},e.prototype.copyAnimationRange=function(e,t,i){if(void 0===i&&(i=!1),this._ranges[t]||!e.getAnimationRange(t))return!1;var n,r,o=!0,a=this._getHighestAnimationFrame()+1,s={},c=e.bones;for(r=0,n=c.length;r<n;r++)s[c[r].name]=c[r];this.bones.length!==c.length&&(m.a.Warn("copyAnimationRange: this rig has "+this.bones.length+" bones, while source as "+c.length),o=!1);var l=i&&this.dimensionsAtRest&&e.dimensionsAtRest?this.dimensionsAtRest.divide(e.dimensionsAtRest):null;for(r=0,n=this.bones.length;r<n;r++){var u=this.bones[r].name,h=s[u];h?o=o&&this.bones[r].copyAnimationRange(h,t,a,i,l):(m.a.Warn("copyAnimationRange: not same rig, missing source bone "+u),o=!1)}var d=e.getAnimationRange(t);return d&&(this._ranges[t]=new F(t,d.from+a,d.to+a)),o},e.prototype.returnToRest=function(){for(var e=0;e<this.bones.length;e++)this.bones[e].returnToRest()},e.prototype._getHighestAnimationFrame=function(){for(var e=0,t=0,i=this.bones.length;t<i;t++)if(this.bones[t].animations[0]){var n=this.bones[t].animations[0].getHighestFrame();e<n&&(e=n)}return e},e.prototype.beginAnimation=function(e,t,i,n){var r=this.getAnimationRange(e);return r?this._scene.beginAnimation(this,r.from,r.to,t,i,n):null},e.prototype._markAsDirty=function(){this._isDirty=!0},e.prototype._registerMeshWithPoseMatrix=function(e){this._meshesWithPoseMatrix.push(e)},e.prototype._unregisterMeshWithPoseMatrix=function(e){var t=this._meshesWithPoseMatrix.indexOf(e);t>-1&&this._meshesWithPoseMatrix.splice(t,1)},e.prototype._computeTransformMatrices=function(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(var i=0;i<this.bones.length;i++){var n=this.bones[i];n._childUpdateId++;var r=n.getParent();if(r?n.getLocalMatrix().multiplyToRef(r.getWorldMatrix(),n.getWorldMatrix()):t?n.getLocalMatrix().multiplyToRef(t,n.getWorldMatrix()):n.getWorldMatrix().copyFrom(n.getLocalMatrix()),-1!==n._index){var o=null===n._index?i:n._index;n.getInvertedAbsoluteTransform().multiplyToArray(n.getWorldMatrix(),e,16*o)}}this._identity.copyToArray(e,16*this.bones.length)},e.prototype.prepare=function(){if(this._numBonesWithLinkedTransformNode>0)for(var e=0,t=this.bones;e<t.length;e++){var i=t[e];i._linkedTransformNode&&(i._linkedTransformNode.computeWorldMatrix(),i._matrix=i._linkedTransformNode._localMatrix,i.markAsDirty())}if(this._isDirty){if(this.needInitialSkinMatrix)for(var n=0;n<this._meshesWithPoseMatrix.length;n++){var r=this._meshesWithPoseMatrix[n],o=r.getPoseMatrix();if(r._bonesTransformMatrices&&r._bonesTransformMatrices.length===16*(this.bones.length+1)||(r._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1))),this._synchronizedWithMesh!==r){this._synchronizedWithMesh=r;for(var s=0;s<this.bones.length;s++){var c=this.bones[s];if(!c.getParent())c.getBaseMatrix().multiplyToRef(o,a.c.Matrix[1]),c._updateDifferenceMatrix(a.c.Matrix[1])}if(this.isUsingTextureForMatrices){var l=4*(this.bones.length+1);r._transformMatrixTexture&&r._transformMatrixTexture.getSize().width===l||(r._transformMatrixTexture&&r._transformMatrixTexture.dispose(),r._transformMatrixTexture=rt.CreateRGBATexture(r._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,g.a.TEXTURE_NEAREST_SAMPLINGMODE,g.a.TEXTURETYPE_FLOAT))}}this._computeTransformMatrices(r._bonesTransformMatrices,o),this.isUsingTextureForMatrices&&r._transformMatrixTexture&&r._transformMatrixTexture.update(r._bonesTransformMatrices)}else this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=rt.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,g.a.TEXTURE_NEAREST_SAMPLINGMODE,g.a.TEXTURETYPE_FLOAT))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices);this._isDirty=!1,this._scene._activeBones.addCount(this.bones.length,!1)}},e.prototype.getAnimatables=function(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(var e=0;e<this.bones.length;e++)this._animatables.push(this.bones[e])}return this._animatables},e.prototype.clone=function(t,i){var n=new e(t,i||t,this._scene);n.needInitialSkinMatrix=this.needInitialSkinMatrix,n.overrideMesh=this.overrideMesh;for(var r=0;r<this.bones.length;r++){var o=this.bones[r],a=null,s=o.getParent();if(s){var c=this.bones.indexOf(s);a=n.bones[c]}var l=new J(o.name,n,a,o.getBaseMatrix().clone(),o.getRestPose().clone());l._index=o._index,o._linkedTransformNode&&l.linkTransformNode(o._linkedTransformNode),O.a.DeepCopy(o.animations,l.animations)}if(this._ranges)for(var u in n._ranges={},this._ranges){var h=this._ranges[u];h&&(n._ranges[u]=h.clone())}return this._isDirty=!0,n},e.prototype.enableBlending=function(e){void 0===e&&(e=.01),this.bones.forEach(function(t){t.animations.forEach(function(t){t.enableBlending=!0,t.blendingSpeed=e})})},e.prototype.dispose=function(){this._meshesWithPoseMatrix=[],this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)},e.prototype.serialize=function(){var e={};e.name=this.name,e.id=this.id,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(var t=0;t<this.bones.length;t++){var i=this.bones[t],n=i.getParent(),r={parentBoneIndex:n?this.bones.indexOf(n):-1,name:i.name,matrix:i.getBaseMatrix().toArray(),rest:i.getRestPose().toArray()};for(var o in e.bones.push(r),i.length&&(r.length=i.length),i.metadata&&(r.metadata=i.metadata),i.animations&&i.animations.length>0&&(r.animation=i.animations[0].serialize()),e.ranges=[],this._ranges){var a=this._ranges[o];if(a){var s={};s.name=o,s.from=a.from,s.to=a.to,e.ranges.push(s)}}}return e},e.Parse=function(t,i){var n,r=new e(t.name,t.id,i);for(t.dimensionsAtRest&&(r.dimensionsAtRest=a.e.FromArray(t.dimensionsAtRest)),r.needInitialSkinMatrix=t.needInitialSkinMatrix,n=0;n<t.bones.length;n++){var o=t.bones[n],s=null;o.parentBoneIndex>-1&&(s=r.bones[o.parentBoneIndex]);var c=o.rest?a.a.FromArray(o.rest):null,l=new J(o.name,r,s,a.a.FromArray(o.matrix),c);void 0!==o.id&&null!==o.id&&(l.id=o.id),o.length&&(l.length=o.length),o.metadata&&(l.metadata=o.metadata),o.animation&&l.animations.push(k.Parse(o.animation)),void 0!==o.linkedTransformNodeId&&null!==o.linkedTransformNodeId&&(r._hasWaitingData=!0,l._waitingTransformNodeId=o.linkedTransformNodeId)}if(t.ranges)for(n=0;n<t.ranges.length;n++){var u=t.ranges[n];r.createAnimationRange(u.name,u.from,u.to)}return r},e.prototype.computeAbsoluteTransforms=function(e){void 0===e&&(e=!1);var t=this._scene.getRenderId();(this._lastAbsoluteTransformsUpdateId!=t||e)&&(this.bones[0].computeAbsoluteTransforms(),this._lastAbsoluteTransformsUpdateId=t)},e.prototype.getPoseMatrix=function(){var e=null;return this._meshesWithPoseMatrix.length>0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e},e.prototype.sortBones=function(){for(var e=new Array,t=new Array(this.bones.length),i=0;i<this.bones.length;i++)this._sortBones(i,e,t);this.bones=e},e.prototype._sortBones=function(e,t,i){if(!i[e]){i[e]=!0;var n=this.bones[e];void 0===n._index&&(n._index=e);var r=n.getParent();r&&this._sortBones(this.bones.indexOf(r),t,i),t.push(n)}},e}(),at={},st=function(){function e(e){this.attached={},this.camera=e,this.checkInputs=function(){}}return e.prototype.add=function(e){var t=e.getSimpleName();this.attached[t]?m.a.Warn("camera input of type "+t+" already exists on camera"):(this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedElement&&e.attachControl(this.attachedElement))},e.prototype.remove=function(e){for(var t in this.attached){var i=this.attached[t];i===e&&(i.detachControl(this.attachedElement),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}},e.prototype.removeByType=function(e){for(var t in this.attached){var i=this.attached[t];i.getClassName()===e&&(i.detachControl(this.attachedElement),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}},e.prototype._addCheckInputs=function(e){var t=this.checkInputs;return function(){t(),e()}},e.prototype.attachInput=function(e){this.attachedElement&&e.attachControl(this.attachedElement,this.noPreventDefault)},e.prototype.attachElement=function(e,t){if(void 0===t&&(t=!1),!this.attachedElement)for(var i in t=!Qe.a.ForceAttachControlToAlwaysPreventDefault&&t,this.attachedElement=e,this.noPreventDefault=t,this.attached)this.attached[i].attachControl(e,t)},e.prototype.detachElement=function(e,t){if(void 0===t&&(t=!1),this.attachedElement===e){for(var i in this.attached)this.attached[i].detachControl(e),t&&(this.attached[i].camera=null);this.attachedElement=null}},e.prototype.rebuildInputCheck=function(){for(var e in this.checkInputs=function(){},this.attached){var t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}},e.prototype.clear=function(){this.attachedElement&&this.detachElement(this.attachedElement,!0),this.attached={},this.attachedElement=null,this.checkInputs=function(){}},e.prototype.serialize=function(e){var t={};for(var i in this.attached){var n=this.attached[i],r=N.a.Serialize(n);t[n.getClassName()]=r}e.inputsmgr=t},e.prototype.parse=function(e){var t=e.inputsmgr;if(t)for(var i in this.clear(),t){if(o=at[i]){var n=t[i],r=N.a.Parse(function(){return new o},n,null);this.add(r)}}else for(var i in this.attached){var o;if(o=at[this.attached[i].getClassName()]){r=N.a.Parse(function(){return new o},e,null);this.remove(this.attached[i]),this.add(r)}}},e}(),ct=function(e,t){this.x=e,this.y=t},lt=function(){function e(t,i,n,r,o,a,s){void 0===r&&(r=0),void 0===o&&(o=1),void 0===a&&(a=2),void 0===s&&(s=3),this.id=t,this.index=i,this.browserGamepad=n,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=e.GAMEPAD,this._leftStickAxisX=r,this._leftStickAxisY=o,this._rightStickAxisX=a,this._rightStickAxisY=s,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}return Object.defineProperty(e.prototype,"isConnected",{get:function(){return this._isConnected},enumerable:!0,configurable:!0}),e.prototype.onleftstickchanged=function(e){this._onleftstickchanged=e},e.prototype.onrightstickchanged=function(e){this._onrightstickchanged=e},Object.defineProperty(e.prototype,"leftStick",{get:function(){return this._leftStick},set:function(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rightStick",{get:function(){return this._rightStick},set:function(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e},enumerable:!0,configurable:!0}),e.prototype.update=function(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})},e.prototype.dispose=function(){},e.GAMEPAD=0,e.GENERIC=1,e.XBOX=2,e.POSE_ENABLED=3,e.DUALSHOCK=4,e}(),ut=function(e){function t(t,i,n){var r=e.call(this,t,i,n)||this;return r.onButtonDownObservable=new o.c,r.onButtonUpObservable=new o.c,r.type=lt.GENERIC,r._buttons=new Array(n.buttons.length),r}return Object(h.d)(t,e),t.prototype.onbuttondown=function(e){this._onbuttondown=e},t.prototype.onbuttonup=function(e){this._onbuttonup=e},t.prototype._setButtonValue=function(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e},t.prototype.update=function(){e.prototype.update.call(this);for(var t=0;t<this._buttons.length;t++)this._buttons[t]=this._setButtonValue(this.browserGamepad.buttons[t].value,this._buttons[t],t)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear()},t}(lt),ht=function(){function e(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40,this._yAxisScale=1}return Object.defineProperty(e.prototype,"invertYAxis",{get:function(){return 1!==this._yAxisScale},set:function(e){this._yAxisScale=e?-1:1},enumerable:!0,configurable:!0}),e.prototype.attachControl=function(e,t){var i=this,n=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=n.onGamepadConnectedObservable.add(function(e){e.type!==lt.POSE_ENABLED&&(i.gamepad&&e.type!==lt.XBOX||(i.gamepad=e))}),this._onGamepadDisconnectedObserver=n.onGamepadDisconnectedObservable.add(function(e){i.gamepad===e&&(i.gamepad=null)}),this.gamepad=n.getGamepadByType(lt.XBOX)},e.prototype.detachControl=function(e){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null},e.prototype.checkInputs=function(){if(this.gamepad){var e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){var i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){var n=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=n&&Math.abs(n)>.005&&(e.inertialBetaOffset+=n)}}var r=this.gamepad.leftStick;if(r&&0!=r.y){var o=r.y/this.gamepadMoveSensibility;0!=o&&Math.abs(o)>.005&&(this.camera.inertialRadiusOffset-=o)}}},e.prototype.getClassName=function(){return"ArcRotateCameraGamepadInput"},e.prototype.getSimpleName=function(){return"gamepad"},Object(h.c)([Object(N.c)()],e.prototype,"gamepadRotationSensibility",void 0),Object(h.c)([Object(N.c)()],e.prototype,"gamepadMoveSensibility",void 0),e}();at.ArcRotateCameraGamepadInput=ht;var dt=i(63),ft=function(){function e(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}return e.prototype.attachControl=function(e,t){var i=this;this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(function(){i._keys=[]}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(function(e){var n,r=e.event;r.metaKey||(e.type===dt.a.KEYDOWN?(i._ctrlPressed=r.ctrlKey,i._altPressed=r.altKey,(-1!==i.keysUp.indexOf(r.keyCode)||-1!==i.keysDown.indexOf(r.keyCode)||-1!==i.keysLeft.indexOf(r.keyCode)||-1!==i.keysRight.indexOf(r.keyCode)||-1!==i.keysReset.indexOf(r.keyCode))&&(-1===(n=i._keys.indexOf(r.keyCode))&&i._keys.push(r.keyCode),r.preventDefault&&(t||r.preventDefault()))):-1===i.keysUp.indexOf(r.keyCode)&&-1===i.keysDown.indexOf(r.keyCode)&&-1===i.keysLeft.indexOf(r.keyCode)&&-1===i.keysRight.indexOf(r.keyCode)&&-1===i.keysReset.indexOf(r.keyCode)||((n=i._keys.indexOf(r.keyCode))>=0&&i._keys.splice(n,1),r.preventDefault&&(t||r.preventDefault())))}))},e.prototype.detachControl=function(e){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=[]},e.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var e=this.camera,t=0;t<this._keys.length;t++){var i=this._keys[t];-1!==this.keysLeft.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX-=1/this.panningSensibility:e.inertialAlphaOffset-=this.angularSpeed:-1!==this.keysUp.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY+=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset+=1/this.zoomingSensibility:e.inertialBetaOffset-=this.angularSpeed:-1!==this.keysRight.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX+=1/this.panningSensibility:e.inertialAlphaOffset+=this.angularSpeed:-1!==this.keysDown.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY-=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset-=1/this.zoomingSensibility:e.inertialBetaOffset+=this.angularSpeed:-1!==this.keysReset.indexOf(i)&&e.useInputToRestoreState&&e.restoreState()}},e.prototype.getClassName=function(){return"ArcRotateCameraKeyboardMoveInput"},e.prototype.getSimpleName=function(){return"keyboard"},Object(h.c)([Object(N.c)()],e.prototype,"keysUp",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysDown",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysLeft",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysRight",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysReset",void 0),Object(h.c)([Object(N.c)()],e.prototype,"panningSensibility",void 0),Object(h.c)([Object(N.c)()],e.prototype,"zoomingSensibility",void 0),Object(h.c)([Object(N.c)()],e.prototype,"useAltToZoom",void 0),Object(h.c)([Object(N.c)()],e.prototype,"angularSpeed",void 0),e}();at.ArcRotateCameraKeyboardMoveInput=ft;var pt=function(){function e(){this.wheelPrecision=3,this.wheelDeltaPercentage=0}return e.prototype.computeDeltaFromMouseWheelLegacyEvent=function(e,t){var i=.01*e*this.wheelDeltaPercentage*t;return e>0?i/(1+this.wheelDeltaPercentage):i*(1+this.wheelDeltaPercentage)},e.prototype.attachControl=function(e,t){var i=this;this._wheel=function(e,n){if(e.type===Ve.a.POINTERWHEEL){var r=e.event,o=0,a=r,s=0;if(s=a.wheelDelta?a.wheelDelta:60*-(r.deltaY||r.detail),i.wheelDeltaPercentage){if((o=i.computeDeltaFromMouseWheelLegacyEvent(s,i.camera.radius))>0){for(var c=i.camera.radius,l=i.camera.inertialRadiusOffset+o,u=0;u<20&&Math.abs(l)>.001;u++)c-=l,l*=i.camera.inertia;c=L.a.Clamp(c,0,Number.MAX_VALUE),o=i.computeDeltaFromMouseWheelLegacyEvent(s,c)}}else o=s/(40*i.wheelPrecision);o&&(i.camera.inertialRadiusOffset+=o),r.preventDefault&&(t||r.preventDefault())}},this._observer=this.camera.getScene().onPointerObservable.add(this._wheel,Ve.a.POINTERWHEEL)},e.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._wheel=null)},e.prototype.getClassName=function(){return"ArcRotateCameraMouseWheelInput"},e.prototype.getSimpleName=function(){return"mousewheel"},Object(h.c)([Object(N.c)()],e.prototype,"wheelPrecision",void 0),Object(h.c)([Object(N.c)()],e.prototype,"wheelDeltaPercentage",void 0),e}();at.ArcRotateCameraMouseWheelInput=pt;var _t=function(){function e(){this.buttons=[0,1,2]}return e.prototype.attachControl=function(e,t){var i=this,n=this.camera.getEngine(),r=0,o=null;this.pointA=null,this.pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=function(a,s){var c=a.event,l="touch"===c.pointerType;if(!n.isInVRExclusivePointerMode&&(a.type===Ve.a.POINTERMOVE||-1!==i.buttons.indexOf(c.button))){var u=c.srcElement||c.target;if(i._altKey=c.altKey,i._ctrlKey=c.ctrlKey,i._metaKey=c.metaKey,i._shiftKey=c.shiftKey,i._buttonsPressed=c.buttons,n.isPointerLock){var h=c.movementX||c.mozMovementX||c.webkitMovementX||c.msMovementX||0,d=c.movementY||c.mozMovementY||c.webkitMovementY||c.msMovementY||0;i.onTouch(null,h,d),i.pointA=null,i.pointB=null}else if(a.type===Ve.a.POINTERDOWN&&u){try{u.setPointerCapture(c.pointerId)}catch(e){}null===i.pointA?i.pointA={x:c.clientX,y:c.clientY,pointerId:c.pointerId,type:c.pointerType}:null===i.pointB&&(i.pointB={x:c.clientX,y:c.clientY,pointerId:c.pointerId,type:c.pointerType}),i.onButtonDown(c),t||(c.preventDefault(),e.focus())}else if(a.type===Ve.a.POINTERDOUBLETAP)i.onDoubleTap(c.pointerType);else if(a.type===Ve.a.POINTERUP&&u){try{u.releasePointerCapture(c.pointerId)}catch(e){}l||(i.pointB=null),n._badOS?i.pointA=i.pointB=null:i.pointB&&i.pointA&&i.pointA.pointerId==c.pointerId?(i.pointA=i.pointB,i.pointB=null):i.pointA&&i.pointB&&i.pointB.pointerId==c.pointerId?i.pointB=null:i.pointA=i.pointB=null,(0!==r||o)&&(i.onMultiTouch(i.pointA,i.pointB,r,0,o,null),r=0,o=null),i.onButtonUp(c),t||c.preventDefault()}else if(a.type===Ve.a.POINTERMOVE)if(t||c.preventDefault(),i.pointA&&null===i.pointB){h=c.clientX-i.pointA.x,d=c.clientY-i.pointA.y;i.onTouch(i.pointA,h,d),i.pointA.x=c.clientX,i.pointA.y=c.clientY}else if(i.pointA&&i.pointB){var f=i.pointA.pointerId===c.pointerId?i.pointA:i.pointB;f.x=c.clientX,f.y=c.clientY;var p=i.pointA.x-i.pointB.x,_=i.pointA.y-i.pointB.y,m=p*p+_*_,g={x:(i.pointA.x+i.pointB.x)/2,y:(i.pointA.y+i.pointB.y)/2,pointerId:c.pointerId,type:a.type};i.onMultiTouch(i.pointA,i.pointB,r,m,o,g),o=g,r=m}}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,Ve.a.POINTERDOWN|Ve.a.POINTERUP|Ve.a.POINTERMOVE),this._onLostFocus=function(){i.pointA=i.pointB=null,r=0,o=null,i.onLostFocus()},e.addEventListener("contextmenu",this.onContextMenu.bind(this),!1);var a=this.camera.getScene().getEngine().getHostWindow();a&&De.b.RegisterTopRootEvents(a,[{name:"blur",handler:this._onLostFocus}])},e.prototype.detachControl=function(e){if(this._onLostFocus){var t=this.camera.getScene().getEngine().getHostWindow();t&&De.b.UnregisterTopRootEvents(t,[{name:"blur",handler:this._onLostFocus}])}e&&this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this.onContextMenu&&e.removeEventListener("contextmenu",this.onContextMenu),this._onLostFocus=null),this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0},e.prototype.getClassName=function(){return"BaseCameraPointersInput"},e.prototype.getSimpleName=function(){return"pointers"},e.prototype.onDoubleTap=function(e){},e.prototype.onTouch=function(e,t,i){},e.prototype.onMultiTouch=function(e,t,i,n,r,o){},e.prototype.onContextMenu=function(e){e.preventDefault()},e.prototype.onButtonDown=function(e){},e.prototype.onButtonUp=function(e){},e.prototype.onLostFocus=function(){},Object(h.c)([Object(N.c)()],e.prototype,"buttons",void 0),e}(),mt=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.buttons=[0,1,2],t.angularSensibilityX=1e3,t.angularSensibilityY=1e3,t.pinchPrecision=12,t.pinchDeltaPercentage=0,t.useNaturalPinchZoom=!1,t.panningSensibility=1e3,t.multiTouchPanning=!0,t.multiTouchPanAndZoom=!0,t.pinchInwards=!0,t._isPanClick=!1,t._twoFingerActivityCount=0,t._isPinching=!1,t}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"ArcRotateCameraPointersInput"},t.prototype.onTouch=function(e,t,i){0!==this.panningSensibility&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)},t.prototype.onDoubleTap=function(e){this.camera.useInputToRestoreState&&this.camera.restoreState()},t.prototype.onMultiTouch=function(e,t,i,n,r,o){if(!(0===i&&null===r||0===n&&null===o)){var a=this.pinchInwards?1:-1;if(this.multiTouchPanAndZoom){if(this.useNaturalPinchZoom?this.camera.radius=this.camera.radius*Math.sqrt(i)/Math.sqrt(n):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=.001*(n-i)*this.camera.radius*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(n-i)/(this.pinchPrecision*a*(this.angularSensibilityX+this.angularSensibilityY)/2),0!==this.panningSensibility&&r&&o){var s=o.x-r.x,c=o.y-r.y;this.camera.inertialPanningX+=-s/this.panningSensibility,this.camera.inertialPanningY+=c/this.panningSensibility}}else{this._twoFingerActivityCount++;var l=Math.sqrt(i),u=Math.sqrt(n);if(this._isPinching||this._twoFingerActivityCount<20&&Math.abs(u-l)>this.camera.pinchToPanMaxDistance)this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=.001*(n-i)*this.camera.radius*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(n-i)/(this.pinchPrecision*a*(this.angularSensibilityX+this.angularSensibilityY)/2),this._isPinching=!0;else if(0!==this.panningSensibility&&this.multiTouchPanning&&o&&r){s=o.x-r.x,c=o.y-r.y;this.camera.inertialPanningX+=-s/this.panningSensibility,this.camera.inertialPanningY+=c/this.panningSensibility}}}},t.prototype.onButtonDown=function(e){this._isPanClick=e.button===this.camera._panningMouseButton},t.prototype.onButtonUp=function(e){this._twoFingerActivityCount=0,this._isPinching=!1},t.prototype.onLostFocus=function(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1},Object(h.c)([Object(N.c)()],t.prototype,"buttons",void 0),Object(h.c)([Object(N.c)()],t.prototype,"angularSensibilityX",void 0),Object(h.c)([Object(N.c)()],t.prototype,"angularSensibilityY",void 0),Object(h.c)([Object(N.c)()],t.prototype,"pinchPrecision",void 0),Object(h.c)([Object(N.c)()],t.prototype,"pinchDeltaPercentage",void 0),Object(h.c)([Object(N.c)()],t.prototype,"useNaturalPinchZoom",void 0),Object(h.c)([Object(N.c)()],t.prototype,"panningSensibility",void 0),Object(h.c)([Object(N.c)()],t.prototype,"multiTouchPanning",void 0),Object(h.c)([Object(N.c)()],t.prototype,"multiTouchPanAndZoom",void 0),t}(_t);at.ArcRotateCameraPointersInput=mt;var gt=function(e){function t(t){return e.call(this,t)||this}return Object(h.d)(t,e),t.prototype.addMouseWheel=function(){return this.add(new pt),this},t.prototype.addPointers=function(){return this.add(new mt),this},t.prototype.addKeyboard=function(){return this.add(new ft),this},t}(st);gt.prototype.addVRDeviceOrientation=function(){return this.add(new vt),this};var vt=function(){function e(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=this._onOrientationEvent.bind(this)}return e.prototype.attachControl=function(e,t){var i=this;this.camera.attachControl(e,t);var n=this.camera.getScene().getEngine().getHostWindow();n&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(function(e){"granted"===e?n.addEventListener("deviceorientation",i._deviceOrientationHandler):De.b.Warn("Permission not granted.")}).catch(function(e){De.b.Error(e)}):n.addEventListener("deviceorientation",this._deviceOrientationHandler))},e.prototype._onOrientationEvent=function(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*this.gammaCorrection),this._dirty=!0},e.prototype.checkInputs=function(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)},e.prototype.detachControl=function(e){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)},e.prototype.getClassName=function(){return"ArcRotateCameraVRDeviceOrientationInput"},e.prototype.getSimpleName=function(){return"VRDeviceOrientation"},e}();at.ArcRotateCameraVRDeviceOrientationInput=vt;var yt=function(){function e(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=new Array}return e.prototype.attachControl=function(e,t){var i=this;this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(function(){i._keys=[]}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(function(e){var n,r=e.event;e.type===dt.a.KEYDOWN?-1===i.keysForward.indexOf(r.keyCode)&&-1===i.keysBackward.indexOf(r.keyCode)&&-1===i.keysUp.indexOf(r.keyCode)&&-1===i.keysDown.indexOf(r.keyCode)&&-1===i.keysLeft.indexOf(r.keyCode)&&-1===i.keysRight.indexOf(r.keyCode)||(-1===(n=i._keys.indexOf(r.keyCode))&&i._keys.push(r.keyCode),t||r.preventDefault()):-1===i.keysForward.indexOf(r.keyCode)&&-1===i.keysBackward.indexOf(r.keyCode)&&-1===i.keysUp.indexOf(r.keyCode)&&-1===i.keysDown.indexOf(r.keyCode)&&-1===i.keysLeft.indexOf(r.keyCode)&&-1===i.keysRight.indexOf(r.keyCode)||((n=i._keys.indexOf(r.keyCode))>=0&&i._keys.splice(n,1),t||r.preventDefault())}))},e.prototype.detachControl=function(e){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=[]},e.prototype.getClassName=function(){return"FlyCameraKeyboardInput"},e.prototype._onLostFocus=function(e){this._keys=[]},e.prototype.getSimpleName=function(){return"keyboard"},e.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var e=this.camera,t=0;t<this._keys.length;t++){var i=this._keys[t],n=e._computeLocalCameraSpeed();-1!==this.keysForward.indexOf(i)?e._localDirection.copyFromFloats(0,0,n):-1!==this.keysBackward.indexOf(i)?e._localDirection.copyFromFloats(0,0,-n):-1!==this.keysUp.indexOf(i)?e._localDirection.copyFromFloats(0,n,0):-1!==this.keysDown.indexOf(i)?e._localDirection.copyFromFloats(0,-n,0):-1!==this.keysRight.indexOf(i)?e._localDirection.copyFromFloats(n,0,0):-1!==this.keysLeft.indexOf(i)&&e._localDirection.copyFromFloats(-n,0,0),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),a.e.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}},Object(h.c)([Object(N.c)()],e.prototype,"keysForward",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysBackward",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysUp",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysDown",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysRight",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysLeft",void 0),e}();at.FlyCameraKeyboardInput=yt;var bt=function(){function e(e){void 0===e&&(e=!0),this.buttons=[0,1,2],this.buttonsYaw=[-1,0,1],this.buttonsPitch=[-1,0,1],this.buttonsRoll=[2],this.activeButton=-1,this.angularSensibility=1e3,this.previousPosition=null}return e.prototype.attachControl=function(e,t){var i=this;this.element=e,this.noPreventDefault=t,this._observer=this.camera.getScene().onPointerObservable.add(function(e,t){i._pointerInput(e,t)},Ve.a.POINTERDOWN|Ve.a.POINTERUP|Ve.a.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add(function(){i.camera.rollCorrect&&i.camera.restoreRoll(i.camera.rollCorrect)}),this._mousemoveCallback=function(e){i._onMouseMove(e)},e.addEventListener("mousemove",this._mousemoveCallback,!1)},e.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._mousemoveCallback&&e.removeEventListener("mousemove",this._mousemoveCallback),this._observer=null,this._rollObserver=null,this.previousPosition=null,this.noPreventDefault=void 0)},e.prototype.getClassName=function(){return"FlyCameraMouseInput"},e.prototype.getSimpleName=function(){return"mouse"},e.prototype._pointerInput=function(e,t){var i=e.event,n=this.camera.getEngine();if(!n.isInVRExclusivePointerMode&&(this.touchEnabled||"touch"!==i.pointerType)&&(e.type===Ve.a.POINTERMOVE||-1!==this.buttons.indexOf(i.button))){var r=i.srcElement||i.target;if(e.type===Ve.a.POINTERDOWN&&r){try{r.setPointerCapture(i.pointerId)}catch(i){}this.previousPosition={x:i.clientX,y:i.clientY},this.activeButton=i.button,this.noPreventDefault||(i.preventDefault(),this.element.focus())}else if(e.type===Ve.a.POINTERUP&&r){try{r.releasePointerCapture(i.pointerId)}catch(i){}this.activeButton=-1,this.previousPosition=null,this.noPreventDefault||i.preventDefault()}else if(e.type===Ve.a.POINTERMOVE){if(!this.previousPosition||n.isPointerLock)return;var o=i.clientX-this.previousPosition.x,a=i.clientY-this.previousPosition.y;this.rotateCamera(o,a),this.previousPosition={x:i.clientX,y:i.clientY},this.noPreventDefault||i.preventDefault()}}},e.prototype._onMouseMove=function(e){var t=this.camera.getEngine();if(t.isPointerLock&&!t.isInVRExclusivePointerMode){var i=e.movementX||e.mozMovementX||e.webkitMovementX||e.msMovementX||0,n=e.movementY||e.mozMovementY||e.webkitMovementY||e.msMovementY||0;this.rotateCamera(i,n),this.previousPosition=null,this.noPreventDefault||e.preventDefault()}},e.prototype.rotateCamera=function(e,t){var i=this,n=this.camera;this.camera.getScene().useRightHandedSystem&&(e*=-1),n.parent&&n.parent._getWorldMatrixDeterminant()<0&&(e*=-1);var r,o=e/this.angularSensibility,s=t/this.angularSensibility,c=a.b.RotationYawPitchRoll(n.rotation.y,n.rotation.x,n.rotation.z);if(this.buttonsPitch.some(function(e){return e===i.activeButton})&&(r=a.b.RotationAxis(Z.a.X,s),c.multiplyInPlace(r)),this.buttonsYaw.some(function(e){return e===i.activeButton})){r=a.b.RotationAxis(Z.a.Y,o),c.multiplyInPlace(r);var l=n.bankedTurnLimit+n._trackRoll;if(n.bankedTurn&&-l<n.rotation.z&&n.rotation.z<l){var u=n.bankedTurnMultiplier*-o;r=a.b.RotationAxis(Z.a.Z,u),c.multiplyInPlace(r)}}this.buttonsRoll.some(function(e){return e===i.activeButton})&&(r=a.b.RotationAxis(Z.a.Z,-o),n._trackRoll-=o,c.multiplyInPlace(r)),c.toEulerAnglesToRef(n.rotation)},Object(h.c)([Object(N.c)()],e.prototype,"buttons",void 0),Object(h.c)([Object(N.c)()],e.prototype,"angularSensibility",void 0),e}();at.FlyCameraMouseInput=bt;var Tt=function(){function e(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=new Array}return e.prototype.attachControl=function(e,t){var i=this;this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(function(){i._keys=[]}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(function(e){var n,r=e.event;r.metaKey||(e.type===dt.a.KEYDOWN?(i._ctrlPressed=r.ctrlKey,i._altPressed=r.altKey,i._shiftPressed=r.shiftKey,(-1!==i.keysHeightOffsetIncr.indexOf(r.keyCode)||-1!==i.keysHeightOffsetDecr.indexOf(r.keyCode)||-1!==i.keysRotationOffsetIncr.indexOf(r.keyCode)||-1!==i.keysRotationOffsetDecr.indexOf(r.keyCode)||-1!==i.keysRadiusIncr.indexOf(r.keyCode)||-1!==i.keysRadiusDecr.indexOf(r.keyCode))&&(-1===(n=i._keys.indexOf(r.keyCode))&&i._keys.push(r.keyCode),r.preventDefault&&(t||r.preventDefault()))):-1===i.keysHeightOffsetIncr.indexOf(r.keyCode)&&-1===i.keysHeightOffsetDecr.indexOf(r.keyCode)&&-1===i.keysRotationOffsetIncr.indexOf(r.keyCode)&&-1===i.keysRotationOffsetDecr.indexOf(r.keyCode)&&-1===i.keysRadiusIncr.indexOf(r.keyCode)&&-1===i.keysRadiusDecr.indexOf(r.keyCode)||((n=i._keys.indexOf(r.keyCode))>=0&&i._keys.splice(n,1),r.preventDefault&&(t||r.preventDefault())))}))},e.prototype.detachControl=function(e){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=[]},e.prototype.checkInputs=function(){var e=this;this._onKeyboardObserver&&this._keys.forEach(function(t){-1!==e.keysHeightOffsetIncr.indexOf(t)&&e._modifierHeightOffset()?e.camera.heightOffset+=e.heightSensibility:-1!==e.keysHeightOffsetDecr.indexOf(t)&&e._modifierHeightOffset()?e.camera.heightOffset-=e.heightSensibility:-1!==e.keysRotationOffsetIncr.indexOf(t)&&e._modifierRotationOffset()?(e.camera.rotationOffset+=e.rotationSensibility,e.camera.rotationOffset%=360):-1!==e.keysRotationOffsetDecr.indexOf(t)&&e._modifierRotationOffset()?(e.camera.rotationOffset-=e.rotationSensibility,e.camera.rotationOffset%=360):-1!==e.keysRadiusIncr.indexOf(t)&&e._modifierRadius()?e.camera.radius+=e.radiusSensibility:-1!==e.keysRadiusDecr.indexOf(t)&&e._modifierRadius()&&(e.camera.radius-=e.radiusSensibility)})},e.prototype.getClassName=function(){return"FollowCameraKeyboardMoveInput"},e.prototype.getSimpleName=function(){return"keyboard"},e.prototype._modifierHeightOffset=function(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed},e.prototype._modifierRotationOffset=function(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed},e.prototype._modifierRadius=function(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed},Object(h.c)([Object(N.c)()],e.prototype,"keysHeightOffsetIncr",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysHeightOffsetDecr",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysHeightOffsetModifierAlt",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysHeightOffsetModifierCtrl",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysHeightOffsetModifierShift",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysRotationOffsetIncr",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysRotationOffsetDecr",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysRotationOffsetModifierAlt",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysRotationOffsetModifierCtrl",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysRotationOffsetModifierShift",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysRadiusIncr",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysRadiusDecr",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysRadiusModifierAlt",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysRadiusModifierCtrl",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysRadiusModifierShift",void 0),Object(h.c)([Object(N.c)()],e.prototype,"heightSensibility",void 0),Object(h.c)([Object(N.c)()],e.prototype,"rotationSensibility",void 0),Object(h.c)([Object(N.c)()],e.prototype,"radiusSensibility",void 0),e}();at.FollowCameraKeyboardMoveInput=Tt;var Et=function(){function e(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}return e.prototype.attachControl=function(e,t){var i=this;this._wheel=function(e,n){if(e.type===Ve.a.POINTERWHEEL){var r=e.event,o=0,a=Math.max(-1,Math.min(1,r.deltaY||r.wheelDelta||-r.detail));i.wheelDeltaPercentage?(console.assert(i.axisControlRadius+i.axisControlHeight+i.axisControlRotation<=1,"wheelDeltaPercentage only usable when mouse wheel controlls ONE axis. Currently enabled: axisControlRadius: "+i.axisControlRadius+", axisControlHeightOffset: "+i.axisControlHeight+", axisControlRotationOffset: "+i.axisControlRotation),i.axisControlRadius?o=.01*a*i.wheelDeltaPercentage*i.camera.radius:i.axisControlHeight?o=.01*a*i.wheelDeltaPercentage*i.camera.heightOffset:i.axisControlRotation&&(o=.01*a*i.wheelDeltaPercentage*i.camera.rotationOffset)):o=a*i.wheelPrecision,o&&(i.axisControlRadius?i.camera.radius+=o:i.axisControlHeight?i.camera.heightOffset-=o:i.axisControlRotation&&(i.camera.rotationOffset-=o)),r.preventDefault&&(t||r.preventDefault())}},this._observer=this.camera.getScene().onPointerObservable.add(this._wheel,Ve.a.POINTERWHEEL)},e.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._wheel=null)},e.prototype.getClassName=function(){return"ArcRotateCameraMouseWheelInput"},e.prototype.getSimpleName=function(){return"mousewheel"},Object(h.c)([Object(N.c)()],e.prototype,"axisControlRadius",void 0),Object(h.c)([Object(N.c)()],e.prototype,"axisControlHeight",void 0),Object(h.c)([Object(N.c)()],e.prototype,"axisControlRotation",void 0),Object(h.c)([Object(N.c)()],e.prototype,"wheelPrecision",void 0),Object(h.c)([Object(N.c)()],e.prototype,"wheelDeltaPercentage",void 0),e}();at.FollowCameraMouseWheelInput=Et;var xt=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.angularSensibilityX=1,t.angularSensibilityY=1,t.pinchPrecision=1e4,t.pinchDeltaPercentage=0,t.axisXControlRadius=!1,t.axisXControlHeight=!1,t.axisXControlRotation=!0,t.axisYControlRadius=!1,t.axisYControlHeight=!0,t.axisYControlRotation=!1,t.axisPinchControlRadius=!0,t.axisPinchControlHeight=!1,t.axisPinchControlRotation=!1,t.warningEnable=!0,t._warningCounter=0,t}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"FollowCameraPointersInput"},t.prototype.onTouch=function(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)},t.prototype.onMultiTouch=function(e,t,i,n,r,o){if(!(0===i&&null===r||0===n&&null===o)){var a=(n-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(a*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=a*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=a*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=a*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=a),this.axisPinchControlHeight&&(this.camera.heightOffset+=a),this.axisPinchControlRadius&&(this.camera.radius-=a))}},t.prototype._warning=function(){if(this.warningEnable&&this._warningCounter++%100==0){var e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";console.assert(this.axisXControlRotation+this.axisXControlHeight+this.axisXControlRadius<=1,e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),console.assert(this.axisYControlRotation+this.axisYControlHeight+this.axisYControlRadius<=1,e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),console.assert(this.axisPinchControlRotation+this.axisPinchControlHeight+this.axisPinchControlRadius<=1,e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}},Object(h.c)([Object(N.c)()],t.prototype,"angularSensibilityX",void 0),Object(h.c)([Object(N.c)()],t.prototype,"angularSensibilityY",void 0),Object(h.c)([Object(N.c)()],t.prototype,"pinchPrecision",void 0),Object(h.c)([Object(N.c)()],t.prototype,"pinchDeltaPercentage",void 0),Object(h.c)([Object(N.c)()],t.prototype,"axisXControlRadius",void 0),Object(h.c)([Object(N.c)()],t.prototype,"axisXControlHeight",void 0),Object(h.c)([Object(N.c)()],t.prototype,"axisXControlRotation",void 0),Object(h.c)([Object(N.c)()],t.prototype,"axisYControlRadius",void 0),Object(h.c)([Object(N.c)()],t.prototype,"axisYControlHeight",void 0),Object(h.c)([Object(N.c)()],t.prototype,"axisYControlRotation",void 0),Object(h.c)([Object(N.c)()],t.prototype,"axisPinchControlRadius",void 0),Object(h.c)([Object(N.c)()],t.prototype,"axisPinchControlHeight",void 0),Object(h.c)([Object(N.c)()],t.prototype,"axisPinchControlRotation",void 0),t}(_t);at.FollowCameraPointersInput=xt;var Pt=function(){function e(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this._keys=new Array}return e.prototype.attachControl=function(e,t){var i=this;this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(function(){i._keys=[]}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(function(e){var n,r=e.event;r.metaKey||(e.type===dt.a.KEYDOWN?-1===i.keysUp.indexOf(r.keyCode)&&-1===i.keysDown.indexOf(r.keyCode)&&-1===i.keysLeft.indexOf(r.keyCode)&&-1===i.keysRight.indexOf(r.keyCode)||(-1===(n=i._keys.indexOf(r.keyCode))&&i._keys.push(r.keyCode),t||r.preventDefault()):-1===i.keysUp.indexOf(r.keyCode)&&-1===i.keysDown.indexOf(r.keyCode)&&-1===i.keysLeft.indexOf(r.keyCode)&&-1===i.keysRight.indexOf(r.keyCode)||((n=i._keys.indexOf(r.keyCode))>=0&&i._keys.splice(n,1),t||r.preventDefault()))}))},e.prototype.detachControl=function(e){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=[]},e.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var e=this.camera,t=0;t<this._keys.length;t++){var i=this._keys[t],n=e._computeLocalCameraSpeed();-1!==this.keysLeft.indexOf(i)?e._localDirection.copyFromFloats(-n,0,0):-1!==this.keysUp.indexOf(i)?e._localDirection.copyFromFloats(0,0,n):-1!==this.keysRight.indexOf(i)?e._localDirection.copyFromFloats(n,0,0):-1!==this.keysDown.indexOf(i)&&e._localDirection.copyFromFloats(0,0,-n),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),a.e.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}},e.prototype.getClassName=function(){return"FreeCameraKeyboardMoveInput"},e.prototype._onLostFocus=function(){this._keys=[]},e.prototype.getSimpleName=function(){return"keyboard"},Object(h.c)([Object(N.c)()],e.prototype,"keysUp",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysDown",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysLeft",void 0),Object(h.c)([Object(N.c)()],e.prototype,"keysRight",void 0),e}();at.FreeCameraKeyboardMoveInput=Pt;var At=function(){function e(e){void 0===e&&(e=!0),this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3,this.previousPosition=null,this.onPointerMovedObservable=new o.c,this._allowCameraRotation=!0}return e.prototype.attachControl=function(e,t){var i=this,n=this.camera.getEngine();this._pointerInput||(this._pointerInput=function(r){var o=r.event;if(!n.isInVRExclusivePointerMode&&(i.touchEnabled||"touch"!==o.pointerType)&&(r.type===Ve.a.POINTERMOVE||-1!==i.buttons.indexOf(o.button))){var a=o.srcElement||o.target;if(r.type===Ve.a.POINTERDOWN&&a){try{a.setPointerCapture(o.pointerId)}catch(e){}i.previousPosition={x:o.clientX,y:o.clientY},t||(o.preventDefault(),e.focus())}else if(r.type===Ve.a.POINTERUP&&a){try{a.releasePointerCapture(o.pointerId)}catch(e){}i.previousPosition=null,t||o.preventDefault()}else if(r.type===Ve.a.POINTERMOVE){if(!i.previousPosition||n.isPointerLock)return;var s=o.clientX-i.previousPosition.x,c=o.clientY-i.previousPosition.y;i.camera.getScene().useRightHandedSystem&&(s*=-1),i.camera.parent&&i.camera.parent._getWorldMatrixDeterminant()<0&&(s*=-1),i._allowCameraRotation&&(i.camera.cameraRotation.y+=s/i.angularSensibility,i.camera.cameraRotation.x+=c/i.angularSensibility),i.onPointerMovedObservable.notifyObservers({offsetX:s,offsetY:c}),i.previousPosition={x:o.clientX,y:o.clientY},t||o.preventDefault()}}}),this._onMouseMove=function(e){if(n.isPointerLock&&!n.isInVRExclusivePointerMode){var r=e.movementX||e.mozMovementX||e.webkitMovementX||e.msMovementX||0;i.camera.getScene().useRightHandedSystem&&(r*=-1),i.camera.parent&&i.camera.parent._getWorldMatrixDeterminant()<0&&(r*=-1),i.camera.cameraRotation.y+=r/i.angularSensibility;var o=e.movementY||e.mozMovementY||e.webkitMovementY||e.msMovementY||0;i.camera.cameraRotation.x+=o/i.angularSensibility,i.previousPosition=null,t||e.preventDefault()}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,Ve.a.POINTERDOWN|Ve.a.POINTERUP|Ve.a.POINTERMOVE),e.addEventListener("mousemove",this._onMouseMove,!1),e.addEventListener("contextmenu",this.onContextMenu.bind(this),!1)},e.prototype.onContextMenu=function(e){e.preventDefault()},e.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._onMouseMove&&e.removeEventListener("mousemove",this._onMouseMove),this.onContextMenu&&e.removeEventListener("contextmenu",this.onContextMenu),this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this.previousPosition=null)},e.prototype.getClassName=function(){return"FreeCameraMouseInput"},e.prototype.getSimpleName=function(){return"mouse"},Object(h.c)([Object(N.c)()],e.prototype,"buttons",void 0),Object(h.c)([Object(N.c)()],e.prototype,"angularSensibility",void 0),e}();at.FreeCameraMouseInput=At;var St=function(){function e(){this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array}return e.prototype.attachControl=function(e,t){var i=this,n=null;void 0===this._pointerInput&&(this._onLostFocus=function(){i._offsetX=null,i._offsetY=null},this._pointerInput=function(e){var r=e.event;if("mouse"!==r.pointerType)if(e.type===Ve.a.POINTERDOWN){if(t||r.preventDefault(),i._pointerPressed.push(r.pointerId),1!==i._pointerPressed.length)return;n={x:r.clientX,y:r.clientY}}else if(e.type===Ve.a.POINTERUP){if(t||r.preventDefault(),-1===(o=i._pointerPressed.indexOf(r.pointerId)))return;if(i._pointerPressed.splice(o,1),0!=o)return;n=null,i._offsetX=null,i._offsetY=null}else if(e.type===Ve.a.POINTERMOVE){if(t||r.preventDefault(),!n)return;var o;if(0!=(o=i._pointerPressed.indexOf(r.pointerId)))return;i._offsetX=r.clientX-n.x,i._offsetY=-(r.clientY-n.y)}}),this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,Ve.a.POINTERDOWN|Ve.a.POINTERUP|Ve.a.POINTERMOVE),this._onLostFocus&&e.addEventListener("blur",this._onLostFocus)},e.prototype.detachControl=function(e){this._pointerInput&&e&&(this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null),this._onLostFocus&&(e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null),this._pointerPressed=[],this._offsetX=null,this._offsetY=null)},e.prototype.checkInputs=function(){if(this._offsetX&&this._offsetY){var e=this.camera;if(e.cameraRotation.y+=this._offsetX/this.touchAngularSensibility,this._pointerPressed.length>1)e.cameraRotation.x+=-this._offsetY/this.touchAngularSensibility;else{var t=e._computeLocalCameraSpeed(),i=new a.e(0,0,t*this._offsetY/this.touchMoveSensibility);a.a.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(a.e.TransformCoordinates(i,e._cameraRotationMatrix))}}},e.prototype.getClassName=function(){return"FreeCameraTouchInput"},e.prototype.getSimpleName=function(){return"touch"},Object(h.c)([Object(N.c)()],e.prototype,"touchAngularSensibility",void 0),Object(h.c)([Object(N.c)()],e.prototype,"touchMoveSensibility",void 0),e}();at.FreeCameraTouchInput=St;var Ct=function(e){function t(t){var i=e.call(this,t)||this;return i._mouseInput=null,i}return Object(h.d)(t,e),t.prototype.addKeyboard=function(){return this.add(new Pt),this},t.prototype.addMouse=function(e){return void 0===e&&(e=!0),this._mouseInput||(this._mouseInput=new At(e),this.add(this._mouseInput)),this},t.prototype.removeMouse=function(){return this._mouseInput&&this.remove(this._mouseInput),this},t.prototype.addTouch=function(){return this.add(new St),this},t.prototype.clear=function(){e.prototype.clear.call(this),this._mouseInput=null},t}(st);Ct.prototype.addDeviceOrientation=function(){return this._deviceOrientationInput||(this._deviceOrientationInput=new Rt,this.add(this._deviceOrientationInput)),this};var Rt=function(){function e(){var e=this;this._screenOrientationAngle=0,this._screenQuaternion=new a.b,this._alpha=0,this._beta=0,this._gamma=0,this._onDeviceOrientationChangedObservable=new o.c,this._orientationChanged=function(){e._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,e._screenOrientationAngle=-De.b.ToRadians(e._screenOrientationAngle/2),e._screenQuaternion.copyFromFloats(0,Math.sin(e._screenOrientationAngle),0,Math.cos(e._screenOrientationAngle))},this._deviceOrientation=function(t){e._alpha=null!==t.alpha?t.alpha:0,e._beta=null!==t.beta?t.beta:0,e._gamma=null!==t.gamma?t.gamma:0,null!==t.alpha&&e._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new a.b(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}return e.WaitForOrientationChangeAsync=function(e){return new Promise(function(t,i){var n=!1,r=function(){window.removeEventListener("deviceorientation",r),n=!0,t()};e&&setTimeout(function(){n||(window.removeEventListener("deviceorientation",r),i("WaitForOrientationChangeAsync timed out"))},e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(function(e){"granted"==e?window.addEventListener("deviceorientation",r):De.b.Warn("Permission not granted.")}).catch(function(e){De.b.Error(e)}):window.addEventListener("deviceorientation",r)})},Object.defineProperty(e.prototype,"camera",{get:function(){return this._camera},set:function(e){var t=this;this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new a.b),this._camera&&this._camera.onDisposeObservable.add(function(){t._onDeviceOrientationChangedObservable.clear()})},enumerable:!0,configurable:!0}),e.prototype.attachControl=function(e,t){var i=this,n=this.camera.getScene().getEngine().getHostWindow();if(n){var r=function(){n.addEventListener("orientationchange",i._orientationChanged),n.addEventListener("deviceorientation",i._deviceOrientation),i._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(function(e){"granted"===e?r():De.b.Warn("Permission not granted.")}).catch(function(e){De.b.Error(e)}):r()}},e.prototype.detachControl=function(e){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0},e.prototype.checkInputs=function(){this._alpha&&(a.b.RotationYawPitchRollToRef(De.b.ToRadians(this._alpha),De.b.ToRadians(this._beta),-De.b.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)},e.prototype.getClassName=function(){return"FreeCameraDeviceOrientationInput"},e.prototype.getSimpleName=function(){return"deviceOrientation"},e}();at.FreeCameraDeviceOrientationInput=Rt;var Ot=function(){function e(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this._yAxisScale=1,this._cameraTransform=a.a.Identity(),this._deltaTransform=a.e.Zero(),this._vector3=a.e.Zero(),this._vector2=a.d.Zero()}return Object.defineProperty(e.prototype,"invertYAxis",{get:function(){return 1!==this._yAxisScale},set:function(e){this._yAxisScale=e?-1:1},enumerable:!0,configurable:!0}),e.prototype.attachControl=function(e,t){var i=this,n=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=n.onGamepadConnectedObservable.add(function(e){e.type!==lt.POSE_ENABLED&&(i.gamepad&&e.type!==lt.XBOX||(i.gamepad=e))}),this._onGamepadDisconnectedObserver=n.onGamepadDisconnectedObservable.add(function(e){i.gamepad===e&&(i.gamepad=null)}),this.gamepad=n.getGamepadByType(lt.XBOX)},e.prototype.detachControl=function(e){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null},e.prototype.checkInputs=function(){if(this.gamepad&&this.gamepad.leftStick){var e=this.camera,t=this.gamepad.leftStick,i=t.x/this.gamepadMoveSensibility,n=t.y/this.gamepadMoveSensibility;t.x=Math.abs(i)>.005?0+i:0,t.y=Math.abs(n)>.005?0+n:0;var r=this.gamepad.rightStick;if(r){var o=r.x/this.gamepadAngularSensibility,s=r.y/this.gamepadAngularSensibility*this._yAxisScale;r.x=Math.abs(o)>.001?0+o:0,r.y=Math.abs(s)>.001?0+s:0}else r={x:0,y:0};e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):a.a.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);var c=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*c,0,-t.y*c),a.e.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(r.y,r.x),e.cameraRotation.addInPlace(this._vector2)}},e.prototype.getClassName=function(){return"FreeCameraGamepadInput"},e.prototype.getSimpleName=function(){return"gamepad"},Object(h.c)([Object(N.c)()],e.prototype,"gamepadAngularSensibility",void 0),Object(h.c)([Object(N.c)()],e.prototype,"gamepadMoveSensibility",void 0),e}();at.FreeCameraGamepadInput=Ot;var Mt,It=i(103);!function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Mt||(Mt={}));var Dt=function(){function e(t){var i=this;if(this._leftJoystick=!!t,e._globalJoystickIndex++,this._axisTargetedByLeftAndRight=Mt.X,this._axisTargetedByUpAndDown=Mt.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new It.a,this.deltaPosition=a.e.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=function(t){e.vjCanvasWidth=window.innerWidth,e.vjCanvasHeight=window.innerHeight,e.Canvas&&(e.Canvas.width=e.vjCanvasWidth,e.Canvas.height=e.vjCanvasHeight),e.halfWidth=e.vjCanvasWidth/2},!e.Canvas){window.addEventListener("resize",this._onResize,!1),e.Canvas=document.createElement("canvas"),e.vjCanvasWidth=window.innerWidth,e.vjCanvasHeight=window.innerHeight,e.Canvas.width=window.innerWidth,e.Canvas.height=window.innerHeight,e.Canvas.style.width="100%",e.Canvas.style.height="100%",e.Canvas.style.position="absolute",e.Canvas.style.backgroundColor="transparent",e.Canvas.style.top="0px",e.Canvas.style.left="0px",e.Canvas.style.zIndex="5",e.Canvas.style.msTouchAction="none",e.Canvas.setAttribute("touch-action","none");var n=e.Canvas.getContext("2d");if(!n)throw new Error("Unable to create canvas for virtual joystick");e.vjCanvasContext=n,e.vjCanvasContext.strokeStyle="#ffffff",e.vjCanvasContext.lineWidth=2,document.body.appendChild(e.Canvas)}e.halfWidth=e.Canvas.width/2,this.pressed=!1,this._joystickColor="cyan",this._joystickPointerID=-1,this._joystickPointerPos=new a.d(0,0),this._joystickPreviousPointerPos=new a.d(0,0),this._joystickPointerStartPos=new a.d(0,0),this._deltaJoystickVector=new a.d(0,0),this._onPointerDownHandlerRef=function(e){i._onPointerDown(e)},this._onPointerMoveHandlerRef=function(e){i._onPointerMove(e)},this._onPointerUpHandlerRef=function(e){i._onPointerUp(e)},e.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),e.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),e.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),e.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),e.Canvas.addEventListener("contextmenu",function(e){e.preventDefault()},!1),requestAnimationFrame(function(){i._drawVirtualJoystick()})}return e.prototype.setJoystickSensibility=function(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)},e.prototype._onPointerDown=function(t){t.preventDefault(),(!0===this._leftJoystick?t.clientX<e.halfWidth:t.clientX>e.halfWidth)&&this._joystickPointerID<0?(this._joystickPointerID=t.pointerId,this._joystickPointerStartPos.x=t.clientX,this._joystickPointerStartPos.y=t.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone(),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(t.pointerId.toString(),t)):e._globalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(t.pointerId.toString(),{x:t.clientX,y:t.clientY,prevX:t.clientX,prevY:t.clientY}))},e.prototype._onPointerMove=function(e){if(this._joystickPointerID==e.pointerId){this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY,this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos);var t=(this.reverseLeftRight?-1:1)*this._deltaJoystickVector.x/this._inversedSensibility;switch(this._axisTargetedByLeftAndRight){case Mt.X:this.deltaPosition.x=Math.min(1,Math.max(-1,t));break;case Mt.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,t));break;case Mt.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,t))}var i=(this.reverseUpDown?1:-1)*this._deltaJoystickVector.y/this._inversedSensibility;switch(this._axisTargetedByUpAndDown){case Mt.X:this.deltaPosition.x=Math.min(1,Math.max(-1,i));break;case Mt.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,i));break;case Mt.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,i))}}else{var n=this._touches.get(e.pointerId.toString());n&&(n.x=e.clientX,n.y=e.clientY)}},e.prototype._onPointerUp=function(t){if(this._joystickPointerID==t.pointerId)e.vjCanvasContext.clearRect(this._joystickPointerStartPos.x-64,this._joystickPointerStartPos.y-64,128,128),e.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x-42,this._joystickPreviousPointerPos.y-42,84,84),this._joystickPointerID=-1,this.pressed=!1;else{var i=this._touches.get(t.pointerId.toString());i&&e.vjCanvasContext.clearRect(i.prevX-44,i.prevY-44,88,88)}this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this._touches.remove(t.pointerId.toString())},e.prototype.setJoystickColor=function(e){this._joystickColor=e},e.prototype.setActionOnTouch=function(e){this._action=e},e.prototype.setAxisForLeftRight=function(e){switch(e){case Mt.X:case Mt.Y:case Mt.Z:this._axisTargetedByLeftAndRight=e;break;default:this._axisTargetedByLeftAndRight=Mt.X}},e.prototype.setAxisForUpDown=function(e){switch(e){case Mt.X:case Mt.Y:case Mt.Z:this._axisTargetedByUpAndDown=e;break;default:this._axisTargetedByUpAndDown=Mt.Y}},e.prototype._drawVirtualJoystick=function(){var t=this;this.pressed&&this._touches.forEach(function(i,n){n.pointerId===t._joystickPointerID?(e.vjCanvasContext.clearRect(t._joystickPointerStartPos.x-64,t._joystickPointerStartPos.y-64,128,128),e.vjCanvasContext.clearRect(t._joystickPreviousPointerPos.x-42,t._joystickPreviousPointerPos.y-42,84,84),e.vjCanvasContext.beginPath(),e.vjCanvasContext.lineWidth=6,e.vjCanvasContext.strokeStyle=t._joystickColor,e.vjCanvasContext.arc(t._joystickPointerStartPos.x,t._joystickPointerStartPos.y,40,0,2*Math.PI,!0),e.vjCanvasContext.stroke(),e.vjCanvasContext.closePath(),e.vjCanvasContext.beginPath(),e.vjCanvasContext.strokeStyle=t._joystickColor,e.vjCanvasContext.lineWidth=2,e.vjCanvasContext.arc(t._joystickPointerStartPos.x,t._joystickPointerStartPos.y,60,0,2*Math.PI,!0),e.vjCanvasContext.stroke(),e.vjCanvasContext.closePath(),e.vjCanvasContext.beginPath(),e.vjCanvasContext.strokeStyle=t._joystickColor,e.vjCanvasContext.arc(t._joystickPointerPos.x,t._joystickPointerPos.y,40,0,2*Math.PI,!0),e.vjCanvasContext.stroke(),e.vjCanvasContext.closePath(),t._joystickPreviousPointerPos=t._joystickPointerPos.clone()):(e.vjCanvasContext.clearRect(n.prevX-44,n.prevY-44,88,88),e.vjCanvasContext.beginPath(),e.vjCanvasContext.fillStyle="white",e.vjCanvasContext.beginPath(),e.vjCanvasContext.strokeStyle="red",e.vjCanvasContext.lineWidth=6,e.vjCanvasContext.arc(n.x,n.y,40,0,2*Math.PI,!0),e.vjCanvasContext.stroke(),e.vjCanvasContext.closePath(),n.prevX=n.x,n.prevY=n.y)}),requestAnimationFrame(function(){t._drawVirtualJoystick()})},e.prototype.releaseCanvas=function(){e.Canvas&&(e.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),e.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),e.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),e.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(e.Canvas),e.Canvas=null)},e._globalJoystickIndex=0,e}();Ct.prototype.addVirtualJoystick=function(){return this.add(new wt),this};var wt=function(){function e(){}return e.prototype.getLeftJoystick=function(){return this._leftjoystick},e.prototype.getRightJoystick=function(){return this._rightjoystick},e.prototype.checkInputs=function(){if(this._leftjoystick){var e=this.camera,t=50*e._computeLocalCameraSpeed(),i=a.a.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),n=a.e.TransformCoordinates(new a.e(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(n),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}},e.prototype.attachControl=function(e,t){this._leftjoystick=new Dt(!0),this._leftjoystick.setAxisForUpDown(Mt.Z),this._leftjoystick.setAxisForLeftRight(Mt.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new Dt(!1),this._rightjoystick.setAxisForUpDown(Mt.X),this._rightjoystick.setAxisForLeftRight(Mt.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")},e.prototype.detachControl=function(e){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()},e.prototype.getClassName=function(){return"FreeCameraVirtualJoystickInput"},e.prototype.getSimpleName=function(){return"virtualJoystick"},e}();at.FreeCameraVirtualJoystickInput=wt;var Lt=function(e){function t(t,i,n,r){void 0===r&&(r=!0);var o=e.call(this,t,i,n,r)||this;return o.cameraDirection=new a.e(0,0,0),o.cameraRotation=new a.d(0,0),o.updateUpVectorFromRotation=!1,o._tmpQuaternion=new a.b,o.rotation=new a.e(0,0,0),o.speed=2,o.noRotationConstraint=!1,o.lockedTarget=null,o._currentTarget=a.e.Zero(),o._initialFocalDistance=1,o._viewMatrix=a.a.Zero(),o._camMatrix=a.a.Zero(),o._cameraTransformMatrix=a.a.Zero(),o._cameraRotationMatrix=a.a.Zero(),o._referencePoint=new a.e(0,0,1),o._transformedReferencePoint=a.e.Zero(),o._globalCurrentTarget=a.e.Zero(),o._globalCurrentUpVector=a.e.Zero(),o._defaultUp=a.e.Up(),o._cachedRotationZ=0,o._cachedQuaternionRotationZ=0,o}return Object(h.d)(t,e),t.prototype.getFrontPosition=function(e){this.getWorldMatrix();var t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)},t.prototype._getLockedTargetPosition=function(){return this.lockedTarget?(this.lockedTarget.absolutePosition&&this.lockedTarget.computeWorldMatrix(),this.lockedTarget.absolutePosition||this.lockedTarget):null},t.prototype.storeState=function(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),e.prototype.storeState.call(this)},t.prototype._restoreStateValues=function(){return!!e.prototype._restoreStateValues.call(this)&&(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)},t.prototype._initCache=function(){e.prototype._initCache.call(this),this._cache.lockedTarget=new a.e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new a.e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new a.b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},t.prototype._updateCache=function(t){t||e.prototype._updateCache.call(this);var i=this._getLockedTargetPosition();i?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(i):this._cache.lockedTarget=i.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)},t.prototype._isSynchronizedViewMatrix=function(){if(!e.prototype._isSynchronizedViewMatrix.call(this))return!1;var t=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(t):!t)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))},t.prototype._computeLocalCameraSpeed=function(){var e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))},t.prototype.setTarget=function(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=re.a),a.a.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);var t=e.subtract(this.position);t.x>=0?this.rotation.y=-Math.atan(t.z/t.x)+Math.PI/2:this.rotation.y=-Math.atan(t.z/t.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&a.b.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)},t.prototype.getTarget=function(){return this._currentTarget},t.prototype._decideIfNeedsToMove=function(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},t.prototype._updatePosition=function(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(a.c.Matrix[0]),a.e.TransformNormalToRef(this.cameraDirection,a.c.Matrix[0],a.c.Vector3[0]),void this.position.addInPlace(a.c.Vector3[0]);this.position.addInPlace(this.cameraDirection)},t.prototype._checkInputs=function(){var t=this._decideIfNeedsToMove(),i=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;if(t&&this._updatePosition(),i){if(this.rotation.x+=this.cameraRotation.x,this.rotation.y+=this.cameraRotation.y,this.rotationQuaternion)this.rotation.lengthSquared()&&a.b.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion);if(!this.noRotationConstraint){this.rotation.x>1.570796&&(this.rotation.x=1.570796),this.rotation.x<-1.570796&&(this.rotation.x=-1.570796)}}t&&(Math.abs(this.cameraDirection.x)<this.speed*re.a&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<this.speed*re.a&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<this.speed*re.a&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),i&&(Math.abs(this.cameraRotation.x)<this.speed*re.a&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<this.speed*re.a&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),e.prototype._checkInputs.call(this)},t.prototype._updateCameraRotationMatrix=function(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):a.a.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)},t.prototype._rotateUpVectorWithCameraRotationMatrix=function(){return a.e.TransformNormalToRef(this._defaultUp,this._cameraRotationMatrix,this.upVector),this},t.prototype._getViewMatrix=function(){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),a.e.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?Z.a.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(a.b.FromEulerVectorToRef(this.rotation,this._tmpQuaternion),Z.a.Y.rotateByQuaternionToRef(this._tmpQuaternion,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix},t.prototype._computeViewMatrix=function(e,t,i){if(this.parent){var n=this.parent.getWorldMatrix();a.e.TransformCoordinatesToRef(e,n,this._globalPosition),a.e.TransformCoordinatesToRef(t,n,this._globalCurrentTarget),a.e.TransformNormalToRef(i,n,this._globalCurrentUpVector),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e),this._globalCurrentTarget.copyFrom(t),this._globalCurrentUpVector.copyFrom(i);this.getScene().useRightHandedSystem?a.a.LookAtRHToRef(this._globalPosition,this._globalCurrentTarget,this._globalCurrentUpVector,this._viewMatrix):a.a.LookAtLHToRef(this._globalPosition,this._globalCurrentTarget,this._globalCurrentUpVector,this._viewMatrix)},t.prototype.createRigCamera=function(e,i){if(this.cameraRigMode!==Qe.a.RIG_MODE_NONE){var n=new t(e,this.position.clone(),this.getScene());return n.isRigCamera=!0,n.rigParent=this,this.cameraRigMode!==Qe.a.RIG_MODE_VR&&this.cameraRigMode!==Qe.a.RIG_MODE_WEBVR||(this.rotationQuaternion||(this.rotationQuaternion=new a.b),n._cameraRigParams={},n.rotationQuaternion=new a.b),n}return null},t.prototype._updateRigCameras=function(){var t=this._rigCameras[0],i=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case Qe.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Qe.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Qe.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case Qe.a.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Qe.a.RIG_MODE_STEREOSCOPIC_INTERLACED:var n=this.cameraRigMode===Qe.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,r=this.cameraRigMode===Qe.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*n,t),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*r,i);break;case Qe.a.RIG_MODE_VR:t.rotationQuaternion?(t.rotationQuaternion.copyFrom(this.rotationQuaternion),i.rotationQuaternion.copyFrom(this.rotationQuaternion)):(t.rotation.copyFrom(this.rotation),i.rotation.copyFrom(this.rotation)),t.position.copyFrom(this.position),i.position.copyFrom(this.position)}e.prototype._updateRigCameras.call(this)},t.prototype._getRigCamPositionAndTarget=function(e,i){this.getTarget().subtractToRef(this.position,t._TargetFocalPoint),t._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);var n=t._TargetFocalPoint.addInPlace(this.position);a.a.TranslationToRef(-n.x,-n.y,-n.z,t._TargetTransformMatrix),t._TargetTransformMatrix.multiplyToRef(a.a.RotationY(e),t._RigCamTransformMatrix),a.a.TranslationToRef(n.x,n.y,n.z,t._TargetTransformMatrix),t._RigCamTransformMatrix.multiplyToRef(t._TargetTransformMatrix,t._RigCamTransformMatrix),a.e.TransformCoordinatesToRef(this.position,t._RigCamTransformMatrix,i.position),i.setTarget(n)},t.prototype.getClassName=function(){return"TargetCamera"},t._RigCamTransformMatrix=new a.a,t._TargetTransformMatrix=new a.a,t._TargetFocalPoint=new a.e,Object(h.c)([Object(N.o)()],t.prototype,"rotation",void 0),Object(h.c)([Object(N.c)()],t.prototype,"speed",void 0),Object(h.c)([Object(N.k)("lockedTargetId")],t.prototype,"lockedTarget",void 0),t}(Qe.a),Nt=function(e){function t(t,i,n,r){void 0===r&&(r=!0);var o=e.call(this,t,i,n,r)||this;return o.ellipsoid=new a.e(.5,1,.5),o.ellipsoidOffset=new a.e(0,0,0),o.checkCollisions=!1,o.applyGravity=!1,o._needMoveForGravity=!1,o._oldPosition=a.e.Zero(),o._diffPosition=a.e.Zero(),o._newPosition=a.e.Zero(),o._collisionMask=-1,o._onCollisionPositionChange=function(e,t,i){void 0===i&&(i=null);var n;n=t,o._newPosition.copyFrom(n),o._newPosition.subtractToRef(o._oldPosition,o._diffPosition),o._diffPosition.length()>Oe.a.CollisionsEpsilon&&(o.position.addInPlace(o._diffPosition),o.onCollide&&i&&o.onCollide(i))},o.inputs=new Ct(o),o.inputs.addKeyboard().addMouse(),o}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;return e?e.angularSensibility:0},set:function(e){var t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),t.prototype.attachControl=function(e,t){this.inputs.attachElement(e,t)},t.prototype.detachControl=function(e){this.inputs.detachElement(e),this.cameraDirection=new a.e(0,0,0),this.cameraRotation=new a.d(0,0)},Object.defineProperty(t.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),t.prototype._collideWithWorld=function(e){(this.parent?a.e.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);var t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;var i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},t.prototype._checkInputs=function(){this._localDirection||(this._localDirection=a.e.Zero(),this._transformedDirection=a.e.Zero()),this.inputs.checkInputs(),e.prototype._checkInputs.call(this)},t.prototype._decideIfNeedsToMove=function(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},t.prototype._updatePosition=function(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):e.prototype._updatePosition.call(this)},t.prototype.dispose=function(){this.inputs.clear(),e.prototype.dispose.call(this)},t.prototype.getClassName=function(){return"FreeCamera"},Object(h.c)([Object(N.o)()],t.prototype,"ellipsoid",void 0),Object(h.c)([Object(N.o)()],t.prototype,"ellipsoidOffset",void 0),Object(h.c)([Object(N.c)()],t.prototype,"checkCollisions",void 0),Object(h.c)([Object(N.c)()],t.prototype,"applyGravity",void 0),t}(Lt);B.a.AddNodeConstructor("TouchCamera",function(e,t){return function(){return new Ft(e,a.e.Zero(),t)}});var Ft=function(e){function t(t,i,n){var r=e.call(this,t,i,n)||this;return r.inputs.addTouch(),r._setupInputs(),r}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"touchAngularSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"touchMoveSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"TouchCamera"},t.prototype._setupInputs=function(){var e=this.inputs.attached.mouse;e&&(e.touchEnabled=!1)},t}(Nt);B.a.AddNodeConstructor("ArcRotateCamera",function(e,t){return function(){return new Bt(e,0,0,1,a.e.Zero(),t)}});var Bt=function(e){function t(t,i,n,r,s,c,l){void 0===l&&(l=!0);var u=e.call(this,t,a.e.Zero(),c,l)||this;return u._upVector=a.e.Up(),u.inertialAlphaOffset=0,u.inertialBetaOffset=0,u.inertialRadiusOffset=0,u.lowerAlphaLimit=null,u.upperAlphaLimit=null,u.lowerBetaLimit=.01,u.upperBetaLimit=Math.PI-.01,u.lowerRadiusLimit=null,u.upperRadiusLimit=null,u.inertialPanningX=0,u.inertialPanningY=0,u.pinchToPanMaxDistance=20,u.panningDistanceLimit=null,u.panningOriginTarget=a.e.Zero(),u.panningInertia=.9,u.zoomOnFactor=1,u.targetScreenOffset=a.d.Zero(),u.allowUpsideDown=!0,u.useInputToRestoreState=!0,u._viewMatrix=new a.a,u.panningAxis=new a.e(1,1,0),u.onMeshTargetChangedObservable=new o.c,u.checkCollisions=!1,u.collisionRadius=new a.e(.5,.5,.5),u._previousPosition=a.e.Zero(),u._collisionVelocity=a.e.Zero(),u._newPosition=a.e.Zero(),u._computationVector=a.e.Zero(),u._onCollisionPositionChange=function(e,t,i){void 0===i&&(i=null),i?(u.setPosition(t),u.onCollide&&u.onCollide(i)):u._previousPosition.copyFrom(u._position);var n=Math.cos(u.alpha),r=Math.sin(u.alpha),o=Math.cos(u.beta),a=Math.sin(u.beta);0===a&&(a=1e-4);var s=u._getTargetPosition();u._computationVector.copyFromFloats(u.radius*n*a,u.radius*o,u.radius*r*a),s.addToRef(u._computationVector,u._newPosition),u._position.copyFrom(u._newPosition);var c=u.upVector;u.allowUpsideDown&&u.beta<0&&(c=(c=c.clone()).negate()),u._computeViewMatrix(u._position,s,c),u._viewMatrix.addAtIndex(12,u.targetScreenOffset.x),u._viewMatrix.addAtIndex(13,u.targetScreenOffset.y),u._collisionTriggered=!1},u._target=a.e.Zero(),s&&u.setTarget(s),u.alpha=i,u.beta=n,u.radius=r,u.getViewMatrix(),u.inputs=new gt(u),u.inputs.addKeyboard().addMouseWheel().addPointers(),u}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"target",{get:function(){return this._target},set:function(e){this.setTarget(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this.setPosition(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"upVector",{get:function(){return this._upVector},set:function(e){this._upToYMatrix||(this._YToUpMatrix=new a.a,this._upToYMatrix=new a.a,this._upVector=a.e.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()},enumerable:!0,configurable:!0}),t.prototype.setMatUp=function(){a.a.RotationAlignToRef(a.e.UpReadOnly,this._upVector,this._YToUpMatrix),a.a.RotationAlignToRef(this._upVector,a.e.UpReadOnly,this._upToYMatrix)},Object.defineProperty(t.prototype,"angularSensibilityX",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"angularSensibilityY",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pinchPrecision",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchPrecision:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pinchDeltaPercentage",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useNaturalPinchZoom",{get:function(){var e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom},set:function(e){var t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"panningSensibility",{get:function(){var e=this.inputs.attached.pointers;return e?e.panningSensibility:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"wheelPrecision",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"wheelDeltaPercentage",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bouncingBehavior",{get:function(){return this._bouncingBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useBouncingBehavior",{get:function(){return null!=this._bouncingBehavior},set:function(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new ze,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"framingBehavior",{get:function(){return this._framingBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useFramingBehavior",{get:function(){return null!=this._framingBehavior},set:function(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new Ge,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"autoRotationBehavior",{get:function(){return this._autoRotationBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useAutoRotationBehavior",{get:function(){return null!=this._autoRotationBehavior},set:function(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new ke,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))},enumerable:!0,configurable:!0}),t.prototype._initCache=function(){e.prototype._initCache.call(this),this._cache._target=new a.e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=a.d.Zero()},t.prototype._updateCache=function(t){t||e.prototype._updateCache.call(this),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)},t.prototype._getTargetPosition=function(){if(this._targetHost&&this._targetHost.getAbsolutePosition){var e=this._targetHost.absolutePosition;this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}var t=this._getLockedTargetPosition();return t||this._target},t.prototype.storeState=function(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),e.prototype.storeState.call(this)},t.prototype._restoreStateValues=function(){return!!e.prototype._restoreStateValues.call(this)&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)},t.prototype._isSynchronizedViewMatrix=function(){return!!e.prototype._isSynchronizedViewMatrix.call(this)&&(this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset))},t.prototype.attachControl=function(e,t,i,n){var r=this;void 0===i&&(i=!0),void 0===n&&(n=2),this._useCtrlForPanning=i,this._panningMouseButton=n,this.inputs.attachElement(e,t),this._reset=function(){r.inertialAlphaOffset=0,r.inertialBetaOffset=0,r.inertialRadiusOffset=0,r.inertialPanningX=0,r.inertialPanningY=0}},t.prototype.detachControl=function(e){this.inputs.detachElement(e),this._reset&&this._reset()},t.prototype._checkInputs=function(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){var t=this.inertialAlphaOffset;this.beta<=0&&(t*=-1),this.getScene().useRightHandedSystem&&(t*=-1),this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(t*=-1),this.alpha+=t,this.beta+=this.inertialBetaOffset,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)<re.a&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<re.a&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<this.speed*re.a&&(this.inertialRadiusOffset=0)}if(0!==this.inertialPanningX||0!==this.inertialPanningY){if(this._localDirection||(this._localDirection=a.e.Zero(),this._transformedDirection=a.e.Zero()),this._localDirection.copyFromFloats(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY),this._localDirection.multiplyInPlace(this.panningAxis),this._viewMatrix.invertToRef(this._cameraTransformMatrix),a.e.TransformNormalToRef(this._localDirection,this._cameraTransformMatrix,this._transformedDirection),this.panningAxis.y||(this._transformedDirection.y=0),!this._targetHost)if(this.panningDistanceLimit)this._transformedDirection.addInPlace(this._target),a.e.DistanceSquared(this._transformedDirection,this.panningOriginTarget)<=this.panningDistanceLimit*this.panningDistanceLimit&&this._target.copyFrom(this._transformedDirection);else this._target.addInPlace(this._transformedDirection);this.inertialPanningX*=this.panningInertia,this.inertialPanningY*=this.panningInertia,Math.abs(this.inertialPanningX)<this.speed*re.a&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<this.speed*re.a&&(this.inertialPanningY=0)}this._checkLimits(),e.prototype._checkInputs.call(this)}},t.prototype._checkLimits=function(){null===this.lowerBetaLimit||void 0===this.lowerBetaLimit?this.allowUpsideDown&&this.beta>Math.PI&&(this.beta=this.beta-2*Math.PI):this.beta<this.lowerBetaLimit&&(this.beta=this.lowerBetaLimit),null===this.upperBetaLimit||void 0===this.upperBetaLimit?this.allowUpsideDown&&this.beta<-Math.PI&&(this.beta=this.beta+2*Math.PI):this.beta>this.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alpha<this.lowerAlphaLimit&&(this.alpha=this.lowerAlphaLimit),null!==this.upperAlphaLimit&&this.alpha>this.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit,this.inertialRadiusOffset=0),null!==this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)},t.prototype.rebuildAnglesAndRadius=function(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||a.e.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4),0===this._computationVector.x&&0===this._computationVector.z?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha),this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()},t.prototype.setPosition=function(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())},t.prototype.setTarget=function(e,t,i){if(void 0===t&&(t=!1),void 0===i&&(i=!1),e.getBoundingInfo)this._targetBoundingCenter=t?e.getBoundingInfo().boundingBox.centerWorld.clone():null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{var n=e,r=this._getTargetPosition();if(r&&!i&&r.equals(n))return;this._targetHost=null,this._target=n,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}this.rebuildAnglesAndRadius()},t.prototype._getViewMatrix=function(){var e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta),n=Math.sin(this.beta);0===n&&(n=1e-4);var r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*n,this.radius*i,this.radius*t*n),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||a.e.TransformCoordinatesToRef(this._computationVector,this._YToUpMatrix,this._computationVector),r.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){var o=this.getScene().collisionCoordinator;this._collider||(this._collider=o.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,o.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);var s=this.upVector;this.allowUpsideDown&&n<0&&(s=s.negate()),this._computeViewMatrix(this._position,r,s),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix},t.prototype.zoomOn=function(e,t){void 0===t&&(t=!1),e=e||this.getScene().meshes;var i=Ae.a.MinMax(e),n=a.e.Distance(i.min,i.max);this.radius=n*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:n},t)},t.prototype.focusOn=function(e,t){var i,n;if(void 0===t&&(t=!1),void 0===e.min){var r=e||this.getScene().meshes;i=Ae.a.MinMax(r),n=a.e.Distance(i.min,i.max)}else{i=e,n=e.distance}this._target=Ae.a.Center(i),t||(this.maxZ=2*n)},t.prototype.createRigCamera=function(e,i){var n=0;switch(this.cameraRigMode){case Qe.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Qe.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Qe.a.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Qe.a.RIG_MODE_STEREOSCOPIC_INTERLACED:case Qe.a.RIG_MODE_VR:n=this._cameraRigParams.stereoHalfAngle*(0===i?1:-1);break;case Qe.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:n=this._cameraRigParams.stereoHalfAngle*(0===i?-1:1)}var r=new t(e,this.alpha+n,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r},t.prototype._updateRigCameras=function(){var t=this._rigCameras[0],i=this._rigCameras[1];switch(t.beta=i.beta=this.beta,this.cameraRigMode){case Qe.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Qe.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Qe.a.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Qe.a.RIG_MODE_STEREOSCOPIC_INTERLACED:case Qe.a.RIG_MODE_VR:t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,i.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case Qe.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,i.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}e.prototype._updateRigCameras.call(this)},t.prototype.dispose=function(){this.inputs.clear(),e.prototype.dispose.call(this)},t.prototype.getClassName=function(){return"ArcRotateCamera"},Object(h.c)([Object(N.c)()],t.prototype,"alpha",void 0),Object(h.c)([Object(N.c)()],t.prototype,"beta",void 0),Object(h.c)([Object(N.c)()],t.prototype,"radius",void 0),Object(h.c)([Object(N.o)("target")],t.prototype,"_target",void 0),Object(h.c)([Object(N.o)("upVector")],t.prototype,"_upVector",void 0),Object(h.c)([Object(N.c)()],t.prototype,"inertialAlphaOffset",void 0),Object(h.c)([Object(N.c)()],t.prototype,"inertialBetaOffset",void 0),Object(h.c)([Object(N.c)()],t.prototype,"inertialRadiusOffset",void 0),Object(h.c)([Object(N.c)()],t.prototype,"lowerAlphaLimit",void 0),Object(h.c)([Object(N.c)()],t.prototype,"upperAlphaLimit",void 0),Object(h.c)([Object(N.c)()],t.prototype,"lowerBetaLimit",void 0),Object(h.c)([Object(N.c)()],t.prototype,"upperBetaLimit",void 0),Object(h.c)([Object(N.c)()],t.prototype,"lowerRadiusLimit",void 0),Object(h.c)([Object(N.c)()],t.prototype,"upperRadiusLimit",void 0),Object(h.c)([Object(N.c)()],t.prototype,"inertialPanningX",void 0),Object(h.c)([Object(N.c)()],t.prototype,"inertialPanningY",void 0),Object(h.c)([Object(N.c)()],t.prototype,"pinchToPanMaxDistance",void 0),Object(h.c)([Object(N.c)()],t.prototype,"panningDistanceLimit",void 0),Object(h.c)([Object(N.o)()],t.prototype,"panningOriginTarget",void 0),Object(h.c)([Object(N.c)()],t.prototype,"panningInertia",void 0),Object(h.c)([Object(N.c)()],t.prototype,"zoomOnFactor",void 0),Object(h.c)([Object(N.c)()],t.prototype,"targetScreenOffset",void 0),Object(h.c)([Object(N.c)()],t.prototype,"allowUpsideDown",void 0),Object(h.c)([Object(N.c)()],t.prototype,"useInputToRestoreState",void 0),t}(Lt);B.a.AddNodeConstructor("DeviceOrientationCamera",function(e,t){return function(){return new Ut(e,a.e.Zero(),t)}});var Ut=function(e){function t(t,i,n){var r=e.call(this,t,i,n)||this;return r._tmpDragQuaternion=new a.b,r._disablePointerInputWhenUsingDeviceOrientation=!0,r._dragFactor=0,r._quaternionCache=new a.b,r.inputs.addDeviceOrientation(),r.inputs._deviceOrientationInput&&r.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(function(){r._disablePointerInputWhenUsingDeviceOrientation&&r.inputs._mouseInput&&(r.inputs._mouseInput._allowCameraRotation=!1,r.inputs._mouseInput.onPointerMovedObservable.add(function(e){0!=r._dragFactor&&(r._initialQuaternion||(r._initialQuaternion=new a.b),a.b.FromEulerAnglesToRef(0,e.offsetX*r._dragFactor,0,r._tmpDragQuaternion),r._initialQuaternion.multiplyToRef(r._tmpDragQuaternion,r._initialQuaternion))}))}),r}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"disablePointerInputWhenUsingDeviceOrientation",{get:function(){return this._disablePointerInputWhenUsingDeviceOrientation},set:function(e){this._disablePointerInputWhenUsingDeviceOrientation=e},enumerable:!0,configurable:!0}),t.prototype.enableHorizontalDragging=function(e){void 0===e&&(e=1/300),this._dragFactor=e},t.prototype.getClassName=function(){return"DeviceOrientationCamera"},t.prototype._checkInputs=function(){e.prototype._checkInputs.call(this),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)},t.prototype.resetToCurrentRotation=function(e){var t=this;void 0===e&&(e=Z.a.Y),this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new a.b),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach(function(i){e[i]?t._initialQuaternion[i]*=-1:t._initialQuaternion[i]=0}),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))},t}(Nt),Vt=function(e){function t(t){return e.call(this,t)||this}return Object(h.d)(t,e),t.prototype.addKeyboard=function(){return this.add(new yt),this},t.prototype.addMouse=function(e){return void 0===e&&(e=!0),this.add(new bt(e)),this},t}(st),kt=function(e){function t(t,i,n,r){void 0===r&&(r=!0);var o=e.call(this,t,i,n,r)||this;return o.ellipsoid=new a.e(1,1,1),o.ellipsoidOffset=new a.e(0,0,0),o.checkCollisions=!1,o.applyGravity=!1,o.cameraDirection=a.e.Zero(),o._trackRoll=0,o.rollCorrect=100,o.bankedTurn=!1,o.bankedTurnLimit=Math.PI/2,o.bankedTurnMultiplier=1,o._needMoveForGravity=!1,o._oldPosition=a.e.Zero(),o._diffPosition=a.e.Zero(),o._newPosition=a.e.Zero(),o._collisionMask=-1,o._onCollisionPositionChange=function(e,t,i){void 0===i&&(i=null);var n;n=t,o._newPosition.copyFrom(n),o._newPosition.subtractToRef(o._oldPosition,o._diffPosition),o._diffPosition.length()>Oe.a.CollisionsEpsilon&&(o.position.addInPlace(o._diffPosition),o.onCollide&&i&&o.onCollide(i))},o.inputs=new Vt(o),o.inputs.addKeyboard().addMouse(),o}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;return e?e.angularSensibility:0},set:function(e){var t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysForward",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysForward:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysForward=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysBackward",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysBackward:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),t.prototype.attachControl=function(e,t){this.inputs.attachElement(e,t)},t.prototype.detachControl=function(e){this.inputs.detachElement(e),this.cameraDirection=new a.e(0,0,0)},Object.defineProperty(t.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),t.prototype._collideWithWorld=function(e){(this.parent?a.e.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);var t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;var i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},t.prototype._checkInputs=function(){this._localDirection||(this._localDirection=a.e.Zero(),this._transformedDirection=a.e.Zero()),this.inputs.checkInputs(),e.prototype._checkInputs.call(this)},t.prototype._decideIfNeedsToMove=function(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},t.prototype._updatePosition=function(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):e.prototype._updatePosition.call(this)},t.prototype.restoreRoll=function(e){var t=this._trackRoll,i=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,Math.abs(t-this.rotation.z)<=.001&&(this.rotation.z=t))},t.prototype.dispose=function(){this.inputs.clear(),e.prototype.dispose.call(this)},t.prototype.getClassName=function(){return"FlyCamera"},Object(h.c)([Object(N.o)()],t.prototype,"ellipsoid",void 0),Object(h.c)([Object(N.o)()],t.prototype,"ellipsoidOffset",void 0),Object(h.c)([Object(N.c)()],t.prototype,"checkCollisions",void 0),Object(h.c)([Object(N.c)()],t.prototype,"applyGravity",void 0),t}(Lt),zt=function(e){function t(t){return e.call(this,t)||this}return Object(h.d)(t,e),t.prototype.addKeyboard=function(){return this.add(new Tt),this},t.prototype.addMouseWheel=function(){return this.add(new Et),this},t.prototype.addPointers=function(){return this.add(new xt),this},t.prototype.addVRDeviceOrientation=function(){return console.warn("DeviceOrientation support not yet implemented for FollowCamera."),this},t}(st);B.a.AddNodeConstructor("FollowCamera",function(e,t){return function(){return new jt(e,a.e.Zero(),t)}}),B.a.AddNodeConstructor("ArcFollowCamera",function(e,t){return function(){return new Wt(e,0,0,1,null,t)}});var Gt,jt=function(e){function t(t,i,n,r){void 0===r&&(r=null);var o=e.call(this,t,i,n)||this;return o.radius=12,o.lowerRadiusLimit=null,o.upperRadiusLimit=null,o.rotationOffset=0,o.lowerRotationOffsetLimit=null,o.upperRotationOffsetLimit=null,o.heightOffset=4,o.lowerHeightOffsetLimit=null,o.upperHeightOffsetLimit=null,o.cameraAcceleration=.05,o.maxCameraSpeed=20,o.lockedTarget=r,o.inputs=new zt(o),o.inputs.addKeyboard().addMouseWheel().addPointers(),o}return Object(h.d)(t,e),t.prototype._follow=function(e){if(e){var t;if(e.rotationQuaternion){var i=new a.a;e.rotationQuaternion.toRotationMatrix(i),t=Math.atan2(i.m[8],i.m[10])}else t=e.rotation.y;var n=De.b.ToRadians(this.rotationOffset)+t,r=e.getAbsolutePosition(),o=r.x+Math.sin(n)*this.radius,s=r.z+Math.cos(n)*this.radius,c=o-this.position.x,l=r.y+this.heightOffset-this.position.y,u=s-this.position.z,h=c*this.cameraAcceleration*2,d=l*this.cameraAcceleration,f=u*this.cameraAcceleration*2;(h>this.maxCameraSpeed||h<-this.maxCameraSpeed)&&(h=h<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),(f>this.maxCameraSpeed||f<-this.maxCameraSpeed)&&(f=f<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new a.e(this.position.x+h,this.position.y+d,this.position.z+f),this.setTarget(r)}},t.prototype.attachControl=function(e,t){this.inputs.attachElement(e,t),this._reset=function(){}},t.prototype.detachControl=function(e){this.inputs.detachElement(e),this._reset&&this._reset()},t.prototype._checkInputs=function(){this.inputs.checkInputs(),this._checkLimits(),e.prototype._checkInputs.call(this),this.lockedTarget&&this._follow(this.lockedTarget)},t.prototype._checkLimits=function(){null!==this.lowerRadiusLimit&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit),null!==this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffset<this.lowerHeightOffsetLimit&&(this.heightOffset=this.lowerHeightOffsetLimit),null!==this.upperHeightOffsetLimit&&this.heightOffset>this.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffset<this.lowerRotationOffsetLimit&&(this.rotationOffset=this.lowerRotationOffsetLimit),null!==this.upperRotationOffsetLimit&&this.rotationOffset>this.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)},t.prototype.getClassName=function(){return"FollowCamera"},Object(h.c)([Object(N.c)()],t.prototype,"radius",void 0),Object(h.c)([Object(N.c)()],t.prototype,"lowerRadiusLimit",void 0),Object(h.c)([Object(N.c)()],t.prototype,"upperRadiusLimit",void 0),Object(h.c)([Object(N.c)()],t.prototype,"rotationOffset",void 0),Object(h.c)([Object(N.c)()],t.prototype,"lowerRotationOffsetLimit",void 0),Object(h.c)([Object(N.c)()],t.prototype,"upperRotationOffsetLimit",void 0),Object(h.c)([Object(N.c)()],t.prototype,"heightOffset",void 0),Object(h.c)([Object(N.c)()],t.prototype,"lowerHeightOffsetLimit",void 0),Object(h.c)([Object(N.c)()],t.prototype,"upperHeightOffsetLimit",void 0),Object(h.c)([Object(N.c)()],t.prototype,"cameraAcceleration",void 0),Object(h.c)([Object(N.c)()],t.prototype,"maxCameraSpeed",void 0),Object(h.c)([Object(N.k)("lockedTargetId")],t.prototype,"lockedTarget",void 0),t}(Lt),Wt=function(e){function t(t,i,n,r,o,s){var c=e.call(this,t,a.e.Zero(),s)||this;return c.alpha=i,c.beta=n,c.radius=r,c.target=o,c._cartesianCoordinates=a.e.Zero(),c._follow(),c}return Object(h.d)(t,e),t.prototype._follow=function(){if(this.target){this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);var e=this.target.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}},t.prototype._checkInputs=function(){e.prototype._checkInputs.call(this),this._follow()},t.prototype.getClassName=function(){return"ArcFollowCamera"},t}(Lt),Xt=i(38),Ht=i(39);!function(e){e[e.VIVE=0]="VIVE",e[e.OCULUS=1]="OCULUS",e[e.WINDOWS=2]="WINDOWS",e[e.GEAR_VR=3]="GEAR_VR",e[e.DAYDREAM=4]="DAYDREAM",e[e.GENERIC=5]="GENERIC"}(Gt||(Gt={}));var Yt,Kt,Qt=function(){function e(){}return e.InitiateController=function(e){for(var t=0,i=this._ControllerFactories;t<i.length;t++){var n=i[t];if(n.canCreate(e))return n.create(e)}if(this._DefaultControllerFactory)return this._DefaultControllerFactory(e);throw"The type of gamepad you are trying to load needs to be imported first or is not supported."},e._ControllerFactories=[],e._DefaultControllerFactory=null,e}(),qt=function(e){function t(t){var i=e.call(this,t.id,t.index,t)||this;return i.isXR=!1,i._deviceRoomPosition=a.e.Zero(),i._deviceRoomRotationQuaternion=new a.b,i.devicePosition=a.e.Zero(),i.deviceRotationQuaternion=new a.b,i.deviceScaleFactor=1,i._trackPosition=!0,i._maxRotationDistFromHeadset=Math.PI/5,i._draggedRoomRotation=0,i._leftHandSystemQuaternion=new a.b,i._deviceToWorld=a.a.Identity(),i._pointingPoseNode=null,i._workingMatrix=a.a.Identity(),i._meshAttachedObservable=new o.c,i.type=lt.POSE_ENABLED,i.controllerType=Gt.GENERIC,i.position=a.e.Zero(),i.rotationQuaternion=new a.b,i._calculatedPosition=a.e.Zero(),i._calculatedRotation=new a.b,a.b.RotationYawPitchRollToRef(Math.PI,0,0,i._leftHandSystemQuaternion),i}return Object(h.d)(t,e),t.prototype._disableTrackPosition=function(e){this._trackPosition&&(this._calculatedPosition.copyFrom(e),this._trackPosition=!1)},t.prototype.update=function(){e.prototype.update.call(this),this._updatePoseAndMesh()},t.prototype._updatePoseAndMesh=function(){if(!this.isXR){var e=this.browserGamepad.pose;if(this.updateFromDevice(e),!this._trackPosition&&R.a.LastCreatedScene&&R.a.LastCreatedScene.activeCamera&&R.a.LastCreatedScene.activeCamera.devicePosition)if((t=R.a.LastCreatedScene.activeCamera)._computeDevicePosition(),this._deviceToWorld.setTranslation(t.devicePosition),t.deviceRotationQuaternion){var t;(t=t)._deviceRoomRotationQuaternion.toEulerAnglesToRef(a.c.Vector3[0]);var i=Math.atan2(Math.sin(a.c.Vector3[0].y-this._draggedRoomRotation),Math.cos(a.c.Vector3[0].y-this._draggedRoomRotation));if(Math.abs(i)>this._maxRotationDistFromHeadset){var n=i-(i<0?-this._maxRotationDistFromHeadset:this._maxRotationDistFromHeadset);this._draggedRoomRotation+=n;var r=Math.sin(-n),o=Math.cos(-n);this._calculatedPosition.x=this._calculatedPosition.x*o-this._calculatedPosition.z*r,this._calculatedPosition.z=this._calculatedPosition.x*r+this._calculatedPosition.z*o}}a.e.TransformCoordinatesToRef(this._calculatedPosition,this._deviceToWorld,this.devicePosition),this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix),a.b.FromRotationMatrixToRef(this._workingMatrix,this.deviceRotationQuaternion),this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation),this._mesh&&(this._mesh.position.copyFrom(this.devicePosition),this._mesh.rotationQuaternion&&this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion))}},t.prototype.updateFromDevice=function(e){if(!this.isXR&&e){this.rawPose=e,e.position&&(this._deviceRoomPosition.copyFromFloats(e.position[0],e.position[1],-e.position[2]),this._mesh&&this._mesh.getScene().useRightHandedSystem&&(this._deviceRoomPosition.z*=-1),this._trackPosition&&this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor,this._calculatedPosition),this._calculatedPosition.addInPlace(this.position));var t=this.rawPose;e.orientation&&t.orientation&&4===t.orientation.length&&(this._deviceRoomRotationQuaternion.copyFromFloats(t.orientation[0],t.orientation[1],-t.orientation[2],-t.orientation[3]),this._mesh&&(this._mesh.getScene().useRightHandedSystem?(this._deviceRoomRotationQuaternion.z*=-1,this._deviceRoomRotationQuaternion.w*=-1):this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion,this._deviceRoomRotationQuaternion)),this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion,this._calculatedRotation))}},t.prototype.attachToMesh=function(e){if(this._mesh&&(this._mesh.parent=null),this._mesh=e,this._poseControlledCamera&&(this._mesh.parent=this._poseControlledCamera),this._mesh.rotationQuaternion||(this._mesh.rotationQuaternion=new a.b),!this.isXR&&(this._updatePoseAndMesh(),this._pointingPoseNode)){for(var t=[],i=this._pointingPoseNode;i.parent;)t.push(i.parent),i=i.parent;t.reverse().forEach(function(e){e.computeWorldMatrix(!0)})}this._meshAttachedObservable.notifyObservers(e)},t.prototype.attachToPoseControlledCamera=function(e){this._poseControlledCamera=e,this._mesh&&(this._mesh.parent=this._poseControlledCamera)},t.prototype.dispose=function(){this._mesh&&this._mesh.dispose(),this._mesh=null,e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"mesh",{get:function(){return this._mesh},enumerable:!0,configurable:!0}),t.prototype.getForwardRay=function(e){if(void 0===e&&(e=100),!this.mesh)return new Ht.a(a.e.Zero(),new a.e(0,0,1),e);var t=this._pointingPoseNode?this._pointingPoseNode.getWorldMatrix():this.mesh.getWorldMatrix(),i=t.getTranslation(),n=new a.e(0,0,-1),r=a.e.TransformNormal(n,t),o=a.e.Normalize(r);return new Ht.a(i,o,e)},t.POINTING_POSE="POINTING_POSE",t}(lt);!function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Yt||(Yt={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Kt||(Kt={}));var Zt,Jt,$t=function(e){function t(t,i,n,r){void 0===r&&(r=!1);var a=e.call(this,t,i,n,0,1,2,3)||this;return a._leftTrigger=0,a._rightTrigger=0,a.onButtonDownObservable=new o.c,a.onButtonUpObservable=new o.c,a.onPadDownObservable=new o.c,a.onPadUpObservable=new o.c,a._buttonA=0,a._buttonB=0,a._buttonX=0,a._buttonY=0,a._buttonBack=0,a._buttonStart=0,a._buttonLB=0,a._buttonRB=0,a._buttonLeftStick=0,a._buttonRightStick=0,a._dPadUp=0,a._dPadDown=0,a._dPadLeft=0,a._dPadRight=0,a._isXboxOnePad=!1,a.type=lt.XBOX,a._isXboxOnePad=r,a}return Object(h.d)(t,e),t.prototype.onlefttriggerchanged=function(e){this._onlefttriggerchanged=e},t.prototype.onrighttriggerchanged=function(e){this._onrighttriggerchanged=e},Object.defineProperty(t.prototype,"leftTrigger",{get:function(){return this._leftTrigger},set:function(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rightTrigger",{get:function(){return this._rightTrigger},set:function(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e},enumerable:!0,configurable:!0}),t.prototype.onbuttondown=function(e){this._onbuttondown=e},t.prototype.onbuttonup=function(e){this._onbuttonup=e},t.prototype.ondpaddown=function(e){this._ondpaddown=e},t.prototype.ondpadup=function(e){this._ondpadup=e},t.prototype._setButtonValue=function(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e},t.prototype._setDPadValue=function(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e},Object.defineProperty(t.prototype,"buttonA",{get:function(){return this._buttonA},set:function(e){this._buttonA=this._setButtonValue(e,this._buttonA,Yt.A)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonB",{get:function(){return this._buttonB},set:function(e){this._buttonB=this._setButtonValue(e,this._buttonB,Yt.B)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonX",{get:function(){return this._buttonX},set:function(e){this._buttonX=this._setButtonValue(e,this._buttonX,Yt.X)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonY",{get:function(){return this._buttonY},set:function(e){this._buttonY=this._setButtonValue(e,this._buttonY,Yt.Y)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonStart",{get:function(){return this._buttonStart},set:function(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,Yt.Start)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonBack",{get:function(){return this._buttonBack},set:function(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,Yt.Back)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonLB",{get:function(){return this._buttonLB},set:function(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,Yt.LB)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonRB",{get:function(){return this._buttonRB},set:function(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,Yt.RB)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonLeftStick",{get:function(){return this._buttonLeftStick},set:function(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Yt.LeftStick)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonRightStick",{get:function(){return this._buttonRightStick},set:function(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Yt.RightStick)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadUp",{get:function(){return this._dPadUp},set:function(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Kt.Up)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadDown",{get:function(){return this._dPadDown},set:function(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Kt.Down)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadLeft",{get:function(){return this._dPadLeft},set:function(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Kt.Left)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadRight",{get:function(){return this._dPadRight},set:function(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Kt.Right)},enumerable:!0,configurable:!0}),t.prototype.update=function(){e.prototype.update.call(this),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()},t}(lt);!function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Zt||(Zt={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Jt||(Jt={}));var ei=function(e){function t(t,i,n){var r=e.call(this,t.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),i,n,0,1,2,3)||this;return r._leftTrigger=0,r._rightTrigger=0,r.onButtonDownObservable=new o.c,r.onButtonUpObservable=new o.c,r.onPadDownObservable=new o.c,r.onPadUpObservable=new o.c,r._buttonCross=0,r._buttonCircle=0,r._buttonSquare=0,r._buttonTriangle=0,r._buttonShare=0,r._buttonOptions=0,r._buttonL1=0,r._buttonR1=0,r._buttonLeftStick=0,r._buttonRightStick=0,r._dPadUp=0,r._dPadDown=0,r._dPadLeft=0,r._dPadRight=0,r.type=lt.DUALSHOCK,r}return Object(h.d)(t,e),t.prototype.onlefttriggerchanged=function(e){this._onlefttriggerchanged=e},t.prototype.onrighttriggerchanged=function(e){this._onrighttriggerchanged=e},Object.defineProperty(t.prototype,"leftTrigger",{get:function(){return this._leftTrigger},set:function(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rightTrigger",{get:function(){return this._rightTrigger},set:function(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e},enumerable:!0,configurable:!0}),t.prototype.onbuttondown=function(e){this._onbuttondown=e},t.prototype.onbuttonup=function(e){this._onbuttonup=e},t.prototype.ondpaddown=function(e){this._ondpaddown=e},t.prototype.ondpadup=function(e){this._ondpadup=e},t.prototype._setButtonValue=function(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e},t.prototype._setDPadValue=function(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e},Object.defineProperty(t.prototype,"buttonCross",{get:function(){return this._buttonCross},set:function(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,Zt.Cross)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonCircle",{get:function(){return this._buttonCircle},set:function(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,Zt.Circle)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonSquare",{get:function(){return this._buttonSquare},set:function(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,Zt.Square)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonTriangle",{get:function(){return this._buttonTriangle},set:function(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,Zt.Triangle)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonOptions",{get:function(){return this._buttonOptions},set:function(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,Zt.Options)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonShare",{get:function(){return this._buttonShare},set:function(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,Zt.Share)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonL1",{get:function(){return this._buttonL1},set:function(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,Zt.L1)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonR1",{get:function(){return this._buttonR1},set:function(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,Zt.R1)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonLeftStick",{get:function(){return this._buttonLeftStick},set:function(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Zt.LeftStick)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonRightStick",{get:function(){return this._buttonRightStick},set:function(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Zt.RightStick)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadUp",{get:function(){return this._dPadUp},set:function(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Jt.Up)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadDown",{get:function(){return this._dPadDown},set:function(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Jt.Down)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadLeft",{get:function(){return this._dPadLeft},set:function(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Jt.Left)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadRight",{get:function(){return this._dPadRight},set:function(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Jt.Right)},enumerable:!0,configurable:!0}),t.prototype.update=function(){e.prototype.update.call(this),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()},t}(lt),ti=function(){function e(e){var t=this;if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new o.c,Xt.a.IsWindowObjectExist()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator.getGamepads||navigator.webkitGetGamepads||navigator.msGetGamepads||navigator.webkitGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new o.c(function(e){for(var i in t._babylonGamepads){var n=t._babylonGamepads[i];n&&n._isConnected&&t.onGamepadConnectedObservable.notifyObserver(e,n)}}),this._onGamepadConnectedEvent=function(e){var i,n=e.gamepad;n.index in t._babylonGamepads&&t._babylonGamepads[n.index].isConnected||(t._babylonGamepads[n.index]?((i=t._babylonGamepads[n.index]).browserGamepad=n,i._isConnected=!0):i=t._addNewGamepad(n),t.onGamepadConnectedObservable.notifyObservers(i),t._startMonitoringGamepads())},this._onGamepadDisconnectedEvent=function(e){var i=e.gamepad;for(var n in t._babylonGamepads)if(t._babylonGamepads[n].index===i.index){var r=t._babylonGamepads[n];r._isConnected=!1,t.onGamepadDisconnectedObservable.notifyObservers(r),r.dispose&&r.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){var i=this._scene?this._scene.getEngine().getHostWindow():window;i&&(i.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),i.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}return Object.defineProperty(e.prototype,"gamepads",{get:function(){return this._babylonGamepads},enumerable:!0,configurable:!0}),e.prototype.getGamepadByType=function(e){void 0===e&&(e=lt.XBOX);for(var t=0,i=this._babylonGamepads;t<i.length;t++){var n=i[t];if(n&&n.type===e)return n}return null},e.prototype.dispose=function(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach(function(e){e.dispose()}),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]},e.prototype._addNewGamepad=function(e){var t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);var i=-1!==e.id.search("054c"),n=-1!==e.id.search("Xbox One");return t=n||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")?new $t(e.id,e.index,e,n):i?new ei(e.id,e.index,e):e.pose?Qt.InitiateController(e):new ut(e.id,e.index,e),this._babylonGamepads[t.index]=t,t},e.prototype._startMonitoringGamepads=function(){this._isMonitoring||(this._isMonitoring=!0,this._scene||this._checkGamepadsStatus())},e.prototype._stopMonitoringGamepads=function(){this._isMonitoring=!1},e.prototype._checkGamepadsStatus=function(){var e=this;for(var t in this._updateGamepadObjects(),this._babylonGamepads){var i=this._babylonGamepads[t];i&&i.isConnected&&i.update()}this._isMonitoring&&!this._scene&&Oe.a.QueueNewFrame(function(){e._checkGamepadsStatus()})},e.prototype._updateGamepadObjects=function(){for(var e=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[],t=0;t<e.length;t++){var i=e[t];if(i)if(this._babylonGamepads[i.index])this._babylonGamepads[t].browserGamepad=i,this._babylonGamepads[t].isConnected||(this._babylonGamepads[t]._isConnected=!0,this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[t]));else{var n=this._addNewGamepad(i);this.onGamepadConnectedObservable.notifyObservers(n)}}},e}();Object.defineProperty(K.a.prototype,"gamepadManager",{get:function(){if(!this._gamepadManager){this._gamepadManager=new ti(this);var e=this._getComponent(Fe.a.NAME_GAMEPAD);e||(e=new ii(this),this._addComponent(e))}return this._gamepadManager},enumerable:!0,configurable:!0}),Ct.prototype.addGamepad=function(){return this.add(new Ot),this},gt.prototype.addGamepad=function(){return this.add(new ht),this};var ii=function(){function e(e){this.name=Fe.a.NAME_GAMEPAD,this.scene=e}return e.prototype.register=function(){this.scene._beforeCameraUpdateStage.registerStep(Fe.a.STEP_BEFORECAMERAUPDATE_GAMEPAD,this,this._beforeCameraUpdate)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){var e=this.scene._gamepadManager;e&&(e.dispose(),this.scene._gamepadManager=null)},e.prototype._beforeCameraUpdate=function(){var e=this.scene._gamepadManager;e&&e._isMonitoring&&e._checkGamepadsStatus()},e}();B.a.AddNodeConstructor("FreeCamera",function(e,t){return function(){return new ni(e,a.e.Zero(),t)}});var ni=function(e){function t(t,i,n){var r=e.call(this,t,i,n)||this;return r.inputs.addGamepad(),r}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"gamepadAngularSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gamepadMoveSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"UniversalCamera"},t}(Ft);Qe.a._createDefaultParsedCamera=function(e,t){return new ni(e,a.e.Zero(),t)},B.a.AddNodeConstructor("GamepadCamera",function(e,t){return function(){return new ri(e,a.e.Zero(),t)}});var ri=function(e){function t(t,i,n){return e.call(this,t,i,n)||this}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"GamepadCamera"},t}(ni),oi=i(34),ai=i(8),si="\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}";ai.a.ShadersStore.postprocessVertexShader=si;var ci=i(95),li=i(31);li.a.prototype.createRenderTargetTexture=function(e,t){var i=new ci.a;void 0!==t&&"object"==typeof t?(i.generateMipMaps=t.generateMipMaps,i.generateDepthBuffer=!!t.generateDepthBuffer,i.generateStencilBuffer=!!t.generateStencilBuffer,i.type=void 0===t.type?g.a.TEXTURETYPE_UNSIGNED_INT:t.type,i.samplingMode=void 0===t.samplingMode?g.a.TEXTURE_TRILINEAR_SAMPLINGMODE:t.samplingMode,i.format=void 0===t.format?g.a.TEXTUREFORMAT_RGBA:t.format):(i.generateMipMaps=t,i.generateDepthBuffer=!0,i.generateStencilBuffer=!1,i.type=g.a.TEXTURETYPE_UNSIGNED_INT,i.samplingMode=g.a.TEXTURE_TRILINEAR_SAMPLINGMODE,i.format=g.a.TEXTUREFORMAT_RGBA),(i.type!==g.a.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(i.type!==g.a.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(i.samplingMode=g.a.TEXTURE_NEAREST_SAMPLINGMODE),i.type!==g.a.TEXTURETYPE_FLOAT||this._caps.textureFloat||(i.type=g.a.TEXTURETYPE_UNSIGNED_INT,m.a.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"));var n=this._gl,r=new tt.a(this,tt.b.RenderTarget),o=e.width||e,a=e.height||e,s=e.layers||0,c=this._getSamplingParameters(i.samplingMode,!!i.generateMipMaps),l=0!==s?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D,u=this._getRGBABufferInternalSizedFormat(i.type,i.format),h=this._getInternalFormat(i.format),d=this._getWebGLTextureType(i.type);this._bindTextureDirectly(l,r),0!==s?(r.is2DArray=!0,n.texImage3D(l,0,u,o,a,s,0,h,d,null)):n.texImage2D(l,0,u,o,a,0,h,d,null),n.texParameteri(l,n.TEXTURE_MAG_FILTER,c.mag),n.texParameteri(l,n.TEXTURE_MIN_FILTER,c.min),n.texParameteri(l,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(l,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),i.generateMipMaps&&this._gl.generateMipmap(l),this._bindTextureDirectly(l,null);var f=n.createFramebuffer();return this._bindUnboundFramebuffer(f),r._depthStencilBuffer=this._setupFramebufferDepthAttachments(!!i.generateStencilBuffer,i.generateDepthBuffer,o,a),r.is2DArray||n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,r._webGLTexture,0),this._bindUnboundFramebuffer(null),r._framebuffer=f,r.baseWidth=o,r.baseHeight=a,r.width=o,r.height=a,r.depth=s,r.isReady=!0,r.samples=1,r.generateMipMaps=!!i.generateMipMaps,r.samplingMode=i.samplingMode,r.type=i.type,r.format=i.format,r._generateDepthBuffer=i.generateDepthBuffer,r._generateStencilBuffer=!!i.generateStencilBuffer,this._internalTexturesCache.push(r),r},li.a.prototype.createDepthStencilTexture=function(e,t){if(t.isCube){var i=e.width||e;return this._createDepthStencilCubeTexture(i,t)}return this._createDepthStencilTexture(e,t)},li.a.prototype._createDepthStencilTexture=function(e,t){var i=this._gl,n=e.layers||0,r=0!==n?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D,o=new tt.a(this,tt.b.Depth);if(!this._caps.depthTextureExtension)return m.a.Error("Depth texture is not supported by your browser or hardware."),o;var a=Object(h.a)({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t);this._bindTextureDirectly(r,o,!0),this._setupDepthStencilTexture(o,e,a.generateStencil,a.bilinearFiltering,a.comparisonFunction);var s=a.generateStencil?i.UNSIGNED_INT_24_8:i.UNSIGNED_INT,c=a.generateStencil?i.DEPTH_STENCIL:i.DEPTH_COMPONENT,l=c;return this.webGLVersion>1&&(l=a.generateStencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24),o.is2DArray?i.texImage3D(r,0,l,o.width,o.height,n,0,c,s,null):i.texImage2D(r,0,l,o.width,o.height,0,c,s,null),this._bindTextureDirectly(r,null),o};var ui=function(){function e(e,t,i,n,r,s,c,l,u,h,d,f,p,_,m){void 0===c&&(c=g.a.TEXTURE_NEAREST_SAMPLINGMODE),void 0===h&&(h=null),void 0===d&&(d=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===f&&(f="postprocess"),void 0===_&&(_=!1),void 0===m&&(m=g.a.TEXTUREFORMAT_RGBA),this.name=e,this.width=-1,this.height=-1,this._outputTexture=null,this.autoClear=!0,this.alphaMode=g.a.ALPHA_DISABLE,this.animations=new Array,this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=g.a.SCALEMODE_FLOOR,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._textures=new oi.a(2),this._currentRenderTextureInd=0,this._scaleRatio=new a.d(1,1),this._texelSize=a.d.Zero(),this.onActivateObservable=new o.c,this.onSizeChangedObservable=new o.c,this.onApplyObservable=new o.c,this.onBeforeRenderObservable=new o.c,this.onAfterRenderObservable=new o.c,null!=s?(this._camera=s,this._scene=s.getScene(),s.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):l&&(this._engine=l,this._engine.postProcesses.push(this)),this._options=r,this.renderTargetSamplingMode=c||g.a.TEXTURE_NEAREST_SAMPLINGMODE,this._reusable=u||!1,this._textureType=d,this._textureFormat=m,this._samplers=n||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=f,this._parameters=i||[],this._parameters.push("scale"),this._indexParameters=p,_||this.updateEffect(h)}return Object.defineProperty(e.prototype,"samples",{get:function(){return this._samples},set:function(e){var t=this;this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach(function(e){e.samples!==t._samples&&t._engine.updateRenderTargetTextureSampleCount(e,t._samples)})},enumerable:!0,configurable:!0}),e.prototype.getEffectName=function(){return this._fragmentUrl},Object.defineProperty(e.prototype,"onActivate",{set:function(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onSizeChanged",{set:function(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onApply",{set:function(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputTexture",{get:function(){return this._textures.data[this._currentRenderTextureInd]},set:function(e){this._forcedOutputTexture=e},enumerable:!0,configurable:!0}),e.prototype.getCamera=function(){return this._camera},Object.defineProperty(e.prototype,"texelSize",{get:function(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)},enumerable:!0,configurable:!0}),e.prototype.getClassName=function(){return"PostProcess"},e.prototype.getEngine=function(){return this._engine},e.prototype.getEffect=function(){return this._effect},e.prototype.shareOutputWith=function(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this},e.prototype.useOwnOutput=function(){0==this._textures.length&&(this._textures=new oi.a(2)),this._shareOutputWithPostProcess=null},e.prototype.updateEffect=function(e,t,i,n,r,o){void 0===e&&(e=null),void 0===t&&(t=null),void 0===i&&(i=null),this._effect=this._engine.createEffect({vertex:this._vertexUrl,fragment:this._fragmentUrl},["position"],t||this._parameters,i||this._samplers,null!==e?e:"",void 0,r,o,n||this._indexParameters)},e.prototype.isReusable=function(){return this._reusable},e.prototype.markTextureDirty=function(){this.width=-1},e.prototype.activate=function(e,t,i){var n=this;void 0===t&&(t=null);var r=(e=e||this._camera).getScene(),o=r.getEngine(),a=o.getCaps().maxTextureSize,s=(t?t.width:this._engine.getRenderWidth(!0))*this._options|0,c=(t?t.height:this._engine.getRenderHeight(!0))*this._options|0,l=e.parent;!l||l.leftCamera!=e&&l.rightCamera!=e||(s/=2);var u,h=this._options.width||s,d=this._options.height||c,f=this.renderTargetSamplingMode!==g.a.TEXTURE_NEAREST_LINEAR&&this.renderTargetSamplingMode!==g.a.TEXTURE_NEAREST_NEAREST&&this.renderTargetSamplingMode!==g.a.TEXTURE_LINEAR_LINEAR;if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this.adaptScaleToCurrentViewport){var p=o.currentViewport;p&&(h*=p.width,d*=p.height)}if((f||this.alwaysForcePOT)&&(this._options.width||(h=o.needPOTTextures?Oe.a.GetExponentOfTwo(h,a,this.scaleMode):h),this._options.height||(d=o.needPOTTextures?Oe.a.GetExponentOfTwo(d,a,this.scaleMode):d)),this.width!==h||this.height!==d){if(this._textures.length>0){for(var _=0;_<this._textures.length;_++)this._engine._releaseTexture(this._textures.data[_]);this._textures.reset()}this.width=h,this.height=d;var m={width:this.width,height:this.height},v={generateMipMaps:f,generateDepthBuffer:i||0===e._postProcesses.indexOf(this),generateStencilBuffer:(i||0===e._postProcesses.indexOf(this))&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType,format:this._textureFormat};this._textures.push(this._engine.createRenderTargetTexture(m,v)),this._reusable&&this._textures.push(this._engine.createRenderTargetTexture(m,v)),this._texelSize.copyFromFloats(1/this.width,1/this.height),this.onSizeChangedObservable.notifyObservers(this)}this._textures.forEach(function(e){e.samples!==n.samples&&n._engine.updateRenderTargetTextureSampleCount(e,n.samples)})}return this._shareOutputWithPostProcess?u=this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?(u=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height):u=this.inputTexture,this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(s/h,c/d),this._engine.bindFramebuffer(u,0,s,c,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(u,0,void 0,void 0,this.forceFullscreenViewport)),this.onActivateObservable.notifyObservers(e),this.autoClear&&this.alphaMode===g.a.ALPHA_DISABLE&&this._engine.clear(this.clearColor?this.clearColor:r.clearColor,r._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),u},Object.defineProperty(e.prototype,"isSupported",{get:function(){return this._effect.isSupported},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"aspectRatio",{get:function(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height},enumerable:!0,configurable:!0}),e.prototype.isReady=function(){return this._effect&&this._effect.isReady()},e.prototype.apply=function(){return this._effect&&this._effect.isReady()?(this._engine.enableEffect(this._effect),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),e=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this._effect._bindTexture("textureSampler",e),this._effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._effect),this._effect):null;var e},e.prototype._disposeTextures=function(){if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this._textures.length>0)for(var e=0;e<this._textures.length;e++)this._engine._releaseTexture(this._textures.data[e]);this._textures.dispose()}},e.prototype.dispose=function(e){if(e=e||this._camera,this._disposeTextures(),this._scene){var t=this._scene.postProcesses.indexOf(this);-1!==t&&this._scene.postProcesses.splice(t,1)}else{var i=this._engine.postProcesses.indexOf(this);-1!==i&&this._engine.postProcesses.splice(i,1)}if(e){if(e.detachPostProcess(this),0===e._postProcesses.indexOf(this)&&e._postProcesses.length>0){var n=this._camera._getFirstPostProcess();n&&n.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}},e}(),hi="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}";ai.a.ShadersStore.passPixelShader=hi;var di="\nvarying vec2 vUV;\nuniform samplerCube textureSampler;\nvoid main(void)\n{\nvec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";ai.a.ShadersStore.passCubePixelShader=di;var fi=function(e){function t(t,i,n,r,o,a,s,c){return void 0===n&&(n=null),void 0===s&&(s=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1),e.call(this,t,"pass",null,null,i,n,r,o,a,void 0,s,void 0,null,c)||this}return Object(h.d)(t,e),t}(ui),pi=function(e){function t(t,i,n,r,o,a,s,c){void 0===n&&(n=null),void 0===s&&(s=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1);var l=e.call(this,t,"passCube",null,null,i,n,r,o,a,"#define POSITIVEX",s,void 0,null,c)||this;return l._face=0,l}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"face",{get:function(){return this._face},set:function(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")}},enumerable:!0,configurable:!0}),t}(ui);Oe.a._RescalePostProcessFactory=function(e){return new fi("rescale",1,null,g.a.TEXTURE_BILINEAR_SAMPLINGMODE,e,!1,g.a.TEXTURETYPE_UNSIGNED_INT)};var _i="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}";ai.a.ShadersStore.anaglyphPixelShader=_i;var mi=function(e){function t(t,i,n,r,o,a){var s=e.call(this,t,"anaglyph",null,["leftSampler"],i,n[1],r,o,a)||this;return s._passedProcess=n[0]._rigPostProcess,s.onApplyObservable.add(function(e){e.setTextureFromPostProcess("leftSampler",s._passedProcess)}),s}return Object(h.d)(t,e),t}(ui);Qe.a._setStereoscopicAnaglyphRigMode=function(e){e._rigCameras[0]._rigPostProcess=new fi(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new mi(e.name+"_anaglyph",1,e._rigCameras)},B.a.AddNodeConstructor("AnaglyphArcRotateCamera",function(e,t,i){return function(){return new gi(e,0,0,1,a.e.Zero(),i.interaxial_distance,t)}});var gi=function(e){function t(t,i,n,r,o,a,s){var c=e.call(this,t,i,n,r,o,s)||this;return c.interaxialDistance=a,c.setCameraRigMode(Qe.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:a}),c}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"AnaglyphArcRotateCamera"},t}(Bt);B.a.AddNodeConstructor("AnaglyphFreeCamera",function(e,t,i){return function(){return new vi(e,a.e.Zero(),i.interaxial_distance,t)}});var vi=function(e){function t(t,i,n,r){var o=e.call(this,t,i,r)||this;return o.interaxialDistance=n,o.setCameraRigMode(Qe.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n}),o}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"AnaglyphFreeCamera"},t}(Nt);B.a.AddNodeConstructor("AnaglyphGamepadCamera",function(e,t,i){return function(){return new yi(e,a.e.Zero(),i.interaxial_distance,t)}});var yi=function(e){function t(t,i,n,r){var o=e.call(this,t,i,r)||this;return o.interaxialDistance=n,o.setCameraRigMode(Qe.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n}),o}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"AnaglyphGamepadCamera"},t}(ri);B.a.AddNodeConstructor("AnaglyphUniversalCamera",function(e,t,i){return function(){return new bi(e,a.e.Zero(),i.interaxial_distance,t)}});var bi=function(e){function t(t,i,n,r){var o=e.call(this,t,i,r)||this;return o.interaxialDistance=n,o.setCameraRigMode(Qe.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n}),o}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"AnaglyphUniversalCamera"},t}(ni),Ti="const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamA;\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\nuseCamA=!useCamB;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\n#ifdef IS_STEREOSCOPIC_INTERLACED\nfloat rowNum=floor(vUV.y/stepSize.y);\nuseCamA=mod(rowNum,2.0) == 1.0;\nuseCamB=mod(rowNum,2.0) == 0.0;\ntexCoord1=vec2(vUV.x,vUV.y);\ntexCoord2=vec2(vUV.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\nuseCamA=!useCamB;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else if (useCamA){\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}else {\ndiscard;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}\n";ai.a.ShadersStore.stereoscopicInterlacePixelShader=Ti;var Ei=function(e){function t(t,i,n,r,o,s,c){var l=e.call(this,t,"stereoscopicInterlace",["stepSize"],["camASampler"],1,i[1],o,s,c,r?"#define IS_STEREOSCOPIC_INTERLACED 1":n?"#define IS_STEREOSCOPIC_HORIZ 1":void 0)||this;return l._passedProcess=i[0]._rigPostProcess,l._stepSize=new a.d(1/l.width,1/l.height),l.onSizeChangedObservable.add(function(){l._stepSize=new a.d(1/l.width,1/l.height)}),l.onApplyObservable.add(function(e){e.setTextureFromPostProcess("camASampler",l._passedProcess),e.setFloat2("stepSize",l._stepSize.x,l._stepSize.y)}),l}return Object(h.d)(t,e),t}(ui),xi=function(e){function t(t,i,n,r,o,s){var c=e.call(this,t,"stereoscopicInterlace",["stepSize"],["camASampler"],1,i[1],r,o,s,n?"#define IS_STEREOSCOPIC_HORIZ 1":void 0)||this;return c._passedProcess=i[0]._rigPostProcess,c._stepSize=new a.d(1/c.width,1/c.height),c.onSizeChangedObservable.add(function(){c._stepSize=new a.d(1/c.width,1/c.height)}),c.onApplyObservable.add(function(e){e.setTextureFromPostProcess("camASampler",c._passedProcess),e.setFloat2("stepSize",c._stepSize.x,c._stepSize.y)}),c}return Object(h.d)(t,e),t}(ui);Qe.a._setStereoscopicRigMode=function(e){var t=e.cameraRigMode===Qe.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===Qe.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===Qe.a.RIG_MODE_STEREOSCOPIC_INTERLACED;e._rigCameras[0]._rigPostProcess=new fi(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new Ei(e.name+"_stereoInterlace",e._rigCameras,t,i)},B.a.AddNodeConstructor("StereoscopicArcRotateCamera",function(e,t,i){return function(){return new Pi(e,0,0,1,a.e.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)}});var Pi=function(e){function t(t,i,n,r,o,a,s,c){var l=e.call(this,t,i,n,r,o,c)||this;return l.interaxialDistance=a,l.isStereoscopicSideBySide=s,l.setCameraRigMode(s?Qe.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Qe.a.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:a}),l}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"StereoscopicArcRotateCamera"},t}(Bt);B.a.AddNodeConstructor("StereoscopicFreeCamera",function(e,t,i){return function(){return new Ai(e,a.e.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)}});var Ai=function(e){function t(t,i,n,r,o){var a=e.call(this,t,i,o)||this;return a.interaxialDistance=n,a.isStereoscopicSideBySide=r,a.setCameraRigMode(r?Qe.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Qe.a.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n}),a}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"StereoscopicFreeCamera"},t}(Nt);B.a.AddNodeConstructor("StereoscopicGamepadCamera",function(e,t,i){return function(){return new Si(e,a.e.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)}});var Si=function(e){function t(t,i,n,r,o){var a=e.call(this,t,i,o)||this;return a.interaxialDistance=n,a.isStereoscopicSideBySide=r,a.setCameraRigMode(r?Qe.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Qe.a.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n}),a}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"StereoscopicGamepadCamera"},t}(ri);B.a.AddNodeConstructor("StereoscopicFreeCamera",function(e,t,i){return function(){return new Ci(e,a.e.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)}});var Ci=function(e){function t(t,i,n,r,o){var a=e.call(this,t,i,o)||this;return a.interaxialDistance=n,a.isStereoscopicSideBySide=r,a.setCameraRigMode(r?Qe.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Qe.a.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n}),a}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"StereoscopicUniversalCamera"},t}(ni);B.a.AddNodeConstructor("VirtualJoysticksCamera",function(e,t){return function(){return new Ri(e,a.e.Zero(),t)}});var Ri=function(e){function t(t,i,n){var r=e.call(this,t,i,n)||this;return r.inputs.addVirtualJoystick(),r}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"VirtualJoysticksCamera"},t}(Nt),Oi=function(){function e(){this.compensateDistortion=!0,this.multiviewEnabled=!1}return Object.defineProperty(e.prototype,"aspectRatio",{get:function(){return this.hResolution/(2*this.vResolution)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"aspectRatioFov",{get:function(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"leftHMatrix",{get:function(){var e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return a.a.Translation(e,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rightHMatrix",{get:function(){var e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return a.a.Translation(-e,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"leftPreViewMatrix",{get:function(){return a.a.Translation(.5*this.interpupillaryDistance,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rightPreViewMatrix",{get:function(){return a.a.Translation(-.5*this.interpupillaryDistance,0,0)},enumerable:!0,configurable:!0}),e.GetDefault=function(){var t=new e;return t.hResolution=1280,t.vResolution=800,t.hScreenSize=.149759993,t.vScreenSize=.0935999975,t.vScreenCenter=.0467999987,t.eyeToScreenDistance=.0410000011,t.lensSeparationDistance=.063500002,t.interpupillaryDistance=.064000003,t.distortionK=[1,.219999999,.239999995,0],t.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],t.postProcessScaleFactor=1.714605507808412,t.lensCenterOffset=.151976421,t},e}(),Mi="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn;\nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}";ai.a.ShadersStore.vrDistortionCorrectionPixelShader=Mi;var Ii=function(e){function t(t,i,n,r){var o=e.call(this,t,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,r.postProcessScaleFactor,i,et.a.BILINEAR_SAMPLINGMODE)||this;return o._isRightEye=n,o._distortionFactors=r.distortionK,o._postProcessScaleFactor=r.postProcessScaleFactor,o._lensCenterOffset=r.lensCenterOffset,o.adaptScaleToCurrentViewport=!0,o.onSizeChangedObservable.add(function(){o._scaleIn=new a.d(2,2/o.aspectRatio),o._scaleFactor=new a.d(1/o._postProcessScaleFactor*.5,1/o._postProcessScaleFactor*.5*o.aspectRatio),o._lensCenter=new a.d(o._isRightEye?.5-.5*o._lensCenterOffset:.5+.5*o._lensCenterOffset,.5)}),o.onApplyObservable.add(function(e){e.setFloat2("LensCenter",o._lensCenter.x,o._lensCenter.y),e.setFloat2("Scale",o._scaleFactor.x,o._scaleFactor.y),e.setFloat2("ScaleIn",o._scaleIn.x,o._scaleIn.y),e.setFloat4("HmdWarpParam",o._distortionFactors[0],o._distortionFactors[1],o._distortionFactors[2],o._distortionFactors[3])}),o}return Object(h.d)(t,e),t}(ui),Di="precision mediump sampler2DArray;\nvarying vec2 vUV;\nuniform sampler2DArray multiviewSampler;\nuniform int imageIndex;\nvoid main(void)\n{\ngl_FragColor=texture(multiviewSampler,vec3(vUV,imageIndex));\n}";ai.a.ShadersStore.vrMultiviewToSingleviewPixelShader=Di;var wi=i(83),Li=i(90),Ni=i(91);li.a.prototype.createRenderTargetCubeTexture=function(e,t){var i=Object(h.a)({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:g.a.TEXTURETYPE_UNSIGNED_INT,samplingMode:g.a.TEXTURE_TRILINEAR_SAMPLINGMODE,format:g.a.TEXTUREFORMAT_RGBA},t);i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,(i.type!==g.a.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(i.type!==g.a.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(i.samplingMode=g.a.TEXTURE_NEAREST_SAMPLINGMODE);var n=this._gl,r=new tt.a(this,tt.b.RenderTarget);this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,r,!0);var o=this._getSamplingParameters(i.samplingMode,i.generateMipMaps);i.type!==g.a.TEXTURETYPE_FLOAT||this._caps.textureFloat||(i.type=g.a.TEXTURETYPE_UNSIGNED_INT,m.a.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MAG_FILTER,o.mag),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MIN_FILTER,o.min),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE);for(var a=0;a<6;a++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,this._getRGBABufferInternalSizedFormat(i.type,i.format),e,e,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);var s=n.createFramebuffer();return this._bindUnboundFramebuffer(s),r._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,e,e),i.generateMipMaps&&n.generateMipmap(n.TEXTURE_CUBE_MAP),this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),r._framebuffer=s,r.width=e,r.height=e,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,r._generateDepthBuffer=i.generateDepthBuffer,r._generateStencilBuffer=i.generateStencilBuffer,this._internalTexturesCache.push(r),r};var Fi=function(e){function t(t,i,n,r,s,c,l,u,h,d,f,p,_){void 0===s&&(s=!0),void 0===c&&(c=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===l&&(l=!1),void 0===u&&(u=et.a.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=!0),void 0===d&&(d=!1),void 0===f&&(f=!1),void 0===p&&(p=g.a.TEXTUREFORMAT_RGBA),void 0===_&&(_=!1);var m=e.call(this,null,n,!r)||this;return m.isCube=l,m.renderParticles=!0,m.renderSprites=!1,m.coordinatesMode=et.a.PROJECTION_MODE,m.ignoreCameraViewport=!1,m.onBeforeBindObservable=new o.c,m.onAfterUnbindObservable=new o.c,m.onBeforeRenderObservable=new o.c,m.onAfterRenderObservable=new o.c,m.onClearObservable=new o.c,m.onResizeObservable=new o.c,m._currentRefreshId=-1,m._refreshRate=1,m._samples=1,m.boundingBoxPosition=a.e.Zero(),(n=m.getScene())?(m.renderList=new Array,m._engine=n.getEngine(),m.name=t,m.isRenderTarget=!0,m._initialSizeParameter=i,m._processSizeParameter(i),m._resizeObserver=m.getScene().getEngine().onResizeObservable.add(function(){}),m._generateMipMaps=!!r,m._doNotChangeAspectRatio=s,m._renderingManager=new Ni.b(n),m._renderingManager._useSceneAutoClearSetup=!0,f?m:(m._renderTargetOptions={generateMipMaps:r,type:c,format:p,samplingMode:u,generateDepthBuffer:h,generateStencilBuffer:d},u===et.a.NEAREST_SAMPLINGMODE&&(m.wrapU=et.a.CLAMP_ADDRESSMODE,m.wrapV=et.a.CLAMP_ADDRESSMODE),_||(l?(m._texture=n.getEngine().createRenderTargetCubeTexture(m.getRenderSize(),m._renderTargetOptions),m.coordinatesMode=et.a.INVCUBIC_MODE,m._textureMatrix=a.a.Identity()):m._texture=n.getEngine().createRenderTargetTexture(m._size,m._renderTargetOptions)),m)):m}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"renderList",{get:function(){return this._renderList},set:function(e){this._renderList=e,this._renderList&&this._hookArray(this._renderList)},enumerable:!0,configurable:!0}),t.prototype._hookArray=function(e){var t=this,i=e.push;e.push=function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var o=0===e.length,a=i.apply(e,n);return o&&t.getScene().meshes.forEach(function(e){e._markSubMeshesAsLightDirty()}),a};var n=e.splice;e.splice=function(i,r){var o=n.apply(e,[i,r]);return 0===e.length&&t.getScene().meshes.forEach(function(e){e._markSubMeshesAsLightDirty()}),o}},Object.defineProperty(t.prototype,"onAfterUnbind",{set:function(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onClear",{set:function(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderTargetOptions",{get:function(){return this._renderTargetOptions},enumerable:!0,configurable:!0}),t.prototype._onRatioRescale=function(){this._sizeRatio&&this.resize(this._initialSizeParameter)},Object.defineProperty(t.prototype,"boundingBoxSize",{get:function(){return this._boundingBoxSize},set:function(e){if(!this._boundingBoxSize||!this._boundingBoxSize.equals(e)){this._boundingBoxSize=e;var t=this.getScene();t&&t.markAllMaterialsAsDirty(g.a.MATERIAL_TextureDirtyFlag)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"depthStencilTexture",{get:function(){var e;return(null===(e=this.getInternalTexture())||void 0===e?void 0:e._depthStencilTexture)||null},enumerable:!0,configurable:!0}),t.prototype.createDepthStencilTexture=function(e,t,i){void 0===e&&(e=0),void 0===t&&(t=!0),void 0===i&&(i=!1);var n=this.getInternalTexture();if(this.getScene()&&n){var r=this.getScene().getEngine();n._depthStencilTexture=r.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this.isCube})}},t.prototype._processSizeParameter=function(e){e.ratio?(this._sizeRatio=e.ratio,this._size={width:this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(),this._sizeRatio)}):this._size=e},Object.defineProperty(t.prototype,"samples",{get:function(){return this._samples},set:function(e){if(this._samples!==e){var t=this.getScene();t&&(this._samples=t.getEngine().updateRenderTargetTextureSampleCount(this._texture,e))}},enumerable:!0,configurable:!0}),t.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},Object.defineProperty(t.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!0,configurable:!0}),t.prototype.addPostProcess=function(e){if(!this._postProcessManager){var t=this.getScene();if(!t)return;this._postProcessManager=new Li.a(t),this._postProcesses=new Array}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1},t.prototype.clearPostProcesses=function(e){if(void 0===e&&(e=!1),this._postProcesses){if(e)for(var t=0,i=this._postProcesses;t<i.length;t++){i[t].dispose()}this._postProcesses=[]}},t.prototype.removePostProcess=function(e){if(this._postProcesses){var t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}},t.prototype._shouldRender=function(){return-1===this._currentRefreshId?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)},t.prototype.getRenderSize=function(){return this.getRenderWidth()},t.prototype.getRenderWidth=function(){return this._size.width?this._size.width:this._size},t.prototype.getRenderHeight=function(){return this._size.width?this._size.height:this._size},t.prototype.getRenderLayers=function(){var e=this._size.layers;return e||0},Object.defineProperty(t.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),t.prototype.scale=function(e){var t=Math.max(1,this.getRenderSize()*e);this.resize(t)},t.prototype.getReflectionTextureMatrix=function(){return this.isCube?this._textureMatrix:e.prototype.getReflectionTextureMatrix.call(this)},t.prototype.resize=function(e){var t=this.isCube;this.releaseInternalTexture();var i=this.getScene();i&&(this._processSizeParameter(e),this._texture=t?i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))},t.prototype.render=function(e,t){if(void 0===e&&(e=!1),void 0===t&&(t=!1),s=this.getScene()){var i,n=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(var r=0;r<this._waitingRenderList.length;r++){var o=this._waitingRenderList[r],a=s.getMeshByID(o);a&&this.renderList.push(a)}delete this._waitingRenderList}if(this.renderListPredicate){var s;if(this.renderList?this.renderList.length=0:this.renderList=[],!(s=this.getScene()))return;var c=s.meshes;for(r=0;r<c.length;r++){var l=c[r];this.renderListPredicate(l)&&this.renderList.push(l)}}if(this.onBeforeBindObservable.notifyObservers(this),this.activeCamera?(i=this.activeCamera,n.setViewport(this.activeCamera.viewport,this.getRenderWidth(),this.getRenderHeight()),this.activeCamera!==s.activeCamera&&s.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix(!0))):(i=s.activeCamera)&&n.setViewport(i.viewport,this.getRenderWidth(),this.getRenderHeight()),this._defaultRenderListPrepared=!1,this.is2DArray)for(var u=0;u<this.getRenderLayers();u++)this.renderToTarget(0,e,t,u,i),s.incrementRenderId(),s.resetCachedMaterial();else if(this.isCube)for(var h=0;h<6;h++)this.renderToTarget(h,e,t,void 0,i),s.incrementRenderId(),s.resetCachedMaterial();else this.renderToTarget(0,e,t,void 0,i);this.onAfterUnbindObservable.notifyObservers(this),s.activeCamera&&((s.getEngine().scenes.length>1||this.activeCamera&&this.activeCamera!==s.activeCamera)&&s.setTransformMatrix(s.activeCamera.getViewMatrix(),s.activeCamera.getProjectionMatrix(!0)),n.setViewport(s.activeCamera.viewport)),s.resetCachedMaterial()}},t.prototype._bestReflectionRenderTargetDimension=function(e,t){var i=e*t,n=Oe.a.NearestPOT(i+16384/(128+i));return Math.min(Oe.a.FloorPOT(e),n)},t.prototype._prepareRenderingManager=function(e,t,i,n){var r=this.getScene();if(r){this._renderingManager.reset();for(var o=r.getRenderId(),a=0;a<t;a++){var s=e[a];if(s){if(!s.isReady(0===this.refreshRate)){this.resetRefreshCounter();continue}s._preActivateForIntermediateRendering(o);var c=void 0;if(c=!(!n||!i)&&0==(s.layerMask&i.layerMask),s.isEnabled()&&s.isVisible&&s.subMeshes&&!c&&s._activate(o,!0)&&s.subMeshes.length){s.isAnInstance?s=s.sourceMesh:s._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!1,s._internalAbstractMeshDataInfo._isActiveIntermediate=!0;for(var l=0;l<s.subMeshes.length;l++){var u=s.subMeshes[l];this._renderingManager.dispatch(u,s)}}}}for(var h=0;h<r.particleSystems.length;h++){var d=r.particleSystems[h],f=d.emitter;d.isStarted()&&f&&f.position&&f.isEnabled()&&(e.indexOf(f)>=0&&this._renderingManager.dispatchParticles(d))}}},t.prototype._bindFrameBuffer=function(e,t){void 0===e&&(e=0),void 0===t&&(t=0);var i=this.getScene();if(i){var n=i.getEngine();this._texture&&n.bindFramebuffer(this._texture,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,0,t)}},t.prototype.unbindFrameBuffer=function(e,t){var i=this;this._texture&&e.unBindFramebuffer(this._texture,this.isCube,function(){i.onAfterRenderObservable.notifyObservers(t)})},t.prototype.renderToTarget=function(e,t,i,n,r){void 0===n&&(n=0),void 0===r&&(r=null);var o=this.getScene();if(o){var a=o.getEngine();if(this._texture){this._postProcessManager?this._postProcessManager._prepareFrame(this._texture,this._postProcesses):t&&o.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(e,n),this.is2DArray?this.onBeforeRenderObservable.notifyObservers(n):this.onBeforeRenderObservable.notifyObservers(e);var s=null,c=this.renderList?this.renderList:o.getActiveMeshes().data,l=this.renderList?this.renderList.length:o.getActiveMeshes().length;this.getCustomRenderList&&(s=this.getCustomRenderList(this.is2DArray?n:e,c,l)),s?this._prepareRenderingManager(s,s.length,r,!1):(this._defaultRenderListPrepared||(this._prepareRenderingManager(c,l,r,!this.renderList),this._defaultRenderListPrepared=!0),s=c),this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):a.clear(this.clearColor||o.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||o.updateTransformMatrix(!0);for(var u=0,h=o._beforeRenderTargetDrawStage;u<h.length;u++){h[u].action(this)}this._renderingManager.render(this.customRenderFunction,s,this.renderParticles,this.renderSprites);for(var d=0,f=o._afterRenderTargetDrawStage;d<f.length;d++){f[d].action(this)}this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._texture,e,this._postProcesses,this.ignoreCameraViewport):t&&o.postProcessManager._finalizeFrame(!1,this._texture,e),this._doNotChangeAspectRatio||o.updateTransformMatrix(!0),i&&De.b.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),a),this.isCube&&5!==e?this.onAfterRenderObservable.notifyObservers(e):(this.isCube&&5===e&&a.generateMipMapsForCubemap(this._texture),this.unbindFrameBuffer(a,e))}}},t.prototype.setRenderingOrder=function(e,t,i,n){void 0===t&&(t=null),void 0===i&&(i=null),void 0===n&&(n=null),this._renderingManager.setRenderingOrder(e,t,i,n)},t.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1},t.prototype.clone=function(){var e=this.getSize(),i=new t(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.coordinatesMode=this.coordinatesMode,this.renderList&&(i.renderList=this.renderList.slice(0)),i},t.prototype.serialize=function(){if(!this.name)return null;var t=e.prototype.serialize.call(this);if(t.renderTargetSize=this.getRenderSize(),t.renderList=[],this.renderList)for(var i=0;i<this.renderList.length;i++)t.renderList.push(this.renderList[i].id);return t},t.prototype.disposeFramebufferObjects=function(){var e=this.getInternalTexture(),t=this.getScene();e&&t&&t.getEngine()._releaseFramebufferObjects(e)},t.prototype.dispose=function(){this.onResizeObservable.clear(),this.onClearObservable.clear(),this.onAfterRenderObservable.clear(),this.onAfterUnbindObservable.clear(),this.onBeforeBindObservable.clear(),this.onBeforeRenderObservable.clear(),this._postProcessManager&&(this._postProcessManager.dispose(),this._postProcessManager=null),this.clearPostProcesses(!0),this._resizeObserver&&(this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.renderList=null;var t=this.getScene();if(t){var i=t.customRenderTargets.indexOf(this);i>=0&&t.customRenderTargets.splice(i,1);for(var n=0,r=t.cameras;n<r.length;n++){var o=r[n];(i=o.customRenderTargets.indexOf(this))>=0&&o.customRenderTargets.splice(i,1)}this.depthStencilTexture&&this.getScene().getEngine()._releaseTexture(this.depthStencilTexture),e.prototype.dispose.call(this)}},t.prototype._rebuild=function(){this.refreshRate===t.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=t.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()},t.prototype.freeRenderingGroups=function(){this._renderingManager&&this._renderingManager.freeRenderingGroups()},t.prototype.getViewCount=function(){return 1},t.REFRESHRATE_RENDER_ONCE=0,t.REFRESHRATE_RENDER_ONEVERYFRAME=1,t.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,t}(et.a);et.a._CreateRenderTargetTexture=function(e,t,i,n){return new Fi(e,t,i,n)};var Bi=function(e){function t(t,i){void 0===i&&(i=512);var n=e.call(this,"multiview rtt",i,t,!1,!0,tt.b.Unknown,!1,void 0,!1,!1,!0,void 0,!0)||this,r=t.getEngine().createMultiviewRenderTargetTexture(n.getRenderWidth(),n.getRenderHeight());return r.isMultiview=!0,r.format=g.a.TEXTUREFORMAT_RGBA,n._texture=r,n.samples=n._engine.getCaps().maxSamples||n.samples,n}return Object(h.d)(t,e),t.prototype._bindFrameBuffer=function(e){void 0===e&&(e=0),this._texture&&this.getScene().getEngine().bindMultiviewFramebuffer(this._texture)},t.prototype.getViewCount=function(){return 2},t}(Fi),Ui=i(86);Oe.a.prototype.createMultiviewRenderTargetTexture=function(e,t){var i=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";var n=new tt.a(this,tt.b.Unknown,!0);return n.width=e,n.height=t,n._framebuffer=i.createFramebuffer(),n._colorTextureArray=i.createTexture(),i.bindTexture(i.TEXTURE_2D_ARRAY,n._colorTextureArray),i.texStorage3D(i.TEXTURE_2D_ARRAY,1,i.RGBA8,e,t,2),n._depthStencilTextureArray=i.createTexture(),i.bindTexture(i.TEXTURE_2D_ARRAY,n._depthStencilTextureArray),i.texStorage3D(i.TEXTURE_2D_ARRAY,1,i.DEPTH32F_STENCIL8,e,t,2),n.isReady=!0,n},Oe.a.prototype.bindMultiviewFramebuffer=function(e){var t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),!e._colorTextureArray||!e._depthStencilTextureArray)throw"Invalid multiview frame buffer";this.getCaps().oculusMultiview?(i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,e.samples,0,2),i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,e.samples,0,2)):(i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,0,2))},Qe.a.prototype._useMultiviewToSingleView=!1,Qe.a.prototype._multiviewTexture=null,Qe.a.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==e&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new Bi(this.getScene(),{width:e,height:t})):this._multiviewTexture=new Bi(this.getScene(),{width:e,height:t})},K.a.prototype._transformMatrixR=a.a.Zero(),K.a.prototype._multiviewSceneUbo=null,K.a.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=new wi.a(this.getEngine(),void 0,!0),this._multiviewSceneUbo.addUniform("viewProjection",16),this._multiviewSceneUbo.addUniform("viewProjectionR",16),this._multiviewSceneUbo.addUniform("view",16)},K.a.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,a.c.Matrix[0]),Ui.a.GetRightPlaneToRef(a.c.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.update())},K.a.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(var t=0;t<e._rigCameras.length;t++){var i=this.getEngine();this._activeCamera=e._rigCameras[t],i.setViewport(this._activeCamera.viewport),this.postProcessManager&&(this.postProcessManager._prepareFrame(),this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate))}};var Vi=function(e){function t(t,i,n){var r=e.call(this,t,"vrMultiviewToSingleview",["imageIndex"],["multiviewSampler"],n,i,et.a.BILINEAR_SAMPLINGMODE)||this;return r.onSizeChangedObservable.add(function(){}),r.onApplyObservable.add(function(e){i._scene.activeCamera&&i._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",i._multiviewTexture)}),r}return Object(h.d)(t,e),t}(ui),ki=i(61);Qe.a._setVRRigMode=function(e,t){var i=t.vrCameraMetrics||Oi.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new ki.a(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new a.a,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new ki.a(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new a.a,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new Vi("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(m.a.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new Ii("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new Ii("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))},B.a.AddNodeConstructor("VRDeviceOrientationFreeCamera",function(e,t){return function(){return new zi(e,0,0,1,a.e.Zero(),t)}});var zi=function(e){function t(t,i,n,r,o,a,s,c){void 0===s&&(s=!0),void 0===c&&(c=Oi.GetDefault());var l=e.call(this,t,i,n,r,o,a)||this;return c.compensateDistortion=s,l.setCameraRigMode(Qe.a.RIG_MODE_VR,{vrCameraMetrics:c}),l.inputs.addVRDeviceOrientation(),l}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"VRDeviceOrientationArcRotateCamera"},t}(Bt);B.a.AddNodeConstructor("VRDeviceOrientationFreeCamera",function(e,t){return function(){return new Gi(e,a.e.Zero(),t)}});var Gi=function(e){function t(t,i,n,r,o){void 0===r&&(r=!0),void 0===o&&(o=Oi.GetDefault());var a=e.call(this,t,i,n)||this;return o.compensateDistortion=r,a.setCameraRigMode(Qe.a.RIG_MODE_VR,{vrCameraMetrics:o}),a}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"VRDeviceOrientationFreeCamera"},t}(Ut);B.a.AddNodeConstructor("VRDeviceOrientationGamepadCamera",function(e,t){return function(){return new ji(e,a.e.Zero(),t)}});var ji=function(e){function t(t,i,n,r,o){void 0===r&&(r=!0),void 0===o&&(o=Oi.GetDefault());var a=e.call(this,t,i,n,r,o)||this;return a.inputs.addGamepad(),a}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"VRDeviceOrientationGamepadCamera"},t}(Gi),Wi=i(80);Qe.a._setWebVRRigMode=function(e,t){if(t.vrDisplay){var i=t.vrDisplay.getEyeParameters("left"),n=t.vrDisplay.getEyeParameters("right");e._rigCameras[0].viewport=new ki.a(0,0,.5,1),e._rigCameras[0].setCameraRigParameter("left",!0),e._rigCameras[0].setCameraRigParameter("specs",t.specs),e._rigCameras[0].setCameraRigParameter("eyeParameters",i),e._rigCameras[0].setCameraRigParameter("frameData",t.frameData),e._rigCameras[0].setCameraRigParameter("parentCamera",t.parentCamera),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new a.a,e._rigCameras[0].getProjectionMatrix=e._getWebVRProjectionMatrix,e._rigCameras[0].parent=e,e._rigCameras[0]._getViewMatrix=e._getWebVRViewMatrix,e._rigCameras[1].viewport=new ki.a(.5,0,.5,1),e._rigCameras[1].setCameraRigParameter("eyeParameters",n),e._rigCameras[1].setCameraRigParameter("specs",t.specs),e._rigCameras[1].setCameraRigParameter("frameData",t.frameData),e._rigCameras[1].setCameraRigParameter("parentCamera",t.parentCamera),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new a.a,e._rigCameras[1].getProjectionMatrix=e._getWebVRProjectionMatrix,e._rigCameras[1].parent=e,e._rigCameras[1]._getViewMatrix=e._getWebVRViewMatrix}},Object.defineProperty(Oe.a.prototype,"isInVRExclusivePointerMode",{get:function(){return this._vrExclusivePointerMode},enumerable:!0,configurable:!0}),Oe.a.prototype._prepareVRComponent=function(){this._vrSupported=!1,this._vrExclusivePointerMode=!1,this.onVRDisplayChangedObservable=new o.c,this.onVRRequestPresentComplete=new o.c,this.onVRRequestPresentStart=new o.c},Oe.a.prototype.isVRDevicePresent=function(){return!!this._vrDisplay},Oe.a.prototype.getVRDevice=function(){return this._vrDisplay},Oe.a.prototype.initWebVR=function(){return this.initWebVRAsync(),this.onVRDisplayChangedObservable},Oe.a.prototype.initWebVRAsync=function(){var e=this,t=function(){var t={vrDisplay:e._vrDisplay,vrSupported:e._vrSupported};e.onVRDisplayChangedObservable.notifyObservers(t),e._webVRInitPromise=new Promise(function(e){e(t)})};if(!this._onVrDisplayConnect){this._onVrDisplayConnect=function(i){e._vrDisplay=i.display,t()},this._onVrDisplayDisconnect=function(){e._vrDisplay.cancelAnimationFrame(e._frameHandler),e._vrDisplay=void 0,e._frameHandler=Oe.a.QueueNewFrame(e._boundRenderFunction),t()},this._onVrDisplayPresentChange=function(){e._vrExclusivePointerMode=e._vrDisplay&&e._vrDisplay.isPresenting};var i=this.getHostWindow();i&&(i.addEventListener("vrdisplayconnect",this._onVrDisplayConnect),i.addEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),i.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange))}return this._webVRInitPromise=this._webVRInitPromise||this._getVRDisplaysAsync(),this._webVRInitPromise.then(t),this._webVRInitPromise},Oe.a.prototype._getVRDisplaysAsync=function(){var e=this;return new Promise(function(t){navigator.getVRDisplays?navigator.getVRDisplays().then(function(i){e._vrSupported=!0,e._vrDisplay=i[0],t({vrDisplay:e._vrDisplay,vrSupported:e._vrSupported})}):(e._vrDisplay=void 0,e._vrSupported=!1,t({vrDisplay:e._vrDisplay,vrSupported:e._vrSupported}))})},Oe.a.prototype.enableVR=function(e){var t=this;if(this._vrDisplay&&!this._vrDisplay.isPresenting){this.onVRRequestPresentStart.notifyObservers(this);var i={highRefreshRate:!!this.vrPresentationAttributes&&this.vrPresentationAttributes.highRefreshRate,foveationLevel:this.vrPresentationAttributes?this.vrPresentationAttributes.foveationLevel:1,multiview:(this.getCaps().multiview||this.getCaps().oculusMultiview)&&e.useMultiview};this._vrDisplay.requestPresent([Object(h.a)({source:this.getRenderingCanvas(),attributes:i},i)]).then(function(){t.onVRRequestPresentComplete.notifyObservers(!0),t._onVRFullScreenTriggered()}).catch(function(){t.onVRRequestPresentComplete.notifyObservers(!1)})}},Oe.a.prototype._onVRFullScreenTriggered=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting){this._oldSize=new U.a(this.getRenderWidth(),this.getRenderHeight()),this._oldHardwareScaleFactor=this.getHardwareScalingLevel();var e=this._vrDisplay.getEyeParameters("left");this.setHardwareScalingLevel(1),this.setSize(2*e.renderWidth,e.renderHeight)}else this.setHardwareScalingLevel(this._oldHardwareScaleFactor),this.setSize(this._oldSize.width,this._oldSize.height)},Oe.a.prototype.disableVR=function(){var e=this;this._vrDisplay&&this._vrDisplay.isPresenting&&this._vrDisplay.exitPresent().then(function(){return e._onVRFullScreenTriggered()}).catch(function(){return e._onVRFullScreenTriggered()}),Xt.a.IsWindowObjectExist()&&(window.removeEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted),window.removeEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted),this._onVrDisplayConnect&&(window.removeEventListener("vrdisplayconnect",this._onVrDisplayConnect),this._onVrDisplayDisconnect&&window.removeEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),this._onVrDisplayPresentChange&&window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),this._onVrDisplayConnect=null,this._onVrDisplayDisconnect=null))},Oe.a.prototype._connectVREvents=function(e,t){var i=this;if(this._onVRDisplayPointerRestricted=function(){e&&e.requestPointerLock()},this._onVRDisplayPointerUnrestricted=function(){if(t)t.exitPointerLock&&t.exitPointerLock();else{var e=i.getHostWindow();e.document&&e.document.exitPointerLock&&e.document.exitPointerLock()}},Xt.a.IsWindowObjectExist()){var n=this.getHostWindow();n.addEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted,!1),n.addEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted,!1)}},Oe.a.prototype._submitVRFrame=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting)try{this._vrDisplay.submitFrame()}catch(e){De.b.Warn("webVR submitFrame has had an unexpected failure: "+e)}},Oe.a.prototype.isVRPresenting=function(){return this._vrDisplay&&this._vrDisplay.isPresenting},Oe.a.prototype._requestVRFrame=function(){this._frameHandler=Oe.a.QueueNewFrame(this._boundRenderFunction,this._vrDisplay)},B.a.AddNodeConstructor("WebVRFreeCamera",function(e,t){return function(){return new Xi(e,a.e.Zero(),t)}}),B.a.AddNodeConstructor("WebVRGamepadCamera",function(e,t){return function(){return new Xi(e,a.e.Zero(),t)}});var Xi=function(e){function t(t,i,n,r){void 0===r&&(r={});var s=e.call(this,t,i,n)||this;s.webVROptions=r,s._vrDevice=null,s.rawPose=null,s._specsVersion="1.1",s._attached=!1,s._descendants=[],s._deviceRoomPosition=a.e.Zero(),s._deviceRoomRotationQuaternion=a.b.Identity(),s._standingMatrix=null,s.devicePosition=a.e.Zero(),s.deviceRotationQuaternion=a.b.Identity(),s.deviceScaleFactor=1,s._deviceToWorld=a.a.Identity(),s._worldToDevice=a.a.Identity(),s.controllers=[],s.onControllersAttachedObservable=new o.c,s.onControllerMeshLoadedObservable=new o.c,s.onPoseUpdatedFromDeviceObservable=new o.c,s._poseSet=!1,s.rigParenting=!0,s._defaultHeight=void 0,s._htmlElementAttached=null,s._detachIfAttached=function(){var e=s.getEngine().getVRDevice();e&&!e.isPresenting&&s._htmlElementAttached&&s.detachControl(s._htmlElementAttached)},s._workingVector=a.e.Zero(),s._oneVector=a.e.One(),s._workingMatrix=a.a.Identity(),s._tmpMatrix=new a.a,s._cache.position=a.e.Zero(),r.defaultHeight&&(s._defaultHeight=r.defaultHeight,s.position.y=s._defaultHeight),s.minZ=.1,5===arguments.length&&(s.webVROptions=arguments[4]),null==s.webVROptions.trackPosition&&(s.webVROptions.trackPosition=!0),null==s.webVROptions.controllerMeshes&&(s.webVROptions.controllerMeshes=!0),null==s.webVROptions.defaultLightingOnControllers&&(s.webVROptions.defaultLightingOnControllers=!0),s.rotationQuaternion=new a.b,s.webVROptions&&s.webVROptions.positionScale&&(s.deviceScaleFactor=s.webVROptions.positionScale);var c=s.getEngine();return s._onVREnabled=function(e){e&&s.initControllers()},c.onVRRequestPresentComplete.add(s._onVREnabled),c.initWebVR().add(function(e){e.vrDisplay&&s._vrDevice!==e.vrDisplay&&(s._vrDevice=e.vrDisplay,s.setCameraRigMode(Qe.a.RIG_MODE_WEBVR,{parentCamera:s,vrDisplay:s._vrDevice,frameData:s._frameData,specs:s._specsVersion}),s._attached&&s.getEngine().enableVR(s.webVROptions))}),"undefined"!=typeof VRFrameData&&(s._frameData=new VRFrameData),r.useMultiview&&(s.getScene().getEngine().getCaps().multiview?(s._useMultiviewToSingleView=!0,s._rigPostProcess=new Vi("VRMultiviewToSingleview",s,1)):(m.a.Warn("Multiview is not supported, falling back to standard rendering"),s._useMultiviewToSingleView=!1)),n.onBeforeCameraRenderObservable.add(function(e){e.parent===s&&s.rigParenting&&(s._descendants=s.getDescendants(!0,function(e){var t=s.controllers.some(function(t){return t._mesh===e}),i=-1!==s._rigCameras.indexOf(e);return!t&&!i}),s._descendants.forEach(function(t){t.parent=e}))}),n.onAfterCameraRenderObservable.add(function(e){e.parent===s&&s.rigParenting&&s._descendants.forEach(function(e){e.parent=s})}),s}return Object(h.d)(t,e),t.prototype.deviceDistanceToRoomGround=function(){return this._standingMatrix?(this._standingMatrix.getTranslationToRef(this._workingVector),this._deviceRoomPosition.y+this._workingVector.y):this._defaultHeight||0},t.prototype.useStandingMatrix=function(e){var t=this;void 0===e&&(e=function(e){}),this.getEngine().initWebVRAsync().then(function(i){i.vrDisplay&&i.vrDisplay.stageParameters&&i.vrDisplay.stageParameters.sittingToStandingTransform&&t.webVROptions.trackPosition?(t._standingMatrix=new a.a,a.a.FromFloat32ArrayToRefScaled(i.vrDisplay.stageParameters.sittingToStandingTransform,0,1,t._standingMatrix),t.getScene().useRightHandedSystem||t._standingMatrix&&t._standingMatrix.toggleModelMatrixHandInPlace(),e(!0)):e(!1)})},t.prototype.useStandingMatrixAsync=function(){var e=this;return new Promise(function(t){e.useStandingMatrix(function(e){t(e)})})},t.prototype.dispose=function(){this._detachIfAttached(),this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled),this._updateCacheWhenTrackingDisabledObserver&&this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver),e.prototype.dispose.call(this)},t.prototype.getControllerByName=function(e){for(var t=0,i=this.controllers;t<i.length;t++){var n=i[t];if(n.hand===e)return n}return null},Object.defineProperty(t.prototype,"leftController",{get:function(){return this._leftController||(this._leftController=this.getControllerByName("left")),this._leftController},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rightController",{get:function(){return this._rightController||(this._rightController=this.getControllerByName("right")),this._rightController},enumerable:!0,configurable:!0}),t.prototype.getForwardRay=function(t){return void 0===t&&(t=100),this.leftCamera?e.prototype.getForwardRay.call(this,t,this.leftCamera.getWorldMatrix(),this.leftCamera.globalPosition):e.prototype.getForwardRay.call(this,t)},t.prototype._checkInputs=function(){this._vrDevice&&this._vrDevice.isPresenting&&(this._vrDevice.getFrameData(this._frameData),this.updateFromDevice(this._frameData.pose)),e.prototype._checkInputs.call(this)},t.prototype.updateFromDevice=function(e){e&&e.orientation&&4===e.orientation.length&&(this.rawPose=e,this._deviceRoomRotationQuaternion.copyFromFloats(e.orientation[0],e.orientation[1],-e.orientation[2],-e.orientation[3]),this.getScene().useRightHandedSystem&&(this._deviceRoomRotationQuaternion.z*=-1,this._deviceRoomRotationQuaternion.w*=-1),this.webVROptions.trackPosition&&this.rawPose.position&&(this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0],this.rawPose.position[1],-this.rawPose.position[2]),this.getScene().useRightHandedSystem&&(this._deviceRoomPosition.z*=-1)),this._poseSet=!0)},t.prototype.attachControl=function(t,i){e.prototype.attachControl.call(this,t,i),this._attached=!0,this._htmlElementAttached=t,i=!Qe.a.ForceAttachControlToAlwaysPreventDefault&&i,this._vrDevice&&this.getEngine().enableVR(this.webVROptions);var n=this._scene.getEngine().getHostWindow();n&&n.addEventListener("vrdisplaypresentchange",this._detachIfAttached)},t.prototype.detachControl=function(t){this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),e.prototype.detachControl.call(this,t),this._attached=!1,this.getEngine().disableVR(),window.removeEventListener("vrdisplaypresentchange",this._detachIfAttached)},t.prototype.getClassName=function(){return"WebVRFreeCamera"},t.prototype.resetToCurrentRotation=function(){this._vrDevice.resetPose()},t.prototype._updateRigCameras=function(){var e=this._rigCameras[0],t=this._rigCameras[1];e.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),t.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),e.position.copyFrom(this._deviceRoomPosition),t.position.copyFrom(this._deviceRoomPosition)},t.prototype._correctPositionIfNotTrackPosition=function(e,t){void 0===t&&(t=!1),this.rawPose&&this.rawPose.position&&!this.webVROptions.trackPosition&&(a.a.TranslationToRef(this.rawPose.position[0],this.rawPose.position[1],-this.rawPose.position[2],this._tmpMatrix),t||this._tmpMatrix.invert(),this._tmpMatrix.multiplyToRef(e,e))},t.prototype._updateCache=function(t){var i=this;this.rotationQuaternion.equals(this._cache.rotationQuaternion)&&this.position.equals(this._cache.position)||(this.updateCacheCalled||(this.updateCacheCalled=!0,this.update()),this.rotationQuaternion.toRotationMatrix(this._workingMatrix),a.e.TransformCoordinatesToRef(this._deviceRoomPosition,this._workingMatrix,this._workingVector),this.devicePosition.subtractToRef(this._workingVector,this._workingVector),a.a.ComposeToRef(this._oneVector,this.rotationQuaternion,this._workingVector,this._deviceToWorld),this._deviceToWorld.getTranslationToRef(this._workingVector),this._workingVector.addInPlace(this.position),this._workingVector.subtractInPlace(this._cache.position),this._deviceToWorld.setTranslation(this._workingVector),this._deviceToWorld.invertToRef(this._worldToDevice),this.controllers.forEach(function(e){e._deviceToWorld.copyFrom(i._deviceToWorld),i._correctPositionIfNotTrackPosition(e._deviceToWorld),e.update()})),t||e.prototype._updateCache.call(this),this.updateCacheCalled=!1},t.prototype._computeDevicePosition=function(){a.e.TransformCoordinatesToRef(this._deviceRoomPosition,this._deviceToWorld,this.devicePosition)},t.prototype.update=function(){this._computeDevicePosition(),a.a.FromQuaternionToRef(this._deviceRoomRotationQuaternion,this._workingMatrix),this._workingMatrix.multiplyToRef(this._deviceToWorld,this._workingMatrix),a.b.FromRotationMatrixToRef(this._workingMatrix,this.deviceRotationQuaternion),this._poseSet&&this.onPoseUpdatedFromDeviceObservable.notifyObservers(null),e.prototype.update.call(this)},t.prototype._getViewMatrix=function(){return a.a.Identity()},t.prototype._getWebVRViewMatrix=function(){var e=this._cameraRigParams.parentCamera;e._updateCache();var t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftViewMatrix:this._cameraRigParams.frameData.rightViewMatrix;return a.a.FromArrayToRef(t,0,this._webvrViewMatrix),this.getScene().useRightHandedSystem||this._webvrViewMatrix.toggleModelMatrixHandInPlace(),this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix),a.e.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),1!==e.deviceScaleFactor&&(this._webvrViewMatrix.invert(),e.deviceScaleFactor&&(this._webvrViewMatrix.multiplyAtIndex(12,e.deviceScaleFactor),this._webvrViewMatrix.multiplyAtIndex(13,e.deviceScaleFactor),this._webvrViewMatrix.multiplyAtIndex(14,e.deviceScaleFactor)),this._webvrViewMatrix.invert()),e._correctPositionIfNotTrackPosition(this._webvrViewMatrix,!0),e._worldToDevice.multiplyToRef(this._webvrViewMatrix,this._webvrViewMatrix),this._workingMatrix=this._workingMatrix||a.a.Identity(),this._webvrViewMatrix.invertToRef(this._workingMatrix),this._workingMatrix.multiplyToRef(e.getWorldMatrix(),this._workingMatrix),this._workingMatrix.getTranslationToRef(this._globalPosition),this._markSyncedWithParent(),this._webvrViewMatrix},t.prototype._getWebVRProjectionMatrix=function(){var e=this.parent;e._vrDevice.depthNear=e.minZ,e._vrDevice.depthFar=e.maxZ;var t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftProjectionMatrix:this._cameraRigParams.frameData.rightProjectionMatrix;return a.a.FromArrayToRef(t,0,this._projectionMatrix),this.getScene().useRightHandedSystem||this._projectionMatrix.toggleProjectionMatrixHandInPlace(),this._projectionMatrix},t.prototype.initControllers=function(){var e=this;this.controllers=[];var t=this.getScene().gamepadManager;this._onGamepadDisconnectedObserver=t.onGamepadDisconnectedObservable.add(function(t){if(t.type===lt.POSE_ENABLED){var i=t;i.defaultModel&&i.defaultModel.setEnabled(!1),"right"===i.hand&&(e._rightController=null),"left"===i.hand&&(e._leftController=null);var n=e.controllers.indexOf(i);-1!==n&&e.controllers.splice(n,1)}}),this._onGamepadConnectedObserver=t.onGamepadConnectedObservable.add(function(t){if(t.type===lt.POSE_ENABLED){var i=t;if(e.webVROptions.trackPosition||(i._disableTrackPosition(new a.e("left"==i.hand?-.15:.15,-.5,.25)),e._updateCacheWhenTrackingDisabledObserver||(e._updateCacheWhenTrackingDisabledObserver=e._scene.onBeforeRenderObservable.add(function(){e._updateCache()}))),i.deviceScaleFactor=e.deviceScaleFactor,i._deviceToWorld.copyFrom(e._deviceToWorld),e._correctPositionIfNotTrackPosition(i._deviceToWorld),e.webVROptions.controllerMeshes&&(i.defaultModel?i.defaultModel.setEnabled(!0):i.initControllerMesh(e.getScene(),function(t){if(t.scaling.scaleInPlace(e.deviceScaleFactor),e.onControllerMeshLoadedObservable.notifyObservers(i),e.webVROptions.defaultLightingOnControllers){e._lightOnControllers||(e._lightOnControllers=new Wi.a("vrControllersLight",new a.e(0,1,0),e.getScene()));var n=function(e,t){var i=e.getChildren();i&&0!==i.length&&i.forEach(function(e){t.includedOnlyMeshes.push(e),n(e,t)})};e._lightOnControllers.includedOnlyMeshes.push(t),n(t,e._lightOnControllers)}})),i.attachToPoseControlledCamera(e),-1===e.controllers.indexOf(i)){e.controllers.push(i);for(var n=!1,r=0;r<e.controllers.length;r++)e.controllers[r].controllerType===Gt.VIVE&&(n?e.controllers[r].hand="right":(n=!0,e.controllers[r].hand="left"));e.controllers.length>=2&&e.onControllersAttachedObservable.notifyObservers(e.controllers)}}})},t}(Nt),Hi=function(e){function t(t){var i=e.call(this,t)||this;return i.onTriggerStateChangedObservable=new o.c,i.onMainButtonStateChangedObservable=new o.c,i.onSecondaryButtonStateChangedObservable=new o.c,i.onPadStateChangedObservable=new o.c,i.onPadValuesChangedObservable=new o.c,i.pad={x:0,y:0},i._changes={pressChanged:!1,touchChanged:!1,valueChanged:!1,changed:!1},i._buttons=new Array(t.buttons.length),i.hand=t.hand,i}return Object(h.d)(t,e),t.prototype.onButtonStateChange=function(e){this._onButtonStateChange=e},Object.defineProperty(t.prototype,"defaultModel",{get:function(){return this._defaultModel},enumerable:!0,configurable:!0}),t.prototype.update=function(){e.prototype.update.call(this);for(var t=0;t<this._buttons.length;t++)this._setButtonValue(this.browserGamepad.buttons[t],this._buttons[t],t);this.leftStick.x===this.pad.x&&this.leftStick.y===this.pad.y||(this.pad.x=this.leftStick.x,this.pad.y=this.leftStick.y,this.onPadValuesChangedObservable.notifyObservers(this.pad))},t.prototype._setButtonValue=function(e,t,i){e||(e={pressed:!1,touched:!1,value:0}),t?(this._checkChanges(e,t),this._changes.changed&&(this._onButtonStateChange&&this._onButtonStateChange(this.index,i,e),this._handleButtonChange(i,e,this._changes)),this._buttons[i].pressed=e.pressed,this._buttons[i].touched=e.touched,this._buttons[i].value=e.value<1e-8?0:e.value):this._buttons[i]={pressed:e.pressed,touched:e.touched,value:e.value}},t.prototype._checkChanges=function(e,t){return this._changes.pressChanged=e.pressed!==t.pressed,this._changes.touchChanged=e.touched!==t.touched,this._changes.valueChanged=e.value!==t.value,this._changes.changed=this._changes.pressChanged||this._changes.touchChanged||this._changes.valueChanged,this._changes},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._defaultModel=null,this.onTriggerStateChangedObservable.clear(),this.onMainButtonStateChangedObservable.clear(),this.onSecondaryButtonStateChangedObservable.clear(),this.onPadStateChangedObservable.clear(),this.onPadValuesChangedObservable.clear()},t}(qt),Yi=i(40),Ki=i(32);li.a.prototype.createDynamicTexture=function(e,t,i,n){var r=new tt.a(this,tt.b.Dynamic);return r.baseWidth=e,r.baseHeight=t,i&&(e=this.needPOTTextures?li.a.GetExponentOfTwo(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?li.a.GetExponentOfTwo(t,this._caps.maxTextureSize):t),r.width=e,r.height=t,r.isReady=!1,r.generateMipMaps=i,r.samplingMode=n,this.updateTextureSamplingMode(n,r),this._internalTexturesCache.push(r),r},li.a.prototype.updateDynamicTexture=function(e,t,i,n,r,o){if(void 0===n&&(n=!1),void 0===o&&(o=!1),e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0,o),this._unpackFlipY(i),n&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);var a=r?this._getInternalFormat(r):this._gl.RGBA;this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,a,this._gl.UNSIGNED_BYTE,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),n&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.isReady=!0}};var Qi=i(70),qi=function(e){function t(t,i,n,r,o,a){void 0===n&&(n=null),void 0===o&&(o=g.a.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===a&&(a=g.a.TEXTUREFORMAT_RGBA);var s=e.call(this,null,n,!r,void 0,o,void 0,void 0,void 0,void 0,a)||this;s.name=t,s._engine=s.getScene().getEngine(),s.wrapU=et.a.CLAMP_ADDRESSMODE,s.wrapV=et.a.CLAMP_ADDRESSMODE,s._generateMipMaps=r,i.getContext?(s._canvas=i,s._texture=s._engine.createDynamicTexture(i.width,i.height,r,o)):(s._canvas=Qi.a.CreateCanvas(1,1),i.width||0===i.width?s._texture=s._engine.createDynamicTexture(i.width,i.height,r,o):s._texture=s._engine.createDynamicTexture(i,i,r,o));var c=s.getSize();return s._canvas.width=c.width,s._canvas.height=c.height,s._context=s._canvas.getContext("2d"),s}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"DynamicTexture"},Object.defineProperty(t.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),t.prototype._recreate=function(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._engine.createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)},t.prototype.scale=function(e){var t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)},t.prototype.scaleTo=function(e,t){var i=this.getSize();i.width=e,i.height=t,this._recreate(i)},t.prototype.getContext=function(){return this._context},t.prototype.clear=function(){var e=this.getSize();this._context.fillRect(0,0,e.width,e.height)},t.prototype.update=function(e,t){void 0===t&&(t=!1),this._engine.updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0)},t.prototype.drawText=function(e,t,i,n,r,o,a,s){void 0===s&&(s=!0);var c=this.getSize();if(o&&(this._context.fillStyle=o,this._context.fillRect(0,0,c.width,c.height)),this._context.font=n,null==t){var l=this._context.measureText(e);t=(c.width-l.width)/2}if(null==i){var u=parseInt(n.replace(/\D/g,""));i=c.height/2+u/3.65}this._context.fillStyle=r,this._context.fillText(e,t,i),s&&this.update(a)},t.prototype.clone=function(){var e=this.getScene();if(!e)return this;var i=this.getSize(),n=new t(this.name,i,e,this._generateMipMaps);return n.hasAlpha=this.hasAlpha,n.level=this.level,n.wrapU=this.wrapU,n.wrapV=this.wrapV,n},t.prototype.serialize=function(){var t=this.getScene();t&&!t.isReady()&&m.a.Warn("The scene must be ready before serializing the dynamic texture");var i=e.prototype.serialize.call(this);return this._canvas.toDataURL&&(i.base64String=this._canvas.toDataURL()),i.invertY=this._invertY,i.samplingMode=this.samplingMode,i},t.prototype._rebuild=function(){this.update()},t}(et.a),Zi=(i(99),i(58),i(100),"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}");ai.a.ShadersStore.imageProcessingPixelShader=Zi;var Ji=function(e){function t(t,i,n,r,o,a,s,c){void 0===n&&(n=null),void 0===s&&(s=g.a.TEXTURETYPE_UNSIGNED_INT);var l=e.call(this,t,"imageProcessing",[],[],i,n,r,o,a,null,s,"postprocess",null,!0)||this;return l._fromLinearSpace=!0,l._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1},c?(c.applyByPostProcess=!0,l._attachImageProcessingConfiguration(c,!0),l.fromLinearSpace=!1):(l._attachImageProcessingConfiguration(null,!0),l.imageProcessingConfiguration.applyByPostProcess=!0),l.onApply=function(e){l.imageProcessingConfiguration.bind(e,l.aspectRatio)},l}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)},enumerable:!0,configurable:!0}),t.prototype._attachImageProcessingConfiguration=function(e,t){var i=this;if(void 0===t&&(t=!1),e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{var n=null,r=this.getEngine(),o=this.getCamera();if(o)n=o.getScene();else if(r&&r.scenes){var a=r.scenes;n=a[a.length-1]}else n=R.a.LastCreatedScene;this._imageProcessingConfiguration=n.imageProcessingConfiguration}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(function(){i._updateParameters()})),t||this._updateParameters()}},Object.defineProperty(t.prototype,"colorCurves",{get:function(){return this.imageProcessingConfiguration.colorCurves},set:function(e){this.imageProcessingConfiguration.colorCurves=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"colorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"colorGradingTexture",{get:function(){return this.imageProcessingConfiguration.colorGradingTexture},set:function(e){this.imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"colorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"exposure",{get:function(){return this.imageProcessingConfiguration.exposure},set:function(e){this.imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"toneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"toneMappingType",{get:function(){return this._imageProcessingConfiguration.toneMappingType},set:function(e){this._imageProcessingConfiguration.toneMappingType=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"contrast",{get:function(){return this.imageProcessingConfiguration.contrast},set:function(e){this.imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteStretch",{get:function(){return this.imageProcessingConfiguration.vignetteStretch},set:function(e){this.imageProcessingConfiguration.vignetteStretch=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteCentreX",{get:function(){return this.imageProcessingConfiguration.vignetteCentreX},set:function(e){this.imageProcessingConfiguration.vignetteCentreX=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteCentreY",{get:function(){return this.imageProcessingConfiguration.vignetteCentreY},set:function(e){this.imageProcessingConfiguration.vignetteCentreY=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteWeight",{get:function(){return this.imageProcessingConfiguration.vignetteWeight},set:function(e){this.imageProcessingConfiguration.vignetteWeight=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteColor",{get:function(){return this.imageProcessingConfiguration.vignetteColor},set:function(e){this.imageProcessingConfiguration.vignetteColor=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteCameraFov",{get:function(){return this.imageProcessingConfiguration.vignetteCameraFov},set:function(e){this.imageProcessingConfiguration.vignetteCameraFov=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteBlendMode",{get:function(){return this.imageProcessingConfiguration.vignetteBlendMode},set:function(e){this.imageProcessingConfiguration.vignetteBlendMode=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteEnabled",{get:function(){return this.imageProcessingConfiguration.vignetteEnabled},set:function(e){this.imageProcessingConfiguration.vignetteEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fromLinearSpace",{get:function(){return this._fromLinearSpace},set:function(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"ImageProcessingPostProcess"},t.prototype._updateParameters=function(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);var e="";for(var t in this._defines)this._defines[t]&&(e+="#define "+t+";\r\n");var i=["textureSampler"],n=["scale"];Yi.a&&(Yi.a.PrepareSamplers(i,this._defines),Yi.a.PrepareUniforms(n,this._defines)),this.updateEffect(e,n,i)},t.prototype.dispose=function(t){e.prototype.dispose.call(this,t),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)},Object(h.c)([Object(N.c)()],t.prototype,"_fromLinearSpace",void 0),t}(ui),$i=i(15),en=i(4);Ae.a._GroundMeshParser=function(e,t){return tn.Parse(e,t)};var tn=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.generateOctree=!1,n}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"GroundMesh"},Object.defineProperty(t.prototype,"subdivisions",{get:function(){return Math.min(this._subdivisionsX,this._subdivisionsY)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subdivisionsX",{get:function(){return this._subdivisionsX},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subdivisionsY",{get:function(){return this._subdivisionsY},enumerable:!0,configurable:!0}),t.prototype.optimize=function(e,t){void 0===t&&(t=32),this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)},t.prototype.getHeightAtCoordinates=function(e,t){var i=this.getWorldMatrix(),n=a.c.Matrix[5];i.invertToRef(n);var r=a.c.Vector3[8];if(a.e.TransformCoordinatesFromFloatsToRef(e,0,t,n,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&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var o=this._getFacetAt(e,t),s=-(o.x*e+o.z*t+o.w)/o.y;return a.e.TransformCoordinatesFromFloatsToRef(0,s,0,i,r),r.y},t.prototype.getNormalAtCoordinates=function(e,t){var i=new a.e(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i},t.prototype.getNormalAtCoordinatesToRef=function(e,t,i){var n=this.getWorldMatrix(),r=a.c.Matrix[5];n.invertToRef(r);var o=a.c.Vector3[8];if(a.e.TransformCoordinatesFromFloatsToRef(e,0,t,r,o),e=o.x,t=o.z,e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var s=this._getFacetAt(e,t);return a.e.TransformNormalFromFloatsToRef(s.x,s.y,s.z,n,i),this},t.prototype.updateCoordinateHeights=function(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this},t.prototype._getFacetAt=function(e,t){var i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),n=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[n*this._subdivisionsX+i];return t<r.slope.x*e+r.slope.y?r.facet1:r.facet2},t.prototype._initHeightQuads=function(){var e=this._subdivisionsX,t=this._subdivisionsY;this._heightQuads=new Array;for(var i=0;i<t;i++)for(var n=0;n<e;n++){var r={slope:a.d.Zero(),facet1:new a.f(0,0,0,0),facet2:new a.f(0,0,0,0)};this._heightQuads[i*e+n]=r}return this},t.prototype._computeHeightQuads=function(){var e=this.getVerticesData(en.b.PositionKind);if(!e)return this;for(var t=a.c.Vector3[3],i=a.c.Vector3[2],n=a.c.Vector3[1],r=a.c.Vector3[0],o=a.c.Vector3[4],s=a.c.Vector3[5],c=a.c.Vector3[6],l=a.c.Vector3[7],u=a.c.Vector3[8],h=0,d=0,f=0,p=0,_=0,m=0,g=0,v=this._subdivisionsX,y=this._subdivisionsY,b=0;b<y;b++)for(var T=0;T<v;T++){h=3*T,d=b*(v+1)*3,f=(b+1)*(v+1)*3,t.x=e[d+h],t.y=e[d+h+1],t.z=e[d+h+2],i.x=e[d+h+3],i.y=e[d+h+4],i.z=e[d+h+5],n.x=e[f+h],n.y=e[f+h+1],n.z=e[f+h+2],r.x=e[f+h+3],r.y=e[f+h+4],r.z=e[f+h+5],p=(r.z-t.z)/(r.x-t.x),_=t.z-p*t.x,i.subtractToRef(t,o),n.subtractToRef(t,s),r.subtractToRef(t,c),a.e.CrossToRef(c,s,l),a.e.CrossToRef(o,c,u),l.normalize(),u.normalize(),m=-(l.x*t.x+l.y*t.y+l.z*t.z),g=-(u.x*i.x+u.y*i.y+u.z*i.z);var E=this._heightQuads[b*v+T];E.slope.copyFromFloats(p,_),E.facet1.copyFromFloats(l.x,l.y,l.z,m),E.facet2.copyFromFloats(u.x,u.y,u.z,g)}return this},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.subdivisionsX=this._subdivisionsX,t.subdivisionsY=this._subdivisionsY,t.minX=this._minX,t.maxX=this._maxX,t.minZ=this._minZ,t.maxZ=this._maxZ,t.width=this._width,t.height=this._height},t.Parse=function(e,i){var n=new t(e.name,i);return n._subdivisionsX=e.subdivisionsX||1,n._subdivisionsY=e.subdivisionsY||1,n._minX=e.minX,n._maxX=e.maxX,n._minZ=e.minZ,n._maxZ=e.maxZ,n._width=e.width,n._height=e.height,n},t}(Ae.a);$i.a.CreateGround=function(e){var t,i,n=[],r=[],o=[],s=[],c=e.width||1,l=e.height||1,u=e.subdivisionsX||e.subdivisions||1,h=e.subdivisionsY||e.subdivisions||1;for(t=0;t<=h;t++)for(i=0;i<=u;i++){var d=new a.e(i*c/u-c/2,0,(h-t)*l/h-l/2),f=new a.e(0,1,0);r.push(d.x,d.y,d.z),o.push(f.x,f.y,f.z),s.push(i/u,1-t/h)}for(t=0;t<h;t++)for(i=0;i<u;i++)n.push(i+1+(t+1)*(u+1)),n.push(i+1+t*(u+1)),n.push(i+t*(u+1)),n.push(i+(t+1)*(u+1)),n.push(i+1+(t+1)*(u+1)),n.push(i+t*(u+1));var p=new $i.a;return p.indices=n,p.positions=r,p.normals=o,p.uvs=s,p},$i.a.CreateTiledGround=function(e){var t,i,n,r,o=void 0!==e.xmin&&null!==e.xmin?e.xmin:-1,s=void 0!==e.zmin&&null!==e.zmin?e.zmin:-1,c=void 0!==e.xmax&&null!==e.xmax?e.xmax:1,l=void 0!==e.zmax&&null!==e.zmax?e.zmax:1,u=e.subdivisions||{w:1,h:1},h=e.precision||{w:1,h:1},d=new Array,f=new Array,p=new Array,_=new Array;u.h=u.h<1?1:u.h,u.w=u.w<1?1:u.w,h.w=h.w<1?1:h.w,h.h=h.h<1?1:h.h;var m=(c-o)/u.w,g=(l-s)/u.h;function v(e,n,r,o){var s=f.length/3,c=h.w+1;for(t=0;t<h.h;t++)for(i=0;i<h.w;i++){var l=[s+i+t*c,s+(i+1)+t*c,s+(i+1)+(t+1)*c,s+i+(t+1)*c];d.push(l[1]),d.push(l[2]),d.push(l[3]),d.push(l[0]),d.push(l[1]),d.push(l[3])}var u=a.e.Zero(),m=new a.e(0,1,0);for(t=0;t<=h.h;t++)for(u.z=t*(o-n)/h.h+n,i=0;i<=h.w;i++)u.x=i*(r-e)/h.w+e,u.y=0,f.push(u.x,u.y,u.z),p.push(m.x,m.y,m.z),_.push(i/h.w,t/h.h)}for(n=0;n<u.h;n++)for(r=0;r<u.w;r++)v(o+r*m,s+n*g,o+(r+1)*m,s+(n+1)*g);var y=new $i.a;return y.indices=d,y.positions=f,y.normals=p,y.uvs=_,y},$i.a.CreateGroundFromHeightMap=function(e){var t,i,n=[],r=[],o=[],c=[],l=e.colorFilter||new s.a(.3,.59,.11),u=e.alphaFilter||0,h=!1;if(e.minHeight>e.maxHeight){h=!0;var d=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=d}for(t=0;t<=e.subdivisions;t++)for(i=0;i<=e.subdivisions;i++){var f=new a.e(i*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-t)*e.height/e.subdivisions-e.height/2),p=4*(((f.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(f.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth),_=e.buffer[p]/255,m=e.buffer[p+1]/255,g=e.buffer[p+2]/255,v=e.buffer[p+3]/255;h&&(_=1-_,m=1-m,g=1-g);var y=_*l.r+m*l.g+g*l.b;f.y=v>=u?e.minHeight+(e.maxHeight-e.minHeight)*y:e.minHeight-re.a,r.push(f.x,f.y,f.z),o.push(0,0,0),c.push(i/e.subdivisions,1-t/e.subdivisions)}for(t=0;t<e.subdivisions;t++)for(i=0;i<e.subdivisions;i++){var b=i+1+(t+1)*(e.subdivisions+1),T=i+1+t*(e.subdivisions+1),E=i+t*(e.subdivisions+1),x=i+(t+1)*(e.subdivisions+1),P=r[3*b+1]>=e.minHeight,A=r[3*T+1]>=e.minHeight,S=r[3*E+1]>=e.minHeight;P&&A&&S&&(n.push(b),n.push(T),n.push(E)),r[3*x+1]>=e.minHeight&&P&&S&&(n.push(x),n.push(b),n.push(E))}$i.a.ComputeNormals(r,n,o);var C=new $i.a;return C.indices=n,C.positions=r,C.normals=o,C.uvs=c,C},Ae.a.CreateGround=function(e,t,i,n,r,o){var a={width:t,height:i,subdivisions:n,updatable:o};return nn.CreateGround(e,a,r)},Ae.a.CreateTiledGround=function(e,t,i,n,r,o,a,s,c){var l={xmin:t,zmin:i,xmax:n,zmax:r,subdivisions:o,precision:a,updatable:c};return nn.CreateTiledGround(e,l,s)},Ae.a.CreateGroundFromHeightMap=function(e,t,i,n,r,o,a,s,c,l,u){var h={width:i,height:n,subdivisions:r,minHeight:o,maxHeight:a,updatable:c,onReady:l,alphaFilter:u};return nn.CreateGroundFromHeightMap(e,t,h,s)};var nn=function(){function e(){}return e.CreateGround=function(e,t,i){var n=new tn(e,i);return n._setReady(!1),n._subdivisionsX=t.subdivisionsX||t.subdivisions||1,n._subdivisionsY=t.subdivisionsY||t.subdivisions||1,n._width=t.width||1,n._height=t.height||1,n._maxX=n._width/2,n._maxZ=n._height/2,n._minX=-n._maxX,n._minZ=-n._maxZ,$i.a.CreateGround(t).applyToMesh(n,t.updatable),n._setReady(!0),n},e.CreateTiledGround=function(e,t,i){void 0===i&&(i=null);var n=new Ae.a(e,i);return $i.a.CreateTiledGround(t).applyToMesh(n,t.updatable),n},e.CreateGroundFromHeightMap=function(e,t,i,n){void 0===n&&(n=null);var r=i.width||10,o=i.height||10,a=i.subdivisions||1,c=i.minHeight||0,l=i.maxHeight||1,u=i.colorFilter||new s.a(.3,.59,.11),h=i.alphaFilter||0,d=i.updatable,f=i.onReady;n=n||R.a.LastCreatedScene;var p=new tn(e,n);p._subdivisionsX=a,p._subdivisionsY=a,p._width=r,p._height=o,p._maxX=p._width/2,p._maxZ=p._height/2,p._minX=-p._maxX,p._minZ=-p._maxZ,p._setReady(!1);return De.b.LoadImage(t,function(e){var t=e.width,i=e.height,s=Qi.a.CreateCanvas(t,i).getContext("2d");if(!s)throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");if(!n.isDisposed){s.drawImage(e,0,0);var _=s.getImageData(0,0,t,i).data;$i.a.CreateGroundFromHeightMap({width:r,height:o,subdivisions:a,minHeight:c,maxHeight:l,colorFilter:u,buffer:_,bufferWidth:t,bufferHeight:i,alphaFilter:h}).applyToMesh(p,d),f&&f(p),p._setReady(!0)}},function(){},n.offlineProvider),p},e}();$i.a.CreateTorus=function(e){for(var t=[],i=[],n=[],r=[],o=e.diameter||1,s=e.thickness||.5,c=e.tessellation||16,l=0===e.sideOrientation?0:e.sideOrientation||$i.a.DEFAULTSIDE,u=c+1,h=0;h<=c;h++)for(var d=h/c,f=h*Math.PI*2/c-Math.PI/2,p=a.a.Translation(o/2,0,0).multiply(a.a.RotationY(f)),_=0;_<=c;_++){var m=1-_/c,g=_*Math.PI*2/c+Math.PI,v=Math.cos(g),y=Math.sin(g),b=new a.e(v,y,0),T=b.scale(s/2),E=new a.d(d,m);T=a.e.TransformCoordinates(T,p),b=a.e.TransformNormal(b,p),i.push(T.x,T.y,T.z),n.push(b.x,b.y,b.z),r.push(E.x,E.y);var x=(h+1)%u,P=(_+1)%u;t.push(h*u+_),t.push(h*u+P),t.push(x*u+_),t.push(h*u+P),t.push(x*u+P),t.push(x*u+_)}$i.a._ComputeSides(l,i,t,n,r,e.frontUVs,e.backUVs);var A=new $i.a;return A.indices=t,A.positions=i,A.normals=n,A.uvs=r,A},Ae.a.CreateTorus=function(e,t,i,n,r,o,a){var s={diameter:t,thickness:i,tessellation:n,sideOrientation:a,updatable:o};return on.CreateTorus(e,s,r)};var rn,on=function(){function e(){}return e.CreateTorus=function(e,t,i){var n=new Ae.a(e,i);return t.sideOrientation=Ae.a._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,$i.a.CreateTorus(t).applyToMesh(n,t.updatable),n},e}(),an=i(59),sn=function(){function e(){}return e.GetDefaults=function(){var t=new e;return t.canvasOptions={antialias:!0,depth:!0,stencil:!1,alpha:!0,multiview:!1,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t},e}(),cn=function(){function e(e,t){var i=this;if(void 0===t&&(t=sn.GetDefaults()),this._options=t,this._canvas=null,this.xrLayer=null,this._engine=e.scene.getEngine(),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{var n=document.createElement("canvas");n.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(n)}e.onXRSessionInit.add(function(){i._addCanvas()}),e.onXRSessionEnded.add(function(){i._removeCanvas()})}return e.prototype.dispose=function(){this._removeCanvas(),this._setManagedOutputCanvas(null)},e.prototype.initializeXRLayerAsync=function(e){var t=this,i=function(){return new XRWebGLLayer(e,t.canvasContext,t._options.canvasOptions)};return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(function(){return t.xrLayer=i(),t.xrLayer}):(this.xrLayer=i(),Promise.resolve(this.xrLayer))},e.prototype._addCanvas=function(){this._canvas&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas)},e.prototype._removeCanvas=function(){this._canvas&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas)},e.prototype._setManagedOutputCanvas=function(e){this._removeCanvas(),e?(this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)},e}(),ln=function(){function e(e){this.scene=e,this._sessionEnded=!1,this.baseLayer=null,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new o.c,this.onXRReferenceSpaceChanged=new o.c,this.onXRSessionEnded=new o.c,this.onXRSessionInit=new o.c}return Object.defineProperty(e.prototype,"referenceSpace",{get:function(){return this._referenceSpace},set:function(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this._sessionEnded||this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear()},e.prototype.exitXRAsync=function(){return this.session&&!this._sessionEnded?this.session.end().catch(function(e){m.a.Warn("could not end XR session. It has ended already.")}):Promise.resolve()},e.prototype.getRenderTargetTextureForEye=function(e){return this._rttProvider.getRenderTargetForEye(e)},e.prototype.getWebXRRenderTarget=function(e){var t=this.scene.getEngine();return this._xrNavigator.xr.native?this._xrNavigator.xr.getWebXRRenderTarget(t):((e=e||{}).canvasElement=t.getRenderingCanvas()||void 0,new cn(this,e))},e.prototype.initializeAsync=function(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")},e.prototype.initializeSessionAsync=function(e,t){var i=this;return void 0===e&&(e="immersive-vr"),void 0===t&&(t={}),this._xrNavigator.xr.requestSession(e,t).then(function(e){return i.session=e,i.onXRSessionInit.notifyObservers(e),i._sessionEnded=!1,i.session.addEventListener("end",function(){var e=i.scene.getEngine();i._sessionEnded=!0,i._rttProvider=null,e.framebufferDimensionsObject=null,e.restoreDefaultFramebuffer(),e.customAnimationFrameRequester=null,i.onXRSessionEnded.notifyObservers(null),e._renderLoop()},{once:!0}),i.session})},e.prototype.isSessionSupportedAsync=function(t){return e.IsSessionSupportedAsync(t)},e.prototype.resetReferenceSpace=function(){this.referenceSpace=this.baseReferenceSpace},e.prototype.runXRRenderLoop=function(){var e=this,t=this.scene.getEngine();if(t.customAnimationFrameRequester={requestAnimationFrame:this.session.requestAnimationFrame.bind(this.session),renderFunction:function(i,n){e._sessionEnded||(e.currentFrame=n,e.currentTimestamp=i,n&&(e.onXRFrameObservable.notifyObservers(n),t.framebufferDimensionsObject=e.baseLayer,t._renderLoop(),t.framebufferDimensionsObject=null))}},this._xrNavigator.xr.native)this._rttProvider=this._xrNavigator.xr.getNativeRenderTargetProvider(this.session,this._createRenderTargetTexture.bind(this));else{var i=this._createRenderTargetTexture(this.baseLayer.framebufferWidth,this.baseLayer.framebufferHeight,this.baseLayer.framebuffer);this._rttProvider={getRenderTargetForEye:function(){return i}},t.framebufferDimensionsObject=this.baseLayer}window.cancelAnimationFrame&&window.cancelAnimationFrame(t._frameHandler),t._renderLoop()},e.prototype.setReferenceSpaceTypeAsync=function(e){var t=this;return void 0===e&&(e="local-floor"),this.session.requestReferenceSpace(e).then(function(e){return e},function(e){return m.a.Error("XR.requestReferenceSpace failed for the following reason: "),m.a.Error(e),m.a.Log('Defaulting to universally-supported "viewer" reference space type.'),t.session.requestReferenceSpace("viewer").then(function(e){var i=new XRRigidTransform({x:0,y:-t.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(i)},function(e){throw m.a.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'})}).then(function(e){return t.referenceSpace=t.baseReferenceSpace=e,t.session.requestReferenceSpace("viewer").then(function(e){t.viewerReferenceSpace=e}),t.referenceSpace})},e.prototype.updateRenderStateAsync=function(e){return e.baseLayer&&(this.baseLayer=e.baseLayer),this.session.updateRenderState(e)},e.IsSessionSupportedAsync=function(e){if(!navigator.xr)return Promise.resolve(!1);var t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then(function(e){var t=void 0===e||e;return Promise.resolve(t)}).catch(function(e){return m.a.Warn(e),Promise.resolve(!1)}):Promise.resolve(!1)},e.prototype._createRenderTargetTexture=function(e,t,i){void 0===i&&(i=null);var n=new tt.a(this.scene.getEngine(),tt.b.Unknown,!0);n.width=e,n.height=t,n._framebuffer=i;var r=new Fi("XR renderTargetTexture",{width:e,height:t},this.scene,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,!0);return r._texture=n,r},e}();!function(e){e[e.ENTERING_XR=0]="ENTERING_XR",e[e.EXITING_XR=1]="EXITING_XR",e[e.IN_XR=2]="IN_XR",e[e.NOT_IN_XR=3]="NOT_IN_XR"}(rn||(rn={}));var un,hn=function(){function e(t,i){if(void 0===i&&(i=null),this.scene=t,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=e._idCounter++,i)this._gazeTracker=i.clone("gazeTracker");else{this._gazeTracker=Ae.a.CreateTorus("gazeTracker",.0035,.0025,20,t,!1),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;var n=new Ki.a("targetMat",t);n.specularColor=s.a.Black(),n.emissiveColor=new s.a(.7,.7,.7),n.backFaceCulling=!1,this._gazeTracker.material=n}}return e.prototype._getForwardRay=function(e){return new Ht.a(a.e.Zero(),new a.e(0,0,e))},e.prototype._selectionPointerDown=function(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})},e.prototype._selectionPointerUp=function(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1},e.prototype._activatePointer=function(){this._activePointer=!0},e.prototype._deactivatePointer=function(){this._activePointer=!1},e.prototype._updatePointerDistance=function(e){void 0===e&&(e=100)},e.prototype.dispose=function(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()},e._idCounter=0,e}(),dn=function(e){function t(t,i,n){var r=e.call(this,i,n)||this;r.webVRController=t,r._laserPointer=Ae.a.CreateCylinder("laserPointer",1,.004,2e-4,20,1,i,!1);var o=new Ki.a("laserPointerMat",i);if(o.emissiveColor=new s.a(.7,.7,.7),o.alpha=.6,r._laserPointer.material=o,r._laserPointer.rotation.x=Math.PI/2,r._laserPointer.position.z=-.5,r._laserPointer.isVisible=!1,r._laserPointer.isPickable=!1,!t.mesh){var a=new Ae.a("preloadControllerMesh",i),c=new Ae.a(qt.POINTING_POSE,i);c.rotation.x=-.7,a.addChild(c),t.attachToMesh(a)}return r._setLaserPointerParent(t.mesh),r._meshAttachedObserver=t._meshAttachedObservable.add(function(e){r._setLaserPointerParent(e)}),r}return Object(h.d)(t,e),t.prototype._getForwardRay=function(e){return this.webVRController.getForwardRay(e)},t.prototype._activatePointer=function(){e.prototype._activatePointer.call(this),this._laserPointer.isVisible=!0},t.prototype._deactivatePointer=function(){e.prototype._deactivatePointer.call(this),this._laserPointer.isVisible=!1},t.prototype._setLaserPointerColor=function(e){this._laserPointer.material.emissiveColor=e},t.prototype._setLaserPointerLightingDisabled=function(e){this._laserPointer.material.disableLighting=e},t.prototype._setLaserPointerParent=function(e){var t=function(e){e.isPickable=!1,e.getChildMeshes().forEach(function(e){t(e)})};t(e);var i=e.getChildren(void 0,!1),n=e;this.webVRController._pointingPoseNode=null;for(var r=0;r<i.length;r++)if(i[r].name&&i[r].name.indexOf(qt.POINTING_POSE)>=0){n=i[r],this.webVRController._pointingPoseNode=n;break}this._laserPointer.parent=n},t.prototype._updatePointerDistance=function(e){void 0===e&&(e=100),this._laserPointer.scaling.y=e,this._laserPointer.position.z=-e/2},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._laserPointer.dispose(),this._meshAttachedObserver&&this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver)},t}(hn),fn=function(e){function t(t,i){var n=e.call(this,i)||this;return n.getCamera=t,n}return Object(h.d)(t,e),t.prototype._getForwardRay=function(e){var t=this.getCamera();return t?t.getForwardRay(e):new Ht.a(a.e.Zero(),a.e.Forward())},t}(hn),pn=function(){},_n=function(){function e(t,i){var n=this;if(void 0===i&&(i={}),this.webVROptions=i,this._webVRsupported=!1,this._webVRready=!1,this._webVRrequesting=!1,this._webVRpresenting=!1,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new o.c,this.onAfterEnteringVRObservable=new o.c,this.onExitingVRObservable=new o.c,this.onControllerMeshLoadedObservable=new o.c,this._useCustomVRButton=!1,this._teleportationRequested=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=e.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new a.e(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new a.e(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._leftController=null,this._rightController=null,this._gazeColor=new s.a(.7,.7,.7),this._laserColor=new s.a(.7,.7,.7),this._pickedLaserColor=new s.a(.2,.2,1),this._pickedGazeColor=new s.a(0,0,1),this.onNewMeshSelected=new o.c,this.onMeshSelectedWithController=new o.c,this.onNewMeshPicked=new o.c,this.onBeforeCameraTeleport=new o.c,this.onAfterCameraTeleport=new o.c,this.onSelectedMeshUnselected=new o.c,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._interactionsRequested=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=function(){n.moveButtonToBottomRight(),n._fullscreenVRpresenting&&n._webVRready&&n.exitVR()},this._onFullscreenChange=function(){var e=document;void 0!==e.fullscreen?n._fullscreenVRpresenting=document.fullscreen:void 0!==e.mozFullScreen?n._fullscreenVRpresenting=e.mozFullScreen:void 0!==e.webkitIsFullScreen?n._fullscreenVRpresenting=e.webkitIsFullScreen:void 0!==e.msIsFullScreen?n._fullscreenVRpresenting=e.msIsFullScreen:void 0!==document.msFullscreenElement&&(n._fullscreenVRpresenting=document.msFullscreenElement),!n._fullscreenVRpresenting&&n._inputElement&&(n.exitVR(),!n._useCustomVRButton&&n._btnVR&&(n._btnVR.style.top=n._inputElement.offsetTop+n._inputElement.offsetHeight-70+"px",n._btnVR.style.left=n._inputElement.offsetLeft+n._inputElement.offsetWidth-100+"px",n.updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this.beforeRender=function(){n._leftController&&n._leftController._activePointer&&n._castRayAndSelectObject(n._leftController),n._rightController&&n._rightController._activePointer&&n._castRayAndSelectObject(n._rightController),n._noControllerIsActive&&(n._scene.getEngine().isPointerLock||n.enableGazeEvenWhenNoPointerLock)?n._castRayAndSelectObject(n._cameraGazer):n._cameraGazer._gazeTracker.isVisible=!1},this._onNewGamepadConnected=function(e){if(e.type!==lt.POSE_ENABLED)e.leftStick&&e.onleftstickchanged(function(e){n._teleportationInitialized&&n.teleportationEnabled&&(!n._leftController&&!n._rightController||n._leftController&&!n._leftController._activePointer&&n._rightController&&!n._rightController._activePointer)&&(n._checkTeleportWithRay(e,n._cameraGazer),n._checkTeleportBackwards(e,n._cameraGazer))}),e.rightStick&&e.onrightstickchanged(function(e){n._teleportationInitialized&&n._checkRotate(e,n._cameraGazer)}),e.type===lt.XBOX&&(e.onbuttondown(function(e){n._interactionsEnabled&&e===Yt.A&&n._cameraGazer._selectionPointerDown()}),e.onbuttonup(function(e){n._interactionsEnabled&&e===Yt.A&&n._cameraGazer._selectionPointerUp()}));else{var t=e,i=new dn(t,n._scene,n._cameraGazer._gazeTracker);"right"===t.hand||n._leftController&&n._leftController.webVRController!=t?n._rightController=i:n._leftController=i,n._tryEnableInteractionOnController(i)}},this._tryEnableInteractionOnController=function(e){n._interactionsRequested&&!e._interactionsEnabled&&n._enableInteractionOnController(e),n._teleportationRequested&&!e._teleportationEnabled&&n._enableTeleportationOnController(e)},this._onNewGamepadDisconnected=function(e){e instanceof Hi&&("left"===e.hand&&null!=n._leftController&&(n._leftController.dispose(),n._leftController=null),"right"===e.hand&&null!=n._rightController&&(n._rightController.dispose(),n._rightController=null))},this._workingVector=a.e.Zero(),this._workingQuaternion=a.b.Identity(),this._workingMatrix=a.a.Identity(),this._scene=t,this._inputElement=t.getEngine().getInputElement(),"getVRDisplays"in navigator||(i.useXR=!0),void 0===i.createFallbackVRDeviceOrientationFreeCamera&&(i.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===i.createDeviceOrientationCamera&&(i.createDeviceOrientationCamera=!0),void 0===i.laserToggle&&(i.laserToggle=!0),void 0===i.defaultHeight&&(i.defaultHeight=1.7),i.useCustomVRButton&&(this._useCustomVRButton=!0,i.customVRButton&&(this._btnVR=i.customVRButton)),i.rayLength&&(this._rayLength=i.rayLength),this._defaultHeight=i.defaultHeight,i.positionScale&&(this._rayLength*=i.positionScale,this._defaultHeight*=i.positionScale),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new a.e(0,this._defaultHeight,0),i.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new Ut("deviceOrientationVRHelper",this._position.clone(),t),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof Lt&&this._scene.activeCamera.rotation)){var r=this._scene.activeCamera;r.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(r.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(a.b.RotationYawPitchRoll(r.rotation.y,r.rotation.x,r.rotation.z)),this._deviceOrientationCamera.rotation=r.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl(this._inputElement)}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?ln.IsSessionSupportedAsync("immersive-vr").then(function(e){e?(m.a.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),t.createDefaultXRExperienceAsync({floorMeshes:i.floorMeshes||[]}).then(function(e){n.xr=e,n.xrTestDone=!0,n._cameraGazer=new fn(function(){return n.xr.baseExperience.camera},t),n.xr.baseExperience.onStateChangedObservable.add(function(e){switch(e){case rn.ENTERING_XR:n.onEnteringVRObservable.notifyObservers(n),n._interactionsEnabled||n.xr.pointerSelection.detach(),n.xr.pointerSelection.displayLaserPointer=n._displayLaserPointer;break;case rn.EXITING_XR:n.onExitingVRObservable.notifyObservers(n),n._scene.getEngine().resize();break;case rn.IN_XR:n._hasEnteredVR=!0;break;case rn.NOT_IN_XR:n._hasEnteredVR=!1}})})):n.completeVRInit(t,i)}):this.completeVRInit(t,i)}return Object.defineProperty(e.prototype,"onEnteringVR",{get:function(){return this.onEnteringVRObservable},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onExitingVR",{get:function(){return this.onExitingVRObservable},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onControllerMeshLoaded",{get:function(){return this.onControllerMeshLoadedObservable},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"teleportationTarget",{get:function(){return this._teleportationTarget},set:function(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"gazeTrackerMesh",{get:function(){return this._cameraGazer._gazeTracker},set:function(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._leftController&&this._leftController._gazeTracker&&this._leftController._gazeTracker.dispose(),this._rightController&&this._rightController._gazeTracker&&this._rightController._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker",this._leftController&&(this._leftController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")),this._rightController&&(this._rightController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"leftControllerGazeTrackerMesh",{get:function(){return this._leftController?this._leftController._gazeTracker:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rightControllerGazeTrackerMesh",{get:function(){return this._rightController?this._rightController._gazeTracker:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"displayGaze",{get:function(){return this._displayGaze},set:function(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1,this._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"displayLaserPointer",{get:function(){return this._displayLaserPointer},set:function(e){this._displayLaserPointer=e,e?(this._rightController&&this._rightController._activatePointer(),this._leftController&&this._leftController._activatePointer()):(this._rightController&&(this._rightController._deactivatePointer(),this._rightController._gazeTracker.isVisible=!1),this._leftController&&(this._leftController._deactivatePointer(),this._leftController._gazeTracker.isVisible=!1))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"deviceOrientationCamera",{get:function(){return this._deviceOrientationCamera},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentVRCamera",{get:function(){return this._webVRready?this._webVRCamera:this._scene.activeCamera},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"webVRCamera",{get:function(){return this._webVRCamera},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"vrDeviceOrientationCamera",{get:function(){return this._vrDeviceOrientationCamera},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"vrButton",{get:function(){return this._btnVR},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_teleportationRequestInitiated",{get:function(){return this._cameraGazer._teleportationRequestInitiated||null!==this._leftController&&this._leftController._teleportationRequestInitiated||null!==this._rightController&&this._rightController._teleportationRequestInitiated},enumerable:!0,configurable:!0}),e.prototype.completeVRInit=function(e,t){var i=this;if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(t.useMultiview&&(t.vrDeviceOrientationCameraMetrics||(t.vrDeviceOrientationCameraMetrics=Oi.GetDefault()),t.vrDeviceOrientationCameraMetrics.multiviewEnabled=!0),this._vrDeviceOrientationCamera=new Gi("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._webVRCamera=new Xi("WebVRHelper",this._position,this._scene,t),this._webVRCamera.useStandingMatrix(),this._cameraGazer=new fn(function(){return i.currentVRCamera},e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";var n=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";n+=".babylonVRicon.vrdisplaypresenting { display: none; }";var r=document.createElement("style");r.appendChild(document.createTextNode(n)),document.getElementsByTagName("head")[0].appendChild(r),this.moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",function(){i.isInVRMode?i._scene.getEngine().disableVR():i.enterVR()});var o=this._scene.getEngine().getHostWindow();o&&(o.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("mozfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("msfullscreenchange",this._onFullscreenChange,!1),document.onmsfullscreenchange=this._onFullscreenChange,t.createFallbackVRDeviceOrientationFreeCamera?this.displayVRButton():this._scene.getEngine().onVRDisplayChangedObservable.add(function(e){e.vrDisplay&&i.displayVRButton()}),this._onKeyDown=function(e){27===e.keyCode&&i.isInVRMode&&i.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add(function(){i._hasEnteredVR&&i.exitVROnDoubleTap&&(i.exitVR(),i._fullscreenVRpresenting&&i._scene.getEngine().exitFullscreen())},Ve.a.POINTERDOUBLETAP,!1),this._onVRDisplayChanged=function(e){return i.onVRDisplayChanged(e)},this._onVrDisplayPresentChange=function(){return i.onVrDisplayPresentChange()},this._onVRRequestPresentStart=function(){i._webVRrequesting=!0,i.updateButtonVisibility()},this._onVRRequestPresentComplete=function(){i._webVRrequesting=!1,i.updateButtonVisibility()},e.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged),e.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart),e.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete),o.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),e.onDisposeObservable.add(function(){i.dispose()}),this._webVRCamera.onControllerMeshLoadedObservable.add(function(e){return i._onDefaultMeshLoaded(e)}),this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected),this.updateButtonVisibility(),this._circleEase=new de,this._circleEase.setEasingMode(he.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(function(t){i._interactionsEnabled&&e.activeCamera===i.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===Ve.a.POINTERDOWN?i._cameraGazer._selectionPointerDown():t.type===Ve.a.POINTERUP&&i._cameraGazer._selectionPointerUp())}),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))},e.prototype._onDefaultMeshLoaded=function(e){this._leftController&&this._leftController.webVRController==e&&e.mesh&&this._leftController._setLaserPointerParent(e.mesh),this._rightController&&this._rightController.webVRController==e&&e.mesh&&this._rightController._setLaserPointerParent(e.mesh);try{this.onControllerMeshLoadedObservable.notifyObservers(e)}catch(e){m.a.Warn("Error in your custom logic onControllerMeshLoaded: "+e)}},Object.defineProperty(e.prototype,"isInVRMode",{get:function(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===rn.IN_XR||this._webVRpresenting||this._fullscreenVRpresenting},enumerable:!0,configurable:!0}),e.prototype.onVrDisplayPresentChange=function(){var e=this._scene.getEngine().getVRDevice();if(e){var t=this._webVRpresenting;this._webVRpresenting=e.isPresenting,t&&!this._webVRpresenting&&this.exitVR()}else m.a.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?");this.updateButtonVisibility()},e.prototype.onVRDisplayChanged=function(e){this._webVRsupported=e.vrSupported,this._webVRready=!!e.vrDisplay,this._webVRpresenting=e.vrDisplay&&e.vrDisplay.isPresenting,this.updateButtonVisibility()},e.prototype.moveButtonToBottomRight=function(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){var e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}},e.prototype.displayVRButton=function(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)},e.prototype.updateButtonVisibility=function(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode?this._btnVR.className+=" vrdisplaypresenting":(this._webVRready&&(this._btnVR.className+=" vrdisplayready"),this._webVRsupported&&(this._btnVR.className+=" vrdisplaysupported"),this._webVRrequesting&&(this._btnVR.className+=" vrdisplayrequesting")))},e.prototype.enterVR=function(){var e=this;if(this.xr)this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);else{if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){m.a.Warn("Error in your custom logic onEnteringVR: "+e)}if(this._scene.activeCamera){if(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=a.b.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this.webVRCamera){var t=this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y,i=a.b.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y-t,n=this.webVRCamera.rotationQuaternion.toEulerAngles().y;this.webVRCamera.rotationQuaternion=a.b.FromEulerAngles(0,n+i,0)}this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)}this._webVRrequesting||(this._webVRready?this._webVRpresenting||(this._scene.getEngine().onVRRequestPresentComplete.addOnce(function(t){e.onAfterEnteringVRObservable.notifyObservers({success:t})}),this._webVRCamera.position=this._position,this._scene.activeCamera=this._webVRCamera):this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this.updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(function(){e.onAfterEnteringVRObservable.notifyObservers({success:!0})})),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(this._inputElement),this._interactionsEnabled&&this._scene.registerBeforeRender(this.beforeRender),this._displayLaserPointer&&[this._leftController,this._rightController].forEach(function(e){e&&e._activatePointer()}),this._hasEnteredVR=!0)}},e.prototype.exitVR=function(){if(this.xr)this.xr.baseExperience.exitXRAsync();else if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){m.a.Warn("Error in your custom logic onExitingVR: "+e)}this._webVRpresenting&&this._scene.getEngine().disableVR(),this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(this._inputElement),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this.updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this.beforeRender),this._cameraGazer._gazeTracker.isVisible=!1,this._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1)),this._scene.getEngine().resize(),[this._leftController,this._rightController].forEach(function(e){e&&e._deactivatePointer()}),this._hasEnteredVR=!1;var e=this._scene.getEngine();e._onVrDisplayPresentChange&&e._onVrDisplayPresentChange()}},Object.defineProperty(e.prototype,"position",{get:function(){return this._position},set:function(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)},enumerable:!0,configurable:!0}),e.prototype.enableInteractions=function(){var e=this;if(!this._interactionsEnabled){if(this._interactionsRequested=!0,this.xr)return void(this.xr.baseExperience.state===rn.IN_XR&&this.xr.pointerSelection.attach());this._leftController&&this._enableInteractionOnController(this._leftController),this._rightController&&this._enableInteractionOnController(this._rightController),this.raySelectionPredicate=function(t){return t.isVisible&&(t.isPickable||t.name===e._floorMeshName)},this.meshSelectionPredicate=function(){return!0},this._raySelectionPredicate=function(t){return!!(e._isTeleportationFloor(t)||-1===t.name.indexOf("gazeTracker")&&-1===t.name.indexOf("teleportationTarget")&&-1===t.name.indexOf("torusTeleportation"))&&e.raySelectionPredicate(t)},this._interactionsEnabled=!0}},Object.defineProperty(e.prototype,"_noControllerIsActive",{get:function(){return!(this._leftController&&this._leftController._activePointer||this._rightController&&this._rightController._activePointer)},enumerable:!0,configurable:!0}),e.prototype._isTeleportationFloor=function(e){for(var t=0;t<this._floorMeshesCollection.length;t++)if(this._floorMeshesCollection[t].id===e.id)return!0;return!(!this._floorMeshName||e.name!==this._floorMeshName)},e.prototype.addFloorMesh=function(e){this._floorMeshesCollection&&(this._floorMeshesCollection.indexOf(e)>-1||this._floorMeshesCollection.push(e))},e.prototype.removeFloorMesh=function(e){if(this._floorMeshesCollection){var t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}},e.prototype.enableTeleportation=function(e){var t=this;if(void 0===e&&(e={}),!this._teleportationInitialized){if(this._teleportationRequested=!0,this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){var i=e.floorMeshes||[];if(!i.length){var n=this._scene.getMeshByName(e.floorMeshName);n&&i.push(n)}if(this.xr)return i.forEach(function(e){t.xr.teleportation.addFloorMesh(e)}),void(this.xr.teleportation.attached||this.xr.teleportation.attach());if(!this.xrTestDone){var r=function(){t.xrTestDone&&(t._scene.unregisterBeforeRender(r),t.xr?t.xr.teleportation.attached||t.xr.teleportation.attach():t.enableTeleportation(e))};return void this._scene.registerBeforeRender(r)}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction),null!=this._leftController&&this._enableTeleportationOnController(this._leftController),null!=this._rightController&&this._enableTeleportationOnController(this._rightController);var o=new Yi.a;o.vignetteColor=new s.b(0,0,0,0),o.vignetteEnabled=!0,this._postProcessMove=new Ji("postProcessMove",1,this._webVRCamera,void 0,void 0,void 0,void 0,o),this._webVRCamera.detachPostProcess(this._postProcessMove),this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&(this._createTeleportationCircles(),this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor))}},e.prototype._enableInteractionOnController=function(e){var t=this;e.webVRController.mesh&&(e._interactionsEnabled=!0,this.isInVRMode&&this._displayLaserPointer&&e._activatePointer(),this.webVROptions.laserToggle&&e.webVRController.onMainButtonStateChangedObservable.add(function(i){t._displayLaserPointer&&1===i.value&&(e._activePointer?e._deactivatePointer():e._activatePointer(),t.displayGaze&&(e._gazeTracker.isVisible=e._activePointer))}),e.webVRController.onTriggerStateChangedObservable.add(function(i){var n=e;t._noControllerIsActive&&(n=t._cameraGazer),n._pointerDownOnMeshAsked?i.value<t._padSensibilityDown&&n._selectionPointerUp():i.value>t._padSensibilityUp&&n._selectionPointerDown()}))},e.prototype._checkTeleportWithRay=function(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)<this._padSensibilityDown&&(this._teleportActive&&this.teleportCamera(this._haloCenter),t._teleportationRequestInitiated=!1):e.y<-this._padSensibilityUp&&t._dpadPressed&&(t._activatePointer(),t._teleportationRequestInitiated=!0))},e.prototype._checkRotate=function(e,t){t._teleportationRequestInitiated||(t._rotationLeftAsked?e.x>-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.x<this._padSensibilityDown&&(t._rotationRightAsked=!1):e.x>this._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))},e.prototype._checkTeleportBackwards=function(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;var i=a.b.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),n=this.currentVRCamera.position;this.currentVRCamera.devicePosition&&this.currentVRCamera.deviceRotationQuaternion&&(i=this.currentVRCamera.deviceRotationQuaternion,n=this.currentVRCamera.devicePosition),i.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,a.b.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),a.e.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);var r=new Ht.a(n,this._workingVector),o=this._scene.pickWithRay(r,this._raySelectionPredicate);o&&o.pickedPoint&&o.pickedMesh&&this._isTeleportationFloor(o.pickedMesh)&&o.distance<5&&this.teleportCamera(o.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1},e.prototype._enableTeleportationOnController=function(e){var t=this;e.webVRController.mesh&&(e._interactionsEnabled||this._enableInteractionOnController(e),e._interactionsEnabled=!0,e._teleportationEnabled=!0,e.webVRController.controllerType===Gt.VIVE&&(e._dpadPressed=!1,e.webVRController.onPadStateChangedObservable.add(function(t){e._dpadPressed=t.pressed,e._dpadPressed||(e._rotationLeftAsked=!1,e._rotationRightAsked=!1,e._teleportationBackRequestInitiated=!1)})),e.webVRController.onPadValuesChangedObservable.add(function(i){t.teleportationEnabled&&(t._checkTeleportBackwards(i,e),t._checkTeleportWithRay(i,e)),t._checkRotate(i,e)}))},e.prototype._createTeleportationCircles=function(){this._teleportationTarget=Ae.a.CreateGround("teleportationTarget",2,2,2,this._scene),this._teleportationTarget.isPickable=!1;var e=new qi("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;var t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();var i=new Ki.a("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;var n=Ae.a.CreateTorus("torusTeleportation",.75,.1,25,this._scene,!1);n.isPickable=!1,n.parent=this._teleportationTarget;var r=new k("animationInnerCircle","position.y",30,k.ANIMATIONTYPE_FLOAT,k.ANIMATIONLOOPMODE_CYCLE),o=[];o.push({frame:0,value:0}),o.push({frame:30,value:.4}),o.push({frame:60,value:0}),r.setKeys(o);var a=new Ee;a.setEasingMode(he.EASINGMODE_EASEINOUT),r.setEasingFunction(a),n.animations=[],n.animations.push(r),this._scene.beginAnimation(n,0,60,!0),this._hideTeleportationTarget()},e.prototype._displayTeleportationTarget=function(){this._teleportActive=!0,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!0,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!0))},e.prototype._hideTeleportationTarget=function(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))},e.prototype._rotateCamera=function(e){var t=this;if(this.currentVRCamera instanceof Nt){e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];var i=a.b.FromRotationMatrix(a.a.RotationY(Math.PI/4*this._rotationAngle)),n=new k("animationRotation","rotationQuaternion",90,k.ANIMATIONTYPE_QUATERNION,k.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),r.push({frame:6,value:i}),n.setKeys(r),n.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(n),this._postProcessMove.animations=[];var o=new k("animationPP","vignetteWeight",90,k.ANIMATIONTYPE_FLOAT,k.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:0}),s.push({frame:3,value:4}),s.push({frame:6,value:0}),o.setKeys(s),o.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(o);var c=new k("animationPP2","vignetteStretch",90,k.ANIMATIONTYPE_FLOAT,k.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:3,value:10}),l.push({frame:6,value:0}),c.setKeys(l),c.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(c),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,6,!1,1,function(){t._webVRCamera.detachPostProcess(t._postProcessMove)}),this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}},e.prototype._moveTeleportationSelectorTo=function(e,t,i){if(e.pickedPoint){t._teleportationRequestInitiated&&(this._displayTeleportationTarget(),this._haloCenter.copyFrom(e.pickedPoint),this._teleportationTarget.position.copyFrom(e.pickedPoint));var n=this._convertNormalToDirectionOfRay(e.getNormal(!0,!1),i);if(n){var r=a.e.Cross(Z.a.Y,n),o=a.e.Cross(n,r);a.e.RotationFromAxisToRef(o,n,r,this._teleportationTarget.rotation)}this._teleportationTarget.position.y+=.1}},e.prototype.teleportCamera=function(t){var i=this;if(this.currentVRCamera instanceof Nt){this.webVRCamera.leftCamera?(this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition),this._workingVector.subtractInPlace(this.webVRCamera.position),t.subtractToRef(this._workingVector,this._workingVector)):this._workingVector.copyFrom(t),this.isInVRMode?this._workingVector.y+=this.webVRCamera.deviceDistanceToRoomGround()*this._webVRCamera.deviceScaleFactor:this._workingVector.y+=this._defaultHeight,this.onBeforeCameraTeleport.notifyObservers(this._workingVector);var n,r;if(this._teleportationMode==e.TELEPORTATIONMODE_CONSTANTSPEED){r=90;var o=a.e.Distance(this.currentVRCamera.position,this._workingVector);n=this._teleportationSpeed/o}else r=Math.round(90*this._teleportationTime/1e3),n=1;this.currentVRCamera.animations=[];var s=new k("animationCameraTeleportation","position",90,k.ANIMATIONTYPE_VECTOR3,k.ANIMATIONLOOPMODE_CONSTANT),c=[{frame:0,value:this.currentVRCamera.position},{frame:r,value:this._workingVector}];s.setKeys(c),s.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(s),this._postProcessMove.animations=[];var l=Math.round(r/2),u=new k("animationPP","vignetteWeight",90,k.ANIMATIONTYPE_FLOAT,k.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:l,value:8}),h.push({frame:r,value:0}),u.setKeys(h),this._postProcessMove.animations.push(u);var d=new k("animationPP2","vignetteStretch",90,k.ANIMATIONTYPE_FLOAT,k.ANIMATIONLOOPMODE_CONSTANT),f=[];f.push({frame:0,value:0}),f.push({frame:l,value:10}),f.push({frame:r,value:0}),d.setKeys(f),this._postProcessMove.animations.push(d),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,r,!1,n,function(){i._webVRCamera.detachPostProcess(i._postProcessMove)}),this._scene.beginAnimation(this.currentVRCamera,0,r,!1,n,function(){i.onAfterCameraTeleport.notifyObservers(i._workingVector)}),this._hideTeleportationTarget()}},e.prototype._convertNormalToDirectionOfRay=function(e,t){e&&(Math.acos(a.e.Dot(e,t.direction))<Math.PI/2&&e.scaleInPlace(-1));return e},e.prototype._castRayAndSelectObject=function(e){if(this.currentVRCamera instanceof Nt){var t=e._getForwardRay(this._rayLength),i=this._scene.pickWithRay(t,this._raySelectionPredicate);if(i&&(e._laserPointer&&(i.originMesh=e._laserPointer.parent),this._scene.simulatePointerMove(i,{pointerId:e._id})),e._currentHit=i,i&&i.pickedPoint){if(this._displayGaze){var n=1;e._gazeTracker.isVisible=!0,e._isActionableMesh&&(n=3),this.updateGazeTrackerScale&&(e._gazeTracker.scaling.x=i.distance*n,e._gazeTracker.scaling.y=i.distance*n,e._gazeTracker.scaling.z=i.distance*n);var r=this._convertNormalToDirectionOfRay(i.getNormal(),t);if(r){var o=a.e.Cross(Z.a.Y,r),s=a.e.Cross(r,o);a.e.RotationFromAxisToRef(s,r,o,e._gazeTracker.rotation)}e._gazeTracker.position.copyFrom(i.pickedPoint),e._gazeTracker.position.x<0?e._gazeTracker.position.x+=.002:e._gazeTracker.position.x-=.002,e._gazeTracker.position.y<0?e._gazeTracker.position.y+=.002:e._gazeTracker.position.y-=.002,e._gazeTracker.position.z<0?e._gazeTracker.position.z+=.002:e._gazeTracker.position.z-=.002}e._updatePointerDistance(i.distance)}else e._updatePointerDistance(),e._gazeTracker.isVisible=!1;if(i&&i.pickedMesh){if(this._teleportationInitialized&&this._isTeleportationFloor(i.pickedMesh)&&i.pickedPoint)return e._currentMeshSelected&&!this._isTeleportationFloor(e._currentMeshSelected)&&this._notifySelectedMeshUnselected(e._currentMeshSelected),e._currentMeshSelected=null,void(e._teleportationRequestInitiated&&this._moveTeleportationSelectorTo(i,e,t));if(i.pickedMesh!==e._currentMeshSelected)if(this.meshSelectionPredicate(i.pickedMesh)){this.onNewMeshPicked.notifyObservers(i),e._currentMeshSelected=i.pickedMesh,i.pickedMesh.isPickable&&i.pickedMesh.actionManager?(this.changeGazeColor(this._pickedGazeColor),this.changeLaserColor(this._pickedLaserColor),e._isActionableMesh=!0):(this.changeGazeColor(this._gazeColor),this.changeLaserColor(this._laserColor),e._isActionableMesh=!1);try{this.onNewMeshSelected.notifyObservers(i.pickedMesh);var c=e;c.webVRController&&this.onMeshSelectedWithController.notifyObservers({mesh:i.pickedMesh,controller:c.webVRController})}catch(e){m.a.Warn("Error while raising onNewMeshSelected or onMeshSelectedWithController: "+e)}}else this._notifySelectedMeshUnselected(e._currentMeshSelected),e._currentMeshSelected=null,this.changeGazeColor(this._gazeColor),this.changeLaserColor(this._laserColor)}else this._notifySelectedMeshUnselected(e._currentMeshSelected),e._currentMeshSelected=null,this.changeGazeColor(this._gazeColor),this.changeLaserColor(this._laserColor)}},e.prototype._notifySelectedMeshUnselected=function(e){e&&this.onSelectedMeshUnselected.notifyObservers(e)},e.prototype.setLaserColor=function(e,t){void 0===t&&(t=this._pickedLaserColor),this._laserColor=e,this._pickedLaserColor=t},e.prototype.setLaserLightingState=function(e){void 0===e&&(e=!0),this._leftController&&this._leftController._setLaserPointerLightingDisabled(!e),this._rightController&&this._rightController._setLaserPointerLightingDisabled(!e)},e.prototype.setGazeColor=function(e,t){void 0===t&&(t=this._pickedGazeColor),this._gazeColor=e,this._pickedGazeColor=t},e.prototype.changeLaserColor=function(e){this.updateControllerLaserColor&&(this._leftController&&this._leftController._setLaserPointerColor(e),this._rightController&&this._rightController._setLaserPointerColor(e))},e.prototype.changeGazeColor=function(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e,this._leftController&&(this._leftController._gazeTracker.material.emissiveColor=e),this._rightController&&(this._rightController._gazeTracker.material.emissiveColor=e))},e.prototype.dispose=function(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._webVRCamera&&this._webVRCamera.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._leftController&&this._leftController.dispose(),this._rightController&&this._rightController.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection=[],document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.onmsfullscreenchange=null,this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged),this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart),this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected),this._scene.unregisterBeforeRender(this.beforeRender)},e.prototype.getClassName=function(){return"VRExperienceHelper"},e.TELEPORTATIONMODE_CONSTANTTIME=0,e.TELEPORTATIONMODE_CONSTANTSPEED=1,e}(),mn=i(60),gn=(un={root:0,found:!1},function(e,t,i,n){un.root=0,un.found=!1;var r=t*t-4*e*i;if(r<0)return un;var o=Math.sqrt(r),a=(-t-o)/(2*e),s=(-t+o)/(2*e);if(a>s){var c=s;s=a,a=c}return a>0&&a<n?(un.root=a,un.found=!0,un):s>0&&s<n?(un.root=s,un.found=!0,un):un}),vn=function(){function e(){this._collisionPoint=a.e.Zero(),this._planeIntersectionPoint=a.e.Zero(),this._tempVector=a.e.Zero(),this._tempVector2=a.e.Zero(),this._tempVector3=a.e.Zero(),this._tempVector4=a.e.Zero(),this._edge=a.e.Zero(),this._baseToVertex=a.e.Zero(),this._destinationPoint=a.e.Zero(),this._slidePlaneNormal=a.e.Zero(),this._displacementVector=a.e.Zero(),this._radius=a.e.One(),this._retry=0,this._basePointWorld=a.e.Zero(),this._velocityWorld=a.e.Zero(),this._normalizedVelocity=a.e.Zero(),this._collisionMask=-1}return Object.defineProperty(e.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"slidePlaneNormal",{get:function(){return this._slidePlaneNormal},enumerable:!0,configurable:!0}),e.prototype._initialize=function(e,t,i){this._velocity=t,a.e.NormalizeToRef(t,this._normalizedVelocity),this._basePoint=e,e.multiplyToRef(this._radius,this._basePointWorld),t.multiplyToRef(this._radius,this._velocityWorld),this._velocityWorldLength=this._velocityWorld.length(),this._epsilon=i,this.collisionFound=!1},e.prototype._checkPointInTriangle=function(e,t,i,n,r){t.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),a.e.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var o=a.e.Dot(this._tempVector4,r);return!(o<0)&&(n.subtractToRef(e,this._tempVector3),a.e.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),!((o=a.e.Dot(this._tempVector4,r))<0)&&(a.e.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),(o=a.e.Dot(this._tempVector4,r))>=0))},e.prototype._canDoCollision=function(e,t,i,n){var r=a.e.Distance(this._basePointWorld,e),o=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(r>this._velocityWorldLength+o+t)&&!!function(e,t,i,n){return!(e.x>i.x+n||i.x-n>t.x||e.y>i.y+n||i.y-n>t.y||e.z>i.z+n||i.z-n>t.z)}(i,n,this._basePointWorld,this._velocityWorldLength+o)},e.prototype._testTriangle=function(e,t,i,n,r,o,s){var c,l=!1;t||(t=[]),t[e]||(t[e]=new mn.a(0,0,0,0),t[e].copyFromPoints(i,n,r));var u=t[e];if(o||u.isFrontFacingTo(this._normalizedVelocity,0)){var h=u.signedDistanceTo(this._basePoint),d=a.e.Dot(u.normal,this._velocity);if(0==d){if(Math.abs(h)>=1)return;l=!0,c=0}else{var f=(1-h)/d;if((c=(-1-h)/d)>f){var p=f;f=c,c=p}if(c>1||f<0)return;c<0&&(c=0),c>1&&(c=1)}this._collisionPoint.copyFromFloats(0,0,0);var _=!1,m=1;if(l||(this._basePoint.subtractToRef(u.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(c,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,n,r,u.normal)&&(_=!0,m=c,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!_){var g=this._velocity.lengthSquared(),v=g;this._basePoint.subtractToRef(i,this._tempVector);var y=2*a.e.Dot(this._velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,T=gn(v,y,b,m);T.found&&(m=T.root,_=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(n,this._tempVector),y=2*a.e.Dot(this._velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,(T=gn(v,y,b,m)).found&&(m=T.root,_=!0,this._collisionPoint.copyFrom(n)),this._basePoint.subtractToRef(r,this._tempVector),y=2*a.e.Dot(this._velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,(T=gn(v,y,b,m)).found&&(m=T.root,_=!0,this._collisionPoint.copyFrom(r)),n.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);var E=this._edge.lengthSquared(),x=a.e.Dot(this._edge,this._velocity),P=a.e.Dot(this._edge,this._baseToVertex);if(v=E*-g+x*x,y=E*(2*a.e.Dot(this._velocity,this._baseToVertex))-2*x*P,b=E*(1-this._baseToVertex.lengthSquared())+P*P,(T=gn(v,y,b,m)).found){var A=(x*T.root-P)/E;A>=0&&A<=1&&(m=T.root,_=!0,this._edge.scaleInPlace(A),i.addToRef(this._edge,this._collisionPoint))}r.subtractToRef(n,this._edge),n.subtractToRef(this._basePoint,this._baseToVertex),E=this._edge.lengthSquared(),x=a.e.Dot(this._edge,this._velocity),P=a.e.Dot(this._edge,this._baseToVertex),v=E*-g+x*x,y=E*(2*a.e.Dot(this._velocity,this._baseToVertex))-2*x*P,b=E*(1-this._baseToVertex.lengthSquared())+P*P,(T=gn(v,y,b,m)).found&&(A=(x*T.root-P)/E)>=0&&A<=1&&(m=T.root,_=!0,this._edge.scaleInPlace(A),n.addToRef(this._edge,this._collisionPoint)),i.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),E=this._edge.lengthSquared(),x=a.e.Dot(this._edge,this._velocity),P=a.e.Dot(this._edge,this._baseToVertex),v=E*-g+x*x,y=E*(2*a.e.Dot(this._velocity,this._baseToVertex))-2*x*P,b=E*(1-this._baseToVertex.lengthSquared())+P*P,(T=gn(v,y,b,m)).found&&(A=(x*T.root-P)/E)>=0&&A<=1&&(m=T.root,_=!0,this._edge.scaleInPlace(A),r.addToRef(this._edge,this._collisionPoint))}if(_){var S=m*this._velocity.length();(!this.collisionFound||S<this._nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this._nearestDistance=S,this.collisionFound=!0,this.collidedMesh=s)}}},e.prototype._collide=function(e,t,i,n,r,o,a,s){for(var c=n;c<r;c+=3){var l=t[i[c]-o],u=t[i[c+1]-o],h=t[i[c+2]-o];this._testTriangle(c,e,h,u,l,a,s)}},e.prototype._getResponse=function(e,t){e.addToRef(t,this._destinationPoint),t.scaleInPlace(this._nearestDistance/t.length()),this._basePoint.addToRef(t,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this._epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(mn.a.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,t)},e}(),yn=function(){function e(){this._scaledPosition=a.e.Zero(),this._scaledVelocity=a.e.Zero(),this._finalPosition=a.e.Zero()}return e.prototype.getNewPosition=function(e,t,i,n,r,o,a){e.divideToRef(i._radius,this._scaledPosition),t.divideToRef(i._radius,this._scaledVelocity),i.collidedMesh=null,i._retry=0,i._initialVelocity=this._scaledVelocity,i._initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,n,this._finalPosition,r),this._finalPosition.multiplyInPlace(i._radius),o(a,this._finalPosition,i.collidedMesh)},e.prototype.createCollider=function(){return new vn},e.prototype.init=function(e){this._scene=e},e.prototype._collideWithWorld=function(e,t,i,n,r,o){void 0===o&&(o=null);var a=10*Oe.a.CollisionsEpsilon;if(i._retry>=n)r.copyFrom(e);else{var s=o?o.collisionMask:i.collisionMask;i._initialize(e,t,a);for(var c=0;c<this._scene.meshes.length;c++){var l=this._scene.meshes[c];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==o&&0!=(s&l.collisionGroup)&&l._checkCollision(i)}i.collisionFound?(0===t.x&&0===t.y&&0===t.z||i._getResponse(e,t),t.length()<=a?r.copyFrom(e):(i._retry++,this._collideWithWorld(e,t,i,n,r,o))):e.addToRef(t,r)}},e}();K.a.CollisionCoordinatorFactory=function(){return new yn};var bn=i(53),Tn=i(105),En=i(133),xn=i(96),Pn=i(44),An=i(104),Sn=function(){function e(e,t,i,n,r,o){this.entries=new Array,this._boundingVectors=new Array,this._capacity=i,this._depth=n,this._maxDepth=r,this._creationFunc=o,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}return Object.defineProperty(e.prototype,"capacity",{get:function(){return this._capacity},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"minPoint",{get:function(){return this._minPoint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maxPoint",{get:function(){return this._maxPoint},enumerable:!0,configurable:!0}),e.prototype.addEntry=function(e){if(this.blocks)for(var t=0;t<this.blocks.length;t++){this.blocks[t].addEntry(e)}else this._creationFunc(e,this),this.entries.length>this.capacity&&this._depth<this._maxDepth&&this.createInnerBlocks()},e.prototype.removeEntry=function(e){if(this.blocks)for(var t=0;t<this.blocks.length;t++){this.blocks[t].removeEntry(e)}else{var i=this.entries.indexOf(e);i>-1&&this.entries.splice(i,1)}},e.prototype.addEntries=function(e){for(var t=0;t<e.length;t++){var i=e[t];this.addEntry(i)}},e.prototype.select=function(e,t,i){if(xn.a.IsInFrustum(this._boundingVectors,e)){if(this.blocks){for(var n=0;n<this.blocks.length;n++){this.blocks[n].select(e,t,i)}return}i?t.concat(this.entries):t.concatWithNoDuplicate(this.entries)}},e.prototype.intersects=function(e,t,i,n){if(xn.a.IntersectsSphere(this._minPoint,this._maxPoint,e,t)){if(this.blocks){for(var r=0;r<this.blocks.length;r++){this.blocks[r].intersects(e,t,i,n)}return}n?i.concat(this.entries):i.concatWithNoDuplicate(this.entries)}},e.prototype.intersectsRay=function(e,t){if(e.intersectsBoxMinMax(this._minPoint,this._maxPoint)){if(this.blocks){for(var i=0;i<this.blocks.length;i++){this.blocks[i].intersectsRay(e,t)}return}t.concatWithNoDuplicate(this.entries)}},e.prototype.createInnerBlocks=function(){e._CreateBlocks(this._minPoint,this._maxPoint,this.entries,this._capacity,this._depth,this._maxDepth,this,this._creationFunc)},e._CreateBlocks=function(t,i,n,r,o,s,c,l){c.blocks=new Array;for(var u=new a.e((i.x-t.x)/2,(i.y-t.y)/2,(i.z-t.z)/2),h=0;h<2;h++)for(var d=0;d<2;d++)for(var f=0;f<2;f++){var p=new e(t.add(u.multiplyByFloats(h,d,f)),t.add(u.multiplyByFloats(h+1,d+1,f+1)),r,o+1,s,l);p.addEntries(n),c.blocks.push(p)}},e}(),Cn=function(){function e(e,t,i){void 0===i&&(i=2),this.maxDepth=i,this.dynamicContent=new Array,this._maxBlockCapacity=t||64,this._selectionContent=new oi.b(1024),this._creationFunc=e}return e.prototype.update=function(e,t,i){Sn._CreateBlocks(e,t,i,this._maxBlockCapacity,0,this.maxDepth,this,this._creationFunc)},e.prototype.addMesh=function(e){for(var t=0;t<this.blocks.length;t++){this.blocks[t].addEntry(e)}},e.prototype.removeMesh=function(e){for(var t=0;t<this.blocks.length;t++){this.blocks[t].removeEntry(e)}},e.prototype.select=function(e,t){this._selectionContent.reset();for(var i=0;i<this.blocks.length;i++){this.blocks[i].select(e,this._selectionContent,t)}return t?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent},e.prototype.intersects=function(e,t,i){this._selectionContent.reset();for(var n=0;n<this.blocks.length;n++){this.blocks[n].intersects(e,t,this._selectionContent,i)}return i?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent},e.prototype.intersectsRay=function(e){this._selectionContent.reset();for(var t=0;t<this.blocks.length;t++){this.blocks[t].intersectsRay(e,this._selectionContent)}return this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent},e.CreationFuncForMeshes=function(e,t){var i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},e.CreationFuncForSubMeshes=function(e,t){e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},e}();K.a.prototype.createOrUpdateSelectionOctree=function(e,t){void 0===e&&(e=64),void 0===t&&(t=2);var i=this._getComponent(Fe.a.NAME_OCTREE);i||(i=new Rn(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new Cn(Cn.CreationFuncForMeshes,e,t));var n=this.getWorldExtends();return this._selectionOctree.update(n.min,n.max,this.meshes),this._selectionOctree},Object.defineProperty(K.a.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),Ke.a.prototype.createOrUpdateSubmeshesOctree=function(e,t){void 0===e&&(e=64),void 0===t&&(t=2);var i=this.getScene(),n=i._getComponent(Fe.a.NAME_OCTREE);n||(n=new Rn(i),i._addComponent(n)),this._submeshesOctree||(this._submeshesOctree=new Cn(Cn.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);var r=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(r.minimumWorld,r.maximumWorld,this.subMeshes),this._submeshesOctree};var Rn=function(){function e(e){this.name=Fe.a.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new Ht.a(a.e.Zero(),new a.e(1,1,1)),this.scene=e,this.scene.getActiveMeshCandidates=this.getActiveMeshCandidates.bind(this),this.scene.getActiveSubMeshCandidates=this.getActiveSubMeshCandidates.bind(this),this.scene.getCollidingSubMeshCandidates=this.getCollidingSubMeshCandidates.bind(this),this.scene.getIntersectingSubMeshCandidates=this.getIntersectingSubMeshCandidates.bind(this)}return e.prototype.register=function(){var e=this;this.scene.onMeshRemovedObservable.add(function(t){var i=e.scene.selectionOctree;if(null!=i){var n=i.dynamicContent.indexOf(t);-1!==n&&i.dynamicContent.splice(n,1)}}),this.scene.onMeshImportedObservable.add(function(t){var i=e.scene.selectionOctree;null!=i&&i.addMesh(t)})},e.prototype.getActiveMeshCandidates=function(){return this.scene._selectionOctree?this.scene._selectionOctree.select(this.scene.frustumPlanes):this.scene._getDefaultMeshCandidates()},e.prototype.getActiveSubMeshCandidates=function(e){return e._submeshesOctree&&e.useOctreeForRenderingSelection?e._submeshesOctree.select(this.scene.frustumPlanes):this.scene._getDefaultSubMeshCandidates(e)},e.prototype.getIntersectingSubMeshCandidates=function(e,t){return e._submeshesOctree&&e.useOctreeForPicking?(Ht.a.TransformToRef(t,e.getWorldMatrix(),this._tempRay),e._submeshesOctree.intersectsRay(this._tempRay)):this.scene._getDefaultSubMeshCandidates(e)},e.prototype.getCollidingSubMeshCandidates=function(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){var i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z);return e._submeshesOctree.intersects(t._basePointWorld,i)}return this.scene._getDefaultSubMeshCandidates(e)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){},e}(),On=i(93),Mn=i(150),In=function(){this._timeElapsedQueryEnded=!1},Dn=function(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=Ke.a.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=Ke.a.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE};Oe.a.prototype.createQuery=function(){return this._gl.createQuery()},Oe.a.prototype.deleteQuery=function(e){return this._gl.deleteQuery(e),this},Oe.a.prototype.isQueryResultAvailable=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT_AVAILABLE)},Oe.a.prototype.getQueryResult=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT)},Oe.a.prototype.beginOcclusionQuery=function(e,t){var i=this._getGlAlgorithmType(e);return this._gl.beginQuery(i,t),this},Oe.a.prototype.endOcclusionQuery=function(e){var t=this._getGlAlgorithmType(e);return this._gl.endQuery(t),this},Oe.a.prototype._createTimeQuery=function(){var e=this.getCaps().timerQuery;return e.createQueryEXT?e.createQueryEXT():this.createQuery()},Oe.a.prototype._deleteTimeQuery=function(e){var t=this.getCaps().timerQuery;t.deleteQueryEXT?t.deleteQueryEXT(e):this.deleteQuery(e)},Oe.a.prototype._getTimeQueryResult=function(e){var t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT):this.getQueryResult(e)},Oe.a.prototype._getTimeQueryAvailability=function(e){var t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(e)},Oe.a.prototype.startTimeQuery=function(){var e=this.getCaps(),t=e.timerQuery;if(!t)return null;var i=new In;if(this._gl.getParameter(t.GPU_DISJOINT_EXT),e.canUseTimestampForTimerQuery)i._startTimeQuery=this._createTimeQuery(),t.queryCounterEXT(i._startTimeQuery,t.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;i._timeElapsedQuery=this._createTimeQuery(),t.beginQueryEXT?t.beginQueryEXT(t.TIME_ELAPSED_EXT,i._timeElapsedQuery):this._gl.beginQuery(t.TIME_ELAPSED_EXT,i._timeElapsedQuery),this._currentNonTimestampToken=i}return i},Oe.a.prototype.endTimeQuery=function(e){var t=this.getCaps(),i=t.timerQuery;if(!i||!e)return-1;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery)return-1;e._endTimeQuery||(e._endTimeQuery=this._createTimeQuery(),i.queryCounterEXT(e._endTimeQuery,i.TIMESTAMP_EXT))}else if(!e._timeElapsedQueryEnded){if(!e._timeElapsedQuery)return-1;i.endQueryEXT?i.endQueryEXT(i.TIME_ELAPSED_EXT):this._gl.endQuery(i.TIME_ELAPSED_EXT),e._timeElapsedQueryEnded=!0}var n=this._gl.getParameter(i.GPU_DISJOINT_EXT),r=!1;if(e._endTimeQuery?r=this._getTimeQueryAvailability(e._endTimeQuery):e._timeElapsedQuery&&(r=this._getTimeQueryAvailability(e._timeElapsedQuery)),r&&!n){var o=0;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery||!e._endTimeQuery)return-1;var a=this._getTimeQueryResult(e._startTimeQuery);o=this._getTimeQueryResult(e._endTimeQuery)-a,this._deleteTimeQuery(e._startTimeQuery),this._deleteTimeQuery(e._endTimeQuery),e._startTimeQuery=null,e._endTimeQuery=null}else{if(!e._timeElapsedQuery)return-1;o=this._getTimeQueryResult(e._timeElapsedQuery),this._deleteTimeQuery(e._timeElapsedQuery),e._timeElapsedQuery=null,e._timeElapsedQueryEnded=!1,this._currentNonTimestampToken=null}return o}return-1},Oe.a.prototype._getGlAlgorithmType=function(e){return e===Ke.a.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED},Object.defineProperty(Ke.a.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(Ke.a.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new Dn),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(Ke.a.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(Ke.a.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Ke.a.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Ke.a.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Ke.a.prototype._checkOcclusionQuery=function(){var e=this._occlusionDataStorage;if(e.occlusionType===Ke.a.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;var t=this.getEngine();if(t.webGLVersion<2)return e.isOccluded=!1,!1;if(!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&this._occlusionQuery)if(t.isQueryResultAvailable(this._occlusionQuery)){var i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=1!==i}else{if(e.occlusionInternalRetryCounter++,!(-1!==e.occlusionRetryCount&&e.occlusionInternalRetryCounter>e.occlusionRetryCount))return!1;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==Ke.a.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}var n=this.getScene();if(n.getBoundingBoxRenderer){var r=n.getBoundingBoxRenderer();this._occlusionQuery||(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery),r.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0}return e.isOccluded};Oe.a.prototype.createTransformFeedback=function(){return this._gl.createTransformFeedback()},Oe.a.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},Oe.a.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},Oe.a.prototype.beginTransformFeedback=function(e){void 0===e&&(e=!0),this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},Oe.a.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},Oe.a.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},Oe.a.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)};var wn=function(){};Oe.a.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},Oe.a.prototype.registerView=function(e,t){var i=this;this.views||(this.views=[]);for(var n=0,r=this.views;n<r.length;n++){var o=r[n];if(o.target===e)return o}var a=this.getRenderingCanvas();a&&(e.width=a.width,e.height=a.height);var s={target:e,camera:t};return this.views.push(s),t&&t.onDisposeObservable.add(function(){i.unRegisterView(e)}),s},Oe.a.prototype.unRegisterView=function(e){if(!this.views)return this;for(var t=0,i=this.views;t<i.length;t++){var n=i[t];if(n.target===e){var r=this.views.indexOf(n);-1!==r&&this.views.splice(r,1);break}}return this},Oe.a.prototype._renderViews=function(){if(!this.views)return!1;var e=this.getRenderingCanvas();if(!e)return!1;for(var t=0,i=this.views;t<i.length;t++){var n=i[t],r=n.target,o=r.getContext("2d");if(o){var a=n.camera,s=null,c=null;if(a){if((c=a.getScene()).activeCameras.length)continue;this.activeView=n,s=c.activeCamera,c.activeCamera=a}r.width=r.clientWidth,r.height=r.clientHeight,e.width=r.clientWidth,e.height=r.clientHeight,this._renderFrame(),o.drawImage(e,0,0),s&&c&&(c.activeCamera=s)}}return this.activeView=null,!0};var Ln=i(130),Nn=i(109),Fn=i(85),Bn=[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))],Un=[function(e){return 1},function(e){return e.y},function(e){return e.z},function(e){return e.x},function(e){return e.x*e.y},function(e){return e.y*e.z},function(e){return 3*e.z*e.z-1},function(e){return e.x*e.z},function(e){return e.x*e.x-e.y*e.y}],Vn=function(e,t){return Bn[e]*Un[e](t)},kn=[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],zn=function(){function e(){this.preScaled=!1,this.l00=a.e.Zero(),this.l1_1=a.e.Zero(),this.l10=a.e.Zero(),this.l11=a.e.Zero(),this.l2_2=a.e.Zero(),this.l2_1=a.e.Zero(),this.l20=a.e.Zero(),this.l21=a.e.Zero(),this.l22=a.e.Zero()}return e.prototype.addLight=function(e,t,i){var n=new a.e(t.r,t.g,t.b).scale(i);this.l00=this.l00.add(n.scale(Vn(0,e))),this.l1_1=this.l1_1.add(n.scale(Vn(1,e))),this.l10=this.l10.add(n.scale(Vn(2,e))),this.l11=this.l11.add(n.scale(Vn(3,e))),this.l2_2=this.l2_2.add(n.scale(Vn(4,e))),this.l2_1=this.l2_1.add(n.scale(Vn(5,e))),this.l20=this.l20.add(n.scale(Vn(6,e))),this.l21=this.l21.add(n.scale(Vn(7,e))),this.l22=this.l22.add(n.scale(Vn(8,e)))},e.prototype.scaleInPlace=function(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)},e.prototype.convertIncidentRadianceToIrradiance=function(){this.l00.scaleInPlace(kn[0]),this.l1_1.scaleInPlace(kn[1]),this.l10.scaleInPlace(kn[2]),this.l11.scaleInPlace(kn[3]),this.l2_2.scaleInPlace(kn[4]),this.l2_1.scaleInPlace(kn[5]),this.l20.scaleInPlace(kn[6]),this.l21.scaleInPlace(kn[7]),this.l22.scaleInPlace(kn[8])},e.prototype.convertIrradianceToLambertianRadiance=function(){this.scaleInPlace(1/Math.PI)},e.prototype.preScaleForRendering=function(){this.preScaled=!0,this.l00.scaleInPlace(Bn[0]),this.l1_1.scaleInPlace(Bn[1]),this.l10.scaleInPlace(Bn[2]),this.l11.scaleInPlace(Bn[3]),this.l2_2.scaleInPlace(Bn[4]),this.l2_1.scaleInPlace(Bn[5]),this.l20.scaleInPlace(Bn[6]),this.l21.scaleInPlace(Bn[7]),this.l22.scaleInPlace(Bn[8])},e.FromArray=function(t){var i=new e;return a.e.FromArrayToRef(t[0],0,i.l00),a.e.FromArrayToRef(t[1],0,i.l1_1),a.e.FromArrayToRef(t[2],0,i.l10),a.e.FromArrayToRef(t[3],0,i.l11),a.e.FromArrayToRef(t[4],0,i.l2_2),a.e.FromArrayToRef(t[5],0,i.l2_1),a.e.FromArrayToRef(t[6],0,i.l20),a.e.FromArrayToRef(t[7],0,i.l21),a.e.FromArrayToRef(t[8],0,i.l22),i},e.FromPolynomial=function(t){var i=new e;return i.l00=t.xx.scale(.376127).add(t.yy.scale(.376127)).add(t.zz.scale(.376126)),i.l1_1=t.y.scale(.977204),i.l10=t.z.scale(.977204),i.l11=t.x.scale(.977204),i.l2_2=t.xy.scale(1.16538),i.l2_1=t.yz.scale(1.16538),i.l20=t.zz.scale(1.34567).subtract(t.xx.scale(.672834)).subtract(t.yy.scale(.672834)),i.l21=t.zx.scale(1.16538),i.l22=t.xx.scale(1.16538).subtract(t.yy.scale(1.16538)),i.l1_1.scaleInPlace(-1),i.l11.scaleInPlace(-1),i.l2_1.scaleInPlace(-1),i.l21.scaleInPlace(-1),i.scaleInPlace(Math.PI),i},e}(),Gn=function(){function e(){this.x=a.e.Zero(),this.y=a.e.Zero(),this.z=a.e.Zero(),this.xx=a.e.Zero(),this.yy=a.e.Zero(),this.zz=a.e.Zero(),this.xy=a.e.Zero(),this.yz=a.e.Zero(),this.zx=a.e.Zero()}return Object.defineProperty(e.prototype,"preScaledHarmonics",{get:function(){return this._harmonics||(this._harmonics=zn.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics},enumerable:!0,configurable:!0}),e.prototype.addAmbient=function(e){var t=new a.e(e.r,e.g,e.b);this.xx=this.xx.add(t),this.yy=this.yy.add(t),this.zz=this.zz.add(t)},e.prototype.scaleInPlace=function(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)},e.FromHarmonics=function(t){var i=new e;return i._harmonics=t,i.x=t.l11.scale(1.02333).scale(-1),i.y=t.l1_1.scale(1.02333).scale(-1),i.z=t.l10.scale(1.02333),i.xx=t.l00.scale(.886277).subtract(t.l20.scale(.247708)).add(t.l22.scale(.429043)),i.yy=t.l00.scale(.886277).subtract(t.l20.scale(.247708)).subtract(t.l22.scale(.429043)),i.zz=t.l00.scale(.886277).add(t.l20.scale(.495417)),i.yz=t.l2_1.scale(.858086).scale(-1),i.zx=t.l21.scale(.858086).scale(-1),i.xy=t.l2_2.scale(.858086),i.scaleInPlace(1/Math.PI),i},e.FromArray=function(t){var i=new e;return a.e.FromArrayToRef(t[0],0,i.x),a.e.FromArrayToRef(t[1],0,i.y),a.e.FromArrayToRef(t[2],0,i.z),a.e.FromArrayToRef(t[3],0,i.xx),a.e.FromArrayToRef(t[4],0,i.yy),a.e.FromArrayToRef(t[5],0,i.zz),a.e.FromArrayToRef(t[6],0,i.yz),a.e.FromArrayToRef(t[7],0,i.zx),a.e.FromArrayToRef(t[8],0,i.xy),i},e}(),jn=i(49),Wn=function(e,t,i,n){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=n},Xn=function(){function e(){}return e.ConvertCubeMapTextureToSphericalPolynomial=function(e){if(!e.isCube)return null;var t,i,n=e.getSize().width,r=e.readPixels(0),o=e.readPixels(1);e.isRenderTarget?(t=e.readPixels(3),i=e.readPixels(2)):(t=e.readPixels(2),i=e.readPixels(3));var a=e.readPixels(4),s=e.readPixels(5),c=e.gammaSpace,l=g.a.TEXTUREFORMAT_RGBA,u=g.a.TEXTURETYPE_UNSIGNED_INT;e.textureType!=g.a.TEXTURETYPE_FLOAT&&e.textureType!=g.a.TEXTURETYPE_HALF_FLOAT||(u=g.a.TEXTURETYPE_FLOAT);var h={size:n,right:r,left:o,up:t,down:i,front:a,back:s,format:l,type:u,gammaSpace:c};return this.ConvertCubeMapToSphericalPolynomial(h)},e.ConvertCubeMapToSphericalPolynomial=function(e){for(var t=new zn,i=0,n=2/e.size,r=n,o=.5*n-1,a=0;a<6;a++)for(var c=this.FileFaces[a],l=e[c.name],u=o,h=e.format===g.a.TEXTUREFORMAT_RGBA?4:3,d=0;d<e.size;d++){for(var f=o,p=0;p<e.size;p++){var _=c.worldAxisForFileX.scale(f).add(c.worldAxisForFileY.scale(u)).add(c.worldAxisForNormal);_.normalize();var m=Math.pow(1+f*f+u*u,-1.5),v=l[d*e.size*h+p*h+0],y=l[d*e.size*h+p*h+1],b=l[d*e.size*h+p*h+2];isNaN(v)&&(v=0),isNaN(y)&&(y=0),isNaN(b)&&(b=0),e.type===g.a.TEXTURETYPE_UNSIGNED_INT&&(v/=255,y/=255,b/=255),e.gammaSpace&&(v=Math.pow(L.a.Clamp(v),re.c),y=Math.pow(L.a.Clamp(y),re.c),b=Math.pow(L.a.Clamp(b),re.c));v=L.a.Clamp(v,0,4096),y=L.a.Clamp(y,0,4096),b=L.a.Clamp(b,0,4096);var T=new s.a(v,y,b);t.addLight(_,T,m),i+=m,f+=n}u+=r}var E=6*(4*Math.PI)/6/i;return t.scaleInPlace(E),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),Gn.FromHarmonics(t)},e.FileFaces=[new Wn("right",new a.e(1,0,0),new a.e(0,0,-1),new a.e(0,-1,0)),new Wn("left",new a.e(-1,0,0),new a.e(0,0,1),new a.e(0,-1,0)),new Wn("up",new a.e(0,1,0),new a.e(1,0,0),new a.e(0,0,1)),new Wn("down",new a.e(0,-1,0),new a.e(1,0,0),new a.e(0,0,-1)),new Wn("front",new a.e(0,0,1),new a.e(1,0,0),new a.e(0,-1,0)),new Wn("back",new a.e(0,0,-1),new a.e(-1,0,0),new a.e(0,-1,0))],e}();Object.defineProperty(jn.a.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial)return this._texture._sphericalPolynomial;this._texture.isReady&&(this._texture._sphericalPolynomial=Xn.ConvertCubeMapTextureToSphericalPolynomial(this))}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});var Hn="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void)\n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}";ai.a.ShadersStore.rgbdEncodePixelShader=Hn;var Yn="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void)\n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}";ai.a.ShadersStore.rgbdDecodePixelShader=Yn;var Kn,Qn,qn=function(){function e(){}return e.GetEnvInfo=function(t){for(var i=new DataView(t.buffer,t.byteOffset,t.byteLength),n=0,r=0;r<e._MagicBytes.length;r++)if(i.getUint8(n++)!==e._MagicBytes[r])return m.a.Error("Not a babylon environment map"),null;for(var o="",a=0;a=i.getUint8(n++);)o+=String.fromCharCode(a);var s=JSON.parse(o);return s.specular&&(s.specular.specularDataPosition=n,s.specular.lodGenerationScale=s.specular.lodGenerationScale||.8),s},e.CreateEnvTextureAsync=function(t){var i=this,n=t.getInternalTexture();if(!n)return Promise.reject("The cube texture is invalid.");if(!t._prefiltered)return Promise.reject("The cube texture is invalid (not prefiltered).");var r=n.getEngine();if(r&&r.premultipliedAlpha)return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");if(t.textureType===g.a.TEXTURETYPE_UNSIGNED_INT)return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");var o=r.getRenderingCanvas();if(!o)return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");var a=g.a.TEXTURETYPE_FLOAT;if(!r.getCaps().textureFloatRender&&(a=g.a.TEXTURETYPE_HALF_FLOAT,!r.getCaps().textureHalfFloatRender))return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");var s=n.width,c=new K.a(r),l={},u=[],h=L.a.Log2(n.width);h=Math.round(h);for(var d=function(e){for(var i=Math.pow(2,h-e),n=function(n){var s=t.readPixels(n,e),h=r.createRawTexture(s,i,i,g.a.TEXTUREFORMAT_RGBA,!1,!1,g.a.TEXTURE_NEAREST_SAMPLINGMODE,null,a),d=new Promise(function(t,a){var s=new ui("rgbdEncode","rgbdEncode",null,null,1,null,g.a.TEXTURE_NEAREST_SAMPLINGMODE,r,!1,void 0,g.a.TEXTURETYPE_UNSIGNED_INT,void 0,null,!1);s.getEffect().executeWhenCompiled(function(){s.onApply=function(e){e._bindTexture("textureSampler",h)};var a=r.getRenderWidth(),u=r.getRenderHeight();r.setSize(i,i),c.postProcessManager.directRender([s],null),De.b.ToBlob(o,function(i){var r=new FileReader;r.onload=function(i){var r=i.target.result;l[6*e+n]=r,t()},r.readAsArrayBuffer(i)}),r.setSize(a,u)})});u.push(d)},s=0;s<6;s++)n(s)},f=0;f<=h;f++)d(f);return Promise.all(u).then(function(){c.dispose();for(var n={version:1,width:s,irradiance:i._CreateEnvTextureIrradiance(t),specular:{mipmaps:[],lodGenerationScale:t.lodGenerationScale}},r=0,o=0;o<=h;o++)for(var a=0;a<6;a++){var u=l[6*o+a].byteLength;n.specular.mipmaps.push({length:u,position:r}),r+=u}for(var d=JSON.stringify(n),f=new ArrayBuffer(d.length+1),p=new Uint8Array(f),_=(o=0,d.length);o<_;o++)p[o]=d.charCodeAt(o);p[d.length]=0;var m=e._MagicBytes.length+r+f.byteLength,g=new ArrayBuffer(m),v=new Uint8Array(g),y=new DataView(g),b=0;for(o=0;o<e._MagicBytes.length;o++)y.setUint8(b++,e._MagicBytes[o]);v.set(new Uint8Array(f),b),b+=f.byteLength;for(o=0;o<=h;o++)for(a=0;a<6;a++){var T=l[6*o+a];v.set(new Uint8Array(T),b),b+=T.byteLength}return g})},e._CreateEnvTextureIrradiance=function(e){var t=e.sphericalPolynomial;return null==t?null:{x:[t.x.x,t.x.y,t.x.z],y:[t.y.x,t.y.y,t.y.z],z:[t.z.x,t.z.y,t.z.z],xx:[t.xx.x,t.xx.y,t.xx.z],yy:[t.yy.x,t.yy.y,t.yy.z],zz:[t.zz.x,t.zz.y,t.zz.z],yz:[t.yz.x,t.yz.y,t.yz.z],zx:[t.zx.x,t.zx.y,t.zx.z],xy:[t.xy.x,t.xy.y,t.xy.z]}},e.CreateImageDataArrayBufferViews=function(e,t){if(1!==t.version)throw new Error('Unsupported babylon environment map version "'+t.version+'"');var i=t.specular,n=L.a.Log2(t.width);if(n=Math.round(n)+1,i.mipmaps.length!==6*n)throw new Error('Unsupported specular mipmaps number "'+i.mipmaps.length+'"');for(var r=new Array(n),o=0;o<n;o++){r[o]=new Array(6);for(var a=0;a<6;a++){var s=i.mipmaps[6*o+a];r[o][a]=new Uint8Array(e.buffer,e.byteOffset+i.specularDataPosition+s.position,s.length)}}return r},e.UploadEnvLevelsAsync=function(t,i,n){if(1!==n.version)throw new Error('Unsupported babylon environment map version "'+n.version+'"');var r=n.specular;if(!r)return Promise.resolve();t._lodGenerationScale=r.lodGenerationScale;var o=e.CreateImageDataArrayBufferViews(i,n);return e.UploadLevelsAsync(t,o)},e._OnImageReadyAsync=function(e,t,i,n,r,o,a,s,c,l,u){return new Promise(function(h,d){if(i){var f=t.createTexture(null,!0,!0,null,g.a.TEXTURE_NEAREST_SAMPLINGMODE,null,function(e){d(e)},e);n.getEffect().executeWhenCompiled(function(){n.onApply=function(e){e._bindTexture("textureSampler",f),e.setFloat2("scale",1,1)},t.scenes[0].postProcessManager.directRender([n],l,!0,o,a),t.restoreDefaultFramebuffer(),f.dispose(),URL.revokeObjectURL(r),h()})}else{if(t._uploadImageToTexture(u,e,o,a),s){var p=c[a];p&&t._uploadImageToTexture(p._texture,e,o,0)}h()}})},e.UploadLevelsAsync=function(e,t){var i=this;if(!De.b.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");var n=Math.round(L.a.Log2(e.width))+1,r=e.getEngine(),o=!1,a=!1,s=null,c=null,l=null,u=r.getCaps();if(e.format=g.a.TEXTUREFORMAT_RGBA,e.type=g.a.TEXTURETYPE_UNSIGNED_INT,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,r.updateTextureSamplingMode(g.a.TEXTURE_TRILINEAR_SAMPLINGMODE,e),u.textureLOD?r.webGLVersion<2?o=!1:u.textureHalfFloatRender&&u.textureHalfFloatLinearFiltering?(o=!0,e.type=g.a.TEXTURETYPE_HALF_FLOAT):u.textureFloatRender&&u.textureFloatLinearFiltering&&(o=!0,e.type=g.a.TEXTURETYPE_FLOAT):(o=!1,a=!0,l={}),o)s=new ui("rgbdDecode","rgbdDecode",null,null,1,null,g.a.TEXTURE_TRILINEAR_SAMPLINGMODE,r,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,c=r.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:g.a.TEXTURE_TRILINEAR_SAMPLINGMODE,type:e.type,format:g.a.TEXTUREFORMAT_RGBA});else if(e._isRGBD=!0,e.invertY=!0,a)for(var h=e._lodGenerationScale,d=e._lodGenerationOffset,f=0;f<3;f++){var p=(n-1)*h+d,_=d+(p-d)*(1-f/2),m=Math.round(Math.min(Math.max(_,0),p)),v=new tt.a(r,tt.b.Temp);v.isCube=!0,v.invertY=!0,v.generateMipMaps=!1,r.updateTextureSamplingMode(g.a.TEXTURE_LINEAR_LINEAR,v);var y=new jn.a(null);switch(y.isCube=!0,y._texture=v,l[m]=y,f){case 0:e._lodTextureLow=y;break;case 1:e._lodTextureMid=y;break;case 2:e._lodTextureHigh=y}}var b=[],T=function(n){for(var u=function(u){var h=t[n][u],d=new Blob([h],{type:"image/png"}),f=URL.createObjectURL(d),p=void 0;if("undefined"==typeof Image)p=createImageBitmap(d).then(function(t){return i._OnImageReadyAsync(t,r,o,s,f,u,n,a,l,c,e)});else{var _=new Image;_.src=f,p=new Promise(function(t,h){_.onload=function(){i._OnImageReadyAsync(_,r,o,s,f,u,n,a,l,c,e).then(function(){return t()}).catch(function(e){h(e)})},_.onerror=function(e){h(e)}})}b.push(p)},h=0;h<6;h++)u(h)};for(f=0;f<t.length;f++)T(f);if(t.length<n){var E=void 0,x=Math.pow(2,n-1-t.length),P=x*x*4;switch(e.type){case g.a.TEXTURETYPE_UNSIGNED_INT:E=new Uint8Array(P);break;case g.a.TEXTURETYPE_HALF_FLOAT:E=new Uint16Array(P);break;case g.a.TEXTURETYPE_FLOAT:E=new Float32Array(P)}for(f=t.length;f<n;f++)for(var A=0;A<6;A++)r._uploadArrayBufferViewToTexture(e,E,A,f)}return Promise.all(b).then(function(){c&&(r._releaseFramebufferObjects(c),r._releaseTexture(e),c._swapAndDie(e)),s&&s.dispose(),a&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))})},e.UploadEnvSpherical=function(e,t){1!==t.version&&m.a.Warn('Unsupported babylon environment map version "'+t.version+'"');var i=t.irradiance;if(i){var n=new Gn;a.e.FromArrayToRef(i.x,0,n.x),a.e.FromArrayToRef(i.y,0,n.y),a.e.FromArrayToRef(i.z,0,n.z),a.e.FromArrayToRef(i.xx,0,n.xx),a.e.FromArrayToRef(i.yy,0,n.yy),a.e.FromArrayToRef(i.zz,0,n.zz),a.e.FromArrayToRef(i.yz,0,n.yz),a.e.FromArrayToRef(i.zx,0,n.zx),a.e.FromArrayToRef(i.xy,0,n.xy),e._sphericalPolynomial=n}},e._UpdateRGBDAsync=function(t,i,n,r,o){return t._source=tt.b.CubeRawRGBD,t._bufferViewArrayArray=i,t._lodGenerationScale=r,t._lodGenerationOffset=o,t._sphericalPolynomial=n,e.UploadLevelsAsync(t,i).then(function(){t.isReady=!0})},e._MagicBytes=[134,22,135,150,246,214,150,54],e}();tt.a._UpdateRGBDAsync=qn._UpdateRGBDAsync;var Zn,Jn=((Kn={})[en.b.PositionKind]=0,Kn[en.b.NormalKind]=1,Kn[en.b.TangentKind]=2,Kn[en.b.UVKind]=10,Kn[en.b.UV2Kind]=11,Kn[en.b.UV3Kind]=12,Kn[en.b.UV4Kind]=13,Kn[en.b.ColorKind]=4,Kn[en.b.MatricesIndicesKind]=8,Kn[en.b.MatricesWeightsKind]=9,Kn),$n=((Qn={})[en.b.PositionKind]="a_position",Qn[en.b.NormalKind]="a_normal",Qn[en.b.TangentKind]="a_tangent",Qn[en.b.UVKind]="a_texcoord0",Qn[en.b.UV2Kind]="a_texcoord1",Qn[en.b.UV3Kind]="a_texcoord2",Qn[en.b.UV4Kind]="a_texcoord3",Qn[en.b.ColorKind]="a_color0",Qn[en.b.MatricesIndicesKind]="a_indices",Qn[en.b.MatricesWeightsKind]="a_weight",Qn),er=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t.prototype.lineProcessor=function(e){for(var t=0,i=this._replacements;t<i.length;t++){var n=i[t];e=e.replace(n.searchValue,n.replaceValue)}return e},t.prototype.attributeProcessor=function(t){var i=t.match(/attribute\s+[^\s]+\s+([^\s]+)\s*(?:\[.+\])?\s*;/)[1],n=Jn[i];if(void 0===n&&(n=this._genericAttributeLocation++)>17)throw new Error("Exceeded maximum custom attributes");var r=$n[i];if(void 0===r)throw new Error("Can't find bgfx name mapping");return t=t.replace(i,r),this._replacements.push({searchValue:new RegExp("\\b"+i+"\\b","g"),replaceValue:""+r}),"layout(location="+n+") "+e.prototype.attributeProcessor.call(this,t)},t.prototype.varyingProcessor=function(t,i){var n;return i?n=this._varyingLocationMap[t]:(n=this._varyingLocationCount++,this._varyingLocationMap[t]=n),"layout(location="+n+") "+e.prototype.varyingProcessor.call(this,t,i)},t.prototype.uniformProcessor=function(e){var t=e.match(/uniform\s+([^\s]+)\s+([^\s]+)\s*(?:\[.+\])?\s*;/),i=t[1],n=t[2];switch(i){case"sampler2D":case"samplerCube":var r=i.substr(7),o=this._textureCount++;return this._replacements.push({searchValue:new RegExp("\\b"+n+"\\b"),replaceValue:"sampler"+r+"("+n+"Texture, "+n+")"}),"layout(binding="+o+") uniform texture"+r+" "+n+"Texture;\nlayout(binding="+o+") uniform sampler "+n+";";case"float":this._replacements.push({searchValue:new RegExp("\\b"+n+"\\b"),replaceValue:n+".x"}),e="uniform vec4 "+n+";";break;case"vec2":this._replacements.push({searchValue:new RegExp("\\b"+n+"\\b"),replaceValue:n+".xy"}),e="uniform vec4 "+n+";";break;case"vec3":this._replacements.push({searchValue:new RegExp("\\b"+n+"\\b"),replaceValue:n+".xyz"}),e="uniform vec4 "+n+";"}return this._uniforms.push(e),1===this._uniforms.length?"<UNIFORM>":""},t.prototype.preProcessor=function(e,t,i){return this._genericAttributeLocation=10,i||(this._varyingLocationCount=0,this._varyingLocationMap={}),this._replacements=[],this._textureCount=0,this._uniforms=[],e},t.prototype.postProcessor=function(t,i,n){return t=(t=(t=e.prototype.postProcessor.call(this,t,i,n)).replace("<UNIFORM>","layout(binding=0) uniform Frame {\n"+this._uniforms.join("\n")+"\n};")).replace("out vec4 glFragColor","layout(location=0) out vec4 glFragColor")},t}(Nn.a),tr=function(){function e(){this.isAsync=!1,this.isReady=!1}return e.prototype._handlesSpectorRebuildCallback=function(e){throw new Error("Not implemented")},e}(),ir=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t}(Fn.a),nr=function(){function e(){}return e.POINT=0,e.MINPOINT_MAGPOINT_MIPPOINT=e.POINT,e.BILINEAR=1,e.MINLINEAR_MAGLINEAR_MIPPOINT=e.BILINEAR,e.TRILINEAR=2,e.MINLINEAR_MAGLINEAR_MIPLINEAR=e.TRILINEAR,e.ANISOTROPIC=3,e.POINT_COMPARE=4,e.TRILINEAR_COMPARE=5,e.MINBILINEAR_MAGPOINT=6,e.MINLINEAR_MAGPOINT_MIPLINEAR=e.MINBILINEAR_MAGPOINT,e.MINPOINT_MAGPOINT_MIPLINEAR=7,e.MINPOINT_MAGLINEAR_MIPPOINT=8,e.MINPOINT_MAGLINEAR_MIPLINEAR=9,e.MINLINEAR_MAGPOINT_MIPPOINT=10,e}(),rr=function(){function e(){}return e.CLEAR_COLOR=1,e.CLEAR_DEPTH=2,e.CLEAR_STENCIL=4,e}(),or=function(){function e(){}return e.WRAP=0,e.MIRROR=1,e.CLAMP=2,e.BORDER=3,e.MIRROR_ONCE=4,e}(),ar=function(){function e(){}return e.RGBA8=0,e.RGBA32F=1,e}(),sr=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t.prototype.getInternalTexture=function(){return this},t.prototype.getViewCount=function(){return 1},t}(tt.a),cr=function(e){function t(){var t=e.call(this,null)||this;return t._native=new _native.Engine,t.INVALID_HANDLE=65535,t._webGLVersion=2,t.disableUniformBuffers=!0,t._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:512,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,maxAnisotropy:16,uintIndices:!1,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,textureFloat:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!0,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:1},De.b.Log("Babylon Native (v"+Oe.a.Version+") launched"),"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(){}),t._shaderProcessor=new er,t}return Object(h.d)(t,e),t.prototype.getHardwareScalingLevel=function(){return 1},t.prototype._queueNewFrame=function(e,t){return t.requestAnimationFrame?t.requestAnimationFrame(e):this._native.requestAnimationFrame(e),0},t.prototype._bindUnboundFramebuffer=function(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&this._native.unbindFramebuffer(this._currentFramebuffer),e&&this._native.bindFramebuffer(e),this._currentFramebuffer=e)},t.prototype.getHostDocument=function(){return null},t.prototype.clear=function(e,t,i,n){void 0===n&&(n=!1);var r=0;t&&e&&(this._native.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),r|=rr.CLEAR_COLOR),i&&(this._native.clearDepth(1),r|=rr.CLEAR_DEPTH),n&&(this._native.clearStencil(0),r|=rr.CLEAR_STENCIL),this._native.clear(r)},t.prototype.createIndexBuffer=function(e){var t=this._normalizeIndexData(e),i=new ir;if(i.references=1,i.is32Bits=4===t.BYTES_PER_ELEMENT,i.nativeIndexBuffer=this._native.createIndexBuffer(t),i.nativeVertexBuffer===this.INVALID_HANDLE)throw new Error("Could not create a native index buffer.");return i},t.prototype.createVertexBuffer=function(e){var t=new ir;if(t.references=1,t.nativeVertexBuffer=this._native.createVertexBuffer(ArrayBuffer.isView(e)?e:new Float32Array(e)),t.nativeVertexBuffer===this.INVALID_HANDLE)throw new Error("Could not create a native vertex buffer.");return t},t.prototype.recordVertexArrayObject=function(e,t,i){var n=this._native.createVertexArray();t&&this._native.recordIndexBuffer(n,t.nativeIndexBuffer);for(var r=i.getAttributesNames(),o=0;o<r.length;o++){var a=i.getAttributeLocation(o);if(a>=0){var s=e[r[o]];if(s){var c=s.getBuffer();c&&this._native.recordVertexBuffer(n,c.nativeVertexBuffer,a,s.byteOffset,s.byteStride,s.getSize(),s.type,s.normalized)}}}return n},t.prototype.bindVertexArrayObject=function(e){this._native.bindVertexArray(e)},t.prototype.releaseVertexArrayObject=function(e){this._native.deleteVertexArray(e)},t.prototype.getAttributes=function(e,t){var i=e;return this._native.getAttributes(i.nativeProgram,t)},t.prototype.drawElementsType=function(e,t,i,n){this._drawCalls.addCount(1,!1),this._native.drawIndexed(e,t,i)},t.prototype.drawArraysType=function(e,t,i,n){this._drawCalls.addCount(1,!1),this._native.draw(e,t,i)},t.prototype.createPipelineContext=function(){return new tr},t.prototype._preparePipelineContext=function(e,t,i,n,r,o,a){var s=e;s.nativeProgram=n?this.createRawShaderProgram(e,t,i,void 0,a):this.createShaderProgram(e,t,i,o,void 0,a)},t.prototype._isRenderingStateCompiled=function(e){return!0},t.prototype._executeWhenRenderingStateIsCompiled=function(e,t){t()},t.prototype.createRawShaderProgram=function(e,t,i,n,r){throw void 0===r&&(r=null),new Error("Not Supported")},t.prototype.createShaderProgram=function(e,t,i,n,r,o){void 0===o&&(o=null),this.onBeforeShaderCompilationObservable.notifyObservers(this);var a=this._native.createProgram(li.a._ConcatenateShader(t,n),li.a._ConcatenateShader(i,n));return this.onAfterShaderCompilationObservable.notifyObservers(this),a},t.prototype._setProgram=function(e){this._currentProgram!==e&&(this._native.setProgram(e),this._currentProgram=e)},t.prototype._releaseEffect=function(e){},t.prototype._deletePipelineContext=function(e){},t.prototype.getUniforms=function(e,t){var i=e;return this._native.getUniforms(i.nativeProgram,t)},t.prototype.bindUniformBlock=function(e,t,i){throw new Error("Not Implemented")},t.prototype.bindSamplers=function(e){var t=e.getPipelineContext();this._setProgram(t.nativeProgram);for(var i=e.getSamplers(),n=0;n<i.length;n++){var r=e.getUniform(i[n]);r&&(this._boundUniforms[n]=r)}this._currentEffect=null},t.prototype.setMatrix=function(e,t){e&&this._native.setMatrix(e,t.toArray())},t.prototype.getRenderWidth=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._native.getRenderWidth()},t.prototype.getRenderHeight=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._native.getRenderHeight()},t.prototype.setViewport=function(e,t,i){this._cachedViewport=e,this._native.setViewPort(e.x,e.y,e.width,e.height)},t.prototype.setState=function(e,t,i,n){void 0===t&&(t=0),void 0===n&&(n=!1),this._native.setState(e,t,n)},t.prototype.setZOffset=function(e){this._native.setZOffset(e)},t.prototype.getZOffset=function(){return this._native.getZOffset()},t.prototype.setDepthBuffer=function(e){this._native.setDepthTest(e)},t.prototype.getDepthWrite=function(){return this._native.getDepthWrite()},t.prototype.setDepthWrite=function(e){this._native.setDepthWrite(e)},t.prototype.setColorWrite=function(e){this._native.setColorWrite(e),this._colorWrite=e},t.prototype.getColorWrite=function(){return this._colorWrite},t.prototype.setAlphaConstants=function(e,t,i,n){throw new Error("Setting alpha blend constant color not yet implemented.")},t.prototype.setAlphaMode=function(e,t){void 0===t&&(t=!1),this._alphaMode!==e&&(this._native.setBlendMode(e),t||this.setDepthWrite(e===g.a.ALPHA_DISABLE),this._alphaMode=e)},t.prototype.getAlphaMode=function(){return this._alphaMode},t.prototype.setInt=function(e,t){e&&this._native.setInt(e,t)},t.prototype.setIntArray=function(e,t){e&&this._native.setIntArray(e,t)},t.prototype.setIntArray2=function(e,t){e&&this._native.setIntArray2(e,t)},t.prototype.setIntArray3=function(e,t){e&&this._native.setIntArray3(e,t)},t.prototype.setIntArray4=function(e,t){e&&this._native.setIntArray4(e,t)},t.prototype.setFloatArray=function(e,t){e&&this._native.setFloatArray(e,t)},t.prototype.setFloatArray2=function(e,t){e&&this._native.setFloatArray2(e,t)},t.prototype.setFloatArray3=function(e,t){e&&this._native.setFloatArray3(e,t)},t.prototype.setFloatArray4=function(e,t){e&&this._native.setFloatArray4(e,t)},t.prototype.setArray=function(e,t){e&&this._native.setFloatArray(e,t)},t.prototype.setArray2=function(e,t){e&&this._native.setFloatArray2(e,t)},t.prototype.setArray3=function(e,t){e&&this._native.setFloatArray3(e,t)},t.prototype.setArray4=function(e,t){e&&this._native.setFloatArray4(e,t)},t.prototype.setMatrices=function(e,t){e&&this._native.setMatrices(e,t)},t.prototype.setMatrix3x3=function(e,t){e&&this._native.setMatrix3x3(e,t)},t.prototype.setMatrix2x2=function(e,t){e&&this._native.setMatrix2x2(e,t)},t.prototype.setFloat=function(e,t){e&&this._native.setFloat(e,t)},t.prototype.setFloat2=function(e,t,i){e&&this._native.setFloat2(e,t,i)},t.prototype.setFloat3=function(e,t,i,n){e&&this._native.setFloat3(e,t,i,n)},t.prototype.setFloat4=function(e,t,i,n,r){e&&this._native.setFloat4(e,t,i,n,r)},t.prototype.setColor3=function(e,t){e&&this._native.setFloat3(e,t.r,t.g,t.b)},t.prototype.setColor4=function(e,t,i){e&&this._native.setFloat4(e,t.r,t.g,t.b,i)},t.prototype.wipeCaches=function(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilState.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)},t.prototype._createTexture=function(){return this._native.createTexture()},t.prototype._deleteTexture=function(e){this._native.deleteTexture(e)},t.prototype.createTexture=function(e,t,i,n,r,o,a,s,c,l,u,h){var d=this;void 0===r&&(r=g.a.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===c&&(c=null),void 0===l&&(l=null),void 0===u&&(u=null);for(var f=String(e),p="data:"===f.substr(0,5),_="blob:"===f.substr(0,5),m=c||new tt.a(this,tt.b.Url),v=f.lastIndexOf("."),y=u||(v>-1?f.substring(v).toLowerCase():""),b=null,T=0,E=Oe.a._TextureLoaders;T<E.length;T++){var x=E[T];if(x.canLoad(y)){b=x;break}}n&&n._addPendingData(m),m.url=f,m.generateMipMaps=!t,m.samplingMode=r,m.invertY=i,this.doNotHandleContextLost||(m._buffer=s);var P=null;o&&!c&&(P=m.onLoadedObservable.add(o)),c||this._internalTexturesCache.push(m);if(b)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");var A=function(e,o){if("string"==typeof e)throw new Error("Loading textures from string data not yet implemented.");_&&!d.doNotHandleContextLost&&(m._buffer=e);var a=m._webGLTexture;if(a){if(!d._native.loadTexture(a,e,!t,i))throw new Error("Could not load a native texture.");m.baseWidth=d._native.getTextureWidth(a),m.baseHeight=d._native.getTextureHeight(a),m.width=m.baseWidth,m.height=m.baseHeight,m.isReady=!0;var s=d._getSamplingFilter(r);d._native.setTextureSampling(a,s),n&&n._removePendingData(m),m.onLoadedObservable.notifyObservers(m),m.onLoadedObservable.clear()}else n&&n._removePendingData(m)};if(s instanceof ArrayBuffer)A(s);else if(ArrayBuffer.isView(s))A(s.buffer);else{if(s instanceof Blob)throw new Error("Loading texture from Blob not yet implemented.");if(p)A(De.b.DecodeBase64(s));else{De.b.LoadFile(f,A,void 0,void 0,!0,function(e,o){!function(e,o){n&&n._removePendingData(m),P&&m.onLoadedObservable.remove(P),De.b.UseFallbackTexture&&d.createTexture(De.b.fallbackTexture,t,i,n,r,null,a,s,m),a&&a(e||"Unknown error",o)}("Failed to retrieve "+f+".",o)})}}return m},t.prototype.createCubeTexture=function(e,t,i,n,r,o,a,s,c,l,u,h){var d=this;void 0===r&&(r=null),void 0===o&&(o=null),void 0===s&&(s=null),void 0===c&&(c=!1),void 0===l&&(l=0),void 0===u&&(u=0),void 0===h&&(h=null);var f=h||new tt.a(this,tt.b.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!n,f._lodGenerationScale=l,f._lodGenerationOffset=u,this._doNotHandleContextLost||(f._extension=s,f._files=i);var p=e.lastIndexOf(".");if(".env"===(s||(p>-1?e.substring(p).toLowerCase():""))){if(i&&6===i.length)throw new Error("Multi-file loading not allowed on env files.");this._loadFile(e,function(e){return function(e){var t=qn.GetEnvInfo(e);if(f.width=t.width,f.height=t.width,qn.UploadEnvSpherical(f,t),1!==t.version)throw new Error('Unsupported babylon environment map version "'+t.version+'"');var i=t.specular;if(!i)throw new Error("Nothing else parsed so far");f._lodGenerationScale=i.lodGenerationScale;var n=qn.CreateImageDataArrayBufferViews(e,t);if(f.format=g.a.TEXTUREFORMAT_RGBA,f.type=g.a.TEXTURETYPE_UNSIGNED_INT,f.generateMipMaps=!0,f.getEngine().updateTextureSamplingMode(et.a.TRILINEAR_SAMPLINGMODE,f),f._isRGBD=!0,f.invertY=!0,!d._native.loadEnvTexture(f._webGLTexture,n))throw new Error("Could not load a native cube texture.");f.isReady=!0,r&&r()}(new Uint8Array(e))},void 0,void 0,!0,function(e,t){o&&e&&o(e.status+" "+e.statusText,t)})}else{if(!i||6!==i.length)throw new Error("Cannot load cubemap because 6 files were not defined");var _=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(_.map(function(e){return De.b.LoadFileAsync(e).then(function(e){return new Uint8Array(e)})})).then(function(e){d._native.loadCubeTexture(f._webGLTexture,e,!n)}).then(function(){f.isReady=!0,r&&r()},function(e){o&&o("Failed to load cubemap: "+e.message,e)})}return this._internalTexturesCache.push(f),f},t.prototype._getSamplingFilter=function(e){switch(e){case g.a.TEXTURE_BILINEAR_SAMPLINGMODE:return nr.MINLINEAR_MAGLINEAR_MIPPOINT;case g.a.TEXTURE_TRILINEAR_SAMPLINGMODE:return nr.MINLINEAR_MAGLINEAR_MIPLINEAR;case g.a.TEXTURE_NEAREST_SAMPLINGMODE:return nr.MINPOINT_MAGPOINT_MIPLINEAR;case g.a.TEXTURE_NEAREST_NEAREST_MIPNEAREST:return nr.MINPOINT_MAGPOINT_MIPPOINT;case g.a.TEXTURE_NEAREST_LINEAR_MIPNEAREST:return nr.MINLINEAR_MAGPOINT_MIPPOINT;case g.a.TEXTURE_NEAREST_LINEAR_MIPLINEAR:case g.a.TEXTURE_NEAREST_LINEAR:return nr.MINLINEAR_MAGPOINT_MIPLINEAR;case g.a.TEXTURE_NEAREST_NEAREST:return nr.MINPOINT_MAGPOINT_MIPPOINT;case g.a.TEXTURE_LINEAR_NEAREST_MIPNEAREST:return nr.MINPOINT_MAGLINEAR_MIPPOINT;case g.a.TEXTURE_LINEAR_NEAREST_MIPLINEAR:return nr.MINPOINT_MAGLINEAR_MIPLINEAR;case g.a.TEXTURE_LINEAR_LINEAR:return nr.MINLINEAR_MAGLINEAR_MIPLINEAR;case g.a.TEXTURE_LINEAR_NEAREST:return nr.MINPOINT_MAGLINEAR_MIPLINEAR;default:throw new Error("Unexpected sampling mode: "+e+".")}},t._GetNativeTextureFormat=function(e,t){if(e==g.a.TEXTUREFORMAT_RGBA&&t==g.a.TEXTURETYPE_UNSIGNED_INT)return ar.RGBA8;if(e==g.a.TEXTUREFORMAT_RGBA&&t==g.a.TEXTURETYPE_FLOAT)return ar.RGBA32F;throw new Error("Unexpected texture format or type: format "+e+", type "+t+".")},t.prototype.createRenderTargetTexture=function(e,i){var n=new ci.a;void 0!==i&&"object"==typeof i?(n.generateMipMaps=i.generateMipMaps,n.generateDepthBuffer=void 0===i.generateDepthBuffer||i.generateDepthBuffer,n.generateStencilBuffer=n.generateDepthBuffer&&i.generateStencilBuffer,n.type=void 0===i.type?g.a.TEXTURETYPE_UNSIGNED_INT:i.type,n.samplingMode=void 0===i.samplingMode?g.a.TEXTURE_TRILINEAR_SAMPLINGMODE:i.samplingMode,n.format=void 0===i.format?g.a.TEXTUREFORMAT_RGBA:i.format):(n.generateMipMaps=i,n.generateDepthBuffer=!0,n.generateStencilBuffer=!1,n.type=g.a.TEXTURETYPE_UNSIGNED_INT,n.samplingMode=g.a.TEXTURE_TRILINEAR_SAMPLINGMODE,n.format=g.a.TEXTUREFORMAT_RGBA),(n.type!==g.a.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(n.type!==g.a.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(n.samplingMode=g.a.TEXTURE_NEAREST_SAMPLINGMODE);var r=new sr(this,tt.b.RenderTarget),o=e.width||e,a=e.height||e;n.type!==g.a.TEXTURETYPE_FLOAT||this._caps.textureFloat||(n.type=g.a.TEXTURETYPE_UNSIGNED_INT,m.a.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"));var s=this._native.createFramebuffer(r._webGLTexture,o,a,t._GetNativeTextureFormat(n.format,n.type),n.samplingMode,!!n.generateStencilBuffer,n.generateDepthBuffer,!!n.generateMipMaps);return r._framebuffer=s,r.baseWidth=o,r.baseHeight=a,r.width=o,r.height=a,r.isReady=!0,r.samples=1,r.generateMipMaps=!!n.generateMipMaps,r.samplingMode=n.samplingMode,r.type=n.type,r.format=n.format,r._generateDepthBuffer=n.generateDepthBuffer,r._generateStencilBuffer=!!n.generateStencilBuffer,this._internalTexturesCache.push(r),r},t.prototype.updateTextureSamplingMode=function(e,t){if(t._webGLTexture){var i=this._getSamplingFilter(e);this._native.setTextureSampling(t._webGLTexture,i)}t.samplingMode=e},t.prototype.bindFramebuffer=function(e,t,i,n,r){if(t)throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||n)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");if(r)throw new Error("forceFullscreenViewport for frame buffers not yet supported in NativeEngine.");this._bindUnboundFramebuffer(e._framebuffer)},t.prototype.unBindFramebuffer=function(e,t,i){void 0===t&&(t=!1),t&&m.a.Warn("Disabling mipmap generation not yet supported in NativeEngine. Ignoring."),i&&i(),this._bindUnboundFramebuffer(null)},t.prototype.createDynamicVertexBuffer=function(e){throw new Error("createDynamicVertexBuffer not yet implemented.")},t.prototype.updateDynamicIndexBuffer=function(e,t,i){throw void 0===i&&(i=0),new Error("updateDynamicIndexBuffer not yet implemented.")},t.prototype.updateDynamicVertexBuffer=function(e,t,i,n){throw new Error("updateDynamicVertexBuffer not yet implemented.")},t.prototype._setTexture=function(e,t,i,n){void 0===i&&(i=!1),void 0===n&&(n=!1);var r,o=this._boundUniforms[e];if(!o)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._native.setTexture(o,null)),!1;if(t.video)this._activeChannel=e,t.update();else if(t.delayLoadState===g.a.DELAYLOADSTATE_NOTLOADED)return t.delayLoad(),!1;return r=n?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!(!r||!r._webGLTexture)&&(this._native.setTextureWrapMode(r._webGLTexture,this._getAddressMode(t.wrapU),this._getAddressMode(t.wrapV),this._getAddressMode(t.wrapR)),this._updateAnisotropicLevel(t),this._native.setTexture(o,r._webGLTexture),!0)},t.prototype._updateAnisotropicLevel=function(e){var t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._webGLTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._native.setTextureAnisotropicLevel(t._webGLTexture,i),t._cachedAnisotropicFilteringLevel=i)},t.prototype._getAddressMode=function(e){switch(e){case g.a.TEXTURE_WRAP_ADDRESSMODE:return or.WRAP;case g.a.TEXTURE_CLAMP_ADDRESSMODE:return or.CLAMP;case g.a.TEXTURE_MIRROR_ADDRESSMODE:return or.MIRROR;default:throw new Error("Unexpected wrap mode: "+e+".")}},t.prototype._bindTexture=function(e,t){throw new Error("_bindTexture not implemented.")},t.prototype._deleteBuffer=function(e){e.nativeIndexBuffer&&(this._native.deleteIndexBuffer(e.nativeIndexBuffer),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._native.deleteVertexBuffer(e.nativeVertexBuffer),delete e.nativeVertexBuffer)},t.prototype.releaseEffects=function(){},t.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,n,r,o,a){throw void 0===o&&(o=0),void 0===a&&(a=0),new Error("_uploadCompressedDataToTextureDirectly not implemented.")},t.prototype._uploadDataToTextureDirectly=function(e,t,i,n){throw void 0===i&&(i=0),void 0===n&&(n=0),new Error("_uploadDataToTextureDirectly not implemented.")},t.prototype._uploadArrayBufferViewToTexture=function(e,t,i,n){throw void 0===i&&(i=0),void 0===n&&(n=0),new Error("_uploadArrayBufferViewToTexture not implemented.")},t.prototype._uploadImageToTexture=function(e,t,i,n){throw void 0===i&&(i=0),void 0===n&&(n=0),new Error("_uploadArrayBufferViewToTexture not implemented.")},t}(Oe.a),lr=function(){function e(){}return e.COPY=1,e.CUT=2,e.PASTE=3,e}(),ur=function(){function e(e,t){this.type=e,this.event=t}return e.GetTypeFromCharacter=function(e){switch(e){case 67:return lr.COPY;case 86:return lr.PASTE;case 88:return lr.CUT;default:return-1}},e}(),hr=i(76),dr=i(67),fr=function(){function e(e,t,i){this.lengthComputable=e,this.loaded=t,this.total=i}return e.FromProgressEvent=function(t){return new e(t.lengthComputable,t.loaded,t.total)},e}();!function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(Zn||(Zn={}));var pr=function(){function e(){}return Object.defineProperty(e,"ForceFullSceneLoadingForIncremental",{get:function(){return dr.a.ForceFullSceneLoadingForIncremental},set:function(e){dr.a.ForceFullSceneLoadingForIncremental=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"ShowLoadingScreen",{get:function(){return dr.a.ShowLoadingScreen},set:function(e){dr.a.ShowLoadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"loggingLevel",{get:function(){return dr.a.loggingLevel},set:function(e){dr.a.loggingLevel=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CleanBoneMatrixWeights",{get:function(){return dr.a.CleanBoneMatrixWeights},set:function(e){dr.a.CleanBoneMatrixWeights=e},enumerable:!0,configurable:!0}),e._getDefaultPlugin=function(){return e._registeredPlugins[".babylon"]},e._getPluginForExtension=function(t){var i=e._registeredPlugins[t];return i||(m.a.Warn("Unable to find a plugin to load "+t+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type"),e._getDefaultPlugin())},e._getPluginForDirectLoad=function(t){for(var i in e._registeredPlugins){var n=e._registeredPlugins[i].plugin;if(n.canDirectLoad&&n.canDirectLoad(t))return e._registeredPlugins[i]}return e._getDefaultPlugin()},e._getPluginForFilename=function(t){var i=t.indexOf("?");-1!==i&&(t=t.substring(0,i));var n=t.lastIndexOf("."),r=t.substring(n,t.length).toLowerCase();return e._getPluginForExtension(r)},e._getDirectLoad=function(e){return"data:"===e.substr(0,5)?e.substr(5):null},e._loadData=function(t,i,n,r,o,a,s){var c,l=e._getDirectLoad(t.name),u=s?e._getPluginForExtension(s):l?e._getPluginForDirectLoad(t.name):e._getPluginForFilename(t.name);if(!(c=u.plugin.createPlugin?u.plugin.createPlugin():u.plugin))throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(e.OnPluginActivatedObservable.notifyObservers(c),l)return n(c,c.directLoad?c.directLoad(i,l):l),c;var h=u.isBinary,d=function(e,t){i.isDisposed?o("Scene has been disposed"):n(c,e,t)},f=null,p=!1,_=c.onDisposeObservable;_&&_.add(function(){p=!0,f&&(f.abort(),f=null),a()});var m=r?function(e){r(fr.FromProgressEvent(e))}:void 0,g=function(){if(!p){var e=function(e,t){d(e,t?t.responseURL:void 0)},n=function(e){o(e.message,e)};f=c.requestFile?c.requestFile(i,t.url,e,m,h,n):i._requestFile(t.url,e,m,!0,h,n)}},v=t.file||hr.a.FilesToLoad[t.name.toLowerCase()];if(-1===t.rootUrl.indexOf("file:")||-1!==t.rootUrl.indexOf("file:")&&!v){var y=i.getEngine(),b=y.enableOfflineSupport;if(b){for(var T=!1,E=0,x=i.disableOfflineSupportExceptionRules;E<x.length;E++){if(x[E].test(t.url)){T=!0;break}}b=!T}b&&Oe.a.OfflineProviderFactory?i.offlineProvider=Oe.a.OfflineProviderFactory(t.url,g,y.disableManifestCheck):g()}else if(v){var P=function(e){o(e.message,e)};f=c.readFile?c.readFile(i,v,d,m,h,P):i._readFile(v,d,m,h,P)}else o("Unable to find file named "+t.name);return c},e._getFileInfo=function(e,t){var i,n,r=null;if(t)if(t.name){var o=t;i=e+o.name,n=o.name,r=o}else{var a=t;if("/"===a.substr(0,1))return De.b.Error("Wrong sceneFilename parameter"),null;i=e+a,n=a}else i=e,n=De.b.GetFilename(e),e=De.b.GetFolderPath(e);return{url:i,rootUrl:e,name:n,file:r}},e.GetPluginForExtension=function(t){return e._getPluginForExtension(t).plugin},e.IsPluginForExtensionAvailable=function(t){return!!e._registeredPlugins[t]},e.RegisterPlugin=function(t){if("string"==typeof t.extensions){var i=t.extensions;e._registeredPlugins[i.toLowerCase()]={plugin:t,isBinary:!1}}else{var n=t.extensions;Object.keys(n).forEach(function(i){e._registeredPlugins[i.toLowerCase()]={plugin:t,isBinary:n[i].isBinary}})}},e.ImportMesh=function(t,i,n,r,o,a,s,c){if(void 0===n&&(n=""),void 0===r&&(r=R.a.LastCreatedScene),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===c&&(c=null),!r)return m.a.Error("No scene available to import mesh to"),null;var l=e._getFileInfo(i,n);if(!l)return null;var u={};r._addPendingData(u);var h=function(){r._removePendingData(u)},d=function(e,t){var i="Unable to import meshes from "+l.url+": "+e;s?s(r,i,t):m.a.Error(i),h()},f=a?function(e){try{a(e)}catch(e){d("Error in onProgress callback: "+e,e)}}:void 0,p=function(e,t,i,n){if(r.importedMeshesFiles.push(l.url),o)try{o(e,t,i,n)}catch(e){d("Error in onSuccess callback: "+e,e)}r._removePendingData(u)};return e._loadData(l,r,function(e,i,n){if(e.rewriteRootURL&&(l.rootUrl=e.rewriteRootURL(l.rootUrl,n)),e.importMesh){var o=e,a=new Array,s=new Array,c=new Array;if(!o.importMesh(t,r,i,l.rootUrl,a,s,c,d))return;r.loadingPluginName=e.name,p(a,s,c,[])}else{e.importMeshAsync(t,r,i,l.rootUrl,f,l.name).then(function(t){r.loadingPluginName=e.name,p(t.meshes,t.particleSystems,t.skeletons,t.animationGroups)}).catch(function(e){d(e.message,e)})}},f,d,h,c)},e.ImportMeshAsync=function(t,i,n,r,o,a){return void 0===n&&(n=""),void 0===r&&(r=R.a.LastCreatedScene),void 0===o&&(o=null),void 0===a&&(a=null),new Promise(function(s,c){e.ImportMesh(t,i,n,r,function(e,t,i,n){s({meshes:e,particleSystems:t,skeletons:i,animationGroups:n})},o,function(e,t,i){c(i||new Error(t))},a)})},e.Load=function(t,i,n,r,o,a,s){return void 0===i&&(i=""),void 0===n&&(n=R.a.LastCreatedEngine),void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),n?e.Append(t,i,new K.a(n),r,o,a,s):(De.b.Error("No engine available"),null)},e.LoadAsync=function(t,i,n,r,o){return void 0===i&&(i=""),void 0===n&&(n=R.a.LastCreatedEngine),void 0===r&&(r=null),void 0===o&&(o=null),new Promise(function(a,s){e.Load(t,i,n,function(e){a(e)},r,function(e,t,i){s(i||new Error(t))},o)})},e.Append=function(t,i,n,r,o,a,s){if(void 0===i&&(i=""),void 0===n&&(n=R.a.LastCreatedScene),void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),!n)return m.a.Error("No scene available to append to"),null;var c=e._getFileInfo(t,i);if(!c)return null;e.ShowLoadingScreen&&n.getEngine().displayLoadingUI();var l={};n._addPendingData(l);var u=function(){n._removePendingData(l),n.getEngine().hideLoadingUI()},h=function(e,t){var i="Unable to load from "+c.url+(e?": "+e:"");a?a(n,i,t):m.a.Error(i),u()},d=o?function(e){try{o(e)}catch(e){h("Error in onProgress callback",e)}}:void 0,f=function(){if(r)try{r(n)}catch(e){h("Error in onSuccess callback",e)}n._removePendingData(l)};return e._loadData(c,n,function(t,i){if(t.load){if(!t.load(n,i,c.rootUrl,h))return;n.loadingPluginName=t.name,f()}else{t.loadAsync(n,i,c.rootUrl,d,c.name).then(function(){n.loadingPluginName=t.name,f()}).catch(function(e){h(e.message,e)})}e.ShowLoadingScreen&&n.executeWhenReady(function(){n.getEngine().hideLoadingUI()})},d,h,u,s)},e.AppendAsync=function(t,i,n,r,o){return void 0===i&&(i=""),void 0===n&&(n=R.a.LastCreatedScene),void 0===r&&(r=null),void 0===o&&(o=null),new Promise(function(a,s){e.Append(t,i,n,function(e){a(e)},r,function(e,t,i){s(i||new Error(t))},o)})},e.LoadAssetContainer=function(t,i,n,r,o,a,s){if(void 0===i&&(i=""),void 0===n&&(n=R.a.LastCreatedScene),void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),!n)return m.a.Error("No scene available to load asset container to"),null;var c=e._getFileInfo(t,i);if(!c)return null;var l={};n._addPendingData(l);var u=function(){n._removePendingData(l)},h=function(e,t){var i="Unable to load assets from "+c.url+(e?": "+e:"");t&&t.message&&(i+=" ("+t.message+")"),a?a(n,i,t):m.a.Error(i),u()},d=o?function(e){try{o(e)}catch(e){h("Error in onProgress callback",e)}}:void 0,f=function(e){if(r)try{r(e)}catch(e){h("Error in onSuccess callback",e)}n._removePendingData(l)};return e._loadData(c,n,function(t,i){if(t.loadAssetContainer){var r=t.loadAssetContainer(n,i,c.rootUrl,h);if(!r)return;n.loadingPluginName=t.name,f(r)}else if(t.loadAssetContainerAsync){t.loadAssetContainerAsync(n,i,c.rootUrl,d,c.name).then(function(e){n.loadingPluginName=t.name,f(e)}).catch(function(e){h(e.message,e)})}else h("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");e.ShowLoadingScreen&&n.executeWhenReady(function(){n.getEngine().hideLoadingUI()})},d,h,u,s)},e.LoadAssetContainerAsync=function(t,i,n,r,o){return void 0===i&&(i=""),void 0===n&&(n=R.a.LastCreatedScene),void 0===r&&(r=null),void 0===o&&(o=null),new Promise(function(a,s){e.LoadAssetContainer(t,i,n,function(e){a(e)},r,function(e,t,i){s(i||new Error(t))},o)})},e.ImportAnimations=function(e,t,i,n,r,o,a,s,c){if(void 0===t&&(t=""),void 0===i&&(i=R.a.LastCreatedScene),void 0===n&&(n=!0),void 0===r&&(r=Zn.Clean),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===c&&(c=null),i){if(n){for(var l=0,u=i.animatables;l<u.length;l++){u[l].reset()}i.stopAllAnimations(),i.animationGroups.slice().forEach(function(e){e.dispose()}),i.getNodes().forEach(function(e){e.animations&&(e.animations=[])})}else switch(r){case Zn.Clean:i.animationGroups.slice().forEach(function(e){e.dispose()});break;case Zn.Stop:i.animationGroups.forEach(function(e){e.stop()});break;case Zn.Sync:i.animationGroups.forEach(function(e){e.reset(),e.restart()});break;case Zn.NoSync:break;default:return void m.a.Error("Unknown animation group loading mode value '"+r+"'")}var h=i.animatables.length;this.LoadAssetContainer(e,t,i,function(e){e.mergeAnimationsTo(i,i.animatables.slice(h),o),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),a&&a(i)},s,c)}else m.a.Error("No scene available to load animations to")},e.ImportAnimationsAsync=function(t,i,n,r,o,a,s,c,l){return void 0===i&&(i=""),void 0===n&&(n=R.a.LastCreatedScene),void 0===r&&(r=!0),void 0===o&&(o=Zn.Clean),void 0===a&&(a=null),void 0===s&&(s=null),void 0===c&&(c=null),void 0===l&&(l=null),new Promise(function(s,l){e.ImportAnimations(t,i,n,r,o,a,function(e){s(e)},c,function(e,t,i){l(i||new Error(t))})})},e.NO_LOGGING=g.a.SCENELOADER_NO_LOGGING,e.MINIMAL_LOGGING=g.a.SCENELOADER_MINIMAL_LOGGING,e.SUMMARY_LOGGING=g.a.SCENELOADER_SUMMARY_LOGGING,e.DETAILED_LOGGING=g.a.SCENELOADER_DETAILED_LOGGING,e.OnPluginActivatedObservable=new o.c,e._registeredPlugins={},e}(),_r=function(e){function t(t){var i=e.call(this,t)||this;return i.controllerType=Gt.DAYDREAM,i}return Object(h.d)(t,e),t.prototype.initControllerMesh=function(e,i){var n=this;pr.ImportMesh("",t.MODEL_BASE_URL,t.MODEL_FILENAME,e,function(e){n._defaultModel=e[1],n.attachToMesh(n._defaultModel),i&&i(n._defaultModel)})},t.prototype._handleButtonChange=function(e,t,i){if(0===e){var n=this.onTriggerStateChangedObservable;n&&n.notifyObservers(t)}else m.a.Warn("Unrecognized Daydream button index: "+e)},t.MODEL_BASE_URL="https://controllers.babylonjs.com/generic/",t.MODEL_FILENAME="generic.babylon",t.GAMEPAD_ID_PREFIX="Daydream",t}(Hi);Qt._ControllerFactories.push({canCreate:function(e){return 0===e.id.indexOf(_r.GAMEPAD_ID_PREFIX)},create:function(e){return new _r(e)}});var mr=function(e){function t(t){var i=e.call(this,t)||this;return i._buttonIndexToObservableNameMap=["onPadStateChangedObservable","onTriggerStateChangedObservable"],i.controllerType=Gt.GEAR_VR,i._calculatedPosition=new a.e("left"==i.hand?-.15:.15,-.5,.25),i._disableTrackPosition(i._calculatedPosition),i}return Object(h.d)(t,e),t.prototype.initControllerMesh=function(e,i){var n=this;pr.ImportMesh("",t.MODEL_BASE_URL,t.MODEL_FILENAME,e,function(t){var r=new Ae.a("",e);t[1].parent=r,t[1].position.z=-.15,n._defaultModel=r,n.attachToMesh(n._defaultModel),i&&i(n._defaultModel)})},t.prototype._handleButtonChange=function(e,t,i){if(e<this._buttonIndexToObservableNameMap.length){var n=this[this._buttonIndexToObservableNameMap[e]];n&&n.notifyObservers(t)}},t.MODEL_BASE_URL="https://controllers.babylonjs.com/generic/",t.MODEL_FILENAME="generic.babylon",t.GAMEPAD_ID_PREFIX="Gear VR",t}(Hi);Qt._ControllerFactories.push({canCreate:function(e){return 0===e.id.indexOf(mr.GAMEPAD_ID_PREFIX)||-1!==e.id.indexOf("Oculus Go")||-1!==e.id.indexOf("Vive Focus")},create:function(e){return new mr(e)}});var gr=function(e){function t(t){return e.call(this,t)||this}return Object(h.d)(t,e),t.prototype.initControllerMesh=function(e,i){var n=this;pr.ImportMesh("",t.MODEL_BASE_URL,t.MODEL_FILENAME,e,function(e){n._defaultModel=e[1],n.attachToMesh(n._defaultModel),i&&i(n._defaultModel)})},t.prototype._handleButtonChange=function(e,t,i){console.log("Button id: "+e+"state: "),console.dir(t)},t.MODEL_BASE_URL="https://controllers.babylonjs.com/generic/",t.MODEL_FILENAME="generic.babylon",t}(Hi);Qt._DefaultControllerFactory=function(e){return new gr(e)};var vr=function(e){function t(t){var i=e.call(this,t)||this;return i.onSecondaryTriggerStateChangedObservable=new o.c,i.onThumbRestChangedObservable=new o.c,i.controllerType=Gt.OCULUS,i}return Object(h.d)(t,e),t.prototype.initControllerMesh=function(e,i){var n,r=this;n="left"===this.hand?t.MODEL_LEFT_FILENAME:t.MODEL_RIGHT_FILENAME,pr.ImportMesh("",t._IsQuest?t.QUEST_MODEL_BASE_URL:t.MODEL_BASE_URL,n,e,function(e){r._defaultModel=t._IsQuest?e[0]:e[1],r.attachToMesh(r._defaultModel),i&&i(r._defaultModel)})},Object.defineProperty(t.prototype,"onAButtonStateChangedObservable",{get:function(){if("right"===this.hand)return this.onMainButtonStateChangedObservable;throw new Error("No A button on left hand")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBButtonStateChangedObservable",{get:function(){if("right"===this.hand)return this.onSecondaryButtonStateChangedObservable;throw new Error("No B button on left hand")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onXButtonStateChangedObservable",{get:function(){if("left"===this.hand)return this.onMainButtonStateChangedObservable;throw new Error("No X button on right hand")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onYButtonStateChangedObservable",{get:function(){if("left"===this.hand)return this.onSecondaryButtonStateChangedObservable;throw new Error("No Y button on right hand")},enumerable:!0,configurable:!0}),t.prototype._handleButtonChange=function(e,i,n){var r=i,o="right"===this.hand?-1:1;switch(e){case 0:return void this.onPadStateChangedObservable.notifyObservers(r);case 1:return!t._IsQuest&&this._defaultModel&&(this._defaultModel.getChildren()[3].rotation.x=.2*-r.value,this._defaultModel.getChildren()[3].position.y=.005*-r.value,this._defaultModel.getChildren()[3].position.z=.005*-r.value),void this.onTriggerStateChangedObservable.notifyObservers(r);case 2:return!t._IsQuest&&this._defaultModel&&(this._defaultModel.getChildren()[4].position.x=o*r.value*.0035),void this.onSecondaryTriggerStateChangedObservable.notifyObservers(r);case 3:return!t._IsQuest&&this._defaultModel&&(r.pressed?this._defaultModel.getChildren()[1].position.y=-.001:this._defaultModel.getChildren()[1].position.y=0),void this.onMainButtonStateChangedObservable.notifyObservers(r);case 4:return!t._IsQuest&&this._defaultModel&&(r.pressed?this._defaultModel.getChildren()[2].position.y=-.001:this._defaultModel.getChildren()[2].position.y=0),void this.onSecondaryButtonStateChangedObservable.notifyObservers(r);case 5:return void this.onThumbRestChangedObservable.notifyObservers(r)}},t.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",t.MODEL_LEFT_FILENAME="left.babylon",t.MODEL_RIGHT_FILENAME="right.babylon",t.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",t._IsQuest=!1,t}(Hi);Qt._ControllerFactories.push({canCreate:function(e){return Oe.a.LastCreatedEngine&&Oe.a.LastCreatedEngine._vrDisplay&&"Oculus Quest"===Oe.a.LastCreatedEngine._vrDisplay.displayName&&(vr._IsQuest=!0),-1!==e.id.indexOf("Oculus Touch")},create:function(e){return new vr(e)}});var yr=function(e){function t(t){var i=e.call(this,t)||this;return i.controllerType=Gt.VIVE,i._invertLeftStickY=!0,i}return Object(h.d)(t,e),t.prototype.initControllerMesh=function(e,i){var n=this;pr.ImportMesh("",t.MODEL_BASE_URL,t.MODEL_FILENAME,e,function(e){n._defaultModel=e[1],n.attachToMesh(n._defaultModel),i&&i(n._defaultModel)})},Object.defineProperty(t.prototype,"onLeftButtonStateChangedObservable",{get:function(){return this.onMainButtonStateChangedObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onRightButtonStateChangedObservable",{get:function(){return this.onMainButtonStateChangedObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onMenuButtonStateChangedObservable",{get:function(){return this.onSecondaryButtonStateChangedObservable},enumerable:!0,configurable:!0}),t.prototype._handleButtonChange=function(e,t,i){var n=t;switch(e){case 0:return void this.onPadStateChangedObservable.notifyObservers(n);case 1:return this._defaultModel&&(this._defaultModel.getChildren()[6].rotation.x=.15*-n.value),void this.onTriggerStateChangedObservable.notifyObservers(n);case 2:return void this.onMainButtonStateChangedObservable.notifyObservers(n);case 3:return this._defaultModel&&(n.pressed?this._defaultModel.getChildren()[2].position.y=-.001:this._defaultModel.getChildren()[2].position.y=0),void this.onSecondaryButtonStateChangedObservable.notifyObservers(n)}},t.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",t.MODEL_FILENAME="wand.babylon",t}(Hi);Qt._ControllerFactories.push({canCreate:function(e){return-1!==e.id.toLowerCase().indexOf("openvr")},create:function(e){return new yr(e)}});var br=function(){this.buttonMeshes={},this.axisMeshes={}},Tr=function(e){function t(t){var i=e.call(this,t)||this;return i._mapping={buttons:["thumbstick","trigger","grip","menu","trackpad"],buttonMeshNames:{trigger:"SELECT",menu:"MENU",grip:"GRASP",thumbstick:"THUMBSTICK_PRESS",trackpad:"TOUCHPAD_PRESS"},buttonObservableNames:{trigger:"onTriggerStateChangedObservable",menu:"onSecondaryButtonStateChangedObservable",grip:"onMainButtonStateChangedObservable",thumbstick:"onPadStateChangedObservable",trackpad:"onTrackpadChangedObservable"},axisMeshNames:["THUMBSTICK_X","THUMBSTICK_Y","TOUCHPAD_TOUCH_X","TOUCHPAD_TOUCH_Y"],pointingPoseMeshName:qt.POINTING_POSE},i.onTrackpadChangedObservable=new o.c,i.onTrackpadValuesChangedObservable=new o.c,i.trackpad={x:0,y:0},i.controllerType=Gt.WINDOWS,i._loadedMeshInfo=null,i}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"onTriggerButtonStateChangedObservable",{get:function(){return this.onTriggerStateChangedObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onMenuButtonStateChangedObservable",{get:function(){return this.onSecondaryButtonStateChangedObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onGripButtonStateChangedObservable",{get:function(){return this.onMainButtonStateChangedObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onThumbstickButtonStateChangedObservable",{get:function(){return this.onPadStateChangedObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onTouchpadButtonStateChangedObservable",{get:function(){return this.onTrackpadChangedObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onTouchpadValuesChangedObservable",{get:function(){return this.onTrackpadValuesChangedObservable},enumerable:!0,configurable:!0}),t.prototype._updateTrackpad=function(){!this.browserGamepad.axes||this.browserGamepad.axes[2]==this.trackpad.x&&this.browserGamepad.axes[3]==this.trackpad.y||(this.trackpad.x=this.browserGamepad.axes[this._mapping.axisMeshNames.indexOf("TOUCHPAD_TOUCH_X")],this.trackpad.y=this.browserGamepad.axes[this._mapping.axisMeshNames.indexOf("TOUCHPAD_TOUCH_Y")],this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad))},t.prototype.update=function(){if(e.prototype.update.call(this),this.browserGamepad.axes&&(this._updateTrackpad(),this._loadedMeshInfo))for(var t=0;t<this._mapping.axisMeshNames.length;t++)this._lerpAxisTransform(t,this.browserGamepad.axes[t])},t.prototype._handleButtonChange=function(e,t,i){var n=this._mapping.buttons[e];if(n){this._updateTrackpad();var r=this[this._mapping.buttonObservableNames[n]];r&&r.notifyObservers(t),this._lerpButtonTransform(n,t.value)}},t.prototype._lerpButtonTransform=function(e,t){if(this._loadedMeshInfo){var i=this._loadedMeshInfo.buttonMeshes[e];i&&i.unpressed.rotationQuaternion&&i.pressed.rotationQuaternion&&i.value.rotationQuaternion&&(a.b.SlerpToRef(i.unpressed.rotationQuaternion,i.pressed.rotationQuaternion,t,i.value.rotationQuaternion),a.e.LerpToRef(i.unpressed.position,i.pressed.position,t,i.value.position))}},t.prototype._lerpAxisTransform=function(e,t){if(this._loadedMeshInfo){var i=this._loadedMeshInfo.axisMeshes[e];if(i&&i.min.rotationQuaternion&&i.max.rotationQuaternion&&i.value.rotationQuaternion){var n=.5*t+.5;a.b.SlerpToRef(i.min.rotationQuaternion,i.max.rotationQuaternion,n,i.value.rotationQuaternion),a.e.LerpToRef(i.min.position,i.max.position,n,i.value.position)}}},t.prototype.initControllerMesh=function(e,i,n){var r,o,a=this;if(void 0===n&&(n=!1),pr.IsPluginForExtensionAvailable(".glb")){var s="default";if(this.id&&!n){var c=this.id.match(t.GAMEPAD_ID_PATTERN);s=c&&c[0]||s}o="left"===this.hand?t.MODEL_LEFT_FILENAME:t.MODEL_RIGHT_FILENAME,r=t.MODEL_BASE_URL+s+"/"}else m.a.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models"),r=gr.MODEL_BASE_URL,o=gr.MODEL_FILENAME;pr.ImportMesh("",r,o,e,function(t){a._loadedMeshInfo=a.processModel(e,t),a._loadedMeshInfo&&(a._defaultModel=a._loadedMeshInfo.rootNode,a.attachToMesh(a._defaultModel),i&&i(a._defaultModel))},null,function(e,t){m.a.Log(t),m.a.Warn("Failed to retrieve controller model from the remote server: "+r+o),n||a.initControllerMesh(e,i,!0)})},t.prototype.processModel=function(e,t){for(var i=null,n=new Ae.a(this.id+" "+this.hand,e),r=null,o=0;o<t.length;o++){var a=t[o];if(!a.parent){a.isPickable=!1,r=a;break}}return r?(r.setParent(n),i=this.createMeshInfo(n)):m.a.Warn("Could not find root node in model file."),i},t.prototype.createMeshInfo=function(e){var t,i=new br;for(i.rootNode=e,i.buttonMeshes={},i.axisMeshes={},t=0;t<this._mapping.buttons.length;t++){var n=this._mapping.buttonMeshNames[this._mapping.buttons[t]];if(n){var r=l(e,n);if(r){var o={index:t,value:u(r,"VALUE"),pressed:u(r,"PRESSED"),unpressed:u(r,"UNPRESSED")};o.value&&o.pressed&&o.unpressed?i.buttonMeshes[this._mapping.buttons[t]]=o:m.a.Warn("Missing button submesh under mesh with name: "+n+"(VALUE: "+!!o.value+", PRESSED: "+!!o.pressed+", UNPRESSED:"+!!o.unpressed+")")}else m.a.Warn("Missing button mesh with name: "+n)}else m.a.Log("Skipping unknown button at index: "+t+" with mapped name: "+this._mapping.buttons[t])}for(t=0;t<this._mapping.axisMeshNames.length;t++){var a=this._mapping.axisMeshNames[t];if(a){var s=l(e,a);if(s){var c={index:t,value:u(s,"VALUE"),min:u(s,"MIN"),max:u(s,"MAX")};c.value&&c.min&&c.max?i.axisMeshes[t]=c:m.a.Warn("Missing axis submesh under mesh with name: "+a+"(VALUE: "+!!c.value+", MIN: "+!!c.min+", MAX:"+!!c.max+")")}else m.a.Warn("Missing axis mesh with name: "+a)}else m.a.Log("Skipping unknown axis at index: "+t)}return i.pointingPoseNode=l(e,this._mapping.pointingPoseMeshName),i.pointingPoseNode?this._pointingPoseNode=i.pointingPoseNode:m.a.Warn("Missing pointing pose mesh with name: "+this._mapping.pointingPoseMeshName),i;function l(e,t){return e.getChildren(function(e){return e.name===t},!1)[0]}function u(e,t){return e.getChildren(function(e){return e.name==t},!0)[0]}},t.prototype.getForwardRay=function(t){if(void 0===t&&(t=100),!this._loadedMeshInfo||!this._loadedMeshInfo.pointingPoseNode)return e.prototype.getForwardRay.call(this,t);var i=this._loadedMeshInfo.pointingPoseNode.getWorldMatrix(),n=i.getTranslation(),r=new a.e(0,0,-1),o=a.e.TransformNormal(r,i),s=a.e.Normalize(o);return new Ht.a(n,s,t)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onTrackpadChangedObservable.clear(),this.onTrackpadValuesChangedObservable.clear()},t.MODEL_BASE_URL="https://controllers.babylonjs.com/microsoft/",t.MODEL_LEFT_FILENAME="left.glb",t.MODEL_RIGHT_FILENAME="right.glb",t.GAMEPAD_ID_PREFIX="Spatial Controller (Spatial Interaction Source) ",t.GAMEPAD_ID_PATTERN=/([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/,t}(Hi),Er=function(e){function t(t){var i=e.call(this,t)||this;return i._mapping={buttons:["trigger","grip","trackpad","thumbstick","menu"],buttonMeshNames:{trigger:"SELECT",menu:"MENU",grip:"GRASP",thumbstick:"THUMBSTICK_PRESS",trackpad:"TOUCHPAD_PRESS"},buttonObservableNames:{trigger:"onTriggerStateChangedObservable",menu:"onSecondaryButtonStateChangedObservable",grip:"onMainButtonStateChangedObservable",thumbstick:"onThumbstickStateChangedObservable",trackpad:"onTrackpadChangedObservable"},axisMeshNames:["TOUCHPAD_TOUCH_X","TOUCHPAD_TOUCH_Y","THUMBSTICK_X","THUMBSTICK_Y"],pointingPoseMeshName:qt.POINTING_POSE},i.thumbstickValues={x:0,y:0},i.onThumbstickStateChangedObservable=new o.c,i.onThumbstickValuesChangedObservable=new o.c,i.onTrackpadChangedObservable=i.onPadStateChangedObservable,i.onTrackpadValuesChangedObservable=i.onPadValuesChangedObservable,i}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"onThumbstickButtonStateChangedObservable",{get:function(){return this.onThumbstickStateChangedObservable},enumerable:!0,configurable:!0}),t.prototype._updateTrackpad=function(){!this.browserGamepad.axes||this.browserGamepad.axes[2]==this.thumbstickValues.x&&this.browserGamepad.axes[3]==this.thumbstickValues.y||(this.trackpad.x=this.browserGamepad.axes[2],this.trackpad.y=this.browserGamepad.axes[3],this.onThumbstickValuesChangedObservable.notifyObservers(this.trackpad))},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onThumbstickStateChangedObservable.clear(),this.onThumbstickValuesChangedObservable.clear()},t}(Tr);Qt._ControllerFactories.push({canCreate:function(e){return 0===e.id.indexOf(Tr.GAMEPAD_ID_PREFIX)},create:function(e){return new Tr(e)}});var xr=i(72),Pr=i(66),Ar=i(56),Sr=i(41),Cr=function(e){function t(t,i,n,r){void 0===i&&(i=s.a.Gray()),void 0===n&&(n=Sr.a.DefaultUtilityLayer),void 0===r&&(r=null);var c=e.call(this,n)||this;c._pointerObserver=null,c.snapDistance=0,c.onSnapObservable=new o.c,c.uniformScaling=!1,c.sensitivity=1,c._isEnabled=!0,c._parent=null,c._parent=r,c._coloredMaterial=new Ki.a("",n.utilityLayerScene),c._coloredMaterial.diffuseColor=i,c._coloredMaterial.specularColor=i.subtract(new s.a(.1,.1,.1)),c._hoverMaterial=new Ki.a("",n.utilityLayerScene),c._hoverMaterial.diffuseColor=i.add(new s.a(.3,.3,.3)),c._arrow=new Ke.a("",n.utilityLayerScene);var l=Pr.a.CreateBox("yPosMesh",{size:.4},n.utilityLayerScene),u=an.a.CreateCylinder("cylinder",{diameterTop:.005,height:.275,diameterBottom:.005,tessellation:96},n.utilityLayerScene);u.material=c._coloredMaterial,c._arrow.addChild(l),c._arrow.addChild(u),l.scaling.scaleInPlace(.1),l.material=c._coloredMaterial,l.rotation.x=Math.PI/2,l.position.z+=.3,u.position.z+=.1375,u.rotation.x=Math.PI/2,c._arrow.lookAt(c._rootMesh.position.add(t)),c._rootMesh.addChild(c._arrow),c._arrow.scaling.scaleInPlace(1/3),c.dragBehavior=new He.a({dragAxis:t}),c.dragBehavior.moveAttached=!1,c._rootMesh.addBehavior(c.dragBehavior);var h=0,d=new a.e,f={snapDistance:0};c.dragBehavior.onDragObservable.add(function(e){if(c.attachedMesh){var i=c.sensitivity*e.dragDistance*(3*c.scaleRatio/c._rootMesh.scaling.length()),n=!1,r=0;c.uniformScaling?(c.attachedMesh.scaling.normalizeToRef(d),d.y<0&&d.scaleInPlace(-1)):d.copyFrom(t),0==c.snapDistance?d.scaleToRef(i,d):(h+=i,Math.abs(h)>c.snapDistance?(r=Math.floor(Math.abs(h)/c.snapDistance),h<0&&(r*=-1),h%=c.snapDistance,d.scaleToRef(c.snapDistance*r,d),n=!0):d.scaleInPlace(0)),c.attachedMesh.scaling.addInPlace(d),n&&(f.snapDistance=c.snapDistance*r,c.onSnapObservable.notifyObservers(f))}}),c._pointerObserver=n.utilityLayerScene.onPointerObservable.add(function(e){if(!c._customMeshSet){var t=e.pickInfo&&-1!=c._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)?c._hoverMaterial:c._coloredMaterial;c._rootMesh.getChildMeshes().forEach(function(e){e.material=t,e.color&&(e.color=t.diffuseColor)})}});var p=n._getSharedGizmoLight();return p.includedOnlyMeshes=p.includedOnlyMeshes.concat(c._rootMesh.getChildMeshes()),c}return Object(h.d)(t,e),t.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._arrow&&this._arrow.dispose(),[this._coloredMaterial,this._hoverMaterial].forEach(function(e){e&&e.dispose()}),e.prototype.dispose.call(this)},t.prototype.setCustomMesh=function(t,i){var n=this;void 0===i&&(i=!1),e.prototype.setCustomMesh.call(this,t),i&&(this._rootMesh.getChildMeshes().forEach(function(e){e.material=n._coloredMaterial,e.color&&(e.color=n._coloredMaterial.diffuseColor)}),this._customMeshSet=!1)},t}(Ar.a),Rr=i(48),Or=i(46),Mr=function(e){function t(t,i){void 0===t&&(t=s.a.Gray()),void 0===i&&(i=Sr.a.DefaultKeepDepthUtilityLayer);var n=e.call(this,i)||this;n._boundingDimensions=new a.e(1,1,1),n._renderObserver=null,n._pointerObserver=null,n._scaleDragSpeed=.2,n._tmpQuaternion=new a.b,n._tmpVector=new a.e(0,0,0),n._tmpRotationMatrix=new a.a,n.ignoreChildren=!1,n.includeChildPredicate=null,n.rotationSphereSize=.1,n.scaleBoxSize=.1,n.fixedDragMeshScreenSize=!1,n.fixedDragMeshScreenSizeDistanceFactor=10,n.onDragStartObservable=new o.c,n.onScaleBoxDragObservable=new o.c,n.onScaleBoxDragEndObservable=new o.c,n.onRotationSphereDragObservable=new o.c,n.onRotationSphereDragEndObservable=new o.c,n.scalePivot=null,n._existingMeshScale=new a.e,n._dragMesh=null,n.pointerDragBehavior=new He.a,n.updateScale=!1,n._anchorMesh=new Ke.a("anchor",i.utilityLayerScene),n.coloredMaterial=new Ki.a("",i.utilityLayerScene),n.coloredMaterial.disableLighting=!0,n.hoverColoredMaterial=new Ki.a("",i.utilityLayerScene),n.hoverColoredMaterial.disableLighting=!0,n._lineBoundingBox=new Ke.a("",i.utilityLayerScene),n._lineBoundingBox.rotationQuaternion=new a.b;var r=[];r.push(Or.a.CreateLines("lines",{points:[new a.e(0,0,0),new a.e(n._boundingDimensions.x,0,0)]},i.utilityLayerScene)),r.push(Or.a.CreateLines("lines",{points:[new a.e(0,0,0),new a.e(0,n._boundingDimensions.y,0)]},i.utilityLayerScene)),r.push(Or.a.CreateLines("lines",{points:[new a.e(0,0,0),new a.e(0,0,n._boundingDimensions.z)]},i.utilityLayerScene)),r.push(Or.a.CreateLines("lines",{points:[new a.e(n._boundingDimensions.x,0,0),new a.e(n._boundingDimensions.x,n._boundingDimensions.y,0)]},i.utilityLayerScene)),r.push(Or.a.CreateLines("lines",{points:[new a.e(n._boundingDimensions.x,0,0),new a.e(n._boundingDimensions.x,0,n._boundingDimensions.z)]},i.utilityLayerScene)),r.push(Or.a.CreateLines("lines",{points:[new a.e(0,n._boundingDimensions.y,0),new a.e(n._boundingDimensions.x,n._boundingDimensions.y,0)]},i.utilityLayerScene)),r.push(Or.a.CreateLines("lines",{points:[new a.e(0,n._boundingDimensions.y,0),new a.e(0,n._boundingDimensions.y,n._boundingDimensions.z)]},i.utilityLayerScene)),r.push(Or.a.CreateLines("lines",{points:[new a.e(0,0,n._boundingDimensions.z),new a.e(n._boundingDimensions.x,0,n._boundingDimensions.z)]},i.utilityLayerScene)),r.push(Or.a.CreateLines("lines",{points:[new a.e(0,0,n._boundingDimensions.z),new a.e(0,n._boundingDimensions.y,n._boundingDimensions.z)]},i.utilityLayerScene)),r.push(Or.a.CreateLines("lines",{points:[new a.e(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new a.e(0,n._boundingDimensions.y,n._boundingDimensions.z)]},i.utilityLayerScene)),r.push(Or.a.CreateLines("lines",{points:[new a.e(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new a.e(n._boundingDimensions.x,0,n._boundingDimensions.z)]},i.utilityLayerScene)),r.push(Or.a.CreateLines("lines",{points:[new a.e(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new a.e(n._boundingDimensions.x,n._boundingDimensions.y,0)]},i.utilityLayerScene)),r.forEach(function(e){e.color=t,e.position.addInPlace(new a.e(-n._boundingDimensions.x/2,-n._boundingDimensions.y/2,-n._boundingDimensions.z/2)),e.isPickable=!1,n._lineBoundingBox.addChild(e)}),n._rootMesh.addChild(n._lineBoundingBox),n.setColor(t),n._rotateSpheresParent=new Ke.a("",i.utilityLayerScene),n._rotateSpheresParent.rotationQuaternion=new a.b;for(var c=function(e){var t=Rr.a.CreateSphere("",{diameter:1},i.utilityLayerScene);t.rotationQuaternion=new a.b,t.material=l.coloredMaterial,(f=new He.a({})).moveAttached=!1,f.updateDragPlane=!1,t.addBehavior(f);var r=new a.e(1,0,0),o=0;f.onDragStartObservable.add(function(){r.copyFrom(t.forward),o=0}),f.onDragObservable.add(function(t){if(n.onRotationSphereDragObservable.notifyObservers({}),n.attachedMesh){var i=n.attachedMesh.parent;if(i&&i.scaling&&i.scaling.isNonUniformWithinEpsilon(.001))return void m.a.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");qe.a._RemoveAndStorePivotPoint(n.attachedMesh);var s=r,c=t.dragPlaneNormal.scale(a.e.Dot(t.dragPlaneNormal,s)),l=s.subtract(c).normalizeToNew(),u=a.e.Dot(l,t.delta)<0?Math.abs(t.delta.length()):-Math.abs(t.delta.length());u=u/n._boundingDimensions.length()*n._anchorMesh.scaling.length(),n.attachedMesh.rotationQuaternion||(n.attachedMesh.rotationQuaternion=a.b.RotationYawPitchRoll(n.attachedMesh.rotation.y,n.attachedMesh.rotation.x,n.attachedMesh.rotation.z)),n._anchorMesh.rotationQuaternion||(n._anchorMesh.rotationQuaternion=a.b.RotationYawPitchRoll(n._anchorMesh.rotation.y,n._anchorMesh.rotation.x,n._anchorMesh.rotation.z)),o+=u,Math.abs(o)<=2*Math.PI&&(e>=8?a.b.RotationYawPitchRollToRef(0,0,u,n._tmpQuaternion):e>=4?a.b.RotationYawPitchRollToRef(u,0,0,n._tmpQuaternion):a.b.RotationYawPitchRollToRef(0,u,0,n._tmpQuaternion),n._anchorMesh.addChild(n.attachedMesh),n._anchorMesh.rotationQuaternion.multiplyToRef(n._tmpQuaternion,n._anchorMesh.rotationQuaternion),n._anchorMesh.removeChild(n.attachedMesh),n.attachedMesh.setParent(i)),n.updateBoundingBox(),qe.a._RestorePivotPoint(n.attachedMesh)}n._updateDummy()}),f.onDragStartObservable.add(function(){n.onDragStartObservable.notifyObservers({}),n._selectNode(t)}),f.onDragEndObservable.add(function(){n.onRotationSphereDragEndObservable.notifyObservers({}),n._selectNode(null),n._updateDummy()}),l._rotateSpheresParent.addChild(t)},l=this,u=0;u<12;u++)c(u);n._rootMesh.addChild(n._rotateSpheresParent),n._scaleBoxesParent=new Ke.a("",i.utilityLayerScene),n._scaleBoxesParent.rotationQuaternion=new a.b;for(var h=0;h<2;h++)for(var d=0;d<2;d++)for(var f,p=function(){var e=Pr.a.CreateBox("",{size:1},i.utilityLayerScene);e.material=_.coloredMaterial;var t=new a.e(0==h?-1:1,0==d?-1:1,0==g?-1:1);(f=new He.a({dragAxis:t})).moveAttached=!1,e.addBehavior(f),f.onDragObservable.add(function(t){if(n.onScaleBoxDragObservable.notifyObservers({}),n.attachedMesh){var i=n.attachedMesh.parent;if(i&&i.scaling&&i.scaling.isNonUniformWithinEpsilon(.001))return void m.a.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");qe.a._RemoveAndStorePivotPoint(n.attachedMesh);var r=t.dragDistance/n._boundingDimensions.length()*n._anchorMesh.scaling.length(),o=new a.e(r,r,r);o.scaleInPlace(n._scaleDragSpeed),n.updateBoundingBox(),n.scalePivot?(n.attachedMesh.getWorldMatrix().getRotationMatrixToRef(n._tmpRotationMatrix),n._boundingDimensions.scaleToRef(.5,n._tmpVector),a.e.TransformCoordinatesToRef(n._tmpVector,n._tmpRotationMatrix,n._tmpVector),n._anchorMesh.position.subtractInPlace(n._tmpVector),n._boundingDimensions.multiplyToRef(n.scalePivot,n._tmpVector),a.e.TransformCoordinatesToRef(n._tmpVector,n._tmpRotationMatrix,n._tmpVector),n._anchorMesh.position.addInPlace(n._tmpVector)):(e.absolutePosition.subtractToRef(n._anchorMesh.position,n._tmpVector),n._anchorMesh.position.subtractInPlace(n._tmpVector)),n._anchorMesh.addChild(n.attachedMesh),n._anchorMesh.scaling.addInPlace(o),(n._anchorMesh.scaling.x<0||n._anchorMesh.scaling.y<0||n._anchorMesh.scaling.z<0)&&n._anchorMesh.scaling.subtractInPlace(o),n._anchorMesh.removeChild(n.attachedMesh),n.attachedMesh.setParent(i),qe.a._RestorePivotPoint(n.attachedMesh)}n._updateDummy()}),f.onDragStartObservable.add(function(){n.onDragStartObservable.notifyObservers({}),n._selectNode(e)}),f.onDragEndObservable.add(function(){n.onScaleBoxDragEndObservable.notifyObservers({}),n._selectNode(null),n._updateDummy()}),_._scaleBoxesParent.addChild(e)},_=this,g=0;g<2;g++)p();n._rootMesh.addChild(n._scaleBoxesParent);var v=new Array;return n._pointerObserver=i.utilityLayerScene.onPointerObservable.add(function(e){v[e.event.pointerId]?e.pickInfo&&e.pickInfo.pickedMesh!=v[e.event.pointerId]&&(v[e.event.pointerId].material=n.coloredMaterial,delete v[e.event.pointerId]):n._rotateSpheresParent.getChildMeshes().concat(n._scaleBoxesParent.getChildMeshes()).forEach(function(t){e.pickInfo&&e.pickInfo.pickedMesh==t&&(v[e.event.pointerId]=t,t.material=n.hoverColoredMaterial)})}),n._renderObserver=n.gizmoLayer.originalScene.onBeforeRenderObservable.add(function(){n.attachedMesh&&!n._existingMeshScale.equals(n.attachedMesh.scaling)?n.updateBoundingBox():n.fixedDragMeshScreenSize&&(n._updateRotationSpheres(),n._updateScaleBoxes()),n._dragMesh&&n.attachedMesh&&n.pointerDragBehavior.dragging&&(n._lineBoundingBox.position.rotateByQuaternionToRef(n._rootMesh.rotationQuaternion,n._tmpVector),n.attachedMesh.setAbsolutePosition(n._dragMesh.position.add(n._tmpVector.scale(-1))))}),n.updateBoundingBox(),n}return Object(h.d)(t,e),t.prototype.setColor=function(e){this.coloredMaterial.emissiveColor=e,this.hoverColoredMaterial.emissiveColor=e.clone().add(new s.a(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach(function(t){t.color&&(t.color=e)})},t.prototype._attachedMeshChanged=function(e){var t=this;if(e){qe.a._RemoveAndStorePivotPoint(e);var i=e.parent;this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),e.setParent(i),qe.a._RestorePivotPoint(e),this.updateBoundingBox(),e.getChildMeshes(!1).forEach(function(e){e.markAsDirty("scaling")}),this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce(function(){t._updateDummy()})}},t.prototype._selectNode=function(e){this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach(function(t){t.isVisible=!e||t==e})},t.prototype.updateBoundingBox=function(){if(this.attachedMesh){qe.a._RemoveAndStorePivotPoint(this.attachedMesh);var e=this.attachedMesh.parent;this.attachedMesh.setParent(null);var t=null;this.attachedMesh.skeleton&&(t=this.attachedMesh.skeleton.overrideMesh,this.attachedMesh.skeleton.overrideMesh=null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=a.b.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=a.b.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);var i=this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren,this.includeChildPredicate);i.max.subtractToRef(i.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((i.max.x+i.min.x)/2,(i.max.y+i.min.y)/2,(i.max.z+i.min.z)/2),this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this.attachedMesh.setParent(e),this.attachedMesh.skeleton&&(this.attachedMesh.skeleton.overrideMesh=t)}this._updateRotationSpheres(),this._updateScaleBoxes(),this.attachedMesh&&(this._existingMeshScale.copyFrom(this.attachedMesh.scaling),qe.a._RestorePivotPoint(this.attachedMesh))},t.prototype._updateRotationSpheres=function(){for(var e=this._rotateSpheresParent.getChildMeshes(),t=0;t<3;t++)for(var i=0;i<2;i++)for(var n=0;n<2;n++){var r=4*t+2*i+n;if(0==t&&(e[r].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*i,this._boundingDimensions.z*n),e[r].position.addInPlace(new a.e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(a.e.Cross(e[r].position.normalizeToNew(),a.e.Right()).normalizeToNew().add(e[r].position))),1==t&&(e[r].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y/2,this._boundingDimensions.z*n),e[r].position.addInPlace(new a.e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(a.e.Cross(e[r].position.normalizeToNew(),a.e.Up()).normalizeToNew().add(e[r].position))),2==t&&(e[r].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y*n,this._boundingDimensions.z/2),e[r].position.addInPlace(new a.e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(a.e.Cross(e[r].position.normalizeToNew(),a.e.Forward()).normalizeToNew().add(e[r].position))),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[r].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var o=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[r].scaling.set(o,o,o)}else e[r].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}},t.prototype._updateScaleBoxes=function(){for(var e=this._scaleBoxesParent.getChildMeshes(),t=0;t<2;t++)for(var i=0;i<2;i++)for(var n=0;n<2;n++){var r=4*t+2*i+n;if(e[r])if(e[r].position.set(this._boundingDimensions.x*t,this._boundingDimensions.y*i,this._boundingDimensions.z*n),e[r].position.addInPlace(new a.e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[r].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var o=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[r].scaling.set(o,o,o)}else e[r].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize)}},t.prototype.setEnabledRotationAxis=function(e){this._rotateSpheresParent.getChildMeshes().forEach(function(t,i){i<4?t.setEnabled(-1!=e.indexOf("x")):i<8?t.setEnabled(-1!=e.indexOf("y")):t.setEnabled(-1!=e.indexOf("z"))})},t.prototype.setEnabledScaling=function(e){this._scaleBoxesParent.getChildMeshes().forEach(function(t,i){t.setEnabled(e)})},t.prototype._updateDummy=function(){this._dragMesh&&(this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()),this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling),this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion))},t.prototype.enableDragBehavior=function(){this._dragMesh=Ae.a.CreateBox("dummy",1,this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new a.b,this.pointerDragBehavior.useObjectOrientationForDragging=!1,this._dragMesh.addBehavior(this.pointerDragBehavior)},t.prototype.dispose=function(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateSpheresParent.dispose(),this._scaleBoxesParent.dispose(),this._dragMesh&&this._dragMesh.dispose(),e.prototype.dispose.call(this)},t.MakeNotPickableAndWrapInBoundingBox=function(e){var t=function(e){e.isPickable=!1,e.getChildMeshes().forEach(function(e){t(e)})};t(e),e.rotationQuaternion||(e.rotationQuaternion=a.b.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));var i=e.position.clone(),n=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);var r=Pr.a.CreateBox("box",{size:1},e.getScene()),o=e.getHierarchyBoundingVectors();return o.max.subtractToRef(o.min,r.scaling),0===r.scaling.y&&(r.scaling.y=re.a),0===r.scaling.x&&(r.scaling.x=re.a),0===r.scaling.z&&(r.scaling.z=re.a),r.position.set((o.max.x+o.min.x)/2,(o.max.y+o.min.y)/2,(o.max.z+o.min.z)/2),e.addChild(r),e.rotationQuaternion.copyFrom(n),e.position.copyFrom(i),e.removeChild(r),r.addChild(e),r.visibility=0,r},t.prototype.setCustomMesh=function(e){m.a.Error("Custom meshes are not supported on this gizmo")},t}(Ar.a),Ir=function(e){function t(t,i,n,r,c,l){void 0===i&&(i=s.a.Gray()),void 0===n&&(n=Sr.a.DefaultUtilityLayer),void 0===r&&(r=32),void 0===c&&(c=null),void 0===l&&(l=!1);var u=e.call(this,n)||this;u._pointerObserver=null,u.snapDistance=0,u.onSnapObservable=new o.c,u._isEnabled=!0,u._parent=null,u._parent=c;var h=new Ki.a("",n.utilityLayerScene);h.diffuseColor=i,h.specularColor=i.subtract(new s.a(.1,.1,.1));var d=new Ki.a("",n.utilityLayerScene);d.diffuseColor=i.add(new s.a(.3,.3,.3));var f=new Ke.a("",n.utilityLayerScene),p=Ae.a.CreateTorus("",.6,.03,r,n.utilityLayerScene);p.visibility=0;var _=Ae.a.CreateTorus("",.6,.005,r,n.utilityLayerScene);_.material=h,_.rotation.x=Math.PI/2,p.rotation.x=Math.PI/2,f.addChild(_),f.addChild(p),f.lookAt(u._rootMesh.position.add(t)),u._rootMesh.addChild(f),f.scaling.scaleInPlace(1/3),u.dragBehavior=new He.a({dragPlaneNormal:t}),u.dragBehavior.moveAttached=!1,u.dragBehavior.maxDragAngle=9*Math.PI/20,u.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,u._rootMesh.addBehavior(u.dragBehavior);var m=new a.e;u.dragBehavior.onDragStartObservable.add(function(e){u.attachedMesh&&m.copyFrom(e.dragPlanePoint)});var g=new a.a,v=new a.e,y=new a.e,b={snapDistance:0},T=0,E=new a.a,x=new a.e,P=new a.b;u.dragBehavior.onDragObservable.add(function(e){if(u.attachedMesh){u.attachedMesh.rotationQuaternion&&!l||(u.attachedMesh.rotationQuaternion=a.b.RotationYawPitchRoll(u.attachedMesh.rotation.y,u.attachedMesh.rotation.x,u.attachedMesh.rotation.z));var i=u.attachedMesh.parent;i&&u.attachedMesh.setParent(null);var r=e.dragPlanePoint.subtract(u.attachedMesh.absolutePosition).normalize(),o=m.subtract(u.attachedMesh.absolutePosition).normalize(),s=a.e.Cross(r,o),c=a.e.Dot(r,o),h=Math.atan2(s.length(),c);if(v.copyFrom(t),y.copyFrom(t),u.updateGizmoRotationToMatchAttachedMesh&&(u.attachedMesh.rotationQuaternion.toRotationMatrix(g),y=a.e.TransformCoordinates(v,g)),n.utilityLayerScene.activeCamera){var d=n.utilityLayerScene.activeCamera.position.subtract(u.attachedMesh.position);a.e.Dot(d,y)>0&&(v.scaleInPlace(-1),y.scaleInPlace(-1))}a.e.Dot(y,s)>0&&(h=-h);var f=!1;if(0!=u.snapDistance)if(T+=h,Math.abs(T)>u.snapDistance){var p=Math.floor(Math.abs(T)/u.snapDistance);T<0&&(p*=-1),T%=u.snapDistance,h=u.snapDistance*p,f=!0}else h=0;E.reset(),u.attachedMesh.parent&&(u.attachedMesh.parent.computeWorldMatrix().invertToRef(E),E.getRotationMatrixToRef(E),a.e.TransformCoordinatesToRef(v,E,v));var _=Math.sin(h/2);P.set(v.x*_,v.y*_,v.z*_,Math.cos(h/2)),E.determinant()>0&&(P.toEulerAnglesToRef(x),a.b.RotationYawPitchRollToRef(x.y,-x.x,-x.z,P)),u.updateGizmoRotationToMatchAttachedMesh?u.attachedMesh.rotationQuaternion.multiplyToRef(P,u.attachedMesh.rotationQuaternion):P.multiplyToRef(u.attachedMesh.rotationQuaternion,u.attachedMesh.rotationQuaternion),l&&(u.attachedMesh.rotationQuaternion.toEulerAnglesToRef(x),u.attachedMesh.rotationQuaternion=null,u.attachedMesh.rotation.copyFrom(x)),m.copyFrom(e.dragPlanePoint),f&&(b.snapDistance=h,u.onSnapObservable.notifyObservers(b)),i&&u.attachedMesh.setParent(i)}}),u._pointerObserver=n.utilityLayerScene.onPointerObservable.add(function(e){if(!u._customMeshSet){var t=e.pickInfo&&-1!=u._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)?d:h;u._rootMesh.getChildMeshes().forEach(function(e){e.material=t,e.color&&(e.color=t.diffuseColor)})}});var A=n._getSharedGizmoLight();return A.includedOnlyMeshes=A.includedOnlyMeshes.concat(u._rootMesh.getChildMeshes(!1)),u}return Object(h.d)(t,e),t.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),e.prototype.dispose.call(this)},t}(Ar.a),Dr=function(e){function t(t,i,n){void 0===t&&(t=Sr.a.DefaultUtilityLayer),void 0===i&&(i=32),void 0===n&&(n=!1);var r=e.call(this,t)||this;return r.onDragStartObservable=new o.c,r.onDragEndObservable=new o.c,r.xGizmo=new Ir(new a.e(1,0,0),s.a.Red().scale(.5),t,i,r,n),r.yGizmo=new Ir(new a.e(0,1,0),s.a.Green().scale(.5),t,i,r,n),r.zGizmo=new Ir(new a.e(0,0,1),s.a.Blue().scale(.5),t,i,r,n),[r.xGizmo,r.yGizmo,r.zGizmo].forEach(function(e){e.dragBehavior.onDragStartObservable.add(function(){r.onDragStartObservable.notifyObservers({})}),e.dragBehavior.onDragEndObservable.add(function(){r.onDragEndObservable.notifyObservers({})})}),r.attachedMesh=null,r}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"attachedMesh",{get:function(){return this._meshAttached},set:function(e){this._meshAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach(function(t){t.isEnabled?t.attachedMesh=e:t.attachedMesh=null})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"snapDistance",{get:function(){return this.xGizmo.snapDistance},set:function(e){this.xGizmo&&(this.xGizmo.snapDistance=e,this.yGizmo.snapDistance=e,this.zGizmo.snapDistance=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleRatio",{get:function(){return this.xGizmo.scaleRatio},set:function(e){this.xGizmo&&(this.xGizmo.scaleRatio=e,this.yGizmo.scaleRatio=e,this.zGizmo.scaleRatio=e)},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose(),this.onDragStartObservable.clear(),this.onDragEndObservable.clear()},t.prototype.setCustomMesh=function(e){m.a.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")},t}(Ar.a),wr=i(43),Lr=i(79),Nr=function(e){function t(i,n,r,c){void 0===n&&(n=s.a.Gray()),void 0===r&&(r=Sr.a.DefaultUtilityLayer),void 0===c&&(c=null);var l=e.call(this,r)||this;l._pointerObserver=null,l.snapDistance=0,l.onSnapObservable=new o.c,l._isEnabled=!1,l._parent=null,l._parent=c,l._coloredMaterial=new Ki.a("",r.utilityLayerScene),l._coloredMaterial.diffuseColor=n,l._coloredMaterial.specularColor=n.subtract(new s.a(.1,.1,.1)),l._hoverMaterial=new Ki.a("",r.utilityLayerScene),l._hoverMaterial.diffuseColor=n.add(new s.a(.3,.3,.3)),l._plane=t._CreatePlane(r.utilityLayerScene,l._coloredMaterial),l._plane.lookAt(l._rootMesh.position.add(i)),l._plane.scaling.scaleInPlace(1/3),l._plane.parent=l._rootMesh;var u=0,h=new a.e,d={snapDistance:0};l.dragBehavior=new He.a({dragPlaneNormal:i}),l.dragBehavior.moveAttached=!1,l._rootMesh.addBehavior(l.dragBehavior);var f=new a.e,p=new a.a;l.dragBehavior.onDragObservable.add(function(e){if(l.attachedMesh)if(l.attachedMesh.parent?(l.attachedMesh.parent.computeWorldMatrix().invertToRef(p),p.setTranslationFromFloats(0,0,0),a.e.TransformCoordinatesToRef(e.delta,p,f)):f.copyFrom(e.delta),0==l.snapDistance)l.attachedMesh.position.addInPlace(f);else if(u+=e.dragDistance,Math.abs(u)>l.snapDistance){var t=Math.floor(Math.abs(u)/l.snapDistance);u%=l.snapDistance,f.normalizeToRef(h),h.scaleInPlace(l.snapDistance*t),l.attachedMesh.position.addInPlace(h),d.snapDistance=l.snapDistance*t,l.onSnapObservable.notifyObservers(d)}}),l._pointerObserver=r.utilityLayerScene.onPointerObservable.add(function(e){if(!l._customMeshSet){var t=e.pickInfo&&-1!=l._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)?l._hoverMaterial:l._coloredMaterial;l._rootMesh.getChildMeshes().forEach(function(e){e.material=t})}});var _=r._getSharedGizmoLight();return _.includedOnlyMeshes=_.includedOnlyMeshes.concat(l._rootMesh.getChildMeshes(!1)),l}return Object(h.d)(t,e),t._CreatePlane=function(e,t){var i=new wr.a("plane",e),n=Lr.a.CreatePlane("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return n.material=t,n.parent=i,n.material=t,i},t._CreateArrowInstance=function(e,t){for(var i=new wr.a("arrow",e),n=0,r=t.getChildMeshes();n<r.length;n++){var o=r[n];o.createInstance(o.name).parent=i}return i},t.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),e.prototype.dispose.call(this),this._plane&&this._plane.dispose(),[this._coloredMaterial,this._hoverMaterial].forEach(function(e){e&&e.dispose()})},t}(Ar.a),Fr=function(e){function t(t){void 0===t&&(t=Sr.a.DefaultUtilityLayer);var i=e.call(this,t)||this;return i._meshAttached=null,i.onDragStartObservable=new o.c,i.onDragEndObservable=new o.c,i._planarGizmoEnabled=!1,i.xGizmo=new xr.a(new a.e(1,0,0),s.a.Red().scale(.5),t,i),i.yGizmo=new xr.a(new a.e(0,1,0),s.a.Green().scale(.5),t,i),i.zGizmo=new xr.a(new a.e(0,0,1),s.a.Blue().scale(.5),t,i),i.xPlaneGizmo=new Nr(new a.e(1,0,0),s.a.Red().scale(.5),i.gizmoLayer,i),i.yPlaneGizmo=new Nr(new a.e(0,1,0),s.a.Green().scale(.5),i.gizmoLayer,i),i.zPlaneGizmo=new Nr(new a.e(0,0,1),s.a.Blue().scale(.5),i.gizmoLayer,i),[i.xGizmo,i.yGizmo,i.zGizmo,i.xPlaneGizmo,i.yPlaneGizmo,i.zPlaneGizmo].forEach(function(e){e.dragBehavior.onDragStartObservable.add(function(){i.onDragStartObservable.notifyObservers({})}),e.dragBehavior.onDragEndObservable.add(function(){i.onDragEndObservable.notifyObservers({})})}),i.attachedMesh=null,i}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"attachedMesh",{get:function(){return this._meshAttached},set:function(e){this._meshAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(t){t.isEnabled?t.attachedMesh=e:t.attachedMesh=null})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"planarGizmoEnabled",{get:function(){return this._planarGizmoEnabled},set:function(e){var t=this;this._planarGizmoEnabled=e,[this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(i){i&&(i.isEnabled=e,e&&(i.attachedMesh=t.attachedMesh))},this)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this._updateGizmoRotationToMatchAttachedMesh},set:function(e){this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(t){t&&(t.updateGizmoRotationToMatchAttachedMesh=e)})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"snapDistance",{get:function(){return this._snapDistance},set:function(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(t){t&&(t.snapDistance=e)})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleRatio",{get:function(){return this._scaleRatio},set:function(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(t){t&&(t.scaleRatio=e)})},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(e){e&&e.dispose()}),this.onDragStartObservable.clear(),this.onDragEndObservable.clear()},t.prototype.setCustomMesh=function(e){m.a.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)")},t}(Ar.a);$i.a.CreatePolyhedron=function(e){var t=[];t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]};var i,n,r,o,c,l,u=e.type&&(e.type<0||e.type>=t.length)?0:e.type||0,h=e.size,d=e.sizeX||h||1,f=e.sizeY||h||1,p=e.sizeZ||h||1,_=e.custom||t[u],m=_.face.length,g=e.faceUV||new Array(m),v=e.faceColors,y=void 0===e.flat||e.flat,b=0===e.sideOrientation?0:e.sideOrientation||$i.a.DEFAULTSIDE,T=new Array,E=new Array,x=new Array,P=new Array,A=new Array,S=0,C=0,R=new Array,O=0,M=0;if(y)for(M=0;M<m;M++)v&&void 0===v[M]&&(v[M]=new s.b(1,1,1,1)),g&&void 0===g[M]&&(g[M]=new a.f(0,0,1,1));if(y)for(M=0;M<m;M++){var I=_.face[M].length;for(r=2*Math.PI/I,o=.5*Math.tan(r/2),c=.5,O=0;O<I;O++)T.push(_.vertex[_.face[M][O]][0]*d,_.vertex[_.face[M][O]][1]*f,_.vertex[_.face[M][O]][2]*p),R.push(S),S++,i=g[M].x+(g[M].z-g[M].x)*(.5+o),n=g[M].y+(g[M].w-g[M].y)*(c-.5),P.push(i,n),l=o*Math.cos(r)-c*Math.sin(r),c=o*Math.sin(r)+c*Math.cos(r),o=l,v&&A.push(v[M].r,v[M].g,v[M].b,v[M].a);for(O=0;O<I-2;O++)E.push(R[0+C],R[O+2+C],R[O+1+C]);C+=I}else{for(O=0;O<_.vertex.length;O++)T.push(_.vertex[O][0]*d,_.vertex[O][1]*f,_.vertex[O][2]*p),P.push(0,0);for(M=0;M<m;M++)for(O=0;O<_.face[M].length-2;O++)E.push(_.face[M][0],_.face[M][O+2],_.face[M][O+1])}$i.a.ComputeNormals(T,E,x),$i.a._ComputeSides(b,T,E,x,P,e.frontUVs,e.backUVs);var D=new $i.a;return D.positions=T,D.indices=E,D.normals=x,D.uvs=P,v&&y&&(D.colors=A),D},Ae.a.CreatePolyhedron=function(e,t,i){return Br.CreatePolyhedron(e,t,i)};var Br=function(){function e(){}return e.CreatePolyhedron=function(e,t,i){void 0===i&&(i=null);var n=new Ae.a(e,i);return t.sideOrientation=Ae.a._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,$i.a.CreatePolyhedron(t).applyToMesh(n,t.updatable),n},e}(),Ur=function(e){function t(t){void 0===t&&(t=Sr.a.DefaultUtilityLayer);var i=e.call(this,t)||this;i._meshAttached=null,i._sensitivity=1,i.onDragStartObservable=new o.c,i.onDragEndObservable=new o.c,i.xGizmo=new Cr(new a.e(1,0,0),s.a.Red().scale(.5),t,i),i.yGizmo=new Cr(new a.e(0,1,0),s.a.Green().scale(.5),t,i),i.zGizmo=new Cr(new a.e(0,0,1),s.a.Blue().scale(.5),t,i),i.uniformScaleGizmo=new Cr(new a.e(0,1,0),s.a.Yellow().scale(.5),t,i),i.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh=!1,i.uniformScaleGizmo.uniformScaling=!0,i._uniformScalingMesh=Br.CreatePolyhedron("",{type:1},i.uniformScaleGizmo.gizmoLayer.utilityLayerScene),i._uniformScalingMesh.scaling.scaleInPlace(.02),i._uniformScalingMesh.visibility=0,i._octahedron=Br.CreatePolyhedron("",{type:1},i.uniformScaleGizmo.gizmoLayer.utilityLayerScene),i._octahedron.scaling.scaleInPlace(.007),i._uniformScalingMesh.addChild(i._octahedron),i.uniformScaleGizmo.setCustomMesh(i._uniformScalingMesh,!0);var n=t._getSharedGizmoLight();return n.includedOnlyMeshes=n.includedOnlyMeshes.concat(i._octahedron),[i.xGizmo,i.yGizmo,i.zGizmo,i.uniformScaleGizmo].forEach(function(e){e.dragBehavior.onDragStartObservable.add(function(){i.onDragStartObservable.notifyObservers({})}),e.dragBehavior.onDragEndObservable.add(function(){i.onDragEndObservable.notifyObservers({})})}),i.attachedMesh=null,i}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"attachedMesh",{get:function(){return this._meshAttached},set:function(e){this._meshAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(function(t){t.isEnabled?t.attachedMesh=e:t.attachedMesh=null})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this._updateGizmoRotationToMatchAttachedMesh},set:function(e){e?(this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(function(t){t&&(t.updateGizmoRotationToMatchAttachedMesh=e)})):m.a.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"snapDistance",{get:function(){return this._snapDistance},set:function(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(function(t){t&&(t.snapDistance=e)})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleRatio",{get:function(){return this._scaleRatio},set:function(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(function(t){t&&(t.scaleRatio=e)})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"sensitivity",{get:function(){return this._sensitivity},set:function(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(function(t){t&&(t.sensitivity=e)})},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(function(e){e&&e.dispose()}),this.onDragStartObservable.clear(),this.onDragEndObservable.clear(),[this._uniformScalingMesh,this._octahedron].forEach(function(e){e&&e.dispose()})},t}(Ar.a),Vr=function(){function e(e){var t=this;this.scene=e,this.clearGizmoOnEmptyPointerEvent=!1,this.onAttachedToMeshObservable=new o.c,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObserver=null,this._attachedMesh=null,this._boundingBoxColor=s.a.FromHexString("#0984e3"),this.boundingBoxDragBehavior=new Ze,this.attachableMeshes=null,this.usePointerToAttachGizmos=!0,this._defaultKeepDepthUtilityLayer=new Sr.a(e),this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,this._defaultUtilityLayer=new Sr.a(e),this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null},this._pointerObserver=e.onPointerObservable.add(function(e){if(t.usePointerToAttachGizmos&&e.type==Ve.a.POINTERDOWN)if(e.pickInfo&&e.pickInfo.pickedMesh){var i=e.pickInfo.pickedMesh;if(null==t.attachableMeshes)for(;i&&null!=i.parent;)i=i.parent;else{var n=!1;t.attachableMeshes.forEach(function(e){i&&(i==e||i.isDescendantOf(e))&&(i=e,n=!0)}),n||(i=null)}i instanceof Ke.a?t._attachedMesh!=i&&t.attachToMesh(i):t.clearGizmoOnEmptyPointerEvent&&t.attachToMesh(null)}else t.clearGizmoOnEmptyPointerEvent&&t.attachToMesh(null)})}return Object.defineProperty(e.prototype,"keepDepthUtilityLayer",{get:function(){return this._defaultKeepDepthUtilityLayer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"utilityLayer",{get:function(){return this._defaultUtilityLayer},enumerable:!0,configurable:!0}),e.prototype.attachToMesh=function(e){for(var t in this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=e,this.gizmos){var i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedMesh=e)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToMeshObservable.notifyObservers(e)},Object.defineProperty(e.prototype,"positionGizmoEnabled",{get:function(){return this._gizmosEnabled.positionGizmo},set:function(e){e?(this.gizmos.positionGizmo||(this.gizmos.positionGizmo=new Fr(this._defaultUtilityLayer)),this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedMesh=null),this._gizmosEnabled.positionGizmo=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rotationGizmoEnabled",{get:function(){return this._gizmosEnabled.rotationGizmo},set:function(e){e?(this.gizmos.rotationGizmo||(this.gizmos.rotationGizmo=new Dr(this._defaultUtilityLayer)),this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedMesh=null),this._gizmosEnabled.rotationGizmo=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scaleGizmoEnabled",{get:function(){return this._gizmosEnabled.scaleGizmo},set:function(e){e?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new Ur(this._defaultUtilityLayer),this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedMesh=null),this._gizmosEnabled.scaleGizmo=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"boundingBoxGizmoEnabled",{get:function(){return this._gizmosEnabled.boundingBoxGizmo},set:function(e){e?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new Mr(this._boundingBoxColor,this._defaultKeepDepthUtilityLayer),this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh,this._attachedMesh&&(this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh.addBehavior(this.boundingBoxDragBehavior))):this.gizmos.boundingBoxGizmo&&(this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this.gizmos.boundingBoxGizmo.attachedMesh=null),this._gizmosEnabled.boundingBoxGizmo=e},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){for(var e in this.scene.onPointerObservable.remove(this._pointerObserver),this.gizmos){var t=this.gizmos[e];t&&t.dispose()}this._defaultKeepDepthUtilityLayer.dispose(),this._defaultUtilityLayer.dispose(),this.boundingBoxDragBehavior.detach(),this.onAttachedToMeshObservable.clear()},e}(),kr=i(50),zr=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._needProjectionMatrixCompute=!0,t}return Object(h.d)(t,e),t.prototype._setPosition=function(e){this._position=e},Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this._setPosition(e)},enumerable:!0,configurable:!0}),t.prototype._setDirection=function(e){this._direction=e},Object.defineProperty(t.prototype,"direction",{get:function(){return this._direction},set:function(e){this._setDirection(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowMinZ",{get:function(){return this._shadowMinZ},set:function(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowMaxZ",{get:function(){return this._shadowMaxZ},set:function(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),t.prototype.computeTransformedInformation=function(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=a.e.Zero()),a.e.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=a.e.Zero()),a.e.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0)},t.prototype.getDepthScale=function(){return 50},t.prototype.getShadowDirection=function(e){return this.transformedDirection?this.transformedDirection:this.direction},t.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},t.prototype.setDirectionToTarget=function(e){return this.direction=a.e.Normalize(e.subtract(this.position)),this.direction},t.prototype.getRotation=function(){this.direction.normalize();var e=a.e.Cross(this.direction,Z.a.Y),t=a.e.Cross(e,this.direction);return a.e.RotationFromAxis(e,t,this.direction)},t.prototype.needCube=function(){return!1},t.prototype.needProjectionMatrixCompute=function(){return this._needProjectionMatrixCompute},t.prototype.forceProjectionMatrixCompute=function(){this._needProjectionMatrixCompute=!0},t.prototype._initCache=function(){e.prototype._initCache.call(this),this._cache.position=a.e.Zero()},t.prototype._isSynchronized=function(){return!!this._cache.position.equals(this.position)},t.prototype.computeWorldMatrix=function(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=a.a.Identity()),a.a.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)},t.prototype.getDepthMinZ=function(e){return void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ},t.prototype.getDepthMaxZ=function(e){return void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ},t.prototype.setShadowProjectionMatrix=function(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this},Object(h.c)([Object(N.o)()],t.prototype,"position",null),Object(h.c)([Object(N.o)()],t.prototype,"direction",null),Object(h.c)([Object(N.c)()],t.prototype,"shadowMinZ",null),Object(h.c)([Object(N.c)()],t.prototype,"shadowMaxZ",null),t}(kr.a);B.a.AddNodeConstructor("Light_Type_1",function(e,t){return function(){return new Gr(e,a.e.Zero(),t)}});var Gr=function(e){function t(t,i,n){var r=e.call(this,t,n)||this;return r._shadowFrustumSize=0,r._shadowOrthoScale=.1,r.autoUpdateExtends=!0,r.autoCalcShadowZBounds=!1,r._orthoLeft=Number.MAX_VALUE,r._orthoRight=Number.MIN_VALUE,r._orthoTop=Number.MIN_VALUE,r._orthoBottom=Number.MAX_VALUE,r.position=i.scale(-1),r.direction=i,r}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"shadowFrustumSize",{get:function(){return this._shadowFrustumSize},set:function(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowOrthoScale",{get:function(){return this._shadowOrthoScale},set:function(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"DirectionalLight"},t.prototype.getTypeID=function(){return kr.a.LIGHTTYPEID_DIRECTIONALLIGHT},t.prototype._setDefaultShadowProjectionMatrix=function(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)},t.prototype._setDefaultFixedFrustumShadowProjectionMatrix=function(e){var t=this.getScene().activeCamera;t&&a.a.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e)},t.prototype._setDefaultAutoExtendShadowProjectionMatrix=function(e,t,i){var n=this.getScene().activeCamera;if(n){if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){var r=a.e.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;for(var o=Number.MAX_VALUE,s=Number.MIN_VALUE,c=0;c<i.length;c++){var l=i[c];if(l)for(var u=l.getBoundingInfo().boundingBox,h=0;h<u.vectorsWorld.length;h++)a.e.TransformCoordinatesToRef(u.vectorsWorld[h],t,r),r.x<this._orthoLeft&&(this._orthoLeft=r.x),r.y<this._orthoBottom&&(this._orthoBottom=r.y),r.x>this._orthoRight&&(this._orthoRight=r.x),r.y>this._orthoTop&&(this._orthoTop=r.y),this.autoCalcShadowZBounds&&(r.z<o&&(o=r.z),r.z>s&&(s=r.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=o,this._shadowMaxZ=s)}var d=this._orthoRight-this._orthoLeft,f=this._orthoTop-this._orthoBottom;a.a.OrthoOffCenterLHToRef(this._orthoLeft-d*this.shadowOrthoScale,this._orthoRight+d*this.shadowOrthoScale,this._orthoBottom-f*this.shadowOrthoScale,this._orthoTop+f*this.shadowOrthoScale,void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,e)}},t.prototype._buildUniformLayout=function(){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()},t.prototype.transferToEffect=function(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)},t.prototype.transferToNodeMaterialEffect=function(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)},t.prototype.getDepthMinZ=function(e){return 1},t.prototype.getDepthMaxZ=function(e){return 1},t.prototype.prepareLightSpecificDefines=function(e,t){e["DIRLIGHT"+t]=!0},Object(h.c)([Object(N.c)()],t.prototype,"shadowFrustumSize",null),Object(h.c)([Object(N.c)()],t.prototype,"shadowOrthoScale",null),Object(h.c)([Object(N.c)()],t.prototype,"autoUpdateExtends",void 0),Object(h.c)([Object(N.c)()],t.prototype,"autoCalcShadowZBounds",void 0),t}(zr);Ae.a.CreateHemisphere=function(e,t,i,n){var r={segments:t,diameter:i};return jr.CreateHemisphere(e,r,n)};var jr=function(){function e(){}return e.CreateHemisphere=function(e,t,i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);var n=Rr.a.CreateSphere("",{slice:.5,diameter:t.diameter,segments:t.segments},i),r=Ae.a.CreateDisc("",t.diameter/2,3*t.segments+(4-t.segments),i);r.rotation.x=-Math.PI/2,r.parent=n;var o=Ae.a.MergeMeshes([r,n],!0);return o.name=e,o},e}();B.a.AddNodeConstructor("Light_Type_2",function(e,t){return function(){return new Wr(e,a.e.Zero(),a.e.Zero(),0,0,t)}});var Wr=function(e){function t(t,i,n,r,o,s){var c=e.call(this,t,s)||this;return c._innerAngle=0,c._projectionTextureMatrix=a.a.Zero(),c._projectionTextureLightNear=1e-6,c._projectionTextureLightFar=1e3,c._projectionTextureUpDirection=a.e.Up(),c._projectionTextureViewLightDirty=!0,c._projectionTextureProjectionLightDirty=!0,c._projectionTextureDirty=!0,c._projectionTextureViewTargetVector=a.e.Zero(),c._projectionTextureViewLightMatrix=a.a.Zero(),c._projectionTextureProjectionLightMatrix=a.a.Zero(),c._projectionTextureScalingMatrix=a.a.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),c.position=i,c.direction=n,c.angle=r,c.exponent=o,c}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this._cosHalfAngle=Math.cos(.5*e),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"innerAngle",{get:function(){return this._innerAngle},set:function(e){this._innerAngle=e,this._computeAngleValues()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowAngleScale",{get:function(){return this._shadowAngleScale},set:function(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureMatrix",{get:function(){return this._projectionTextureMatrix},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureLightNear",{get:function(){return this._projectionTextureLightNear},set:function(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureLightFar",{get:function(){return this._projectionTextureLightFar},set:function(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureUpDirection",{get:function(){return this._projectionTextureUpDirection},set:function(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"projectionTexture",{get:function(){return this._projectionTexture},set:function(e){var t=this;if(this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady())){var i=this._projectionTexture;i.onLoadObservable&&i.onLoadObservable.addOnce(function(){t._markMeshesAsLightDirty()})}},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"SpotLight"},t.prototype.getTypeID=function(){return kr.a.LIGHTTYPEID_SPOTLIGHT},t.prototype._setDirection=function(t){e.prototype._setDirection.call(this,t),this._projectionTextureViewLightDirty=!0},t.prototype._setPosition=function(t){e.prototype._setPosition.call(this,t),this._projectionTextureViewLightDirty=!0},t.prototype._setDefaultShadowProjectionMatrix=function(e,t,i){var n=this.getScene().activeCamera;if(n){this._shadowAngleScale=this._shadowAngleScale||1;var r=this._shadowAngleScale*this._angle;a.a.PerspectiveFovLHToRef(r,1,this.getDepthMinZ(n),this.getDepthMaxZ(n),e)}},t.prototype._computeProjectionTextureViewLightMatrix=function(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.position.addToRef(this.direction,this._projectionTextureViewTargetVector),a.a.LookAtLHToRef(this.position,this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)},t.prototype._computeProjectionTextureProjectionLightMatrix=function(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;var e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),n=-i*t,r=1/Math.tan(this._angle/2);a.a.FromValuesToRef(r/1,0,0,0,0,r,0,0,0,0,i,1,0,0,n,0,this._projectionTextureProjectionLightMatrix)},t.prototype._computeProjectionTextureMatrix=function(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof et.a){var e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;a.a.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)},t.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},t.prototype._computeAngleValues=function(){this._lightAngleScale=1/Math.max(.001,Math.cos(.5*this._innerAngle)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale},t.prototype.transferTexturesToEffect=function(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightSampler"+t,this.projectionTexture)),this},t.prototype.transferToEffect=function(e,t){var i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=a.e.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=a.e.Normalize(this.direction)),this.getScene().useRightHandedSystem?this._uniformBuffer.updateFloat4("vLightDirection",-i.x,-i.y,-i.z,this._cosHalfAngle,t):this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this},t.prototype.transferToNodeMaterialEffect=function(e,t){var i;return i=this.computeTransformedInformation()?a.e.Normalize(this.transformedDirection):a.e.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._projectionTexture&&this._projectionTexture.dispose()},t.prototype.prepareLightSpecificDefines=function(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!(!this.projectionTexture||!this.projectionTexture.isReady())},Object(h.c)([Object(N.c)()],t.prototype,"angle",null),Object(h.c)([Object(N.c)()],t.prototype,"innerAngle",null),Object(h.c)([Object(N.c)()],t.prototype,"shadowAngleScale",null),Object(h.c)([Object(N.c)()],t.prototype,"exponent",void 0),Object(h.c)([Object(N.c)()],t.prototype,"projectionTextureLightNear",null),Object(h.c)([Object(N.c)()],t.prototype,"projectionTextureLightFar",null),Object(h.c)([Object(N.c)()],t.prototype,"projectionTextureUpDirection",null),Object(h.c)([Object(N.m)("projectedLightTexture")],t.prototype,"_projectionTexture",void 0),t}(zr),Xr=function(e){function t(t){var i=e.call(this,t)||this;return i._cachedPosition=new a.e,i._cachedForward=new a.e(0,0,1),i._light=null,i.attachedMesh=new Ke.a("",i.gizmoLayer.utilityLayerScene),i._attachedMeshParent=new wr.a("parent",i.gizmoLayer.originalScene),i.attachedMesh.parent=i._attachedMeshParent,i._material=new Ki.a("light",i.gizmoLayer.originalScene),i._material.diffuseColor=new s.a(.5,.5,.5),i._material.specularColor=new s.a(.1,.1,.1),i}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"light",{get:function(){return this._light},set:function(e){var i=this;if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),e instanceof Wi.a?this._lightMesh=t._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=e instanceof Gr?t._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof Wr?t._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):t._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach(function(e){e.material=i._material}),this._lightMesh.parent=this._rootMesh;var n=this.gizmoLayer._getSharedGizmoLight();n.includedOnlyMeshes=n.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new a.b,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction&&(this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(this.attachedMesh.forward)),this._update()}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"material",{get:function(){return this._material},enumerable:!0,configurable:!0}),t.prototype._update=function(){e.prototype._update.call(this),this._light&&(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position&&(this.attachedMesh.position.equals(this._cachedPosition)?(this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)):(this._light.position.copyFrom(this.attachedMesh.position),this._cachedPosition.copyFrom(this.attachedMesh.position))),this._light.direction&&(a.e.DistanceSquared(this.attachedMesh.forward,this._cachedForward)>1e-4?(this._light.direction.copyFrom(this.attachedMesh.forward),this._cachedForward.copyFrom(this.attachedMesh.forward)):a.e.DistanceSquared(this.attachedMesh.forward,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(this.attachedMesh.forward))),this._light.isEnabled()?this._material.diffuseColor.set(this._light.diffuse.r/3,this._light.diffuse.g/3,this._light.diffuse.b/3):this._material.diffuseColor.set(0,0,0))},t.prototype.dispose=function(){this._material.dispose(),e.prototype.dispose.call(this),this._attachedMeshParent.dispose()},t._CreateHemisphericLightMesh=function(e){var i=new Ae.a("hemisphereLight",e),n=jr.CreateHemisphere(i.name,{segments:10,diameter:1},e);n.position.z=-.15,n.rotation.x=Math.PI/2,n.parent=i;var r=this._CreateLightLines(3,e);return r.parent=i,r.position.z,i.scaling.scaleInPlace(t._Scale),i.rotation.x=Math.PI/2,i},t._CreatePointLightMesh=function(e){var i=new Ae.a("pointLight",e),n=Rr.a.CreateSphere(i.name,{segments:10,diameter:1},e);return n.rotation.x=Math.PI/2,n.parent=i,this._CreateLightLines(5,e).parent=i,i.scaling.scaleInPlace(t._Scale),i.rotation.x=Math.PI/2,i},t._CreateSpotLightMesh=function(e){var i=new Ae.a("spotLight",e);Rr.a.CreateSphere(i.name,{segments:10,diameter:1},e).parent=i;var n=jr.CreateHemisphere(i.name,{segments:10,diameter:2},e);return n.parent=i,n.rotation.x=-Math.PI/2,this._CreateLightLines(2,e).parent=i,i.scaling.scaleInPlace(t._Scale),i.rotation.x=Math.PI/2,i},t._CreateDirectionalLightMesh=function(e){var i=new Ae.a("directionalLight",e),n=new Ae.a(i.name,e);n.parent=i,Rr.a.CreateSphere(i.name,{diameter:1.2,segments:10},e).parent=n;var r=Ae.a.CreateCylinder(i.name,6,.3,.3,6,1,e);r.parent=n,(o=r.clone(i.name)).scaling.y=.5,o.position.x+=1.25,(a=r.clone(i.name)).scaling.y=.5,a.position.x+=-1.25;var o,a,s=Ae.a.CreateCylinder(i.name,1,0,.6,6,1,e);return s.position.y+=3,s.parent=n,(o=s.clone(i.name)).position.y=1.5,o.position.x+=1.25,(a=s.clone(i.name)).position.y=1.5,a.position.x+=-1.25,n.scaling.scaleInPlace(t._Scale),n.rotation.z=Math.PI/2,n.rotation.y=Math.PI/2,i},t._Scale=.007,t._CreateLightLines=function(e,t){var i=new Ae.a("root",t);i.rotation.x=Math.PI/2;var n=new Ae.a("linePivot",t);n.parent=i;var r=Ae.a.CreateCylinder("line",2,.2,.3,6,1,t);if(r.position.y=r.scaling.y/2+1.2,r.parent=n,e<2)return n;for(var o=0;o<4;o++){(a=n.clone("lineParentClone")).rotation.z=Math.PI/4,a.rotation.y=Math.PI/2+Math.PI/2*o,a.getChildMeshes()[0].scaling.y=.5,a.getChildMeshes()[0].scaling.x=a.getChildMeshes()[0].scaling.z=.8,a.getChildMeshes()[0].position.y=a.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(o=0;o<4;o++){(a=n.clone("linePivotClone")).rotation.z=Math.PI/2,a.rotation.y=Math.PI/2*o}if(e<4)return i;for(o=0;o<4;o++){var a;(a=n.clone("linePivotClone")).rotation.z=Math.PI+Math.PI/4,a.rotation.y=Math.PI/2+Math.PI/2*o,a.getChildMeshes()[0].scaling.y=.5,a.getChildMeshes()[0].scaling.x=a.getChildMeshes()[0].scaling.z=.8,a.getChildMeshes()[0].position.y=a.getChildMeshes()[0].scaling.y/2+1.2}return e<5?i:((a=n.clone("linePivotClone")).rotation.z=Math.PI,i)},t}(Ar.a);ai.a.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";var Hr="vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}";ai.a.IncludesShadersStore.packingFunctions=Hr;var Yr="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X});\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif";ai.a.IncludesShadersStore.kernelBlurFragment=Yr;var Kr="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif";ai.a.IncludesShadersStore.kernelBlurFragment2=Kr;var Qr="\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g;\nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth;\n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r;\nreturn coc;\n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include<packingFunctions>\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT;\nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";ai.a.ShadersStore.kernelBlurPixelShader=Qr;ai.a.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";var qr="\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}";ai.a.ShadersStore.kernelBlurVertexShader=qr;var Zr=function(e){function t(t,i,n,r,o,a,s,c,l,u,h){void 0===a&&(a=et.a.BILINEAR_SAMPLINGMODE),void 0===l&&(l=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===u&&(u=""),void 0===h&&(h=!1);var d=e.call(this,t,"kernelBlur",["delta","direction","cameraMinMaxZ"],["circleOfConfusionSampler"],r,o,a,s,c,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0)||this;return d.direction=i,d.blockCompilation=h,d._packedFloat=!1,d._staticDefines="",d._staticDefines=u,d.onApplyObservable.add(function(e){d._outputTexture?e.setFloat2("delta",1/d._outputTexture.width*d.direction.x,1/d._outputTexture.height*d.direction.y):e.setFloat2("delta",1/d.width*d.direction.x,1/d.height*d.direction.y)}),d.kernel=n,d}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"kernel",{get:function(){return this._idealKernel},set:function(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this.blockCompilation||this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"packedFloat",{get:function(){return this._packedFloat},set:function(e){this._packedFloat!==e&&(this._packedFloat=e,this.blockCompilation||this._updateParameters())},enumerable:!0,configurable:!0}),t.prototype.updateEffect=function(e,t,i,n,r,o){void 0===e&&(e=null),void 0===t&&(t=null),void 0===i&&(i=null),this._updateParameters(r,o)},t.prototype._updateParameters=function(t,i){for(var n=this._kernel,r=(n-1)/2,o=[],a=[],s=0,c=0;c<n;c++){var l=c/(n-1),u=this._gaussianWeight(2*l-1);o[c]=c-r,a[c]=u,s+=u}for(c=0;c<a.length;c++)a[c]/=s;var h=[],d=[],f=[];for(c=0;c<=r;c+=2){var p=Math.min(c+1,Math.floor(r));if(c===p)f.push({o:o[c],w:a[c]});else{var _=p===r,m=a[c]+a[p]*(_?.5:1),g=o[c]+1/(1+a[c]/a[p]);0===g?(f.push({o:o[c],w:a[c]}),f.push({o:o[c+1],w:a[c+1]})):(f.push({o:g,w:m}),f.push({o:-g,w:m}))}}for(c=0;c<f.length;c++)d[c]=f[c].o,h[c]=f[c].w;o=d,a=h;var v=this.getEngine().getCaps().maxVaryingVectors,y=Math.max(v,0)-1,b=Math.min(o.length,y),T="";T+=this._staticDefines,-1!=this._staticDefines.indexOf("DOF")&&(T+="#define CENTER_WEIGHT "+this._glslFloat(a[b-1])+"\r\n",b--);for(c=0;c<b;c++)T+="#define KERNEL_OFFSET"+c+" "+this._glslFloat(o[c])+"\r\n",T+="#define KERNEL_WEIGHT"+c+" "+this._glslFloat(a[c])+"\r\n";var E=0;for(c=y;c<o.length;c++)T+="#define KERNEL_DEP_OFFSET"+E+" "+this._glslFloat(o[c])+"\r\n",T+="#define KERNEL_DEP_WEIGHT"+E+" "+this._glslFloat(a[c])+"\r\n",E++;this.packedFloat&&(T+="#define PACKEDFLOAT 1"),this.blockCompilation=!1,e.prototype.updateEffect.call(this,T,null,null,{varyingCount:b,depCount:E},t,i)},t.prototype._nearestBestKernel=function(e){for(var t=Math.round(e),i=0,n=[t,t-1,t+1,t-2,t+2];i<n.length;i++){var r=n[i];if(r%2!=0&&Math.floor(r/2)%2==0&&r>0)return Math.max(r,3)}return Math.max(t,3)},t.prototype._gaussianWeight=function(e){var t=-e*e/(1/3*2*(1/3));return 1/(Math.sqrt(2*Math.PI)*(1/3))*Math.exp(t)},t.prototype._glslFloat=function(e,t){return void 0===t&&(t=8),e.toFixed(t).replace(/0+$/,"")},t}(ui),Jr=function(e){function t(t,i,n,r,o,s,c){void 0===o&&(o=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===s&&(s=et.a.BILINEAR_SAMPLINGMODE),void 0===c&&(c=!0);var l=e.call(this,t,i,n,r,!0,o,!1,s,c)||this;return l.scene=n,l.mirrorPlane=new mn.a(0,1,0,1),l._transformMatrix=a.a.Zero(),l._mirrorMatrix=a.a.Zero(),l._adaptiveBlurKernel=0,l._blurKernelX=0,l._blurKernelY=0,l._blurRatio=1,l.ignoreCameraViewport=!0,l._updateGammaSpace(),l._imageProcessingConfigChangeObserver=n.imageProcessingConfiguration.onUpdateParameters.add(function(){l._updateGammaSpace}),l.onBeforeRenderObservable.add(function(){a.a.ReflectionToRef(l.mirrorPlane,l._mirrorMatrix),l._savedViewMatrix=n.getViewMatrix(),l._mirrorMatrix.multiplyToRef(l._savedViewMatrix,l._transformMatrix),n.setTransformMatrix(l._transformMatrix,n.getProjectionMatrix()),n.clipPlane=l.mirrorPlane,n.getEngine().cullBackFaces=!1,n._mirroredCameraPosition=a.e.TransformCoordinates(n.activeCamera.globalPosition,l._mirrorMatrix)}),l.onAfterRenderObservable.add(function(){n.setTransformMatrix(l._savedViewMatrix,n.getProjectionMatrix()),n.getEngine().cullBackFaces=!0,n._mirroredCameraPosition=null,n.clipPlane=null}),l}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"blurRatio",{get:function(){return this._blurRatio},set:function(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"adaptiveBlurKernel",{set:function(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"blurKernel",{set:function(e){this.blurKernelX=e,this.blurKernelY=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"blurKernelX",{get:function(){return this._blurKernelX},set:function(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"blurKernelY",{get:function(){return this._blurKernelY},set:function(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),t.prototype._autoComputeBlurKernel=function(){var e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i},t.prototype._onRatioRescale=function(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()},t.prototype._updateGammaSpace=function(){this.gammaSpace=!this.scene.imageProcessingConfiguration.isEnabled||!this.scene.imageProcessingConfiguration.applyByPostProcess},t.prototype._preparePostProcesses=function(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){var e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender?g.a.TEXTURETYPE_FLOAT:g.a.TEXTURETYPE_HALF_FLOAT;this._blurX=new Zr("horizontal blur",new a.d(1,0),this._blurKernelX,this._blurRatio,null,et.a.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._texture:this._blurX.alwaysForcePOT=!0,this._blurY=new Zr("vertical blur",new a.d(0,1),this._blurKernelY,this._blurRatio,null,et.a.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)},t.prototype.clone=function(){var e=this.getScene();if(!e)return this;var i=this.getSize(),n=new t(this.name,i.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return n.hasAlpha=this.hasAlpha,n.level=this.level,n.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(n.renderList=this.renderList.slice(0)),n},t.prototype.serialize=function(){if(!this.name)return null;var t=e.prototype.serialize.call(this);return t.mirrorPlane=this.mirrorPlane.asArray(),t},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver)},t}(Fi);et.a._CreateMirror=function(e,t,i,n){return new Jr(e,t,i,n)};var $r=i(54);li.a.prototype._createDepthStencilCubeTexture=function(e,t){var i=new tt.a(this,tt.b.Unknown);if(i.isCube=!0,1===this.webGLVersion)return m.a.Error("Depth cube texture is not supported by WebGL 1."),i;var n=Object(h.a)({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t),r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,e,n.generateStencil,n.bilinearFiltering,n.comparisonFunction);for(var o=0;o<6;o++)n.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+o,0,r.DEPTH24_STENCIL8,e,e,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+o,0,r.DEPTH_COMPONENT24,e,e,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),i},li.a.prototype._partialLoadFile=function(e,t,i,n,r){void 0===r&&(r=null);this._loadFile(e,function(e){i[t]=e,i._internalCount++,6===i._internalCount&&n(i)},void 0,void 0,!0,function(e,t){r&&e&&r(e.status+" "+e.statusText,t)})},li.a.prototype._cascadeLoadFiles=function(e,t,i,n){void 0===n&&(n=null);var r=[];r._internalCount=0;for(var o=0;o<6;o++)this._partialLoadFile(i[o],o,r,t,n)},li.a.prototype._cascadeLoadImgs=function(e,t,i,n,r){void 0===n&&(n=null);var o=[];o._internalCount=0;for(var a=0;a<6;a++)this._partialLoadImg(i[a],a,o,e,t,n,r)},li.a.prototype._partialLoadImg=function(e,t,i,n,r,o,a){var s;void 0===o&&(o=null);s=$r.a.LoadImage(e,function(){s&&(i[t]=s,i._internalCount++,n&&n._removePendingData(s)),6===i._internalCount&&r(i)},function(e,t){n&&n._removePendingData(s),o&&o(e,t)},n?n.offlineProvider:null,a),n&&s&&n._addPendingData(s)},li.a.prototype._setCubeMapTextureParams=function(e){var t=this._gl;t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_MIN_FILTER,e?t.LINEAR_MIPMAP_LINEAR:t.LINEAR),t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),this._bindTextureDirectly(t.TEXTURE_CUBE_MAP,null)},li.a.prototype.createCubeTexture=function(e,t,i,n,r,o,a,s,c,l,u,h){var d=this;void 0===r&&(r=null),void 0===o&&(o=null),void 0===s&&(s=null),void 0===c&&(c=!1),void 0===l&&(l=0),void 0===u&&(u=0),void 0===h&&(h=null);var f=this._gl,p=h||new tt.a(this,tt.b.Cube);p.isCube=!0,p.url=e,p.generateMipMaps=!n,p._lodGenerationScale=l,p._lodGenerationOffset=u,this._doNotHandleContextLost||(p._extension=s,p._files=i);for(var _=e.lastIndexOf("."),g=s||(_>-1?e.substring(_).toLowerCase():""),v=null,y=0,b=li.a._TextureLoaders;y<b.length;y++){var T=b[y];if(T.canLoad(g)){v=T;break}}if(v){var E=function(e){d._bindTextureDirectly(f.TEXTURE_CUBE_MAP,p,!0),v.loadCubeData(e,p,c,r,o)};i&&6===i.length?v.supportCascades?this._cascadeLoadFiles(t,function(e){return E(e.map(function(e){return new Uint8Array(e)}))},i,o):o?o("Textures type does not support cascades."):m.a.Warn("Texture loader does not support cascades."):this._loadFile(e,function(e){return E(new Uint8Array(e))},void 0,void 0,!0,function(e,t){o&&e&&o(e.status+" "+e.statusText,t)})}else{if(!i)throw new Error("Cannot load cubemap because files were not defined");this._cascadeLoadImgs(t,function(e){var t=d.needPOTTextures?li.a.GetExponentOfTwo(e[0].width,d._caps.maxCubemapTextureSize):e[0].width,i=t,o=[f.TEXTURE_CUBE_MAP_POSITIVE_X,f.TEXTURE_CUBE_MAP_POSITIVE_Y,f.TEXTURE_CUBE_MAP_POSITIVE_Z,f.TEXTURE_CUBE_MAP_NEGATIVE_X,f.TEXTURE_CUBE_MAP_NEGATIVE_Y,f.TEXTURE_CUBE_MAP_NEGATIVE_Z];d._bindTextureDirectly(f.TEXTURE_CUBE_MAP,p,!0),d._unpackFlipY(!1);for(var s=a?d._getInternalFormat(a):d._gl.RGBA,c=0;c<o.length;c++)if(e[c].width!==t||e[c].height!==i){if(d._prepareWorkingCanvas(),!d._workingCanvas||!d._workingContext)return void m.a.Warn("Cannot create canvas to resize texture.");d._workingCanvas.width=t,d._workingCanvas.height=i,d._workingContext.drawImage(e[c],0,0,e[c].width,e[c].height,0,0,t,i),f.texImage2D(o[c],0,s,s,f.UNSIGNED_BYTE,d._workingCanvas)}else f.texImage2D(o[c],0,s,s,f.UNSIGNED_BYTE,e[c]);n||f.generateMipmap(f.TEXTURE_CUBE_MAP),d._setCubeMapTextureParams(!n),p.width=t,p.height=i,p.isReady=!0,a&&(p.format=a),p.onLoadedObservable.notifyObservers(p),p.onLoadedObservable.clear(),r&&r()},i,o)}return this._internalTexturesCache.push(p),p};var eo=i(36),to=function(e){function t(t,i,n,r,s,c,l,u,h,d,f,p,_){var m;void 0===n&&(n=null),void 0===r&&(r=!1),void 0===s&&(s=null),void 0===c&&(c=null),void 0===l&&(l=null),void 0===u&&(u=g.a.TEXTUREFORMAT_RGBA),void 0===h&&(h=!1),void 0===d&&(d=null),void 0===f&&(f=!1),void 0===p&&(p=.8),void 0===_&&(_=0);var v=e.call(this,i)||this;if(v.onLoadObservable=new o.c,v.boundingBoxPosition=a.e.Zero(),v._rotationY=0,v._files=null,v._forcedExtension=null,v._extensions=null,v._prefiltered=!1,v.name=t,v.url=t,v._noMipmap=r,v.hasAlpha=!1,v._format=u,v.isCube=!0,v._textureMatrix=a.a.Identity(),v._createPolynomials=f,v.coordinatesMode=et.a.CUBIC_MODE,v._extensions=n,v._files=s,v._forcedExtension=d,!t&&!s)return v;var y=t.lastIndexOf("."),b=d||(y>-1?t.substring(y).toLowerCase():""),T=".dds"===b,E=".env"===b;if(E?(v.gammaSpace=!1,v._prefiltered=!1,v.anisotropicFilteringLevel=1):(v._prefiltered=h,h&&(v.gammaSpace=!1,v.anisotropicFilteringLevel=1)),v._texture=v._getFromCache(t,r),!s&&(E||T||n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),s=[],n))for(var x=0;x<n.length;x++)s.push(t+n[x]);v._files=s;var P=function(){v.onLoadObservable.notifyObservers(v),c&&c()};return v._texture?v._texture.isReady?De.b.SetImmediate(function(){return P()}):v._texture.onLoadedObservable.add(function(){return P()}):i.useDelayedTextureLoading?v.delayLoadState=g.a.DELAYLOADSTATE_NOTLOADED:(v._texture=h?i.getEngine().createPrefilteredCubeTexture(t,i,p,_,c,l,u,d,v._createPolynomials):i.getEngine().createCubeTexture(t,i,s,r,c,l,v._format,d,!1,p,_),null===(m=v._texture)||void 0===m||m.onLoadedObservable.add(function(){return v.onLoadObservable.notifyObservers(v)})),v}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"boundingBoxSize",{get:function(){return this._boundingBoxSize},set:function(e){if(!this._boundingBoxSize||!this._boundingBoxSize.equals(e)){this._boundingBoxSize=e;var t=this.getScene();t&&t.markAllMaterialsAsDirty(g.a.MATERIAL_TextureDirtyFlag)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationY",{get:function(){return this._rotationY},set:function(e){this._rotationY=e,this.setReflectionTextureMatrix(a.a.RotationY(this._rotationY))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"noMipmap",{get:function(){return this._noMipmap},enumerable:!0,configurable:!0}),t.CreateFromImages=function(e,i,n){var r="";return e.forEach(function(e){return r+=e}),new t(r,i,null,n,e)},t.CreateFromPrefilteredData=function(e,i,n,r){void 0===n&&(n=null),void 0===r&&(r=!0);var o=i.useDelayedTextureLoading;i.useDelayedTextureLoading=!1;var a=new t(e,i,null,!1,null,null,null,void 0,!0,n,r);return i.useDelayedTextureLoading=o,a},Object.defineProperty(t.prototype,"isPrefiltered",{get:function(){return this._prefiltered},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"CubeTexture"},t.prototype.updateURL=function(e,t,i,n){void 0===n&&(n=!1),this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(g.a.MATERIAL_TextureDirtyFlag)),this.name&&!eo.a.StartsWith(this.name,"data:")||(this.name=e),this.url=e,this.delayLoadState=g.a.DELAYLOADSTATE_NOTLOADED,this._prefiltered=n,this._prefiltered&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1),this._forcedExtension=t||null,i&&(this._delayedOnLoad=i),this.delayLoad(t)},t.prototype.delayLoad=function(e){var t,i=this;if(this.delayLoadState===g.a.DELAYLOADSTATE_NOTLOADED){var n=this.getScene();n&&(this.delayLoadState=g.a.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||(this._prefiltered?this._texture=n.getEngine().createPrefilteredCubeTexture(this.url,n,.8,0,this._delayedOnLoad,void 0,this._format,void 0,this._createPolynomials):this._texture=n.getEngine().createCubeTexture(this.url,n,this._files,this._noMipmap,this._delayedOnLoad,null,this._format,e),null===(t=this._texture)||void 0===t||t.onLoadedObservable.add(function(){return i.onLoadObservable.notifyObservers(i)})))}},t.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},t.prototype.setReflectionTextureMatrix=function(e){var t=this;e.updateFlag!==this._textureMatrix.updateFlag&&(e.isIdentity()!==this._textureMatrix.isIdentity()&&this.getScene().markAllMaterialsAsDirty(g.a.MATERIAL_TextureDirtyFlag,function(e){return-1!==e.getActiveTextures().indexOf(t)}),this._textureMatrix=e)},t.Parse=function(e,i,n){var r=N.a.Parse(function(){var r=!1;return e.prefiltered&&(r=e.prefiltered),new t(n+e.name,i,e.extensions,!1,e.files||null,null,null,void 0,r,e.forcedExtension)},e,i);if(e.boundingBoxPosition&&(r.boundingBoxPosition=a.e.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=a.e.FromArray(e.boundingBoxSize)),e.animations)for(var o=0;o<e.animations.length;o++){var s=e.animations[o],l=c.a.GetClass("BABYLON.Animation");l&&r.animations.push(l.Parse(s))}return r},t.prototype.clone=function(){var e=this,i=this.getScene(),n=0,r=N.a.Clone(function(){if(!i)return e;var r=new t(e.url,i,e._extensions,e._noMipmap,e._files);return n=r.uniqueId,r},this);return r.uniqueId=n,r},Object(h.c)([Object(N.c)("rotationY")],t.prototype,"rotationY",null),Object(h.c)([Object(N.c)("files")],t.prototype,"_files",void 0),Object(h.c)([Object(N.c)("forcedExtension")],t.prototype,"_forcedExtension",void 0),Object(h.c)([Object(N.c)("extensions")],t.prototype,"_extensions",void 0),Object(h.c)([Object(N.j)("textureMatrix")],t.prototype,"_textureMatrix",void 0),t}(jn.a);et.a._CubeTextureParser=to.Parse,c.a.RegisteredTypes["BABYLON.CubeTexture"]=to;var io=i(16),no=i(73),ro=i(81),oo=i(21),ao=" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif";ai.a.IncludesShadersStore.backgroundFragmentDeclaration=ao;var so="layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif\nmat4 view;\n};";ai.a.IncludesShadersStore.backgroundUboDeclaration=so;i(118),i(97),i(98),i(139),i(117),i(106),i(113),i(101),i(121),i(122);var co="#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=saturate(viewAngleToFloor/startAngle);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n";ai.a.ShadersStore.backgroundPixelShader=co;var lo="uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif";ai.a.IncludesShadersStore.backgroundVertexDeclaration=lo;i(74),i(77),i(108),i(123),i(78),i(75),i(102),i(142),i(124);var uo="precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR == 0u) {\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n} else {\ngl_Position=viewProjectionR*finalWorld*vec4(position,1.0);\n}\n#else\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#endif\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n";ai.a.ShadersStore.backgroundVertexShader=uo;var ho=i(64),fo=function(e){function t(){var t=e.call(this)||this;return t.DIFFUSE=!1,t.DIFFUSEDIRECTUV=0,t.GAMMADIFFUSE=!1,t.DIFFUSEHASALPHA=!1,t.OPACITYFRESNEL=!1,t.REFLECTIONBLUR=!1,t.REFLECTIONFRESNEL=!1,t.REFLECTIONFALLOFF=!1,t.TEXTURELODSUPPORT=!1,t.PREMULTIPLYALPHA=!1,t.USERGBCOLOR=!1,t.USEHIGHLIGHTANDSHADOWCOLORS=!1,t.NOISE=!1,t.REFLECTIONBGR=!1,t.IMAGEPROCESSING=!1,t.VIGNETTE=!1,t.VIGNETTEBLENDMODEMULTIPLY=!1,t.VIGNETTEBLENDMODEOPAQUE=!1,t.TONEMAPPING=!1,t.TONEMAPPING_ACES=!1,t.CONTRAST=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=!1,t.SAMPLER3DBGRMAP=!1,t.IMAGEPROCESSINGPOSTPROCESS=!1,t.EXPOSURE=!1,t.MULTIVIEW=!1,t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.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.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.EQUIRECTANGULAR_RELFECTION_FOV=!1,t.MAINUV1=!1,t.MAINUV2=!1,t.UV1=!1,t.UV2=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.POINTSIZE=!1,t.FOG=!1,t.NORMAL=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.SHADOWFLOAT=!1,t.rebuild(),t}return Object(h.d)(t,e),t}(no.a),po=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.primaryColor=s.a.White(),n._primaryColorShadowLevel=0,n._primaryColorHighlightLevel=0,n.reflectionTexture=null,n.reflectionBlur=0,n.diffuseTexture=null,n._shadowLights=null,n.shadowLights=null,n.shadowLevel=0,n.sceneCenter=a.e.Zero(),n.opacityFresnel=!0,n.reflectionFresnel=!1,n.reflectionFalloffDistance=0,n.reflectionAmount=1,n.reflectionReflectance0=.05,n.reflectionReflectance90=.5,n.useRGBColor=!0,n.enableNoise=!1,n._fovMultiplier=1,n.useEquirectangularFOV=!1,n._maxSimultaneousLights=4,n.maxSimultaneousLights=4,n._imageProcessingObserver=null,n.switchToBGR=!1,n._renderTargets=new oi.a(16),n._reflectionControls=a.f.Zero(),n._white=s.a.White(),n._primaryShadowColor=s.a.Black(),n._primaryHighlightColor=s.a.Black(),n._attachImageProcessingConfiguration(null),n.getRenderTargetTextures=function(){return n._renderTargets.reset(),n._diffuseTexture&&n._diffuseTexture.isRenderTarget&&n._renderTargets.push(n._diffuseTexture),n._reflectionTexture&&n._reflectionTexture.isRenderTarget&&n._renderTargets.push(n._reflectionTexture),n._renderTargets},n}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"_perceptualColor",{get:function(){return this.__perceptualColor},set:function(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"primaryColorShadowLevel",{get:function(){return this._primaryColorShadowLevel},set:function(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"primaryColorHighlightLevel",{get:function(){return this._primaryColorHighlightLevel},set:function(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"reflectionStandardFresnelWeight",{set:function(e){var i=e;i<.5?(i*=2,this.reflectionReflectance0=t.StandardReflectance0*i,this.reflectionReflectance90=t.StandardReflectance90*i):(i=2*i-1,this.reflectionReflectance0=t.StandardReflectance0+(1-t.StandardReflectance0)*i,this.reflectionReflectance90=t.StandardReflectance90+(1-t.StandardReflectance90)*i)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fovMultiplier",{get:function(){return this._fovMultiplier},set:function(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))},enumerable:!0,configurable:!0}),t.prototype._attachImageProcessingConfiguration=function(e){var t=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(function(){t._computePrimaryColorFromPerceptualColor(),t._markAllSubMeshesAsImageProcessingDirty()})))},Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this.imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurves",{get:function(){return this.imageProcessingConfiguration.colorCurves},set:function(e){this.imageProcessingConfiguration.colorCurves=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasRenderTargetTextures",{get:function(){return!(!this._diffuseTexture||!this._diffuseTexture.isRenderTarget)||!(!this._reflectionTexture||!this._reflectionTexture.isRenderTarget)},enumerable:!0,configurable:!0}),t.prototype.needAlphaTesting=function(){return!0},t.prototype.needAlphaBlending=function(){return this.alpha<0||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha},t.prototype.isReadyForSubMesh=function(e,t,i){var n=this;if(void 0===i&&(i=!1),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new fo);var r=this.getScene(),o=t._materialDefines;if(!this.checkReadyOnEveryCall&&t.effect&&o._renderId===r.getRenderId())return!0;var a=r.getEngine();if(io.a.PrepareDefinesForLights(r,e,o,!1,this._maxSimultaneousLights),o._needNormals=!0,io.a.PrepareDefinesForMultiview(r,o),o._areTexturesDirty){if(o._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(o.TEXTURELODSUPPORT=!0),this._diffuseTexture&&oo.a.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;io.a.PrepareDefinesForMergedUV(this._diffuseTexture,o,"DIFFUSE"),o.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,o.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,o.OPACITYFRESNEL=this._opacityFresnel}else o.DIFFUSE=!1,o.DIFFUSEHASALPHA=!1,o.GAMMADIFFUSE=!1,o.OPACITYFRESNEL=!1;var s=this._reflectionTexture;if(s&&oo.a.ReflectionTextureEnabled){if(!s.isReadyOrNotBlocking())return!1;switch(o.REFLECTION=!0,o.GAMMAREFLECTION=s.gammaSpace,o.RGBDREFLECTION=s.isRGBD,o.REFLECTIONBLUR=this._reflectionBlur>0,o.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!s.invertZ:s.invertZ,o.LODINREFLECTIONALPHA=s.lodLevelInAlpha,o.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,o.REFLECTIONBGR=this.switchToBGR,s.coordinatesMode===et.a.INVCUBIC_MODE&&(o.INVERTCUBICMAP=!0),o.REFLECTIONMAP_3D=s.isCube,s.coordinatesMode){case et.a.EXPLICIT_MODE:o.REFLECTIONMAP_EXPLICIT=!0;break;case et.a.PLANAR_MODE:o.REFLECTIONMAP_PLANAR=!0;break;case et.a.PROJECTION_MODE:o.REFLECTIONMAP_PROJECTION=!0;break;case et.a.SKYBOX_MODE:o.REFLECTIONMAP_SKYBOX=!0;break;case et.a.SPHERICAL_MODE:o.REFLECTIONMAP_SPHERICAL=!0;break;case et.a.EQUIRECTANGULAR_MODE:o.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case et.a.FIXED_EQUIRECTANGULAR_MODE:o.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case et.a.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:o.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case et.a.CUBIC_MODE:case et.a.INVCUBIC_MODE:default:o.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(o.REFLECTIONFRESNEL=!0,o.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(o.REFLECTIONFRESNEL=!1,o.REFLECTIONFALLOFF=!1)}else o.REFLECTION=!1,o.REFLECTIONFRESNEL=!1,o.REFLECTIONFALLOFF=!1,o.REFLECTIONBLUR=!1,o.REFLECTIONMAP_3D=!1,o.REFLECTIONMAP_SPHERICAL=!1,o.REFLECTIONMAP_PLANAR=!1,o.REFLECTIONMAP_CUBIC=!1,o.REFLECTIONMAP_PROJECTION=!1,o.REFLECTIONMAP_SKYBOX=!1,o.REFLECTIONMAP_EXPLICIT=!1,o.REFLECTIONMAP_EQUIRECTANGULAR=!1,o.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,o.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,o.INVERTCUBICMAP=!1,o.REFLECTIONMAP_OPPOSITEZ=!1,o.LODINREFLECTIONALPHA=!1,o.GAMMAREFLECTION=!1,o.RGBDREFLECTION=!1}o.PREMULTIPLYALPHA=this.alphaMode===g.a.ALPHA_PREMULTIPLIED||this.alphaMode===g.a.ALPHA_PREMULTIPLIED_PORTERDUFF,o.USERGBCOLOR=this._useRGBColor,o.NOISE=this._enableNoise}if(o._areLightsDirty&&(o.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel)),o._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(o)}if(io.a.PrepareDefinesForMisc(e,r,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),o),io.a.PrepareDefinesForFrameBoundValues(r,a,o,i),io.a.PrepareDefinesForAttributes(e,o,!1,!0,!1)&&e&&(r.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(en.b.NormalKind)||(e.createNormals(!0),m.a.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),o.isDirty){o.markAsProcessed(),r.resetCachedMaterial();var c=new ho.a;o.FOG&&c.addFallback(0,"FOG"),o.POINTSIZE&&c.addFallback(1,"POINTSIZE"),o.MULTIVIEW&&c.addFallback(0,"MULTIVIEW"),io.a.HandleFallbacksForShadows(o,c,this._maxSimultaneousLights);var l=[en.b.PositionKind];o.NORMAL&&l.push(en.b.NormalKind),o.UV1&&l.push(en.b.UVKind),o.UV2&&l.push(en.b.UV2Kind),io.a.PrepareAttributesForBones(l,e,o,c),io.a.PrepareAttributesForInstances(l,o);var u=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix"],h=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],d=["Material","Scene"];Yi.a&&(Yi.a.PrepareUniforms(u,o),Yi.a.PrepareSamplers(h,o)),io.a.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:d,samplers:h,defines:o,maxSimultaneousLights:this._maxSimultaneousLights});var f=o.toString();t.setEffect(r.getEngine().createEffect("background",{attributes:l,uniformsNames:u,uniformBuffersNames:d,samplers:h,defines:f,fallbacks:c,onCompiled:function(e){n.onCompiled&&n.onCompiled(e),n.bindSceneUniformBuffer(e,r.getSceneUniformBuffer())},onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},a),o),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady())&&(o._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype._computePrimaryColorFromPerceptualColor=function(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())},t.prototype._computePrimaryColors=function(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))},t.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.create()},t.prototype.unbind=function(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),e.prototype.unbind.call(this)},t.prototype.bindOnlyWorldMatrix=function(e){this._activeEffect.setMatrix("world",e)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),r=i._materialDefines;if(r){var o=i.effect;if(o){this._activeEffect=o,this.bindOnlyWorldMatrix(e),io.a.BindBonesParameters(t,this._activeEffect);var a=this._mustRebind(n,o,t.visibility);if(a){this._uniformBuffer.bindToEffect(o,"Material"),this.bindViewProjection(o);var s=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(n.texturesEnabled&&(this._diffuseTexture&&oo.a.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),io.a.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),s&&oo.a.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",s.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",s.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",s.getSize().width,s.lodGenerationScale,s.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),r.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),n.texturesEnabled&&(this._diffuseTexture&&oo.a.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),s&&oo.a.ReflectionTextureEnabled&&(r.REFLECTIONBLUR&&r.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",s):r.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",s._lodTextureMid||s),this._uniformBuffer.setTexture("reflectionSamplerLow",s._lodTextureLow||s),this._uniformBuffer.setTexture("reflectionSamplerHigh",s._lodTextureHigh||s)):this._uniformBuffer.setTexture("reflectionSampler",s),r.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w)))),io.a.BindClipPlane(this._activeEffect,n),io.a.BindEyePosition(o,n)}!a&&this.isFrozen||(n.lightsEnabled&&io.a.BindLights(n,t,this._activeEffect,r,this._maxSimultaneousLights,!1),this.bindView(o),io.a.BindFogParameters(n,t,this._activeEffect,!0),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._uniformBuffer.update(),this._afterBind(t,this._activeEffect)}}},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||(this._reflectionTexture===t||this._diffuseTexture===t)},t.prototype.dispose=function(t,i){void 0===t&&(t=!1),void 0===i&&(i=!1),i&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e.prototype.dispose.call(this,t)},t.prototype.clone=function(e){var i=this;return N.a.Clone(function(){return new t(e,i.getScene())},this)},t.prototype.serialize=function(){var e=N.a.Serialize(this);return e.customType="BABYLON.BackgroundMaterial",e},t.prototype.getClassName=function(){return"BackgroundMaterial"},t.Parse=function(e,i,n){return N.a.Parse(function(){return new t(e.name,i)},e,i,n)},t.StandardReflectance0=.05,t.StandardReflectance90=.5,Object(h.c)([Object(N.e)()],t.prototype,"_primaryColor",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"primaryColor",void 0),Object(h.c)([Object(N.e)()],t.prototype,"__perceptualColor",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_primaryColorShadowLevel",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_primaryColorHighlightLevel",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"primaryColorHighlightLevel",null),Object(h.c)([Object(N.m)()],t.prototype,"_reflectionTexture",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionTexture",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_reflectionBlur",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionBlur",void 0),Object(h.c)([Object(N.m)()],t.prototype,"_diffuseTexture",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"shadowLights",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_shadowLevel",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"shadowLevel",void 0),Object(h.c)([Object(N.o)()],t.prototype,"_sceneCenter",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"sceneCenter",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_opacityFresnel",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"opacityFresnel",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_reflectionFresnel",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionFresnel",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_reflectionFalloffDistance",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionFalloffDistance",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_reflectionAmount",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionAmount",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_reflectionReflectance0",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionReflectance0",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_reflectionReflectance90",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionReflectance90",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_useRGBColor",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRGBColor",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_enableNoise",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"enableNoise",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_maxSimultaneousLights",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"maxSimultaneousLights",void 0),Object(h.c)([Object(N.i)()],t.prototype,"_imageProcessingConfiguration",void 0),t}(ro.a);c.a.RegisteredTypes["BABYLON.BackgroundMaterial"]=po;var _o=function(){function e(t,i){var n=this;this._errorHandler=function(e,t){n.onErrorObservable.notifyObservers({message:e,exception:t})},this._options=Object(h.a)(Object(h.a)({},e._getDefaultOptions()),t),this._scene=i,this.onErrorObservable=new o.c,this._setupBackground(),this._setupImageProcessing()}return e._getDefaultOptions=function(){return{createGround:!0,groundSize:15,groundTexture:this._groundTextureCDNUrl,groundColor:new s.a(.2,.2,.3).toLinearSpace().scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:g.a.TEXTURETYPE_UNSIGNED_INT,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._skyboxTextureCDNUrl,skyboxColor:new s.a(.2,.2,.3).toLinearSpace().scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:a.e.Zero(),setupImageProcessing:!0,environmentTexture:this._environmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}},Object.defineProperty(e.prototype,"rootMesh",{get:function(){return this._rootMesh},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"skybox",{get:function(){return this._skybox},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"skyboxTexture",{get:function(){return this._skyboxTexture},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"skyboxMaterial",{get:function(){return this._skyboxMaterial},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"ground",{get:function(){return this._ground},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"groundTexture",{get:function(){return this._groundTexture},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"groundMirror",{get:function(){return this._groundMirror},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"groundMirrorRenderList",{get:function(){return this._groundMirror?this._groundMirror.renderList:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"groundMaterial",{get:function(){return this._groundMaterial},enumerable:!0,configurable:!0}),e.prototype.updateOptions=function(e){var t=Object(h.a)(Object(h.a)({},this._options),e);this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()},e.prototype.setMainColor=function(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new s.b(e.r,e.g,e.b,1))},e.prototype._setupImageProcessing=function(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())},e.prototype._setupEnvironmentTexture=function(){if(!this._scene.environmentTexture)if(this._options.environmentTexture instanceof jn.a)this._scene.environmentTexture=this._options.environmentTexture;else{var e=to.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}},e.prototype._setupBackground=function(){this._rootMesh||(this._rootMesh=new Ae.a("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;var e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y},e.prototype._getSceneSize=function(){var e=this,t=this._options.groundSize,i=this._options.skyboxSize,n=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:t,skyboxSize:i,rootPosition:n};var r=this._scene.getWorldExtends(function(t){return t!==e._ground&&t!==e._rootMesh&&t!==e._skybox}),o=r.max.subtract(r.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof Bt&&this._scene.activeCamera.upperRadiusLimit&&(i=t=2*this._scene.activeCamera.upperRadiusLimit);var a=o.length();a>t&&(i=t=2*a),t*=1.1,i*=1.5,(n=r.min.add(o.scale(.5))).y=r.min.y-this._options.groundYBias}return{groundSize:t,skyboxSize:i,rootPosition:n}},e.prototype._setupGround=function(e){var t=this;this._ground&&!this._ground.isDisposed()||(this._ground=Ae.a.CreatePlane("BackgroundPlane",e.groundSize,this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add(function(){t._ground=null})),this._ground.receiveShadows=this._options.enableGroundShadow},e.prototype._setupGroundMaterial=function(){this._groundMaterial||(this._groundMaterial=new po("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=g.a.ALPHA_PREMULTIPLIED_PORTERDUFF,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)},e.prototype._setupGroundDiffuseTexture=function(){if(this._groundMaterial&&!this._groundTexture)if(this._options.groundTexture instanceof jn.a)this._groundMaterial.diffuseTexture=this._options.groundTexture;else{var e=new et.a(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler);e.gammaSpace=!1,e.hasAlpha=!0,this._groundMaterial.diffuseTexture=e}},e.prototype._setupGroundMirrorTexture=function(e){var t=et.a.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new Jr("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,et.a.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new mn.a(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.gammaSpace=!1,this._groundMirror.renderList))for(var i=0;i<this._scene.meshes.length;i++){var n=this._scene.meshes[i];n!==this._ground&&n!==this._skybox&&n!==this._rootMesh&&this._groundMirror.renderList.push(n)}this._groundMirror.clearColor=new s.b(this._options.groundColor.r,this._options.groundColor.g,this._options.groundColor.b,1),this._groundMirror.adaptiveBlurKernel=this._options.groundMirrorBlurKernel},e.prototype._setupMirrorInGroundMaterial=function(){this._groundMaterial&&(this._groundMaterial.reflectionTexture=this._groundMirror,this._groundMaterial.reflectionFresnel=!0,this._groundMaterial.reflectionAmount=this._options.groundMirrorAmount,this._groundMaterial.reflectionStandardFresnelWeight=this._options.groundMirrorFresnelWeight,this._groundMaterial.reflectionFalloffDistance=this._options.groundMirrorFallOffDistance)},e.prototype._setupSkybox=function(e){var t=this;this._skybox&&!this._skybox.isDisposed()||(this._skybox=Ae.a.CreateBox("BackgroundSkybox",e.skyboxSize,this._scene,void 0,Ae.a.BACKSIDE),this._skybox.onDisposeObservable.add(function(){t._skybox=null})),this._skybox.parent=this._rootMesh},e.prototype._setupSkyboxMaterial=function(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new po("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)},e.prototype._setupSkyboxReflectionTexture=function(){this._skyboxMaterial&&(this._skyboxTexture||(this._options.skyboxTexture instanceof jn.a?this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture:(this._skyboxTexture=new to(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=et.a.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture)))},e.prototype.dispose=function(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)},e._groundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",e._skyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",e._environmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env",e}(),mo=function(e){function t(i,n,r,s,c){void 0===c&&(c=null);var l=e.call(this,i,s)||this;l._useDirectMapping=!1,l.onLoadErrorObservable=new o.c,l._imageMode=t.MODE_MONOSCOPIC,l._onBeforeCameraRenderObserver=null,i=i||"photoDome",r.resolution=0|Math.abs(r.resolution)||32,r.size=Math.abs(r.size)||(s.activeCamera?.48*s.activeCamera.maxZ:1e3),void 0===r.useDirectMapping?l._useDirectMapping=!0:l._useDirectMapping=r.useDirectMapping,void 0===r.faceForward&&(r.faceForward=!0),l._setReady(!1);var u=l._material=new po(i+"_material",s);if(l._mesh=Ae.a.CreateSphere(i+"_mesh",r.resolution,r.size,s,!1,Ae.a.BACKSIDE),u.opacityFresnel=!1,u.useEquirectangularFOV=!0,u.fovMultiplier=1,l.photoTexture=new et.a(n,s,!0,!l._useDirectMapping,void 0,void 0,function(e,t){l.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),c&&c(e,t)}),l.photoTexture.anisotropicFilteringLevel=1,l.photoTexture.onLoadObservable.addOnce(function(){l._setReady(!0)}),l._mesh.material=u,l._mesh.parent=l,r.faceForward&&s.activeCamera){var h=s.activeCamera,d=a.e.Forward(),f=a.e.TransformNormal(d,h.getViewMatrix());f.normalize(),l.rotation.y=Math.acos(a.e.Dot(d,f))}return l}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"photoTexture",{get:function(){return this._photoTexture},set:function(e){this._photoTexture!==e&&(this._photoTexture=e,this._useDirectMapping?(this._photoTexture.wrapU=et.a.CLAMP_ADDRESSMODE,this._photoTexture.wrapV=et.a.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._photoTexture):(this._photoTexture.coordinatesMode=et.a.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._photoTexture.wrapV=et.a.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._photoTexture))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"mesh",{get:function(){return this._mesh},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fovMultiplier",{get:function(){return this._material.fovMultiplier},set:function(e){this._material.fovMultiplier=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageMode",{get:function(){return this._imageMode},set:function(e){this._imageMode!==e&&this._changeImageMode(e)},enumerable:!0,configurable:!0}),t.prototype._changeImageMode=function(e){var i=this;switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._imageMode=e,this._photoTexture.uScale=1,this._photoTexture.vScale=1,this._photoTexture.uOffset=0,this._photoTexture.vOffset=0,e){case t.MODE_SIDEBYSIDE:this._photoTexture.uScale=.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(function(e){i._photoTexture.uOffset=e.isRightCamera?.5:0});break;case t.MODE_TOPBOTTOM:this._photoTexture.vScale=.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(function(e){i._photoTexture.vOffset=e.isRightCamera?.5:0})}},t.prototype.dispose=function(t,i){void 0===i&&(i=!1),this._photoTexture.dispose(),this._mesh.dispose(),this._material.dispose(),this.onLoadErrorObservable.clear(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),e.prototype.dispose.call(this,t,i)},t.MODE_MONOSCOPIC=0,t.MODE_TOPBOTTOM=1,t.MODE_SIDEBYSIDE=2,t}(wr.a),go=function(){function e(){}return e.ExpandRGBDTexture=function(e){var t=e._texture;if(t&&e.isRGBD){var i=t.getEngine(),n=i.getCaps(),r=!1;n.textureHalfFloatRender&&n.textureHalfFloatLinearFiltering?(r=!0,t.type=g.a.TEXTURETYPE_HALF_FLOAT):n.textureFloatRender&&n.textureFloatLinearFiltering&&(r=!0,t.type=g.a.TEXTURETYPE_FLOAT),r&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1),e.onLoadObservable.addOnce(function(){if(r){var n=new ui("rgbdDecode","rgbdDecode",null,null,1,null,g.a.TEXTURE_TRILINEAR_SAMPLINGMODE,i,!1,void 0,t.type,void 0,null,!1),o=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:g.a.TEXTUREFORMAT_RGBA});n.getEffect().executeWhenCompiled(function(){n.onApply=function(e){e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([n],o,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),i._releaseFramebufferObjects(o),n&&n.dispose(),o._swapAndDie(t),t.isReady=!0})}})}},e}(),vo=function(){function e(){}return e.GetEnvironmentBRDFTexture=function(e){if(!e.environmentBRDFTexture){var t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;var i=e._blockEntityCollection;e._blockEntityCollection=!1;var n=et.a.CreateFromBase64String(this._environmentBRDFBase64Texture,"EnvironmentBRDFTexture",e,!0,!1,et.a.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;var r=e.getEngine().getLoadedTexturesCache(),o=r.indexOf(n.getInternalTexture());-1!==o&&r.splice(o,1),n.isRGBD=!0,n.wrapU=et.a.CLAMP_ADDRESSMODE,n.wrapV=et.a.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=n,e.useDelayedTextureLoading=t,go.ExpandRGBDTexture(n)}return e.environmentBRDFTexture},e._environmentBRDFBase64Texture="data:image/png;base64, ",e}(),yo=function(){function e(t){this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=e._DefaultIndexOfRefraction,this.indexOfRefraction=e._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._bumpTexture=null,this.bumpTexture=null,this._isTintEnabled=!1,this.isTintEnabled=!1,this.tintColor=s.a.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=t}return e.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},e.prototype.isReadyForSubMesh=function(e,t,i,n){if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&oo.a.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(i.getCaps().standardDerivatives&&this._bumpTexture&&oo.a.ClearCoatBumpTextureEnabled&&!n&&!this._bumpTexture.isReady())return!1;if(this._isTintEnabled&&this._tintTexture&&oo.a.ClearCoatTintTextureEnabled&&!this._tintTexture.isReadyOrNotBlocking())return!1}return!0},e.prototype.prepareDefines=function(t,i){this._isEnabled?(t.CLEARCOAT=!0,t._areTexturesDirty&&i.texturesEnabled&&(this._texture&&oo.a.ClearCoatTextureEnabled?io.a.PrepareDefinesForMergedUV(this._texture,t,"CLEARCOAT_TEXTURE"):t.CLEARCOAT_TEXTURE=!1,this._bumpTexture&&oo.a.ClearCoatBumpTextureEnabled?io.a.PrepareDefinesForMergedUV(this._bumpTexture,t,"CLEARCOAT_BUMP"):t.CLEARCOAT_BUMP=!1,t.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===e._DefaultIndexOfRefraction,this._isTintEnabled?(t.CLEARCOAT_TINT=!0,this._tintTexture&&oo.a.ClearCoatTintTextureEnabled?io.a.PrepareDefinesForMergedUV(this._tintTexture,t,"CLEARCOAT_TINT_TEXTURE"):t.CLEARCOAT_TINT_TEXTURE=!1):(t.CLEARCOAT_TINT=!1,t.CLEARCOAT_TINT_TEXTURE=!1))):(t.CLEARCOAT=!1,t.CLEARCOAT_TEXTURE=!1,t.CLEARCOAT_BUMP=!1,t.CLEARCOAT_TINT=!1,t.CLEARCOAT_TINT_TEXTURE=!1)},e.prototype.bindForSubMesh=function(e,t,i,n,r,o,a){if(!e.useUbo||!r||!e.isSync){this._texture&&oo.a.ClearCoatTextureEnabled&&(e.updateFloat2("vClearCoatInfos",this._texture.coordinatesIndex,this._texture.level),io.a.BindTextureMatrix(this._texture,e,"clearCoat")),this._bumpTexture&&i.getCaps().standardDerivatives&&oo.a.ClearCoatTextureEnabled&&!n&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),io.a.BindTextureMatrix(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",o?1:-1,a?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",o?-1:1,a?-1:1)),this._tintTexture&&oo.a.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),io.a.BindTextureMatrix(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);var s=1-this._indexOfRefraction,c=1+this._indexOfRefraction,l=Math.pow(-s/c,2),u=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",l,u,s,c),this._isTintEnabled&&(e.updateFloat4("vClearCoatTintParams",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintThickness)),e.updateFloat("clearCoatColorAtDistance",Math.max(1e-5,this.tintColorAtDistance)))}t.texturesEnabled&&(this._texture&&oo.a.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._bumpTexture&&i.getCaps().standardDerivatives&&oo.a.ClearCoatBumpTextureEnabled&&!n&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&oo.a.ClearCoatTintTextureEnabled&&e.setTexture("clearCoatTintSampler",this._tintTexture))},e.prototype.hasTexture=function(e){return this._texture===e||(this._bumpTexture===e||this._tintTexture===e)},e.prototype.getActiveTextures=function(e){this._texture&&e.push(this._texture),this._bumpTexture&&e.push(this._bumpTexture),this._tintTexture&&e.push(this._tintTexture)},e.prototype.getAnimatables=function(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)},e.prototype.dispose=function(e){e&&(this._texture&&this._texture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._tintTexture&&this._tintTexture.dispose())},e.prototype.getClassName=function(){return"PBRClearCoatConfiguration"},e.AddFallbacks=function(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i},e.AddUniforms=function(e){e.push("vClearCoatTangentSpaceParams","vClearCoatParams","vClearCoatRefractionParams","vClearCoatTintParams","clearCoatColorAtDistance","clearCoatMatrix","clearCoatBumpMatrix","clearCoatTintMatrix","vClearCoatInfos","vClearCoatBumpInfos","vClearCoatTintInfos")},e.AddSamplers=function(e){e.push("clearCoatSampler","clearCoatBumpSampler","clearCoatTintSampler")},e.PrepareUniformBuffer=function(e){e.addUniform("vClearCoatParams",2),e.addUniform("vClearCoatRefractionParams",4),e.addUniform("vClearCoatInfos",2),e.addUniform("clearCoatMatrix",16),e.addUniform("vClearCoatBumpInfos",2),e.addUniform("vClearCoatTangentSpaceParams",2),e.addUniform("clearCoatBumpMatrix",16),e.addUniform("vClearCoatTintParams",4),e.addUniform("clearCoatColorAtDistance",1),e.addUniform("vClearCoatTintInfos",2),e.addUniform("clearCoatTintMatrix",16)},e.prototype.copyTo=function(e){N.a.Clone(function(){return e},this)},e.prototype.serialize=function(){return N.a.Serialize(this)},e.prototype.parse=function(e,t,i){var n=this;N.a.Parse(function(){return n},e,t,i)},e._DefaultIndexOfRefraction=1.5,Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"isEnabled",void 0),Object(h.c)([Object(N.c)()],e.prototype,"intensity",void 0),Object(h.c)([Object(N.c)()],e.prototype,"roughness",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"indexOfRefraction",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"texture",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"bumpTexture",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"isTintEnabled",void 0),Object(h.c)([Object(N.e)()],e.prototype,"tintColor",void 0),Object(h.c)([Object(N.c)()],e.prototype,"tintColorAtDistance",void 0),Object(h.c)([Object(N.c)()],e.prototype,"tintThickness",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"tintTexture",void 0),e}(),bo=function(){function e(e){this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new a.d(1,0),this._texture=null,this.texture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e}return e.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},e.prototype.isReadyForSubMesh=function(e,t){return!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&oo.a.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())},e.prototype.prepareDefines=function(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!t.isVerticesDataPresent(en.b.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&i.texturesEnabled&&(this._texture&&oo.a.AnisotropicTextureEnabled?io.a.PrepareDefinesForMergedUV(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1)},e.prototype.bindForSubMesh=function(e,t,i){e.useUbo&&i&&e.isSync||(this._texture&&oo.a.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),io.a.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&oo.a.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)},e.prototype.hasTexture=function(e){return this._texture===e},e.prototype.getActiveTextures=function(e){this._texture&&e.push(this._texture)},e.prototype.getAnimatables=function(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)},e.prototype.dispose=function(e){e&&this._texture&&this._texture.dispose()},e.prototype.getClassName=function(){return"PBRAnisotropicConfiguration"},e.AddFallbacks=function(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i},e.AddUniforms=function(e){e.push("vAnisotropy","vAnisotropyInfos","anisotropyMatrix")},e.PrepareUniformBuffer=function(e){e.addUniform("vAnisotropy",3),e.addUniform("vAnisotropyInfos",2),e.addUniform("anisotropyMatrix",16)},e.AddSamplers=function(e){e.push("anisotropySampler")},e.prototype.copyTo=function(e){N.a.Clone(function(){return e},this)},e.prototype.serialize=function(){return N.a.Serialize(this)},e.prototype.parse=function(e,t,i){var n=this;N.a.Parse(function(){return n},e,t,i)},Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"isEnabled",void 0),Object(h.c)([Object(N.c)()],e.prototype,"intensity",void 0),Object(h.c)([Object(N.n)()],e.prototype,"direction",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"texture",void 0),e}(),To=function(){function e(t){this._useEnergyConservation=e.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=e.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=e.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=e.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=e.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=e.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=e.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=e.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=t}return e.prototype._markAllSubMeshesAsMiscDirty=function(){this._internalMarkAllSubMeshesAsMiscDirty()},e.prototype.prepareDefines=function(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation},e.prototype.getClassName=function(){return"PBRBRDFConfiguration"},e.prototype.copyTo=function(e){N.a.Clone(function(){return e},this)},e.prototype.serialize=function(){return N.a.Serialize(this)},e.prototype.parse=function(e,t,i){var n=this;N.a.Parse(function(){return n},e,t,i)},e.DEFAULT_USE_ENERGY_CONSERVATION=!0,e.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,e.DEFAULT_USE_SPHERICAL_HARMONICS=!0,e.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsMiscDirty")],e.prototype,"useEnergyConservation",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsMiscDirty")],e.prototype,"useSmithVisibilityHeightCorrelated",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsMiscDirty")],e.prototype,"useSphericalHarmonics",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsMiscDirty")],e.prototype,"useSpecularGlossinessInputEnergyConservation",void 0),e}(),Eo=function(){function e(e){this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=s.a.White(),this._texture=null,this.texture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e}return e.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},e.prototype.isReadyForSubMesh=function(e,t){return!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&oo.a.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())},e.prototype.prepareDefines=function(e,t){this._isEnabled?(e.SHEEN=this._isEnabled,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&oo.a.SheenTextureEnabled?io.a.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"):e.SHEEN_TEXTURE=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_LINKWITHALBEDO=!1)},e.prototype.bindForSubMesh=function(e,t,i){e.useUbo&&i&&e.isSync||(this._texture&&oo.a.SheenTextureEnabled&&(e.updateFloat2("vSheenInfos",this._texture.coordinatesIndex,this._texture.level),io.a.BindTextureMatrix(this._texture,e,"sheen")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity)),t.texturesEnabled&&this._texture&&oo.a.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture)},e.prototype.hasTexture=function(e){return this._texture===e},e.prototype.getActiveTextures=function(e){this._texture&&e.push(this._texture)},e.prototype.getAnimatables=function(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)},e.prototype.dispose=function(e){e&&this._texture&&this._texture.dispose()},e.prototype.getClassName=function(){return"PBRSheenConfiguration"},e.AddFallbacks=function(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i},e.AddUniforms=function(e){e.push("vSheenColor","vSheenInfos","sheenMatrix")},e.PrepareUniformBuffer=function(e){e.addUniform("vSheenColor",4),e.addUniform("vSheenInfos",2),e.addUniform("sheenMatrix",16)},e.AddSamplers=function(e){e.push("sheenSampler")},e.prototype.copyTo=function(e){N.a.Clone(function(){return e},this)},e.prototype.serialize=function(){return N.a.Serialize(this)},e.prototype.parse=function(e,t,i){var n=this;N.a.Parse(function(){return n},e,t,i)},Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"isEnabled",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"linkSheenWithAlbedo",void 0),Object(h.c)([Object(N.c)()],e.prototype,"intensity",void 0),Object(h.c)([Object(N.e)()],e.prototype,"color",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"texture",void 0),e}(),xo=function(){function e(e){this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isScatteringEnabled=!1,this.refractionIntensity=1,this.translucencyIntensity=1,this.scatteringIntensity=1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1,this.indexOfRefraction=1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.tintColor=s.a.White(),this.tintColorAtDistance=1,this.diffusionDistance=s.a.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e}return e.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},e.prototype.isReadyForSubMesh=function(e,t){if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&oo.a.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;var i=this._getRefractionTexture(t);if(i&&oo.a.RefractionTextureEnabled&&!i.isReadyOrNotBlocking())return!1}return!0},e.prototype.prepareDefines=function(e,t){if(e._areTexturesDirty&&(e.SUBSURFACE=!1,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_SCATERRING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_REFRACTION=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled)&&(e.SUBSURFACE=!0,e._areTexturesDirty&&t.texturesEnabled&&this._thicknessTexture&&oo.a.ThicknessTextureEnabled&&io.a.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),e.SS_MASK_FROM_THICKNESS_TEXTURE=this._useMaskFromThicknessTexture),this._isRefractionEnabled&&t.texturesEnabled)){var i=this._getRefractionTexture(t);i&&oo.a.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency)}},e.prototype.bindForSubMesh=function(e,t,i,n,r){var o=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&oo.a.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),io.a.BindTextureMatrix(this._thicknessTexture,e,"thickness")),e.updateFloat2("vThicknessParam",this.minimumThickness,this.maximumThickness-this.minimumThickness),o&&oo.a.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",o.getReflectionTextureMatrix());var a=1;o.isCube||o.depth&&(a=o.depth),e.updateFloat4("vRefractionInfos",o.level,1/this._indexOfRefraction,a,this._invertRefractionY?-1:1),e.updateFloat3("vRefractionMicrosurfaceInfos",o.getSize().width,o.lodGenerationScale,o.lodGenerationOffset)}e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,this.tintColorAtDistance),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,this.scatteringIntensity)}t.texturesEnabled&&(this._thicknessTexture&&oo.a.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),o&&oo.a.RefractionTextureEnabled&&(r?e.setTexture("refractionSampler",o):(e.setTexture("refractionSampler",o._lodTextureMid||o),e.setTexture("refractionSamplerLow",o._lodTextureLow||o),e.setTexture("refractionSamplerHigh",o._lodTextureHigh||o))))},e.prototype.unbind=function(e){return!(!this._refractionTexture||!this._refractionTexture.isRenderTarget)&&(e.setTexture("refractionSampler",null),!0)},e.prototype._getRefractionTexture=function(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null},Object.defineProperty(e.prototype,"disableAlphaBlending",{get:function(){return this.isRefractionEnabled&&this._linkRefractionWithTransparency},enumerable:!0,configurable:!0}),e.prototype.fillRenderTargetTextures=function(e){oo.a.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)},e.prototype.hasTexture=function(e){return this._thicknessTexture===e||this._refractionTexture===e},e.prototype.hasRenderTargetTextures=function(){return!!(oo.a.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)},e.prototype.getActiveTextures=function(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture)},e.prototype.getAnimatables=function(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture)},e.prototype.dispose=function(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose())},e.prototype.getClassName=function(){return"PBRSubSurfaceConfiguration"},e.AddFallbacks=function(e,t,i){return e.SS_SCATERRING&&t.addFallback(i++,"SS_SCATERRING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i},e.AddUniforms=function(e){e.push("vDiffusionDistance","vTintColor","vSubSurfaceIntensity","vRefractionMicrosurfaceInfos","vRefractionInfos","vThicknessInfos","vThicknessParam","refractionMatrix","thicknessMatrix")},e.AddSamplers=function(e){e.push("thicknessSampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh")},e.PrepareUniformBuffer=function(e){e.addUniform("vRefractionMicrosurfaceInfos",3),e.addUniform("vRefractionInfos",4),e.addUniform("refractionMatrix",16),e.addUniform("vThicknessInfos",2),e.addUniform("thicknessMatrix",16),e.addUniform("vThicknessParam",2),e.addUniform("vDiffusionDistance",3),e.addUniform("vTintColor",4),e.addUniform("vSubSurfaceIntensity",3)},e.prototype.copyTo=function(e){N.a.Clone(function(){return e},this)},e.prototype.serialize=function(){return N.a.Serialize(this)},e.prototype.parse=function(e,t,i){var n=this;N.a.Parse(function(){return n},e,t,i)},Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"isRefractionEnabled",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"isTranslucencyEnabled",void 0),Object(h.c)([Object(N.c)()],e.prototype,"refractionIntensity",void 0),Object(h.c)([Object(N.c)()],e.prototype,"translucencyIntensity",void 0),Object(h.c)([Object(N.c)()],e.prototype,"scatteringIntensity",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"thicknessTexture",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"refractionTexture",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"indexOfRefraction",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"invertRefractionY",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"linkRefractionWithTransparency",void 0),Object(h.c)([Object(N.c)()],e.prototype,"minimumThickness",void 0),Object(h.c)([Object(N.c)()],e.prototype,"maximumThickness",void 0),Object(h.c)([Object(N.e)()],e.prototype,"tintColor",void 0),Object(h.c)([Object(N.c)()],e.prototype,"tintColorAtDistance",void 0),Object(h.c)([Object(N.e)()],e.prototype,"diffusionDistance",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"useMaskFromThicknessTexture",void 0),e}(),Po="uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float visibility;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize;\n#endif\n#endif\n\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;\nuniform vec4 vClearCoatRefractionParams;\n#ifdef CLEARCOAT_TEXTURE\nuniform vec2 vClearCoatInfos;\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;\nuniform vec2 vClearCoatTangentSpaceParams;\nuniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;\nuniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;\nuniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#endif\n\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;\nuniform mat4 anisotropyMatrix;\n#endif\n#endif\n\n#ifdef SHEEN\nuniform vec4 vSheenColor;\n#ifdef SHEEN_TEXTURE\nuniform vec2 vSheenInfos;\nuniform mat4 sheenMatrix;\n#endif\n#endif\n\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;\nuniform mat4 thicknessMatrix;\n#endif\nuniform vec2 vThicknessParam;\nuniform vec3 vDiffusionDistance;\nuniform vec4 vTintColor;\nuniform vec3 vSubSurfaceIntensity;\n#endif";ai.a.IncludesShadersStore.pbrFragmentDeclaration=Po;var Ao="layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec4 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float visibility;\nuniform vec2 vClearCoatParams;\nuniform vec4 vClearCoatRefractionParams;\nuniform vec2 vClearCoatInfos;\nuniform mat4 clearCoatMatrix;\nuniform vec2 vClearCoatBumpInfos;\nuniform vec2 vClearCoatTangentSpaceParams;\nuniform mat4 clearCoatBumpMatrix;\nuniform vec4 vClearCoatTintParams;\nuniform float clearCoatColorAtDistance;\nuniform vec2 vClearCoatTintInfos;\nuniform mat4 clearCoatTintMatrix;\nuniform vec3 vAnisotropy;\nuniform vec2 vAnisotropyInfos;\nuniform mat4 anisotropyMatrix;\nuniform vec4 vSheenColor;\nuniform vec2 vSheenInfos;\nuniform mat4 sheenMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec2 vThicknessInfos;\nuniform mat4 thicknessMatrix;\nuniform vec2 vThicknessParam;\nuniform vec3 vDiffusionDistance;\nuniform vec4 vTintColor;\nuniform vec3 vSubSurfaceIntensity;\n};\nuniform Scene {\nmat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif\nmat4 view;\n};";ai.a.IncludesShadersStore.pbrUboDeclaration=Ao;var So="uniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\nvarying vec4 vClipSpacePosition;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif";ai.a.IncludesShadersStore.pbrFragmentExtraDeclaration=So;var Co="#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n#ifdef CLEARCOAT\n#ifdef CLEARCOAT_TEXTURE\n#if CLEARCOAT_TEXTUREDIRECTUV == 1\n#define vClearCoatUV vMainUV1\n#elif CLEARCOAT_TEXTUREDIRECTUV == 2\n#define vClearCoatUV vMainUV2\n#else\nvarying vec2 vClearCoatUV;\n#endif\nuniform sampler2D clearCoatSampler;\n#endif\n#ifdef CLEARCOAT_BUMP\n#if CLEARCOAT_BUMPDIRECTUV == 1\n#define vClearCoatBumpUV vMainUV1\n#elif CLEARCOAT_BUMPDIRECTUV == 2\n#define vClearCoatBumpUV vMainUV2\n#else\nvarying vec2 vClearCoatBumpUV;\n#endif\nuniform sampler2D clearCoatBumpSampler;\n#endif\n#ifdef CLEARCOAT_TINT_TEXTURE\n#if CLEARCOAT_TINT_TEXTUREDIRECTUV == 1\n#define vClearCoatTintUV vMainUV1\n#elif CLEARCOAT_TINT_TEXTUREDIRECTUV == 2\n#define vClearCoatTintUV vMainUV2\n#else\nvarying vec2 vClearCoatTintUV;\n#endif\nuniform sampler2D clearCoatTintSampler;\n#endif\n#endif\n#ifdef SHEEN\n#ifdef SHEEN_TEXTURE\n#if SHEEN_TEXTUREDIRECTUV == 1\n#define vSheenUV vMainUV1\n#elif SHEEN_TEXTUREDIRECTUV == 2\n#define vSheenUV vMainUV2\n#else\nvarying vec2 vSheenUV;\n#endif\nuniform sampler2D sheenSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_TEXTURE\n#if ANISOTROPIC_TEXTUREDIRECTUV == 1\n#define vAnisotropyUV vMainUV1\n#elif ANISOTROPIC_TEXTUREDIRECTUV == 2\n#define vAnisotropyUV vMainUV2\n#else\nvarying vec2 vAnisotropyUV;\n#endif\nuniform sampler2D anisotropySampler;\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;\nuniform sampler2D reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\n#if SS_THICKNESSANDMASK_TEXTUREDIRECTUV == 1\n#define vThicknessUV vMainUV1\n#elif SS_THICKNESSANDMASK_TEXTUREDIRECTUV == 2\n#define vThicknessUV vMainUV2\n#else\nvarying vec2 vThicknessUV;\n#endif\nuniform sampler2D thicknessSampler;\n#endif\n#endif";ai.a.IncludesShadersStore.pbrFragmentSamplersDeclaration=Co;i(107);var Ro="\n#define RECIPROCAL_PI2 0.15915494\n#define RECIPROCAL_PI 0.31830988618\n\n#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nreturn square(roughness)+MINIMUMVARIANCE;\n}\nfloat fresnelGrazingReflectance(float reflectance0) {\n\n\nfloat reflectance90=saturate(reflectance0*25.0);\nreturn reflectance90;\n}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);\nvec3 nDfdy=dFdy(normalVector.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n\ngeometricAlphaGFactor*=0.75;\nreturn vec2(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n\n\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {\nfloat alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);\nfloat alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);\nreturn vec2(alphaT,alphaB);\n}\n\n\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy) {\nvec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;\nvec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);\nvec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);\nvec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));\nreturn anisotropicNormal;\n\n}\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\n\n\n\nvec3 cocaLambert(vec3 alpha,float distance) {\nreturn exp(-alpha*distance);\n}\n\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {\nreturn cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));\n}\n\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {\nreturn -log(color)/distance;\n}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {\nvec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);\nreturn clearCoatAbsorption;\n}\n#endif\n\n\n\n\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n#endif";ai.a.IncludesShadersStore.pbrHelperFunctions=Ro;var Oo="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;\nuniform vec3 vSphericalL1_1;\nuniform vec3 vSphericalL10;\nuniform vec3 vSphericalL11;\nuniform vec3 vSphericalL2_2;\nuniform vec3 vSphericalL2_1;\nuniform vec3 vSphericalL20;\nuniform vec3 vSphericalL21;\nuniform vec3 vSphericalL22;\n\n\n\n\n\n\n\nvec3 computeEnvironmentIrradiance(vec3 normal) {\nreturn vSphericalL00\n+vSphericalL1_1*(normal.y)\n+vSphericalL10*(normal.z)\n+vSphericalL11*(normal.x)\n+vSphericalL2_2*(normal.y*normal.x)\n+vSphericalL2_1*(normal.y*normal.z)\n+vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+vSphericalL21*(normal.z*normal.x)\n+vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));\n}\n#else\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\n\nvec3 computeEnvironmentIrradiance(vec3 normal) {\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif\n#endif";ai.a.IncludesShadersStore.harmonicsFunctions=Oo;var Mo="\nstruct preLightingInfo\n{\n\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat lightDistance;\n\nfloat attenuation;\n\nvec3 L;\nvec3 H;\nfloat NdotV;\nfloat NdotLUnclamped;\nfloat NdotL;\nfloat VdotH;\nfloat roughness;\n};\npreLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\n\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\n\nresult.lightDistance=sqrt(result.lightDistanceSquared);\n\nresult.L=normalize(result.lightOffset);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\nresult.NdotLUnclamped=dot(N,result.L);\nresult.NdotL=saturateEps(result.NdotLUnclamped);\nreturn result;\n}\npreLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\n\nresult.lightDistance=length(-lightData.xyz);\n\nresult.L=normalize(-lightData.xyz);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\nresult.NdotLUnclamped=dot(N,result.L);\nresult.NdotL=saturateEps(result.NdotLUnclamped);\nreturn result;\n}\npreLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\n\n\nresult.NdotL=dot(N,lightData.xyz)*0.5+0.5;\nresult.NdotL=saturateEps(result.NdotL);\nresult.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;\n}";ai.a.IncludesShadersStore.pbrDirectLightingSetupFunctions=Mo;var Io="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/maxEps(lightDistanceSquared);\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nfloat lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=saturate(1.0-factor*factor);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977;\n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=saturate(cd*lightAngleScale+lightAngleOffset);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}";ai.a.IncludesShadersStore.pbrDirectLightingFalloffFunctions=Io;var Do="\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\n\n\n\n#ifdef MS_BRDF_ENERGY_CONSERVATION\n\n\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\nreturn 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);\n}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {\n\nvec2 UV=vec2(NdotV,perceptualRoughness);\n\nvec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;\n}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#endif\nreturn reflectance;\n}\n#endif\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));\n}\n#endif\n#if defined(SHEEN) && defined(REFLECTION)\n\nvec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {\nvec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;\nreturn sheenEnvironmentReflectance;\n}\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);\n}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);\n}\n#ifdef CLEARCOAT\n\n\n\n\n\nvec3 getR0RemappedForClearCoat(vec3 f0) {\n#ifdef CLEARCOAT_DEFAULTIOR\n#ifdef MOBILE\nreturn saturate(f0*(f0*0.526868+0.529324)-0.0482256);\n#else\nreturn saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);\n#endif\n#else\nvec3 s=sqrt(f0);\nvec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);\nreturn t*t;\n#endif\n}\n#endif\n\n\n\n\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\n#ifdef SHEEN\n\nfloat normalDistributionFunction_CharlieSheen(float NdotH,float alphaG)\n{\nfloat invR=1./alphaG;\nfloat cos2h=NdotH*NdotH;\nfloat sin2h=1.-cos2h;\nreturn (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);\n}\n#endif\n#ifdef ANISOTROPIC\n\n\nfloat normalDistributionFunction_BurleyGGX_Anisotropic(float NdotH,float TdotH,float BdotH,const vec2 alphaTB) {\nfloat a2=alphaTB.x*alphaTB.y;\nvec3 v=vec3(alphaTB.y*TdotH,alphaTB.x*BdotH,a2*NdotH);\nfloat v2=dot(v,v);\nfloat w2=a2/v2;\nreturn a2*w2*w2*RECIPROCAL_PI;\n}\n#endif\n\n\n\n\n#ifdef BRDF_V_HEIGHT_CORRELATED\n\n\n\nfloat smithVisibility_GGXCorrelated(float NdotL,float NdotV,float alphaG) {\n#ifdef MOBILE\n\nfloat GGXV=NdotL*(NdotV*(1.0-alphaG)+alphaG);\nfloat GGXL=NdotV*(NdotL*(1.0-alphaG)+alphaG);\nreturn 0.5/(GGXV+GGXL);\n#else\nfloat a2=alphaG*alphaG;\nfloat GGXV=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);\nfloat GGXL=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);\nreturn 0.5/(GGXV+GGXL);\n#endif\n}\n#else\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfloat smithVisibilityG1_TrowbridgeReitzGGXFast(float dot,float alphaG)\n{\n#ifdef MOBILE\n\nreturn 1.0/(dot+alphaG+(1.0-alphaG)*dot ));\n#else\nfloat alphaSquared=alphaG*alphaG;\nreturn 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot));\n#endif\n}\nfloat smithVisibility_TrowbridgeReitzGGXFast(float NdotL,float NdotV,float alphaG)\n{\nfloat visibility=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);\n\nreturn visibility;\n}\n#endif\n#ifdef ANISOTROPIC\n\n\nfloat smithVisibility_GGXCorrelated_Anisotropic(float NdotL,float NdotV,float TdotV,float BdotV,float TdotL,float BdotL,const vec2 alphaTB) {\nfloat lambdaV=NdotL*length(vec3(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));\nfloat lambdaL=NdotV*length(vec3(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));\nfloat v=0.5/(lambdaV+lambdaL);\nreturn v;\n}\n#endif\n#ifdef CLEARCOAT\nfloat visibility_Kelemen(float VdotH) {\n\n\n\nreturn 0.25/(VdotH*VdotH);\n}\n#endif\n#ifdef SHEEN\n\n\n\nfloat visibility_Ashikhmin(float NdotL,float NdotV)\n{\nreturn 1./(4.*(NdotL+NdotV-NdotL*NdotV));\n}\n#endif\n\n\n\n\n\n\n\nfloat diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {\n\n\nfloat diffuseFresnelNV=pow5(saturateEps(1.0-NdotL));\nfloat diffuseFresnelNL=pow5(saturateEps(1.0-NdotV));\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel/PI;\n}\n#ifdef SS_TRANSLUCENCY\n\n\nvec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {\nvec3 S=1./maxEps(diffusionDistance);\nvec3 temp=exp((-0.333333333*thickness)*S);\nreturn tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);\n}\n\n\nfloat computeWrappedDiffuseNdotL(float NdotL,float w) {\nfloat t=1.0+w;\nfloat invt2=1.0/square(t);\nreturn saturate((NdotL+w)*invt2);\n}\n#endif\n";ai.a.IncludesShadersStore.pbrBRDFFunctions=Do;var wo="#define CLEARCOATREFLECTANCE90 1.0\n\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef CLEARCOAT\n\n\nvec4 clearCoat;\n#endif\n#ifdef SHEEN\nvec3 sheen;\n#endif\n};\n\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) {\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=saturate(lightRoughness+roughness);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nvec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {\nreturn mix(groundColor,lightColor,info.NdotL);\n}\nvec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {\nfloat diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);\nreturn diffuseTerm*info.attenuation*info.NdotL*lightColor;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}\n#ifdef SS_TRANSLUCENCY\nvec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {\nfloat NdotL=absEps(info.NdotLUnclamped);\n\nfloat wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);\n\nfloat trAdapt=step(0.,info.NdotLUnclamped);\nvec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);\nfloat diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);\nreturn diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;\n}\n#endif\n#ifdef SPECULARTERM\nvec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {\nfloat NdotH=saturateEps(dot(N,info.H));\nfloat roughness=max(info.roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nvec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\n#ifdef BRDF_V_HEIGHT_CORRELATED\nfloat smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);\n#else\nfloat smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);\n#endif\nvec3 specTerm=fresnel*distribution*smithVisibility;\nreturn specTerm*info.attenuation*info.NdotL*lightColor;\n}\n#endif\n#ifdef ANISOTROPIC\nvec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {\nfloat NdotH=saturateEps(dot(N,info.H));\nfloat TdotH=dot(T,info.H);\nfloat BdotH=dot(B,info.H);\nfloat TdotV=dot(T,V);\nfloat BdotV=dot(B,V);\nfloat TdotL=dot(T,info.L);\nfloat BdotL=dot(B,info.L);\nfloat alphaG=convertRoughnessToAverageSlope(info.roughness);\nvec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);\nalphaTB=max(alphaTB,square(geometricRoughnessFactor));\nvec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);\nfloat distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);\nfloat smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);\nvec3 specTerm=fresnel*distribution*smithVisibility;\nreturn specTerm*info.attenuation*info.NdotL*lightColor;\n}\n#endif\n#ifdef CLEARCOAT\nvec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {\nfloat NccdotL=saturateEps(dot(Ncc,info.L));\nfloat NccdotH=saturateEps(dot(Ncc,info.H));\nfloat clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);\nfloat fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);\nfresnel*=clearCoatIntensity;\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);\nfloat kelemenVisibility=visibility_Kelemen(info.VdotH);\nfloat clearCoatTerm=fresnel*distribution*kelemenVisibility;\nreturn vec4(\nclearCoatTerm*info.attenuation*NccdotL*lightColor,\n1.0-fresnel\n);\n}\nvec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {\nvec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);\nfloat NdotLRefract=saturateEps(dot(Ncc,LRefract));\nvec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);\nreturn absorption;\n}\n#endif\n#ifdef SHEEN\nvec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {\nfloat NdotH=saturateEps(dot(N,info.H));\nfloat roughness=max(info.roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n\nfloat fresnel=1.;\nfloat distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);\nfloat ashikhminvisibility=visibility_Ashikhmin(info.NdotL,info.NdotV);\nfloat sheenTerm=fresnel*distribution*ashikhminvisibility;\nreturn sheenTerm*info.attenuation*info.NdotL*lightColor;\n}\n#endif\n";ai.a.IncludesShadersStore.pbrDirectLightingFunctions=wo;var Lo="#if defined(REFLECTION) || defined(SS_REFRACTION)\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {\nfloat microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {\nfloat lod=log2(cubeMapDimensionPixels)*roughness;\nreturn lod;\n}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn saturate(square(temp)-1.0+ambientOcclusion);\n}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=saturate(1.0+1.1*dot(reflection,normal));\nreturn square(temp);\n}\n#endif\n\n\n\n\n#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nreturn getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);\n}\n#endif";ai.a.IncludesShadersStore.pbrIBLFunctions=Lo;i(119),i(120),i(146),i(140);var No="#if DEBUGMODE>0\nif (vClipSpacePosition.x/vClipSpacePosition.w<vDebugMode.x) {\nreturn;\n}\n\n#if DEBUGMODE == 1\ngl_FragColor.rgb=vPositionW.rgb;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE == 2 && defined(NORMAL)\ngl_FragColor.rgb=vNormalW.rgb;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE == 3 && (defined(BUMP) || defined(PARALLAX) || defined(ANISOTROPIC))\n\ngl_FragColor.rgb=TBN[0];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE == 4 && (defined(BUMP) || defined(PARALLAX) || defined(ANISOTROPIC))\n\ngl_FragColor.rgb=TBN[1];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE == 5\n\ngl_FragColor.rgb=normalW;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE == 6 && defined(MAINUV1)\ngl_FragColor.rgb=vec3(vMainUV1,0.0);\n#elif DEBUGMODE == 7 && defined(MAINUV2)\ngl_FragColor.rgb=vec3(vMainUV2,0.0);\n#elif DEBUGMODE == 8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\n\ngl_FragColor.rgb=TBNClearCoat[0];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE == 9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\n\ngl_FragColor.rgb=TBNClearCoat[1];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE == 10 && defined(CLEARCOAT)\n\ngl_FragColor.rgb=clearCoatNormalW;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE == 11 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicNormal;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE == 12 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicTangent;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE == 13 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicBitangent;\n#define DEBUGMODE_NORMALIZE\n\n#elif DEBUGMODE == 20 && defined(ALBEDO)\ngl_FragColor.rgb=albedoTexture.rgb;\n#elif DEBUGMODE == 21 && defined(AMBIENT)\ngl_FragColor.rgb=ambientOcclusionColorMap.rgb;\n#elif DEBUGMODE == 22 && defined(OPACITY)\ngl_FragColor.rgb=opacityMap.rgb;\n#elif DEBUGMODE == 23 && defined(EMISSIVE)\ngl_FragColor.rgb=emissiveColorTex.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE == 24 && defined(LIGHTMAP)\ngl_FragColor.rgb=lightmapColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE == 25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=surfaceMetallicColorMap.rgb;\n#elif DEBUGMODE == 26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW)\ngl_FragColor.rgb=surfaceReflectivityColorMap.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE == 27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE)\ngl_FragColor.rgb=vec3(clearCoatMapData.rg,0.0);\n#elif DEBUGMODE == 28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\ngl_FragColor.rgb=clearCoatTintMapData.rgb;\n#elif DEBUGMODE == 29 && defined(SHEEN) && defined(SHEEN_TEXTURE)\ngl_FragColor.rgb=sheenMapData.rgb;\n#elif DEBUGMODE == 30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE)\ngl_FragColor.rgb=anisotropyMapData.rgb;\n#elif DEBUGMODE == 31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE)\ngl_FragColor.rgb=thicknessMap.rgb;\n\n#elif DEBUGMODE == 40 && defined(SS_REFRACTION)\n\ngl_FragColor.rgb=environmentRefraction.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE == 41 && defined(REFLECTION)\ngl_FragColor.rgb=environmentRadiance.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE == 42 && defined(CLEARCOAT) && defined(REFLECTION)\ngl_FragColor.rgb=environmentClearCoatRadiance;\n#define DEBUGMODE_GAMMA\n\n#elif DEBUGMODE == 50\ngl_FragColor.rgb=diffuseBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE == 51 && defined(SPECULARTERM)\ngl_FragColor.rgb=specularBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE == 52 && defined(CLEARCOAT)\ngl_FragColor.rgb=clearCoatBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE == 53 && defined(SHEEN)\ngl_FragColor.rgb=sheenBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE == 54 && defined(REFLECTION)\ngl_FragColor.rgb=environmentIrradiance.rgb;\n#define DEBUGMODE_GAMMA\n\n#elif DEBUGMODE == 60\ngl_FragColor.rgb=surfaceAlbedo.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE == 61\ngl_FragColor.rgb=specularEnvironmentR0;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE == 62 && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=vec3(metallicRoughness.r);\n#elif DEBUGMODE == 71 && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=metallicF0;\n#elif DEBUGMODE == 63\ngl_FragColor.rgb=vec3(roughness);\n#elif DEBUGMODE == 64\ngl_FragColor.rgb=vec3(alphaG);\n#elif DEBUGMODE == 65\ngl_FragColor.rgb=vec3(NdotV);\n#elif DEBUGMODE == 66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT)\ngl_FragColor.rgb=clearCoatColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE == 67 && defined(CLEARCOAT)\ngl_FragColor.rgb=vec3(clearCoatRoughness);\n#elif DEBUGMODE == 68 && defined(CLEARCOAT)\ngl_FragColor.rgb=vec3(clearCoatNdotV);\n#elif DEBUGMODE == 69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY)\ngl_FragColor.rgb=transmittance;\n#elif DEBUGMODE == 70 && defined(SUBSURFACE) && defined(SS_REFRACTION)\ngl_FragColor.rgb=refractionTransmittance;\n\n#elif DEBUGMODE == 80 && defined(RADIANCEOCCLUSION)\ngl_FragColor.rgb=vec3(seo);\n#elif DEBUGMODE == 81 && defined(HORIZONOCCLUSION)\ngl_FragColor.rgb=vec3(eho);\n#elif DEBUGMODE == 82 && defined(MS_BRDF_ENERGY_CONSERVATION)\ngl_FragColor.rgb=vec3(energyConservationFactor);\n#elif DEBUGMODE == 83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ngl_FragColor.rgb=specularEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE == 84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ngl_FragColor.rgb=clearCoatEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE == 85 && defined(SHEEN) && defined(REFLECTION)\ngl_FragColor.rgb=sheenEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE == 86 && defined(ALPHABLEND)\ngl_FragColor.rgb=vec3(luminanceOverAlpha);\n#elif DEBUGMODE == 87\ngl_FragColor.rgb=vec3(alpha);\n#endif\ngl_FragColor.rgb*=vDebugMode.y;\n#ifdef DEBUGMODE_NORMALIZE\ngl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5;\n#endif\n#ifdef DEBUGMODE_GAMMA\ngl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb);\n#endif\ngl_FragColor.a=1.0;\n#endif";ai.a.IncludesShadersStore.pbrDebug=No;var Fo="#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE\n#endif\n\n#include<__decl__pbrFragment>\n#include<pbrFragmentExtraDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<pbrFragmentSamplersDeclaration>\n#include<imageProcessingDeclaration>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n\n#include<helperFunctions>\n#include<pbrHelperFunctions>\n#include<imageProcessingFunctions>\n#include<shadowsFragmentFunctions>\n#include<harmonicsFunctions>\n#include<pbrDirectLightingSetupFunctions>\n#include<pbrDirectLightingFalloffFunctions>\n#include<pbrBRDFFunctions>\n#include<pbrDirectLightingFunctions>\n#include<pbrIBLFunctions>\n#include<bumpFragmentFunctions>\n#ifdef REFLECTION\n#include<reflectionFunction>\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#ifdef CLEARCOAT\n\nvec3 clearCoatNormalW=normalW;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\n#ifdef GAMMAALBEDO\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\n#else\nsurfaceAlbedo*=albedoTexture.rgb;\n#endif\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALBEDO\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\n#include<depthPrePass>\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n#ifdef REFLECTANCE\n\n\n\n\n\nsurfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r);\n#else\nvec3 metallicF0=vec3(vReflectivityColor.a,vReflectivityColor.a,vReflectivityColor.a);\n#ifdef METALLICF0FACTORFROMMETALLICMAP\n#ifdef REFLECTIVITY\nmetallicF0*=surfaceMetallicColorMap.a;\n#endif\n#endif\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r);\n#endif\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE\n#endif\n#endif\n#endif\n\nmicroSurface=saturate(microSurface);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\n\nfloat NdotV=absEps(NdotVUnclamped);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nvec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz);\n#ifdef SPECULARAA\n\nalphaG+=AARoughnessFactors.y;\n#endif\n#ifdef ANISOTROPIC\nfloat anisotropy=vAnisotropy.b;\nvec3 anisotropyDirection=vec3(vAnisotropy.xy,0.);\n#ifdef ANISOTROPIC_TEXTURE\nvec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y;\nanisotropy*=anisotropyMapData.b;\nanisotropyDirection.rg*=anisotropyMapData.rg*2.0-1.0;\n#endif\nmat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));\nvec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);\nvec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));\nvec3 anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy);\n#endif\n\n#ifdef SS_REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\n#ifdef ANISOTROPIC\nvec3 refractionVector=refract(-viewDirectionW,anisotropicNormal,vRefractionInfos.y);\n#else\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#endif\n#ifdef SS_REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef SS_REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#elif defined(SS_LINEARSPECULARREFRACTION)\nfloat refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,roughness);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef SS_LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef SS_RGBDREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef SS_GAMMAREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\n#ifdef ANISOTROPIC\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicNormal);\n#else\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#elif defined(LINEARSPECULARREFLECTION)\nfloat reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\n#ifdef ANISOTROPIC\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicNormal,0)).xyz;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=computeEnvironmentIrradiance(irradianceVector);\n#endif\n#elif defined(USEIRRADIANCEMAP)\nenvironmentIrradiance=sampleReflection(irradianceSampler,reflectionCoords).rgb;\n#ifdef RGBDREFLECTION\nenvironmentIrradiance.rgb=fromRGBD(environmentIrradiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\n#ifdef SHEEN\nfloat sheenIntensity=vSheenColor.a;\n#ifdef SHEEN_TEXTURE\nvec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset)*vSheenInfos.y;\nsheenIntensity*=sheenMapData.a;\n#endif\n#ifdef SHEEN_LINKWITHALBEDO\nfloat sheenFactor=pow5(1.0-sheenIntensity);\nvec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);\nfloat sheenRoughness=sheenIntensity;\n\nsurfaceAlbedo.rgb*=sheenFactor;\n#else\nvec3 sheenColor=vSheenColor.rgb;\n#ifdef SHEEN_TEXTURE\nsheenColor.rgb*=toLinearSpace(sheenMapData.rgb);\n#endif\nfloat sheenRoughness=roughness;\n\nsheenIntensity*=(1.-reflectance);\n\nsheenColor*=sheenIntensity;\n#endif\n\n#if defined(REFLECTION)\nfloat sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness);\n#ifdef SPECULARAA\n\nsheenAlphaG+=AARoughnessFactors.y;\n#endif\nvec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);\n\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat sheenReflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,sheenAlphaG,NdotVUnclamped);\n#elif defined(LINEARSPECULARREFLECTION)\nfloat sheenReflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,sheenRoughness);\n#else\nfloat sheenReflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,sheenAlphaG);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nsheenReflectionLOD=sheenReflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nenvironmentSheenRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,sheenReflectionLOD);\n#else\nfloat lodSheenReflectionNormalized=saturate(sheenReflectionLOD/log2(vReflectionMicrosurfaceInfos.x));\nfloat lodSheenReflectionNormalizedDoubled=lodSheenReflectionNormalized*2.0;\nvec4 environmentSheenMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodSheenReflectionNormalizedDoubled<1.0){\nenvironmentSheenRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSheenMid,\nlodSheenReflectionNormalizedDoubled\n);\n}else{\nenvironmentSheenRadiance=mix(\nenvironmentSheenMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodSheenReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentSheenRadiance.rgb=fromRGBD(environmentSheenRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentSheenRadiance.rgb=toLinearSpace(environmentSheenRadiance.rgb);\n#endif\n\nenvironmentSheenRadiance.rgb*=vReflectionInfos.x;\nenvironmentSheenRadiance.rgb*=vReflectionColor.rgb;\n#endif\n#endif\n\n#ifdef CLEARCOAT\n\nfloat clearCoatIntensity=vClearCoatParams.x;\nfloat clearCoatRoughness=vClearCoatParams.y;\n#ifdef CLEARCOAT_TEXTURE\nvec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y;\nclearCoatIntensity*=clearCoatMapData.x;\nclearCoatRoughness*=clearCoatMapData.y;\n#endif\n#ifdef CLEARCOAT_TINT\nvec3 clearCoatColor=vClearCoatTintParams.rgb;\nfloat clearCoatThickness=vClearCoatTintParams.a;\n#ifdef CLEARCOAT_TINT_TEXTURE\nvec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset);\nclearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb);\nclearCoatThickness*=clearCoatTintMapData.a;\n#endif\nclearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);\n#endif\n\n\n\n\nvec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0);\nspecularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);\n#ifdef CLEARCOAT_BUMP\n#ifdef NORMALXYSCALE\nfloat clearCoatNormalScale=1.0;\n#else\nfloat clearCoatNormalScale=vClearCoatBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBNClearCoat=vTBN;\n#else\nmat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,vClearCoatBumpUV,vClearCoatTangentSpaceParams);\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nclearCoatNormalW=normalize(texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset).xyz*2.0-1.0);\nclearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW);\n#else\nclearCoatNormalW=perturbNormal(TBNClearCoat,texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset).xyz,vClearCoatBumpInfos.y);\n#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nclearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nclearCoatNormalW=gl_FrontFacing ? clearCoatNormalW : -clearCoatNormalW;\n#endif\n\nvec2 clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);\n\nfloat clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);\n\nfloat clearCoatNdotV=absEps(clearCoatNdotVUnclamped);\n#ifdef CLEARCOAT_TINT\n\nvec3 clearCoatVRefract=-refract(vPositionW,clearCoatNormalW,vClearCoatRefractionParams.y);\n\nfloat clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract));\nvec3 absorption=vec3(0.);\n#endif\n\n#if defined(REFLECTION)\nfloat clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness);\n#ifdef SPECULARAA\n\nclearCoatAlphaG+=clearCoatAARoughnessFactors.y;\n#endif\nvec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);\nvec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nclearCoatReflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 clearCoatReflectionCoords=clearCoatReflectionVector;\n#else\nvec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nclearCoatReflectionCoords/=clearCoatReflectionVector.z;\n#endif\nclearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat clearCoatReflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,clearCoatAlphaG,clearCoatNdotVUnclamped);\n#elif defined(LINEARSPECULARREFLECTION)\nfloat sheenReflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,clearCoatRoughness);\n#else\nfloat clearCoatReflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,clearCoatAlphaG);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nclearCoatReflectionLOD=clearCoatReflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nfloat requestedClearCoatReflectionLOD=clearCoatReflectionLOD;\nenvironmentClearCoatRadiance=sampleReflectionLod(reflectionSampler,clearCoatReflectionCoords,requestedClearCoatReflectionLOD);\n#else\nfloat lodClearCoatReflectionNormalized=saturate(clearCoatReflectionLOD/log2(vReflectionMicrosurfaceInfos.x));\nfloat lodClearCoatReflectionNormalizedDoubled=lodClearCoatReflectionNormalized*2.0;\nvec4 environmentClearCoatMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodClearCoatReflectionNormalizedDoubled<1.0){\nenvironmentClearCoatRadiance=mix(\nsampleReflection(reflectionSamplerHigh,clearCoatReflectionCoords),\nenvironmentClearCoatMid,\nlodClearCoatReflectionNormalizedDoubled\n);\n}else{\nenvironmentClearCoatRadiance=mix(\nenvironmentClearCoatMid,\nsampleReflection(reflectionSamplerLow,clearCoatReflectionCoords),\nlodClearCoatReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentClearCoatRadiance.rgb=fromRGBD(environmentClearCoatRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentClearCoatRadiance.rgb=toLinearSpace(environmentClearCoatRadiance.rgb);\n#endif\n\nenvironmentClearCoatRadiance.rgb*=vReflectionInfos.x;\nenvironmentClearCoatRadiance.rgb*=vReflectionColor.rgb;\n#endif\n#endif\n\n#if defined(ENVIRONMENTBRDF)\n\nvec3 environmentBrdf=getBRDFLookup(NdotV,roughness);\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 energyConservationFactor=getEnergyConservationFactor(specularEnvironmentR0,environmentBrdf);\n#endif\n#endif\n\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nfloat refractionIntensity=vSubSurfaceIntensity.x;\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nrefractionIntensity*=(1.0-alpha);\n\nalpha=1.0;\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nfloat translucencyIntensity=vSubSurfaceIntensity.y;\n#endif\n#ifdef SS_SCATTERING\nfloat scatteringIntensity=vSubSurfaceIntensity.z;\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset);\nfloat thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x;\n#ifdef SS_MASK_FROM_THICKNESS_TEXTURE\n#ifdef SS_REFRACTION\nrefractionIntensity*=thicknessMap.g;\n#endif\n#ifdef SS_TRANSLUCENCY\ntranslucencyIntensity*=thicknessMap.b;\n#endif\n#ifdef SS_SCATTERING\nscatteringIntensity*=thicknessMap.a;\n#endif\n#endif\n#else\nfloat thickness=vThicknessParam.y;\n#endif\n#ifdef SS_TRANSLUCENCY\nthickness=maxEps(thickness);\nvec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);\ntransmittance*=translucencyIntensity;\n#endif\n#endif\n\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef CLEARCOAT\nvec3 clearCoatBase=vec3(0.,0.,0.);\n#endif\n#ifdef SHEEN\nvec3 sheenBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);\n#ifdef RGBDLIGHTMAP\nlightmapColor.rgb=fromRGBD(lightmapColor);\n#endif\n#ifdef GAMMALIGHTMAP\nlightmapColor.rgb=toLinearSpace(lightmapColor.rgb);\n#endif\nlightmapColor.rgb*=vLightmapInfos.y;\n#endif\n\npreLightingInfo preInfo;\nlightingInfo info;\nfloat shadow=1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\nvec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(specularEnvironmentR0,environmentBrdf);\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#if defined(SHEEN) && defined(REFLECTION)\nvec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentBrdf);\n#ifdef RADIANCEOCCLUSION\nsheenEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nsheenEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#endif\n\n#ifdef CLEARCOAT\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness);\nvec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf);\n#ifdef RADIANCEOCCLUSION\nfloat clearCoatSeo=environmentRadianceOcclusion(ambientMonochrome,clearCoatNdotVUnclamped);\nclearCoatEnvironmentReflectance*=clearCoatSeo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW);\nclearCoatEnvironmentReflectance*=clearCoatEho;\n#endif\n#endif\n#endif\n#else\n\nvec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness));\n#endif\nclearCoatEnvironmentReflectance*=clearCoatIntensity;\n#if defined(CLEARCOAT_TINT)\n\nabsorption=computeClearCoatAbsorption(clearCoatNdotVRefract,clearCoatNdotVRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);\n#ifdef REFLECTION\nenvironmentIrradiance*=absorption;\n#ifdef SHEEN\nsheenEnvironmentReflectance*=absorption;\n#endif\n#endif\nspecularEnvironmentReflectance*=absorption;\n#endif\n\nfloat fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);\nfresnelIBLClearCoat*=clearCoatIntensity;\nfloat conservationFactor=(1.-fresnelIBLClearCoat);\n#ifdef REFLECTION\nenvironmentIrradiance*=conservationFactor;\n#ifdef SHEEN\nsheenEnvironmentReflectance*=conservationFactor;\n#endif\n#endif\nspecularEnvironmentReflectance*=conservationFactor;\n#endif\n\n#ifdef SS_REFRACTION\nvec3 refractionTransmittance=vec3(refractionIntensity);\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);\n\n\n\n\n\nrefractionTransmittance*=cocaLambert(volumeAlbedo,thickness);\n#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY)\n\nfloat maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);\nvec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);\n\nenvironmentRefraction.rgb*=volumeAlbedo;\n#else\n\nvec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);\nrefractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y);\n#endif\n\nsurfaceAlbedo*=(1.-refractionIntensity);\n#ifdef REFLECTION\n\nenvironmentIrradiance*=(1.-refractionIntensity);\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity);\n\nrefractionTransmittance*=1.0-specularEnvironmentReflectance;\n#endif\n\n#if defined(REFLECTION) && defined(SS_TRANSLUCENCY)\n#if defined(USESPHERICALINVERTEX)\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\n#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP)\nvec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector);\n#elif defined(USEIRRADIANCEMAP)\nvec3 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceVector).rgb;\n#ifdef RGBDREFLECTION\nrefractionIrradiance.rgb=fromRGBD(refractionIrradiance);\n#endif\n#ifdef GAMMAREFLECTION\nrefractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb);\n#endif\n#else\nvec3 refractionIrradiance=vec3(0.);\n#endif\nrefractionIrradiance*=transmittance;\n#endif\n\n\n\n#ifndef METALLICWORKFLOW\n#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\n#if defined(SS_TRANSLUCENCY)\nfinalIrradiance+=refractionIrradiance;\n#endif\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalSpecularScaled*=energyConservationFactor;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalRadianceScaled*=energyConservationFactor;\n#endif\n#endif\n\n#ifdef SS_REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractionTransmittance;\n#endif\n\n#ifdef CLEARCOAT\nvec3 finalClearCoat=clearCoatBase;\nfinalClearCoat=max(finalClearCoat,0.0);\n\nvec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalClearCoatScaled*=energyConservationFactor;\n#endif\n\n#ifdef REFLECTION\nvec3 finalClearCoatRadiance=environmentClearCoatRadiance.rgb;\nfinalClearCoatRadiance*=clearCoatEnvironmentReflectance;\n\nvec3 finalClearCoatRadianceScaled=finalClearCoatRadiance*vLightingIntensity.z;\n#endif\n#ifdef SS_REFRACTION\nfinalRefraction*=conservationFactor;\n#ifdef CLEARCOAT_TINT\nfinalRefraction*=absorption;\n#endif\n#endif\n#endif\n\n#ifdef SHEEN\nvec3 finalSheen=sheenBase*sheenColor;\nfinalSheen=max(finalSheen,0.0);\nvec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w;\n\n\n\n\n\n#ifdef REFLECTION\nvec3 finalSheenRadiance=environmentSheenRadiance.rgb;\nfinalSheenRadiance*=sheenEnvironmentReflectance;\n\nvec3 finalSheenRadianceScaled=finalSheenRadiance*vLightingIntensity.z;\n#endif\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#if defined(CLEARCOAT)\nluminanceOverAlpha+=getLuminance(finalClearCoatRadianceScaled);\n#endif\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalClearCoatScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha);\n#endif\n#endif\n#endif\n\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalAmbient=vAmbientColor;\nfinalAmbient*=surfaceAlbedo.rgb;\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalAmbient*ambientOcclusionColor +\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef CLEARCOAT\n\n\nfinalClearCoatScaled +\n#endif\n#ifdef SHEEN\n\n\nfinalSheenScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#ifdef CLEARCOAT\n\n\nfinalClearCoatRadianceScaled +\n#endif\n#ifdef SHEEN\n\n\nfinalSheenRadianceScaled +\n#endif\n#endif\n#ifdef SS_REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor.rgb;\n#else\nfinalColor.rgb+=lightmapColor.rgb;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\nfinalColor.a*=visibility;\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=finalColor;\n#include<pbrDebug>\n}\n";ai.a.ShadersStore.pbrPixelShader=Fo;var Bo="uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef CLEARCOAT\n#ifdef CLEARCOAT_TEXTURE\nuniform vec2 vClearCoatInfos;\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;\nuniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;\nuniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;\nuniform mat4 anisotropyMatrix;\n#endif\n#endif\n\n#ifdef SHEEN\n#ifdef SHEEN_TEXTURE\nuniform vec2 vSheenInfos;\nuniform mat4 sheenMatrix;\n#endif\n#endif\n\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;\nuniform mat4 thicknessMatrix;\n#endif\n#endif\n";ai.a.IncludesShadersStore.pbrVertexDeclaration=Bo;i(147),i(88),i(89),i(94),i(141),i(143);var Uo="precision highp float;\n#include<__decl__pbrVertex>\n#define CUSTOM_VERTEX_BEGIN\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE) && CLEARCOAT_TEXTUREDIRECTUV == 0\nvarying vec2 vClearCoatUV;\n#endif\n#if defined(CLEARCOAT_BUMP) && CLEARCOAT_BUMPDIRECTUV == 0\nvarying vec2 vClearCoatBumpUV;\n#endif\n#if defined(CLEARCOAT_TINT_TEXTURE) && CLEARCOAT_TINT_TEXTUREDIRECTUV == 0\nvarying vec2 vClearCoatTintUV;\n#endif\n#endif\n#ifdef SHEEN\n#if defined(SHEEN_TEXTURE) && SHEEN_TEXTUREDIRECTUV == 0\nvarying vec2 vSheenUV;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#if defined(ANISOTROPIC_TEXTURE) && ANISOTROPIC_TEXTUREDIRECTUV == 0\nvarying vec2 vAnisotropyUV;\n#endif\n#endif\n#ifdef SUBSURFACE\n#if defined(SS_THICKNESSANDMASK_TEXTURE) && SS_THICKNESSANDMASK_TEXTUREDIRECTUV == 0\nvarying vec2 vThicknessUV;\n#endif\n#endif\n\nvarying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR == 0u) {\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n} else {\ngl_Position=viewProjectionR*finalWorld*vec4(positionUpdated,1.0);\n}\n#else\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#endif\n#if DEBUGMODE>0\nvClipSpacePosition=gl_Position;\n#endif\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE) && CLEARCOAT_TEXTUREDIRECTUV == 0\nif (vClearCoatInfos.x == 0.)\n{\nvClearCoatUV=vec2(clearCoatMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvClearCoatUV=vec2(clearCoatMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(CLEARCOAT_BUMP) && CLEARCOAT_BUMPDIRECTUV == 0\nif (vClearCoatBumpInfos.x == 0.)\n{\nvClearCoatBumpUV=vec2(clearCoatBumpMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvClearCoatBumpUV=vec2(clearCoatBumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(CLEARCOAT_TINT_TEXTURE) && CLEARCOAT_TINT_TEXTUREDIRECTUV == 0\nif (vClearCoatTintInfos.x == 0.)\n{\nvClearCoatTintUV=vec2(clearCoatTintMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvClearCoatTintUV=vec2(clearCoatTintMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#endif\n#ifdef SHEEN\n#if defined(SHEEN_TEXTURE) && SHEEN_TEXTUREDIRECTUV == 0\nif (vSheenInfos.x == 0.)\n{\nvSheenUV=vec2(sheenMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvSheenUV=vec2(sheenMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#endif\n#ifdef ANISOTROPIC\n#if defined(ANISOTROPIC_TEXTURE) && ANISOTROPIC_TEXTUREDIRECTUV == 0\nif (vAnisotropyInfos.x == 0.)\n{\nvAnisotropyUV=vec2(anisotropyMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvAnisotropyUV=vec2(anisotropyMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#endif\n#ifdef SUBSURFACE\n#if defined(SS_THICKNESSANDMASK_TEXTURE) && SS_THICKNESSANDMASK_TEXTUREDIRECTUV == 0\nif (vThicknessInfos.x == 0.)\n{\nvThicknessUV=vec2(thicknessMatrix*vec4(uvUpdated,1.0,0.0));\n}\nelse\n{\nvThicknessUV=vec2(thicknessMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}";ai.a.ShadersStore.pbrVertexShader=Uo;var Vo=function(e){function t(){var t=e.call(this)||this;return t.PBR=!0,t.MAINUV1=!1,t.MAINUV2=!1,t.UV1=!1,t.UV2=!1,t.ALBEDO=!1,t.GAMMAALBEDO=!1,t.ALBEDODIRECTUV=0,t.VERTEXCOLOR=!1,t.AMBIENT=!1,t.AMBIENTDIRECTUV=0,t.AMBIENTINGRAYSCALE=!1,t.OPACITY=!1,t.VERTEXALPHA=!1,t.OPACITYDIRECTUV=0,t.OPACITYRGB=!1,t.ALPHATEST=!1,t.DEPTHPREPASS=!1,t.ALPHABLEND=!1,t.ALPHAFROMALBEDO=!1,t.ALPHATESTVALUE="0.5",t.SPECULAROVERALPHA=!1,t.RADIANCEOVERALPHA=!1,t.ALPHAFRESNEL=!1,t.LINEARALPHAFRESNEL=!1,t.PREMULTIPLYALPHA=!1,t.EMISSIVE=!1,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITY=!1,t.REFLECTIVITYDIRECTUV=0,t.SPECULARTERM=!1,t.MICROSURFACEFROMREFLECTIVITYMAP=!1,t.MICROSURFACEAUTOMATIC=!1,t.LODBASEDMICROSFURACE=!1,t.MICROSURFACEMAP=!1,t.MICROSURFACEMAPDIRECTUV=0,t.METALLICWORKFLOW=!1,t.ROUGHNESSSTOREINMETALMAPALPHA=!1,t.ROUGHNESSSTOREINMETALMAPGREEN=!1,t.METALLNESSSTOREINMETALMAPBLUE=!1,t.AOSTOREINMETALMAPRED=!1,t.METALLICF0FACTORFROMMETALLICMAP=!1,t.ENVIRONMENTBRDF=!1,t.ENVIRONMENTBRDF_RGBD=!1,t.NORMAL=!1,t.TANGENT=!1,t.BUMP=!1,t.BUMPDIRECTUV=0,t.OBJECTSPACE_NORMALMAP=!1,t.PARALLAX=!1,t.PARALLAXOCCLUSION=!1,t.NORMALXYSCALE=!0,t.LIGHTMAP=!1,t.LIGHTMAPDIRECTUV=0,t.USELIGHTMAPASSHADOWMAP=!1,t.GAMMALIGHTMAP=!1,t.RGBDLIGHTMAP=!1,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.SPHERICAL_HARMONICS=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1,t.RADIANCEOCCLUSION=!1,t.HORIZONOCCLUSION=!1,t.INSTANCES=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.BONETEXTURE=!1,t.NONUNIFORMSCALING=!1,t.MORPHTARGETS=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_UV=!1,t.NUM_MORPH_INFLUENCERS=0,t.IMAGEPROCESSING=!1,t.VIGNETTE=!1,t.VIGNETTEBLENDMODEMULTIPLY=!1,t.VIGNETTEBLENDMODEOPAQUE=!1,t.TONEMAPPING=!1,t.TONEMAPPING_ACES=!1,t.CONTRAST=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=!1,t.SAMPLER3DBGRMAP=!1,t.IMAGEPROCESSINGPOSTPROCESS=!1,t.EXPOSURE=!1,t.MULTIVIEW=!1,t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1,t.TWOSIDEDLIGHTING=!1,t.SHADOWFLOAT=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.POINTSIZE=!1,t.FOG=!1,t.LOGARITHMICDEPTH=!1,t.FORCENORMALFORWARD=!1,t.SPECULARAA=!1,t.CLEARCOAT=!1,t.CLEARCOAT_DEFAULTIOR=!1,t.CLEARCOAT_TEXTURE=!1,t.CLEARCOAT_TEXTUREDIRECTUV=0,t.CLEARCOAT_BUMP=!1,t.CLEARCOAT_BUMPDIRECTUV=0,t.CLEARCOAT_TINT=!1,t.CLEARCOAT_TINT_TEXTURE=!1,t.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,t.ANISOTROPIC=!1,t.ANISOTROPIC_TEXTURE=!1,t.ANISOTROPIC_TEXTUREDIRECTUV=0,t.BRDF_V_HEIGHT_CORRELATED=!1,t.MS_BRDF_ENERGY_CONSERVATION=!1,t.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1,t.SHEEN=!1,t.SHEEN_TEXTURE=!1,t.SHEEN_TEXTUREDIRECTUV=0,t.SHEEN_LINKWITHALBEDO=!1,t.SUBSURFACE=!1,t.SS_REFRACTION=!1,t.SS_TRANSLUCENCY=!1,t.SS_SCATERRING=!1,t.SS_THICKNESSANDMASK_TEXTURE=!1,t.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,t.SS_REFRACTIONMAP_3D=!1,t.SS_REFRACTIONMAP_OPPOSITEZ=!1,t.SS_LODINREFRACTIONALPHA=!1,t.SS_GAMMAREFRACTION=!1,t.SS_RGBDREFRACTION=!1,t.SS_LINEARSPECULARREFRACTION=!1,t.SS_LINKREFRACTIONTOTRANSPARENCY=!1,t.SS_MASK_FROM_THICKNESS_TEXTURE=!1,t.UNLIT=!1,t.DEBUGMODE=0,t.rebuild(),t}return Object(h.d)(t,e),t.prototype.reset=function(){e.prototype.reset.call(this),this.ALPHATESTVALUE="0.5",this.PBR=!0},t}(no.a),ko=function(e){function t(i,n){var r=e.call(this,i,n)||this;return r._directIntensity=1,r._emissiveIntensity=1,r._environmentIntensity=1,r._specularIntensity=1,r._lightingInfos=new a.f(r._directIntensity,r._emissiveIntensity,r._environmentIntensity,r._specularIntensity),r._disableBumpMap=!1,r._albedoTexture=null,r._ambientTexture=null,r._ambientTextureStrength=1,r._ambientTextureImpactOnAnalyticalLights=t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,r._opacityTexture=null,r._reflectionTexture=null,r._emissiveTexture=null,r._reflectivityTexture=null,r._metallicTexture=null,r._metallic=null,r._roughness=null,r._metallicF0Factor=.5,r._useMetallicF0FactorFromMetallicTexture=!1,r._microSurfaceTexture=null,r._bumpTexture=null,r._lightmapTexture=null,r._ambientColor=new s.a(0,0,0),r._albedoColor=new s.a(1,1,1),r._reflectivityColor=new s.a(1,1,1),r._reflectionColor=new s.a(1,1,1),r._emissiveColor=new s.a(0,0,0),r._microSurface=.9,r._useLightmapAsShadowmap=!1,r._useHorizonOcclusion=!0,r._useRadianceOcclusion=!0,r._useAlphaFromAlbedoTexture=!1,r._useSpecularOverAlpha=!0,r._useMicroSurfaceFromReflectivityMapAlpha=!1,r._useRoughnessFromMetallicTextureAlpha=!0,r._useRoughnessFromMetallicTextureGreen=!1,r._useMetallnessFromMetallicTextureBlue=!1,r._useAmbientOcclusionFromMetallicTextureRed=!1,r._useAmbientInGrayScale=!1,r._useAutoMicroSurfaceFromReflectivityMap=!1,r._lightFalloff=t.LIGHTFALLOFF_PHYSICAL,r._useRadianceOverAlpha=!0,r._useObjectSpaceNormalMap=!1,r._useParallax=!1,r._useParallaxOcclusion=!1,r._parallaxScaleBias=.05,r._disableLighting=!1,r._maxSimultaneousLights=4,r._invertNormalMapX=!1,r._invertNormalMapY=!1,r._twoSidedLighting=!1,r._alphaCutOff=.4,r._forceAlphaTest=!1,r._useAlphaFresnel=!1,r._useLinearAlphaFresnel=!1,r._transparencyMode=null,r._environmentBRDFTexture=null,r._forceIrradianceInFragment=!1,r._forceNormalForward=!1,r._enableSpecularAntiAliasing=!1,r._imageProcessingObserver=null,r._renderTargets=new oi.a(16),r._globalAmbientColor=new s.a(0,0,0),r._useLogarithmicDepth=!1,r._unlit=!1,r._debugMode=0,r.debugMode=0,r.debugLimit=-1,r.debugFactor=1,r.clearCoat=new yo(r._markAllSubMeshesAsTexturesDirty.bind(r)),r.anisotropy=new bo(r._markAllSubMeshesAsTexturesDirty.bind(r)),r.brdf=new To(r._markAllSubMeshesAsMiscDirty.bind(r)),r.sheen=new Eo(r._markAllSubMeshesAsTexturesDirty.bind(r)),r.subSurface=new xo(r._markAllSubMeshesAsTexturesDirty.bind(r)),r._rebuildInParallel=!1,r._attachImageProcessingConfiguration(null),r.getRenderTargetTextures=function(){return r._renderTargets.reset(),oo.a.ReflectionTextureEnabled&&r._reflectionTexture&&r._reflectionTexture.isRenderTarget&&r._renderTargets.push(r._reflectionTexture),r.subSurface.fillRenderTargetTextures(r._renderTargets),r._renderTargets},r._environmentBRDFTexture=vo.GetEnvironmentBRDFTexture(n),r}return Object(h.d)(t,e),t.prototype._attachImageProcessingConfiguration=function(e){var t=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(function(){t._markAllSubMeshesAsImageProcessingDirty()})))},Object.defineProperty(t.prototype,"hasRenderTargetTextures",{get:function(){return!!(oo.a.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this.subSurface.hasRenderTargetTextures()},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"PBRBaseMaterial"},Object.defineProperty(t.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transparencyMode",{get:function(){return this._transparencyMode},set:function(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===t.PBRMATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_disableAlphaBlending",{get:function(){return this.subSurface.disableAlphaBlending||this._transparencyMode===t.PBRMATERIAL_OPAQUE||this._transparencyMode===t.PBRMATERIAL_ALPHATEST},enumerable:!0,configurable:!0}),t.prototype.needAlphaBlending=function(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())},t.prototype.needAlphaBlendingForMesh=function(t){return!(this._disableAlphaBlending&&t.visibility>=1)&&e.prototype.needAlphaBlendingForMesh.call(this,t)},t.prototype.needAlphaTesting=function(){return!!this._forceAlphaTest||!this.subSurface.disableAlphaBlending&&(null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&(null==this._transparencyMode||this._transparencyMode===t.PBRMATERIAL_ALPHATEST))},t.prototype._shouldUseAlphaFromAlbedoTexture=function(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==t.PBRMATERIAL_OPAQUE},t.prototype.getAlphaTestTexture=function(){return this._albedoTexture},t.prototype.isReadyForSubMesh=function(e,t,i){if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new Vo);var n=t._materialDefines;if(!this.checkReadyOnEveryCall&&t.effect&&n._renderId===this.getScene().getRenderId())return!0;var r=this.getScene(),o=r.getEngine();if(n._areTexturesDirty&&r.texturesEnabled){if(this._albedoTexture&&oo.a.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&oo.a.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&oo.a.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;var a=this._getReflectionTexture();if(a&&oo.a.ReflectionTextureEnabled){if(!a.isReadyOrNotBlocking())return!1;if(a.irradianceTexture&&!a.irradianceTexture.isReadyOrNotBlocking())return!1}if(this._lightmapTexture&&oo.a.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&oo.a.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(oo.a.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&oo.a.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&oo.a.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(!(this.subSurface.isReadyForSubMesh(n,r)&&this.clearCoat.isReadyForSubMesh(n,r,o,this._disableBumpMap)&&this.sheen.isReadyForSubMesh(n,r)&&this.anisotropy.isReadyForSubMesh(n,r)))return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;o.getCaps().standardDerivatives||e.isVerticesDataPresent(en.b.NormalKind)||(e.createNormals(!0),m.a.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));var s=t.effect,c=n._areLightsDisposed,l=this._prepareEffect(e,n,this.onCompiled,this.onError,i);if(l)if(this.allowShaderHotSwapping&&s&&!l.isReady()){if(l=s,this._rebuildInParallel=!0,n.markAsUnprocessed(),c)return n._areLightsDisposed=!0,!1}else this._rebuildInParallel=!1,r.resetCachedMaterial(),t.setEffect(l,n),this.buildUniformLayout();return!(!t.effect||!t.effect.isReady())&&(n._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype.isMetallicWorkflow=function(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)},t.prototype._prepareEffect=function(e,t,i,n,r,o){if(void 0===i&&(i=null),void 0===n&&(n=null),void 0===r&&(r=null),void 0===o&&(o=null),this._prepareDefines(e,t,r,o),!t.isDirty)return null;t.markAsProcessed();var a=this.getScene().getEngine(),s=new ho.a,c=0;t.USESPHERICALINVERTEX&&s.addFallback(c++,"USESPHERICALINVERTEX"),t.FOG&&s.addFallback(c,"FOG"),t.SPECULARAA&&s.addFallback(c,"SPECULARAA"),t.POINTSIZE&&s.addFallback(c,"POINTSIZE"),t.LOGARITHMICDEPTH&&s.addFallback(c,"LOGARITHMICDEPTH"),t.PARALLAX&&s.addFallback(c,"PARALLAX"),t.PARALLAXOCCLUSION&&s.addFallback(c++,"PARALLAXOCCLUSION"),c=bo.AddFallbacks(t,s,c),c=bo.AddFallbacks(t,s,c),c=xo.AddFallbacks(t,s,c),c=Eo.AddFallbacks(t,s,c),t.ENVIRONMENTBRDF&&s.addFallback(c++,"ENVIRONMENTBRDF"),t.TANGENT&&s.addFallback(c++,"TANGENT"),t.BUMP&&s.addFallback(c++,"BUMP"),c=io.a.HandleFallbacksForShadows(t,s,this._maxSimultaneousLights,c++),t.SPECULARTERM&&s.addFallback(c++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&s.addFallback(c++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&s.addFallback(c++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&s.addFallback(c++,"LIGHTMAP"),t.NORMAL&&s.addFallback(c++,"NORMAL"),t.AMBIENT&&s.addFallback(c++,"AMBIENT"),t.EMISSIVE&&s.addFallback(c++,"EMISSIVE"),t.VERTEXCOLOR&&s.addFallback(c++,"VERTEXCOLOR"),t.MORPHTARGETS&&s.addFallback(c++,"MORPHTARGETS"),t.MULTIVIEW&&s.addFallback(0,"MULTIVIEW");var l=[en.b.PositionKind];t.NORMAL&&l.push(en.b.NormalKind),t.TANGENT&&l.push(en.b.TangentKind),t.UV1&&l.push(en.b.UVKind),t.UV2&&l.push(en.b.UV2Kind),t.VERTEXCOLOR&&l.push(en.b.ColorKind),io.a.PrepareAttributesForBones(l,e,t,s),io.a.PrepareAttributesForInstances(l,t),io.a.PrepareAttributesForMorphTargets(l,e,t);var u="pbr",h=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode"],d=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler"],f=["Material","Scene"];xo.AddUniforms(h),xo.AddSamplers(d),yo.AddUniforms(h),yo.AddSamplers(d),bo.AddUniforms(h),bo.AddSamplers(d),Eo.AddUniforms(h),Eo.AddSamplers(d),Yi.a&&(Yi.a.PrepareUniforms(h,t),Yi.a.PrepareSamplers(d,t)),io.a.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:f,samplers:d,defines:t,maxSimultaneousLights:this._maxSimultaneousLights}),this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,h,f,d,t));var p=t.toString();return a.createEffect(u,{attributes:l,uniformsNames:h,uniformBuffersNames:f,samplers:d,defines:p,fallbacks:s,onCompiled:i,onError:n,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS}},a)},t.prototype._prepareDefines=function(e,i,n,r){void 0===n&&(n=null),void 0===r&&(r=null);var o=this.getScene(),a=o.getEngine();if(io.a.PrepareDefinesForLights(o,e,i,!0,this._maxSimultaneousLights,this._disableLighting),i._needNormals=!0,io.a.PrepareDefinesForMultiview(o,i),i.METALLICWORKFLOW=this.isMetallicWorkflow(),i._areTexturesDirty){if(i._needUVs=!1,o.texturesEnabled){o.getEngine().getCaps().textureLOD&&(i.LODBASEDMICROSFURACE=!0),this._albedoTexture&&oo.a.DiffuseTextureEnabled?(io.a.PrepareDefinesForMergedUV(this._albedoTexture,i,"ALBEDO"),i.GAMMAALBEDO=this._albedoTexture.gammaSpace):i.ALBEDO=!1,this._ambientTexture&&oo.a.AmbientTextureEnabled?(io.a.PrepareDefinesForMergedUV(this._ambientTexture,i,"AMBIENT"),i.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):i.AMBIENT=!1,this._opacityTexture&&oo.a.OpacityTextureEnabled?(io.a.PrepareDefinesForMergedUV(this._opacityTexture,i,"OPACITY"),i.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):i.OPACITY=!1;var s=this._getReflectionTexture();if(s&&oo.a.ReflectionTextureEnabled){switch(i.REFLECTION=!0,i.GAMMAREFLECTION=s.gammaSpace,i.RGBDREFLECTION=s.isRGBD,i.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!s.invertZ:s.invertZ,i.LODINREFLECTIONALPHA=s.lodLevelInAlpha,i.LINEARSPECULARREFLECTION=s.linearSpecularLOD,s.coordinatesMode===et.a.INVCUBIC_MODE&&(i.INVERTCUBICMAP=!0),i.REFLECTIONMAP_3D=s.isCube,i.REFLECTIONMAP_CUBIC=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,s.coordinatesMode){case et.a.EXPLICIT_MODE:i.REFLECTIONMAP_EXPLICIT=!0;break;case et.a.PLANAR_MODE:i.REFLECTIONMAP_PLANAR=!0;break;case et.a.PROJECTION_MODE:i.REFLECTIONMAP_PROJECTION=!0;break;case et.a.SKYBOX_MODE:i.REFLECTIONMAP_SKYBOX=!0;break;case et.a.SPHERICAL_MODE:i.REFLECTIONMAP_SPHERICAL=!0;break;case et.a.EQUIRECTANGULAR_MODE:i.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case et.a.FIXED_EQUIRECTANGULAR_MODE:i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case et.a.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case et.a.CUBIC_MODE:case et.a.INVCUBIC_MODE:default:i.REFLECTIONMAP_CUBIC=!0,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!!s.boundingBoxSize}s.coordinatesMode!==et.a.SKYBOX_MODE&&(s.irradianceTexture?(i.USEIRRADIANCEMAP=!0,i.USESPHERICALFROMREFLECTIONMAP=!1):s.isCube&&(i.USESPHERICALFROMREFLECTIONMAP=!0,i.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||o.getEngine().getCaps().maxVaryingVectors<=8?i.USESPHERICALINVERTEX=!1:i.USESPHERICALINVERTEX=!0))}else i.REFLECTION=!1,i.REFLECTIONMAP_3D=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_CUBIC=!1,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,i.INVERTCUBICMAP=!1,i.USESPHERICALFROMREFLECTIONMAP=!1,i.USEIRRADIANCEMAP=!1,i.USESPHERICALINVERTEX=!1,i.REFLECTIONMAP_OPPOSITEZ=!1,i.LODINREFLECTIONALPHA=!1,i.GAMMAREFLECTION=!1,i.RGBDREFLECTION=!1,i.LINEARSPECULARREFLECTION=!1;this._lightmapTexture&&oo.a.LightmapTextureEnabled?(io.a.PrepareDefinesForMergedUV(this._lightmapTexture,i,"LIGHTMAP"),i.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,i.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,i.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):i.LIGHTMAP=!1,this._emissiveTexture&&oo.a.EmissiveTextureEnabled?io.a.PrepareDefinesForMergedUV(this._emissiveTexture,i,"EMISSIVE"):i.EMISSIVE=!1,oo.a.SpecularTextureEnabled?(this._metallicTexture?(io.a.PrepareDefinesForMergedUV(this._metallicTexture,i,"REFLECTIVITY"),i.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,i.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,i.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,i.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,i.METALLICF0FACTORFROMMETALLICMAP=this._useMetallicF0FactorFromMetallicTexture):this._reflectivityTexture?(io.a.PrepareDefinesForMergedUV(this._reflectivityTexture,i,"REFLECTIVITY"),i.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,i.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap):i.REFLECTIVITY=!1,this._microSurfaceTexture?io.a.PrepareDefinesForMergedUV(this._microSurfaceTexture,i,"MICROSURFACEMAP"):i.MICROSURFACEMAP=!1):(i.REFLECTIVITY=!1,i.MICROSURFACEMAP=!1),o.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&oo.a.BumpTextureEnabled&&!this._disableBumpMap?(io.a.PrepareDefinesForMergedUV(this._bumpTexture,i,"BUMP"),this._useParallax&&this._albedoTexture&&oo.a.DiffuseTextureEnabled?(i.PARALLAX=!0,i.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):i.PARALLAX=!1,i.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):i.BUMP=!1,this._environmentBRDFTexture&&oo.a.ReflectionTextureEnabled?(i.ENVIRONMENTBRDF=!0,i.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(i.ENVIRONMENTBRDF=!1,i.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?i.ALPHAFROMALBEDO=!0:i.ALPHAFROMALBEDO=!1}i.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===t.LIGHTFALLOFF_STANDARD?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===t.LIGHTFALLOFF_GLTF?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!0):(i.USEPHYSICALLIGHTFALLOFF=!0,i.USEGLTFLIGHTFALLOFF=!1),i.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?i.TWOSIDEDLIGHTING=!0:i.TWOSIDEDLIGHTING=!1,i.SPECULARAA=o.getEngine().getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(i._areTexturesDirty||i._areMiscDirty)&&(i.ALPHATESTVALUE=this._alphaCutOff+(this._alphaCutOff%1==0?".":""),i.PREMULTIPLYALPHA=this.alphaMode===g.a.ALPHA_PREMULTIPLIED||this.alphaMode===g.a.ALPHA_PREMULTIPLIED_PORTERDUFF,i.ALPHABLEND=this.needAlphaBlendingForMesh(e),i.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,i.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),i._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(i),i.FORCENORMALFORWARD=this._forceNormalForward,i.RADIANCEOCCLUSION=this._useRadianceOcclusion,i.HORIZONOCCLUSION=this._useHorizonOcclusion,i._areMiscDirty&&(io.a.PrepareDefinesForMisc(e,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,i),i.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(en.b.NormalKind),i.DEBUGMODE=this._debugMode),this.subSurface.prepareDefines(i,o),this.clearCoat.prepareDefines(i,o),this.anisotropy.prepareDefines(i,e,o),this.brdf.prepareDefines(i),this.sheen.prepareDefines(i,o),io.a.PrepareDefinesForFrameBoundValues(o,a,i,!!n,r),io.a.PrepareDefinesForAttributes(e,i,!0,!0,!0,this._transparencyMode!==t.PBRMATERIAL_OPAQUE)},t.prototype.forceCompilation=function(e,t,i){var n=this,r=Object(h.a)({clipPlane:!1,useInstances:!1},i),o=new Vo,a=this._prepareEffect(e,o,void 0,void 0,r.useInstances,r.clipPlane);a.isReady()?t&&t(this):a.onCompileObservable.add(function(){t&&t(n)})},t.prototype.buildUniformLayout=function(){var e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("reflectionMatrix",16),e.addUniform("vReflectionColor",3),e.addUniform("vAlbedoColor",4),e.addUniform("vLightingIntensity",4),e.addUniform("vReflectionMicrosurfaceInfos",3),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("visibility",1),yo.PrepareUniformBuffer(e),bo.PrepareUniformBuffer(e),Eo.PrepareUniformBuffer(e),xo.PrepareUniformBuffer(e),e.create()},t.prototype.unbind=function(){if(this._activeEffect){var t=!1;this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&(this._activeEffect.setTexture("reflection2DSampler",null),t=!0),this.subSurface.unbind(this._activeEffect)&&(t=!0),t&&this._markAllSubMeshesAsTexturesDirty()}e.prototype.unbind.call(this)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),r=i._materialDefines;if(r){var o=i.effect;if(o){this._activeEffect=o,r.INSTANCES||this.bindOnlyWorldMatrix(e),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var a=this._mustRebind(n,o,t.visibility);io.a.BindBonesParameters(t,this._activeEffect);var c=null,l=this._uniformBuffer;if(a){var u=n.getEngine();if(l.bindToEffect(o,"Material"),this.bindViewProjection(o),c=this._getReflectionTexture(),!l.useUbo||!this.isFrozen||!l.isSync){if(n.texturesEnabled){if(this._albedoTexture&&oo.a.DiffuseTextureEnabled&&(l.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),io.a.BindTextureMatrix(this._albedoTexture,l,"albedo")),this._ambientTexture&&oo.a.AmbientTextureEnabled&&(l.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),io.a.BindTextureMatrix(this._ambientTexture,l,"ambient")),this._opacityTexture&&oo.a.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),io.a.BindTextureMatrix(this._opacityTexture,l,"opacity")),c&&oo.a.ReflectionTextureEnabled){if(l.updateMatrix("reflectionMatrix",c.getReflectionTextureMatrix()),l.updateFloat2("vReflectionInfos",c.level,0),c.boundingBoxSize){var h=c;l.updateVector3("vReflectionPosition",h.boundingBoxPosition),l.updateVector3("vReflectionSize",h.boundingBoxSize)}if(!r.USEIRRADIANCEMAP){var d=c.sphericalPolynomial;if(r.USESPHERICALFROMREFLECTIONMAP&&d)if(r.SPHERICAL_HARMONICS){var f=d.preScaledHarmonics;this._activeEffect.setVector3("vSphericalL00",f.l00),this._activeEffect.setVector3("vSphericalL1_1",f.l1_1),this._activeEffect.setVector3("vSphericalL10",f.l10),this._activeEffect.setVector3("vSphericalL11",f.l11),this._activeEffect.setVector3("vSphericalL2_2",f.l2_2),this._activeEffect.setVector3("vSphericalL2_1",f.l2_1),this._activeEffect.setVector3("vSphericalL20",f.l20),this._activeEffect.setVector3("vSphericalL21",f.l21),this._activeEffect.setVector3("vSphericalL22",f.l22)}else this._activeEffect.setFloat3("vSphericalX",d.x.x,d.x.y,d.x.z),this._activeEffect.setFloat3("vSphericalY",d.y.x,d.y.y,d.y.z),this._activeEffect.setFloat3("vSphericalZ",d.z.x,d.z.y,d.z.z),this._activeEffect.setFloat3("vSphericalXX_ZZ",d.xx.x-d.zz.x,d.xx.y-d.zz.y,d.xx.z-d.zz.z),this._activeEffect.setFloat3("vSphericalYY_ZZ",d.yy.x-d.zz.x,d.yy.y-d.zz.y,d.yy.z-d.zz.z),this._activeEffect.setFloat3("vSphericalZZ",d.zz.x,d.zz.y,d.zz.z),this._activeEffect.setFloat3("vSphericalXY",d.xy.x,d.xy.y,d.xy.z),this._activeEffect.setFloat3("vSphericalYZ",d.yz.x,d.yz.y,d.yz.z),this._activeEffect.setFloat3("vSphericalZX",d.zx.x,d.zx.y,d.zx.z)}l.updateFloat3("vReflectionMicrosurfaceInfos",c.getSize().width,c.lodGenerationScale,c.lodGenerationOffset)}this._emissiveTexture&&oo.a.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),io.a.BindTextureMatrix(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&oo.a.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),io.a.BindTextureMatrix(this._lightmapTexture,l,"lightmap")),oo.a.SpecularTextureEnabled&&(this._metallicTexture?(l.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),io.a.BindTextureMatrix(this._metallicTexture,l,"reflectivity")):this._reflectivityTexture&&(l.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),io.a.BindTextureMatrix(this._reflectivityTexture,l,"reflectivity")),this._microSurfaceTexture&&(l.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),io.a.BindTextureMatrix(this._microSurfaceTexture,l,"microSurfaceSampler"))),this._bumpTexture&&u.getCaps().standardDerivatives&&oo.a.BumpTextureEnabled&&!this._disableBumpMap&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),io.a.BindTextureMatrix(this._bumpTexture,l,"bump"),n._mirroredCameraPosition?l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&l.updateFloat("pointSize",this.pointSize),r.METALLICWORKFLOW){s.c.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,s.c.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness;var p=.08*this._metallicF0Factor;l.updateColor4("vReflectivityColor",s.c.Color3[0],p)}else l.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);l.updateColor3("vEmissiveColor",oo.a.EmissiveTextureEnabled?this._emissiveColor:s.a.BlackReadOnly),l.updateColor3("vReflectionColor",this._reflectionColor),!r.SS_REFRACTION&&this.subSurface.linkRefractionWithTransparency?l.updateColor4("vAlbedoColor",this._albedoColor,1):l.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),l.updateFloat("visibility",t.visibility),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*n.environmentIntensity,this._lightingInfos.w=this._specularIntensity,l.updateVector4("vLightingIntensity",this._lightingInfos)}n.texturesEnabled&&(this._albedoTexture&&oo.a.DiffuseTextureEnabled&&l.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&oo.a.AmbientTextureEnabled&&l.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&oo.a.OpacityTextureEnabled&&l.setTexture("opacitySampler",this._opacityTexture),c&&oo.a.ReflectionTextureEnabled&&(r.LODBASEDMICROSFURACE?l.setTexture("reflectionSampler",c):(l.setTexture("reflectionSampler",c._lodTextureMid||c),l.setTexture("reflectionSamplerLow",c._lodTextureLow||c),l.setTexture("reflectionSamplerHigh",c._lodTextureHigh||c)),r.USEIRRADIANCEMAP&&l.setTexture("irradianceSampler",c.irradianceTexture)),r.ENVIRONMENTBRDF&&l.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&oo.a.EmissiveTextureEnabled&&l.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&oo.a.LightmapTextureEnabled&&l.setTexture("lightmapSampler",this._lightmapTexture),oo.a.SpecularTextureEnabled&&(this._metallicTexture?l.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&l.setTexture("reflectivitySampler",this._reflectivityTexture),this._microSurfaceTexture&&l.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&u.getCaps().standardDerivatives&&oo.a.BumpTextureEnabled&&!this._disableBumpMap&&l.setTexture("bumpSampler",this._bumpTexture)),this.subSurface.bindForSubMesh(l,n,u,this.isFrozen,r.LODBASEDMICROSFURACE),this.clearCoat.bindForSubMesh(l,n,u,this._disableBumpMap,this.isFrozen,this._invertNormalMapX,this._invertNormalMapY),this.anisotropy.bindForSubMesh(l,n,this.isFrozen),this.sheen.bindForSubMesh(l,n,this.isFrozen),io.a.BindClipPlane(this._activeEffect,n),n.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor);var _=n._forcedViewPosition?n._forcedViewPosition:n._mirroredCameraPosition?n._mirroredCameraPosition:n.activeCamera.globalPosition,m=n.useRightHandedSystem===(null!=n._mirroredCameraPosition);o.setFloat4("vEyePosition",_.x,_.y,_.z,m?-1:1),o.setColor3("vAmbientColor",this._globalAmbientColor),o.setFloat2("vDebugMode",this.debugLimit,this.debugFactor)}!a&&this.isFrozen||(n.lightsEnabled&&!this._disableLighting&&io.a.BindLights(n,t,this._activeEffect,r,this._maxSimultaneousLights,this._rebuildInParallel),(n.fogEnabled&&t.applyFog&&n.fogMode!==K.a.FOGMODE_NONE||c)&&this.bindView(o),io.a.BindFogParameters(n,t,this._activeEffect,!0),r.NUM_MORPH_INFLUENCERS&&io.a.BindMorphTargetParameters(t,this._activeEffect),this._imageProcessingConfiguration.bind(this._activeEffect),io.a.BindLogDepth(r,this._activeEffect,n)),l.update(),this._afterBind(t,this._activeEffect)}}},t.prototype.getAnimatables=function(){var e=[];return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),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._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),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.subSurface.getAnimatables(e),this.clearCoat.getAnimatables(e),this.sheen.getAnimatables(e),this.anisotropy.getAnimatables(e),e},t.prototype._getReflectionTexture=function(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._albedoTexture&&t.push(this._albedoTexture),this._ambientTexture&&t.push(this._ambientTexture),this._opacityTexture&&t.push(this._opacityTexture),this._reflectionTexture&&t.push(this._reflectionTexture),this._emissiveTexture&&t.push(this._emissiveTexture),this._reflectivityTexture&&t.push(this._reflectivityTexture),this._metallicTexture&&t.push(this._metallicTexture),this._microSurfaceTexture&&t.push(this._microSurfaceTexture),this._bumpTexture&&t.push(this._bumpTexture),this._lightmapTexture&&t.push(this._lightmapTexture),this.subSurface.getActiveTextures(t),this.clearCoat.getActiveTextures(t),this.sheen.getActiveTextures(t),this.anisotropy.getActiveTextures(t),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||(this._albedoTexture===t||(this._ambientTexture===t||(this._opacityTexture===t||(this._reflectionTexture===t||(this._reflectivityTexture===t||(this._metallicTexture===t||(this._microSurfaceTexture===t||(this._bumpTexture===t||(this._lightmapTexture===t||(this.subSurface.hasTexture(t)||this.clearCoat.hasTexture(t)||this.sheen.hasTexture(t)||this.anisotropy.hasTexture(t)))))))))))},t.prototype.dispose=function(t,i){i&&(this._albedoTexture&&this._albedoTexture.dispose(),this._ambientTexture&&this._ambientTexture.dispose(),this._opacityTexture&&this._opacityTexture.dispose(),this._reflectionTexture&&this._reflectionTexture.dispose(),this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._emissiveTexture&&this._emissiveTexture.dispose(),this._metallicTexture&&this._metallicTexture.dispose(),this._reflectivityTexture&&this._reflectivityTexture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._lightmapTexture&&this._lightmapTexture.dispose()),this.subSurface.dispose(i),this.clearCoat.dispose(i),this.sheen.dispose(i),this.anisotropy.dispose(i),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e.prototype.dispose.call(this,t,i)},t.PBRMATERIAL_OPAQUE=0,t.PBRMATERIAL_ALPHATEST=1,t.PBRMATERIAL_ALPHABLEND=2,t.PBRMATERIAL_ALPHATESTANDBLEND=3,t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,t.LIGHTFALLOFF_PHYSICAL=0,t.LIGHTFALLOFF_GLTF=1,t.LIGHTFALLOFF_STANDARD=2,Object(h.c)([Object(N.i)()],t.prototype,"_imageProcessingConfiguration",void 0),Object(h.c)([Object(N.b)("_markAllSubMeshesAsMiscDirty")],t.prototype,"debugMode",void 0),Object(h.c)([Object(N.c)()],t.prototype,"useLogarithmicDepth",null),Object(h.c)([Object(N.c)()],t.prototype,"transparencyMode",null),t}(ro.a),zo=function(e){function t(i,n){var r=e.call(this,i,n)||this;return r.directIntensity=1,r.emissiveIntensity=1,r.environmentIntensity=1,r.specularIntensity=1,r.disableBumpMap=!1,r.ambientTextureStrength=1,r.ambientTextureImpactOnAnalyticalLights=t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,r.metallicF0Factor=.5,r.useMetallicF0FactorFromMetallicTexture=!1,r.ambientColor=new s.a(0,0,0),r.albedoColor=new s.a(1,1,1),r.reflectivityColor=new s.a(1,1,1),r.reflectionColor=new s.a(1,1,1),r.emissiveColor=new s.a(0,0,0),r.microSurface=1,r.useLightmapAsShadowmap=!1,r.useAlphaFromAlbedoTexture=!1,r.forceAlphaTest=!1,r.alphaCutOff=.4,r.useSpecularOverAlpha=!0,r.useMicroSurfaceFromReflectivityMapAlpha=!1,r.useRoughnessFromMetallicTextureAlpha=!0,r.useRoughnessFromMetallicTextureGreen=!1,r.useMetallnessFromMetallicTextureBlue=!1,r.useAmbientOcclusionFromMetallicTextureRed=!1,r.useAmbientInGrayScale=!1,r.useAutoMicroSurfaceFromReflectivityMap=!1,r.useRadianceOverAlpha=!0,r.useObjectSpaceNormalMap=!1,r.useParallax=!1,r.useParallaxOcclusion=!1,r.parallaxScaleBias=.05,r.disableLighting=!1,r.forceIrradianceInFragment=!1,r.maxSimultaneousLights=4,r.invertNormalMapX=!1,r.invertNormalMapY=!1,r.twoSidedLighting=!1,r.useAlphaFresnel=!1,r.useLinearAlphaFresnel=!1,r.environmentBRDFTexture=null,r.forceNormalForward=!1,r.enableSpecularAntiAliasing=!1,r.useHorizonOcclusion=!0,r.useRadianceOcclusion=!0,r.unlit=!1,r._environmentBRDFTexture=vo.GetEnvironmentBRDFTexture(n),r}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"refractionTexture",{get:function(){return this.subSurface.refractionTexture},set:function(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"indexOfRefraction",{get:function(){return 1/this.subSurface.indexOfRefraction},set:function(e){this.subSurface.indexOfRefraction=1/e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"invertRefractionY",{get:function(){return this.subSurface.invertRefractionY},set:function(e){this.subSurface.invertRefractionY=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"linkRefractionWithTransparency",{get:function(){return this.subSurface.linkRefractionWithTransparency},set:function(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"usePhysicalLightFalloff",{get:function(){return this._lightFalloff===ko.LIGHTFALLOFF_PHYSICAL},set:function(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?ko.LIGHTFALLOFF_PHYSICAL:ko.LIGHTFALLOFF_STANDARD)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useGLTFLightFalloff",{get:function(){return this._lightFalloff===ko.LIGHTFALLOFF_GLTF},set:function(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?ko.LIGHTFALLOFF_GLTF:ko.LIGHTFALLOFF_STANDARD)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this._imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurves",{get:function(){return this._imageProcessingConfiguration.colorCurves},set:function(e){this._imageProcessingConfiguration.colorCurves=e},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"PBRMaterial"},t.prototype.clone=function(e){var i=this,n=N.a.Clone(function(){return new t(e,i.getScene())},this);return n.id=e,n.name=e,this.clearCoat.copyTo(n.clearCoat),this.anisotropy.copyTo(n.anisotropy),this.brdf.copyTo(n.brdf),this.sheen.copyTo(n.sheen),this.subSurface.copyTo(n.subSurface),n},t.prototype.serialize=function(){var e=N.a.Serialize(this);return e.customType="BABYLON.PBRMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e},t.Parse=function(e,i,n){var r=N.a.Parse(function(){return new t(e.name,i)},e,i,n);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,i,n),e.anisotropy&&r.anisotropy.parse(e.anisotropy,i,n),e.brdf&&r.brdf.parse(e.brdf,i,n),e.sheen&&r.sheen.parse(e.sheen,i,n),e.subSurface&&r.subSurface.parse(e.subSurface,i,n),r},t.PBRMATERIAL_OPAQUE=ko.PBRMATERIAL_OPAQUE,t.PBRMATERIAL_ALPHATEST=ko.PBRMATERIAL_ALPHATEST,t.PBRMATERIAL_ALPHABLEND=ko.PBRMATERIAL_ALPHABLEND,t.PBRMATERIAL_ALPHATESTANDBLEND=ko.PBRMATERIAL_ALPHATESTANDBLEND,t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=ko.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"directIntensity",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveIntensity",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"environmentIntensity",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"specularIntensity",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"disableBumpMap",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"albedoTexture",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientTexture",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientTextureStrength",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"opacityTexture",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionTexture",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveTexture",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectivityTexture",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallicTexture",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallic",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"roughness",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallicF0Factor",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useMetallicF0FactorFromMetallicTexture",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"microSurfaceTexture",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"bumpTexture",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty",null)],t.prototype,"lightmapTexture",void 0),Object(h.c)([Object(N.e)("ambient"),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientColor",void 0),Object(h.c)([Object(N.e)("albedo"),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"albedoColor",void 0),Object(h.c)([Object(N.e)("reflectivity"),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectivityColor",void 0),Object(h.c)([Object(N.e)("reflection"),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionColor",void 0),Object(h.c)([Object(N.e)("emissive"),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveColor",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"microSurface",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useLightmapAsShadowmap",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"useAlphaFromAlbedoTexture",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"forceAlphaTest",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"alphaCutOff",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useSpecularOverAlpha",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRoughnessFromMetallicTextureGreen",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useMetallnessFromMetallicTextureBlue",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAmbientInGrayScale",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),Object(h.c)([Object(N.c)()],t.prototype,"usePhysicalLightFalloff",null),Object(h.c)([Object(N.c)()],t.prototype,"useGLTFLightFalloff",null),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRadianceOverAlpha",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useObjectSpaceNormalMap",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useParallax",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useParallaxOcclusion",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"parallaxScaleBias",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"forceIrradianceInFragment",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapX",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapY",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"twoSidedLighting",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAlphaFresnel",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useLinearAlphaFresnel",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"environmentBRDFTexture",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"forceNormalForward",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"enableSpecularAntiAliasing",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useHorizonOcclusion",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRadianceOcclusion",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsMiscDirty")],t.prototype,"unlit",void 0),t}(ko);c.a.RegisteredTypes["BABYLON.PBRMaterial"]=zo;function Go(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}var jo=Go("DXT1"),Wo=Go("DXT3"),Xo=Go("DXT5"),Ho=Go("DX10"),Yo=function(){function e(){}return e.GetDDSInfo=function(e){var t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35),n=1;131072&t[2]&&(n=Math.max(1,t[7]));var r=t[21],o=r===Ho?i[32]:0,a=g.a.TEXTURETYPE_UNSIGNED_INT;switch(r){case 113:a=g.a.TEXTURETYPE_HALF_FLOAT;break;case 116:a=g.a.TEXTURETYPE_FLOAT;break;case Ho:if(10===o){a=g.a.TEXTURETYPE_HALF_FLOAT;break}if(2===o){a=g.a.TEXTURETYPE_FLOAT;break}}return{width:t[4],height:t[3],mipmapCount:n,isFourCC:4==(4&t[20]),isRGB:64==(64&t[20]),isLuminance:131072==(131072&t[20]),isCube:512==(512&t[28]),isCompressed:r===jo||r===Wo||r===Xo,dxgiFormat:o,textureType:a}},e._ToHalfFloat=function(t){e._FloatView||(e._FloatView=new Float32Array(1),e._Int32View=new Int32Array(e._FloatView.buffer)),e._FloatView[0]=t;var i=e._Int32View[0],n=i>>16&32768,r=i>>12&2047,o=i>>23&255;return o<103?n:o>142?(n|=31744,n|=(255==o?0:1)&&8388607&i):o<113?n|=((r|=2048)>>114-o)+(r>>113-o&1):(n|=o-112<<10|r>>1,n+=1&r)},e._FromHalfFloat=function(e){var t=(32768&e)>>15,i=(31744&e)>>10,n=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(n/Math.pow(2,10)):31==i?n?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+n/Math.pow(2,10))},e._GetHalfFloatAsFloatRGBAArrayBuffer=function(t,i,n,r,o,a){for(var s=new Float32Array(r),c=new Uint16Array(o,n),l=0,u=0;u<i;u++)for(var h=0;h<t;h++){var d=4*(h+u*t);s[l]=e._FromHalfFloat(c[d]),s[l+1]=e._FromHalfFloat(c[d+1]),s[l+2]=e._FromHalfFloat(c[d+2]),e.StoreLODInAlphaChannel?s[l+3]=a:s[l+3]=e._FromHalfFloat(c[d+3]),l+=4}return s},e._GetHalfFloatRGBAArrayBuffer=function(t,i,n,r,o,a){if(e.StoreLODInAlphaChannel){for(var s=new Uint16Array(r),c=new Uint16Array(o,n),l=0,u=0;u<i;u++)for(var h=0;h<t;h++){var d=4*(h+u*t);s[l]=c[d],s[l+1]=c[d+1],s[l+2]=c[d+2],s[l+3]=e._ToHalfFloat(a),l+=4}return s}return new Uint16Array(o,n,r)},e._GetFloatRGBAArrayBuffer=function(t,i,n,r,o,a){if(e.StoreLODInAlphaChannel){for(var s=new Float32Array(r),c=new Float32Array(o,n),l=0,u=0;u<i;u++)for(var h=0;h<t;h++){var d=4*(h+u*t);s[l]=c[d],s[l+1]=c[d+1],s[l+2]=c[d+2],s[l+3]=a,l+=4}return s}return new Float32Array(o,n,r)},e._GetFloatAsUIntRGBAArrayBuffer=function(t,i,n,r,o,a){for(var s=new Uint8Array(r),c=new Float32Array(o,n),l=0,u=0;u<i;u++)for(var h=0;h<t;h++){var d=4*(h+u*t);s[l]=255*L.a.Clamp(c[d]),s[l+1]=255*L.a.Clamp(c[d+1]),s[l+2]=255*L.a.Clamp(c[d+2]),e.StoreLODInAlphaChannel?s[l+3]=a:s[l+3]=255*L.a.Clamp(c[d+3]),l+=4}return s},e._GetHalfFloatAsUIntRGBAArrayBuffer=function(t,i,n,r,o,a){for(var s=new Uint8Array(r),c=new Uint16Array(o,n),l=0,u=0;u<i;u++)for(var h=0;h<t;h++){var d=4*(h+u*t);s[l]=255*L.a.Clamp(e._FromHalfFloat(c[d])),s[l+1]=255*L.a.Clamp(e._FromHalfFloat(c[d+1])),s[l+2]=255*L.a.Clamp(e._FromHalfFloat(c[d+2])),e.StoreLODInAlphaChannel?s[l+3]=a:s[l+3]=255*L.a.Clamp(e._FromHalfFloat(c[d+3])),l+=4}return s},e._GetRGBAArrayBuffer=function(e,t,i,n,r,o,a,s,c){for(var l=new Uint8Array(n),u=new Uint8Array(r,i),h=0,d=0;d<t;d++)for(var f=0;f<e;f++){var p=4*(f+d*e);l[h]=u[p+o],l[h+1]=u[p+a],l[h+2]=u[p+s],l[h+3]=u[p+c],h+=4}return l},e._ExtractLongWordOrder=function(t){return 0===t||255===t||-16777216===t?0:1+e._ExtractLongWordOrder(t>>8)},e._GetRGBArrayBuffer=function(e,t,i,n,r,o,a,s){for(var c=new Uint8Array(n),l=new Uint8Array(r,i),u=0,h=0;h<t;h++)for(var d=0;d<e;d++){var f=3*(d+h*e);c[u]=l[f+o],c[u+1]=l[f+a],c[u+2]=l[f+s],u+=3}return c},e._GetLuminanceArrayBuffer=function(e,t,i,n,r){for(var o=new Uint8Array(n),a=new Uint8Array(r,i),s=0,c=0;c<t;c++)for(var l=0;l<e;l++){var u=l+c*e;o[s]=a[u],s++}return o},e.UploadDDSLevels=function(t,i,n,r,o,a,s,c){void 0===s&&(s=-1);var l=null;r.sphericalPolynomial&&(l=new Array);var u,h,d,f,p,_,v,y=t.getCaps().s3tc,b=new Int32Array(n.buffer,n.byteOffset,31),T=0,E=0,x=1;if(542327876===b[0])if(r.isFourCC||r.isRGB||r.isLuminance)if(!r.isCompressed||y){var P=b[22];f=b[1]+4;var A,S=!1;if(r.isFourCC)switch(u=b[21]){case jo:x=8,E=y.COMPRESSED_RGBA_S3TC_DXT1_EXT;break;case Wo:x=16,E=y.COMPRESSED_RGBA_S3TC_DXT3_EXT;break;case Xo:x=16,E=y.COMPRESSED_RGBA_S3TC_DXT5_EXT;break;case 113:case 116:S=!0;break;case Ho:f+=20;var C=!1;switch(r.dxgiFormat){case 10:case 2:S=!0,C=!0;break;case 88:r.isRGB=!0,r.isFourCC=!1,P=32,C=!0}if(C)break;default:return void console.error("Unsupported FourCC code:",(A=u,String.fromCharCode(255&A,A>>8&255,A>>16&255,A>>24&255)))}var R=e._ExtractLongWordOrder(b[23]),O=e._ExtractLongWordOrder(b[24]),M=e._ExtractLongWordOrder(b[25]),I=e._ExtractLongWordOrder(b[26]);S&&(E=t._getRGBABufferInternalSizedFormat(r.textureType)),_=1,131072&b[2]&&!1!==o&&(_=Math.max(1,b[7]));for(var D=c||0;D<a;D++){for(h=b[4],d=b[3],v=0;v<_;++v){if(-1===s||s===v){var w=-1===s?v:0;if(!r.isCompressed&&r.isFourCC){i.format=g.a.TEXTUREFORMAT_RGBA,T=h*d*4;var L=null;t._badOS||t._badDesktopOS||!t.getCaps().textureHalfFloat&&!t.getCaps().textureFloat?(128===P?(L=e._GetFloatAsUIntRGBAArrayBuffer(h,d,n.byteOffset+f,T,n.buffer,w),l&&0==w&&l.push(e._GetFloatRGBAArrayBuffer(h,d,n.byteOffset+f,T,n.buffer,w))):64===P&&(L=e._GetHalfFloatAsUIntRGBAArrayBuffer(h,d,n.byteOffset+f,T,n.buffer,w),l&&0==w&&l.push(e._GetHalfFloatAsFloatRGBAArrayBuffer(h,d,n.byteOffset+f,T,n.buffer,w))),i.type=g.a.TEXTURETYPE_UNSIGNED_INT):128===P?(i.type=g.a.TEXTURETYPE_FLOAT,L=e._GetFloatRGBAArrayBuffer(h,d,n.byteOffset+f,T,n.buffer,w),l&&0==w&&l.push(L)):64!==P||t.getCaps().textureHalfFloat?(i.type=g.a.TEXTURETYPE_HALF_FLOAT,L=e._GetHalfFloatRGBAArrayBuffer(h,d,n.byteOffset+f,T,n.buffer,w),l&&0==w&&l.push(e._GetHalfFloatAsFloatRGBAArrayBuffer(h,d,f,T,n.buffer,w))):(i.type=g.a.TEXTURETYPE_FLOAT,L=e._GetHalfFloatAsFloatRGBAArrayBuffer(h,d,n.byteOffset+f,T,n.buffer,w),l&&0==w&&l.push(L)),L&&t._uploadDataToTextureDirectly(i,L,D,w)}else if(r.isRGB)i.type=g.a.TEXTURETYPE_UNSIGNED_INT,24===P?(i.format=g.a.TEXTUREFORMAT_RGB,T=h*d*3,p=e._GetRGBArrayBuffer(h,d,n.byteOffset+f,T,n.buffer,R,O,M),t._uploadDataToTextureDirectly(i,p,D,w)):(i.format=g.a.TEXTUREFORMAT_RGBA,T=h*d*4,p=e._GetRGBAArrayBuffer(h,d,n.byteOffset+f,T,n.buffer,R,O,M,I),t._uploadDataToTextureDirectly(i,p,D,w));else if(r.isLuminance){var N=t._getUnpackAlignement(),F=h;T=Math.floor((h+N-1)/N)*N*(d-1)+F,p=e._GetLuminanceArrayBuffer(h,d,n.byteOffset+f,T,n.buffer),i.format=g.a.TEXTUREFORMAT_LUMINANCE,i.type=g.a.TEXTURETYPE_UNSIGNED_INT,t._uploadDataToTextureDirectly(i,p,D,w)}else T=Math.max(4,h)/4*Math.max(4,d)/4*x,p=new Uint8Array(n.buffer,n.byteOffset+f,T),i.type=g.a.TEXTURETYPE_UNSIGNED_INT,t._uploadCompressedDataToTextureDirectly(i,E,h,d,p,D,w)}f+=P?h*d*(P/8):T,h*=.5,d*=.5,h=Math.max(1,h),d=Math.max(1,d)}if(void 0!==c)break}l&&l.length>0?r.sphericalPolynomial=Xn.ConvertCubeMapToSphericalPolynomial({size:b[4],right:l[0],left:l[1],up:l[2],down:l[3],front:l[4],back:l[5],format:g.a.TEXTUREFORMAT_RGBA,type:g.a.TEXTURETYPE_FLOAT,gammaSpace:!1}):r.sphericalPolynomial=void 0}else m.a.Error("Compressed textures are not supported on this platform.");else m.a.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");else m.a.Error("Invalid magic number in DDS header")},e.StoreLODInAlphaChannel=!1,e}();li.a.prototype.createPrefilteredCubeTexture=function(e,t,i,n,r,o,a,s,c){var l=this;void 0===r&&(r=null),void 0===o&&(o=null),void 0===s&&(s=null),void 0===c&&(c=!0);return this.createCubeTexture(e,t,null,!1,function(e){if(e){var o=e.texture;if(c?e.info.sphericalPolynomial&&(o._sphericalPolynomial=e.info.sphericalPolynomial):o._sphericalPolynomial=new Gn,o._source=tt.b.CubePrefiltered,l.getCaps().textureLOD)r&&r(o);else{var a=l._gl,s=e.width;if(s){for(var u=[],h=0;h<3;h++){var d=1-h/2,f=n,p=L.a.Log2(s)*i+n,_=f+(p-f)*d,g=Math.round(Math.min(Math.max(_,0),p)),v=new tt.a(l,tt.b.Temp);if(v.type=o.type,v.format=o.format,v.width=Math.pow(2,Math.max(L.a.Log2(s)-g,0)),v.height=v.width,v.isCube=!0,l._bindTextureDirectly(a.TEXTURE_CUBE_MAP,v,!0),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),e.isDDS){var y=e.info,b=e.data;l._unpackFlipY(y.isCompressed),Yo.UploadDDSLevels(l,v,b,y,!0,6,g)}else m.a.Warn("DDS is the only prefiltered cube map supported so far.");l._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);var T=new jn.a(t);T.isCube=!0,T._texture=v,v.isReady=!0,u.push(T)}o._lodTextureHigh=u[2],o._lodTextureMid=u[1],o._lodTextureLow=u[0],r&&r(o)}}}else r&&r(null)},o,a,s,c,i,n)};var Ko=function(){function e(){this.supportCascades=!0}return e.prototype.canLoad=function(e){return eo.a.EndsWith(e,".dds")},e.prototype.loadCubeData=function(e,t,i,n,r){var o,a=t.getEngine(),s=!1;if(Array.isArray(e))for(var c=0;c<e.length;c++){var l=e[c];o=Yo.GetDDSInfo(l),t.width=o.width,t.height=o.height,s=(o.isRGB||o.isLuminance||o.mipmapCount>1)&&t.generateMipMaps,a._unpackFlipY(o.isCompressed),Yo.UploadDDSLevels(a,t,l,o,s,6,-1,c),o.isFourCC||1!==o.mipmapCount||a.generateMipMapsForCubemap(t)}else{var u=e;o=Yo.GetDDSInfo(u),t.width=o.width,t.height=o.height,i&&(o.sphericalPolynomial=new Gn),s=(o.isRGB||o.isLuminance||o.mipmapCount>1)&&t.generateMipMaps,a._unpackFlipY(o.isCompressed),Yo.UploadDDSLevels(a,t,u,o,s,6),o.isFourCC||1!==o.mipmapCount||a.generateMipMapsForCubemap(t,!1)}a._setCubeMapTextureParams(s),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n({isDDS:!0,width:t.width,info:o,data:e,texture:t})},e.prototype.loadData=function(e,t,i){var n=Yo.GetDDSInfo(e),r=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps&&n.width>>n.mipmapCount-1==1;i(n.width,n.height,r,n.isFourCC,function(){Yo.UploadDDSLevels(t.getEngine(),t,e,n,r,1)})},e}();Oe.a._TextureLoaders.push(new Ko);var Qo=function(){function e(){this.supportCascades=!1}return e.prototype.canLoad=function(e){return eo.a.EndsWith(e,".env")},e.prototype.loadCubeData=function(e,t,i,n,r){if(!Array.isArray(e)){var o=qn.GetEnvInfo(e);o?(t.width=o.width,t.height=o.width,qn.UploadEnvSpherical(t,o),qn.UploadEnvLevelsAsync(t,e,o).then(function(){t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()})):r&&r("Can not parse the environment file",null)}},e.prototype.loadData=function(e,t,i){throw".env not supported in 2d."},e}();Oe.a._TextureLoaders.push(new Qo);var qo=function(){function e(t,i,n,r){if(this.data=t,this.isInvalid=!1,!e.IsValid(t))return this.isInvalid=!0,void m.a.Error("texture missing KTX identifier");var o=Uint32Array.BYTES_PER_ELEMENT,a=new DataView(this.data.buffer,this.data.byteOffset+12,13*o),s=67305985===a.getUint32(0,!0);this.glType=a.getUint32(1*o,s),this.glTypeSize=a.getUint32(2*o,s),this.glFormat=a.getUint32(3*o,s),this.glInternalFormat=a.getUint32(4*o,s),this.glBaseInternalFormat=a.getUint32(5*o,s),this.pixelWidth=a.getUint32(6*o,s),this.pixelHeight=a.getUint32(7*o,s),this.pixelDepth=a.getUint32(8*o,s),this.numberOfArrayElements=a.getUint32(9*o,s),this.numberOfFaces=a.getUint32(10*o,s),this.numberOfMipmapLevels=a.getUint32(11*o,s),this.bytesOfKeyValueData=a.getUint32(12*o,s),0===this.glType?(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0!==this.pixelHeight&&0===this.pixelDepth?0===this.numberOfArrayElements?this.numberOfFaces===i?this.loadType=e.COMPRESSED_2D:m.a.Error("number of faces expected"+i+", but found "+this.numberOfFaces):m.a.Error("texture arrays not currently supported"):m.a.Error("only 2D textures currently supported")):m.a.Error("only compressed formats currently supported")}return e.prototype.uploadLevels=function(t,i){switch(this.loadType){case e.COMPRESSED_2D:this._upload2DCompressedLevels(t,i);break;case e.TEX_2D:case e.COMPRESSED_3D:case e.TEX_3D:}},e.prototype._upload2DCompressedLevels=function(t,i){for(var n=e.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,o=this.pixelHeight,a=i?this.numberOfMipmapLevels:1,s=0;s<a;s++){var c=new Int32Array(this.data.buffer,this.data.byteOffset+n,1)[0];n+=4;for(var l=0;l<this.numberOfFaces;l++){var u=new Uint8Array(this.data.buffer,this.data.byteOffset+n,c);t.getEngine()._uploadCompressedDataToTextureDirectly(t,this.glInternalFormat,r,o,u,l,s),n+=c,n+=3-(c+3)%4}r=Math.max(1,.5*r),o=Math.max(1,.5*o)}},e.IsValid=function(e){if(e.byteLength>=12){var t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1},e.HEADER_LEN=64,e.COMPRESSED_2D=0,e.COMPRESSED_3D=1,e.TEX_2D=2,e.TEX_3D=3,e}(),Zo=function(){function e(t){var i=this;e._ModulePromise||(e._ModulePromise=new Promise(function(n){LIBKTX().then(function(r){r.GL.makeContextCurrent(r.GL.registerContext(t._gl,{majorVersion:t._webGLVersion})),e._TranscodeFormat=i._determineTranscodeFormat(r.TranscodeTarget,t.getCaps()),n({module:r})})}))}return e.prototype.uploadAsync=function(t,i){return e._ModulePromise.then(function(n){var r=new n.module.ktxTexture(t);try{r.isBasisSupercompressed&&r.transcodeBasis(e._TranscodeFormat,0),i.width=i.baseWidth=r.baseWidth,i.height=i.baseHeight=r.baseHeight,i.generateMipMaps=!1;var o=r.glUpload();if(0!==o.error)throw new Error("Failed to upload: "+o.error);i._webGLTexture=o.texture,i.isReady=!0}finally{r.delete()}})},e.prototype._determineTranscodeFormat=function(e,t){if(t.s3tc)return e.BC1_OR_3;if(t.etc2)return e.ETC;throw new Error("No compatible format available")},e.IsValid=function(e){if(e.byteLength>=12){var t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1},e}(),Jo=function(){function e(){this.supportCascades=!1}return e.prototype.canLoad=function(e){return eo.a.EndsWith(e,".ktx")||eo.a.EndsWith(e,".ktx2")},e.prototype.loadCubeData=function(e,t,i,n,r){if(!Array.isArray(e)){t._invertVScale=!t.invertY;var o=t.getEngine(),a=new qo(e,6),s=a.numberOfMipmapLevels>1&&t.generateMipMaps;o._unpackFlipY(!0),a.uploadLevels(t,t.generateMipMaps),t.width=a.pixelWidth,t.height=a.pixelHeight,o._setCubeMapTextureParams(s),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()}},e.prototype.loadData=function(e,t,i){if(qo.IsValid(e)){t._invertVScale=!t.invertY;var n=new qo(e,1);i(n.pixelWidth,n.pixelHeight,t.generateMipMaps,!0,function(){n.uploadLevels(t,t.generateMipMaps)},n.isInvalid)}else if(Zo.IsValid(e)){new Zo(t.getEngine()).uploadAsync(e,t).then(function(){i(t.width,t.height,!1,!0,function(){},!1)},function(e){m.a.Warn("Failed to load KTX2 texture data: "+e.message),i(0,0,!1,!1,function(){},!0)})}else i(0,0,!1,!1,function(){},!0)},e}();Oe.a._TextureLoaders.unshift(new Jo);var $o=function(e){function t(t,i,n){var r=e.call(this,t,a.e.Zero(),i)||this;return r._xrSessionManager=n,r._firstFrame=!1,r._referenceQuaternion=a.b.Identity(),r._referencedPosition=new a.e,r._xrInvPositionCache=new a.e,r._xrInvQuaternionCache=a.b.Identity(),r.compensateOnFirstFrame=!0,r.minZ=.1,r.rotationQuaternion=new a.b,r.cameraRigMode=Qe.a.RIG_MODE_CUSTOM,r.updateUpVectorFromRotation=!0,r._updateNumberOfRigCameras(1),r._xrSessionManager.onXRSessionInit.add(function(){r._referencedPosition.copyFromFloats(0,0,0),r._referenceQuaternion.copyFromFloats(0,0,0,1),r._firstFrame=r.compensateOnFirstFrame}),r._xrSessionManager.onXRFrameObservable.add(function(e){r._firstFrame&&r._updateFromXRSession(),r._updateReferenceSpace(),r._updateFromXRSession()},void 0,!0),r}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"realWorldHeight",{get:function(){var e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y:0},enumerable:!0,configurable:!0}),t.prototype._updateForDualEyeDebugging=function(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new ki.a(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new ki.a(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null},t.prototype.setTransformationFromNonVRCamera=function(e,t){(void 0===e&&(e=this.getScene().activeCamera),void 0===t&&(t=!0),e&&e!==this)&&(e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,a.b.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace())},t.prototype.getClassName=function(){return"WebXRCamera"},t.prototype._updateFromXRSession=function(){var e=this,t=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);t&&(t.transform&&(this._referencedPosition.copyFrom(t.transform.position),this._referenceQuaternion.copyFrom(t.transform.orientation),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))),this.rigCameras.length!==t.views.length&&this._updateNumberOfRigCameras(t.views.length),t.views.forEach(function(t,i){var n=e.rigCameras[i];if(n.isLeftCamera||n.isRightCamera||("right"===t.eye?n._isRightCamera=!0:"left"===t.eye&&(n._isLeftCamera=!0)),t.transform.position?(n.position.copyFrom(t.transform.position),n.rotationQuaternion.copyFrom(t.transform.orientation),e._scene.useRightHandedSystem||(n.position.z*=-1,n.rotationQuaternion.z*=-1,n.rotationQuaternion.w*=-1)):(a.a.FromFloat32ArrayToRefScaled(t.transform.matrix,0,1,n._computedViewMatrix),e._scene.useRightHandedSystem||n._computedViewMatrix.toggleModelMatrixHandInPlace()),a.a.FromFloat32ArrayToRefScaled(t.projectionMatrix,0,1,n._projectionMatrix),e._scene.useRightHandedSystem||n._projectionMatrix.toggleProjectionMatrixHandInPlace(),e._xrSessionManager.session.renderState.baseLayer){var r=e._xrSessionManager.session.renderState.baseLayer.getViewport(t),o=e._xrSessionManager.session.renderState.baseLayer.framebufferWidth,s=e._xrSessionManager.session.renderState.baseLayer.framebufferHeight;n.viewport.width=r.width/o,n.viewport.height=r.height/s,n.viewport.x=r.x/o,n.viewport.y=r.y/s}n.outputRenderTarget=e._xrSessionManager.getRenderTargetTextureForEye(t.eye)}))},t.prototype._updateNumberOfRigCameras=function(e){for(void 0===e&&(e=1);this.rigCameras.length<e;){var t=new Lt("XR-RigCamera: "+this.rigCameras.length,a.e.Zero(),this.getScene());t.minZ=.1,t.rotationQuaternion=new a.b,t.updateUpVectorFromRotation=!0,t.isRigCamera=!0,t.rigParent=this,this.rigCameras.push(t)}for(;this.rigCameras.length>e;){var i=this.rigCameras.pop();i&&i.dispose()}},t.prototype._updateReferenceSpace=function(){this.position.equals(this._referencedPosition)&&this.rotationQuaternion.equals(this._referenceQuaternion)||(this.position.subtractToRef(this._referencedPosition,this._referencedPosition),this._referenceQuaternion.conjugateInPlace(),this._referenceQuaternion.multiplyToRef(this.rotationQuaternion,this._referenceQuaternion),this._updateReferenceSpaceOffset(this._referencedPosition,this._referenceQuaternion.normalize()))},t.prototype._updateReferenceSpaceOffset=function(e,t,i){if(void 0===i&&(i=!1),this._xrSessionManager.referenceSpace&&this._xrSessionManager.currentFrame){this._xrInvPositionCache.copyFrom(e),t?this._xrInvQuaternionCache.copyFrom(t):this._xrInvQuaternionCache.copyFromFloats(0,0,0,1),this._scene.useRightHandedSystem||(this._xrInvPositionCache.z*=-1,this._xrInvQuaternionCache.z*=-1,this._xrInvQuaternionCache.w*=-1),this._xrInvPositionCache.negateInPlace(),this._xrInvQuaternionCache.conjugateInPlace(),this._xrInvPositionCache.rotateByQuaternionToRef(this._xrInvQuaternionCache,this._xrInvPositionCache),i&&(this._xrInvPositionCache.y=0);var n=new XRRigidTransform(Object(h.a)({},this._xrInvPositionCache),Object(h.a)({},this._xrInvQuaternionCache)),r=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(n),o=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(r);if(o){var s=new a.e;s.copyFrom(o.transform.position),this._scene.useRightHandedSystem||(s.z*=-1),this.position.subtractToRef(s,s),this._scene.useRightHandedSystem||(s.z*=-1),s.negateInPlace();var c=new XRRigidTransform(Object(h.a)({},s));this._xrSessionManager.referenceSpace=r.getOffsetReferenceSpace(c)}}},t}(Nt),ea=function(){function e(){}return e.ANCHOR_SYSTEM="xr-anchor-system",e.BACKGROUND_REMOVER="xr-background-remover",e.HIT_TEST="xr-hit-test",e.PHYSICS_CONTROLLERS="xr-physics-controller",e.PLANE_DETECTION="xr-plane-detection",e.POINTER_SELECTION="xr-controller-pointer-selection",e.TELEPORTATION="xr-controller-teleportation",e}(),ta=function(){function e(e){var t=this;this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add(function(){t.getEnabledFeatures().forEach(function(e){var i=t._features[e];!i.enabled||i.featureImplementation.attached||i.featureImplementation.disableAutoAttach||t.attachFeature(e)})}),this._xrSessionManager.onXRSessionEnded.add(function(){t.getEnabledFeatures().forEach(function(e){var i=t._features[e];i.enabled&&i.featureImplementation.attached&&t.detachFeature(e)})})}return e.AddWebXRFeature=function(e,t,i,n){void 0===i&&(i=1),void 0===n&&(n=!1),this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),n&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t},e.ConstructFeature=function(e,t,i,n){void 0===t&&(t=1);var r=this._AvailableFeatures[e][t];if(!r)throw new Error("feature not found");return r(i,n)},e.GetAvailableFeatures=function(){return Object.keys(this._AvailableFeatures)},e.GetAvailableVersions=function(e){return Object.keys(this._AvailableFeatures[e])},e.GetLatestVersionOfFeature=function(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1},e.GetStableVersionOfFeature=function(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1},e.prototype.attachFeature=function(e){var t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&t.featureImplementation.attach()},e.prototype.detachFeature=function(e){var t=this._features[e];t&&t.featureImplementation.attached&&t.featureImplementation.detach()},e.prototype.disableFeature=function(e){var t="string"==typeof e?e:e.Name,i=this._features[t];return!(!i||!i.enabled)&&(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),!0)},e.prototype.dispose=function(){var e=this;this.getEnabledFeatures().forEach(function(t){e.disableFeature(t),e._features[t].featureImplementation.dispose()})},e.prototype.enableFeature=function(t,i,n,r){void 0===i&&(i="latest"),void 0===n&&(n={}),void 0===r&&(r=!0);var o="string"==typeof t?t:t.Name,a=0;if("string"==typeof i){if(!i)throw new Error("Error in provided version - "+o+" ("+i+")");if(-1===(a="stable"===i?e.GetStableVersionOfFeature(o):"latest"===i?e.GetLatestVersionOfFeature(o):+i)||isNaN(a))throw new Error("feature not found - "+o+" ("+i+")")}else a=i;var s=this._features[o],c=e.ConstructFeature(o,a,this._xrSessionManager,n);if(!c)throw new Error("feature not found - "+o);return s&&this.disableFeature(o),this._features[o]={featureImplementation:c(),enabled:!0,version:a},r?this._xrSessionManager.session&&!s.featureImplementation.attached&&this.attachFeature(o):this._features[o].featureImplementation.disableAutoAttach=!0,this._features[o].featureImplementation},e.prototype.getEnabledFeature=function(e){return this._features[e]&&this._features[e].featureImplementation},e.prototype.getEnabledFeatures=function(){return Object.keys(this._features)},e._AvailableFeatures={},e}(),ia=function(){function e(e){var t=this;this.scene=e,this._nonVRCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this.onInitialXRPoseSetObservable=new o.c,this.onStateChangedObservable=new o.c,this.state=rn.NOT_IN_XR,this.sessionManager=new ln(e),this.camera=new $o("",e,this.sessionManager),this.featuresManager=new ta(this.sessionManager),e.onDisposeObservable.add(function(){t.exitXRAsync()})}return e.CreateAsync=function(t){var i=new e(t);return i.sessionManager.initializeAsync().then(function(){return i._supported=!0,i}).catch(function(e){throw i._setState(rn.NOT_IN_XR),i.dispose(),e})},e.prototype.dispose=function(){this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),this._nonVRCamera&&(this.scene.activeCamera=this._nonVRCamera)},e.prototype.enterXRAsync=function(e,t,i){var n=this;if(void 0===i&&(i=this.sessionManager.getWebXRRenderTarget()),!this._supported)throw"WebXR not supported in this browser or environment";this._setState(rn.ENTERING_XR);var r={optionalFeatures:"viewer"!==t&&"local"!==t?[t]:[]};return"immersive-ar"===e&&"local"!==t&&m.a.Warn("We recommend using 'local' reference space type when using 'immersive-ar' session mode"),this.sessionManager.isSessionSupportedAsync(e).then(function(t){if(!t)throw new Error('Session mode "'+e+'" not supported in browser');return n.sessionManager.initializeSessionAsync(e,r)}).then(function(){return n.sessionManager.setReferenceSpaceTypeAsync(t)}).then(function(){return i.initializeXRLayerAsync(n.sessionManager.session)}).then(function(){return n.sessionManager.updateRenderStateAsync({depthFar:n.camera.maxZ,depthNear:n.camera.minZ,baseLayer:i.xrLayer})}).then(function(){return n.sessionManager.runXRRenderLoop(),n._originalSceneAutoClear=n.scene.autoClear,n._nonVRCamera=n.scene.activeCamera,n.scene.autoClear=!1,n.scene.activeCamera=n.camera,"immersive-ar"!==e?n._nonXRToXRCamera():n.camera.compensateOnFirstFrame=!1,n.sessionManager.onXRSessionEnded.addOnce(function(){n.camera.rigCameras.forEach(function(e){e.outputRenderTarget=null}),n.scene.autoClear=n._originalSceneAutoClear,n.scene.activeCamera=n._nonVRCamera,"immersive-ar"!==e&&n.camera.compensateOnFirstFrame&&(n._nonVRCamera.setPosition?n._nonVRCamera.setPosition(n.camera.position):n._nonVRCamera.position.copyFrom(n.camera.position)),n._setState(rn.NOT_IN_XR)}),n.sessionManager.onXRFrameObservable.addOnce(function(){n._setState(rn.IN_XR)}),n.sessionManager}).catch(function(e){throw console.log(e),console.log(e.message),n._setState(rn.NOT_IN_XR),e})},e.prototype.exitXRAsync=function(){return this._setState(rn.EXITING_XR),this.sessionManager.exitXRAsync()},e.prototype._nonXRToXRCamera=function(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)},e.prototype._setState=function(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))},e}(),na=function(){function e(e,t,i,n){void 0===i&&(i=-1),void 0===n&&(n=[]),this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=n,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new o.c,this.onButtonStateChangedObservable=new o.c}return Object.defineProperty(e.prototype,"axes",{get:function(){return this._axes},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"changes",{get:function(){return this._changes},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasChanges",{get:function(){return this._hasChanges},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"pressed",{get:function(){return this._pressed},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"touched",{get:function(){return this._touched},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this._currentValue},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()},e.prototype.isAxes=function(){return 0!==this._axesIndices.length},e.prototype.isButton=function(){return-1!==this._buttonIndex},e.prototype.update=function(e){var t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){var n=e.buttons[this._buttonIndex];if(!n)return;this._currentValue!==n.value&&(this.changes.value={current:n.value,previous:this._currentValue},t=!0,this._currentValue=n.value),this._touched!==n.touched&&(this.changes.touched={current:n.touched,previous:this._touched},t=!0,this._touched=n.touched),this._pressed!==n.pressed&&(this.changes.pressed={current:n.pressed,previous:this._pressed},t=!0,this._pressed=n.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))},e.BUTTON_TYPE="button",e.SQUEEZE_TYPE="squeeze",e.THUMBSTICK_TYPE="thumbstick",e.TOUCHPAD_TYPE="touchpad",e.TRIGGER_TYPE="trigger",e}(),ra=function(){function e(e,t,i,n,r){var a=this;void 0===r&&(r=!1),this.scene=e,this.layout=t,this.gamepadObject=i,this.handness=n,this._initComponent=function(e){if(e){var t=a.layout.components[e],i=t.type,n=t.gamepadIndices.button,r=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&r.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),a.components[e]=new na(e,i,n,r)}},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new o.c,t.components&&Object.keys(t.components).forEach(this._initComponent)}return e.prototype.dispose=function(){var e=this;this.getComponentIds().forEach(function(t){return e.getComponent(t).dispose()}),this.rootMesh&&this.rootMesh.dispose()},e.prototype.getAllComponentsOfType=function(e){var t=this;return this.getComponentIds().map(function(e){return t.components[e]}).filter(function(t){return t.type===e})},e.prototype.getComponent=function(e){return this.components[e]},e.prototype.getComponentIds=function(){return Object.keys(this.components)},e.prototype.getComponentOfType=function(e){return this.getAllComponentsOfType(e)[0]||null},e.prototype.getMainComponent=function(){return this.getComponent(this.layout.selectComponentId)},e.prototype.loadModel=function(){return Object(h.b)(this,void 0,void 0,function(){var e,t,i=this;return Object(h.e)(this,function(n){return e=!this._getModelLoadingConstraints(),t=this._getGenericFilenameAndPath(),e?m.a.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),[2,new Promise(function(n,r){pr.ImportMesh("",t.path,t.filename,i.scene,function(t){e?i._getGenericParentMesh(t):i._setRootMesh(t),i._processLoadedModel(t),i._modelReady=!0,i.onModelLoadedObservable.notifyObservers(i),n(!0)},null,function(e,n){m.a.Log(n),m.a.Warn("Failed to retrieve controller model of type "+i.profileId+" from the remote server: "+t.path+t.filename),r(n)})})]})})},e.prototype.updateFromXRFrame=function(e){var t=this;this.getComponentIds().forEach(function(e){return t.getComponent(e).update(t.gamepadObject)}),this.updateModel(e)},e.prototype._getChildByName=function(e,t){return e.getChildren(function(e){return e.name===t},!1)[0]},e.prototype._getImmediateChildByName=function(e,t){return e.getChildren(function(e){return e.name==t},!0)[0]},e.prototype._lerpTransform=function(e,t,i){if(e.minMesh&&e.maxMesh&&e.minMesh.rotationQuaternion&&e.maxMesh.rotationQuaternion&&e.valueMesh.rotationQuaternion){var n=i?.5*t+.5:t;a.b.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,n,e.valueMesh.rotationQuaternion),a.e.LerpToRef(e.minMesh.position,e.maxMesh.position,n,e.valueMesh.position)}},e.prototype.updateModel=function(e){this._modelReady&&this._updateModel(e)},e.prototype._getGenericFilenameAndPath=function(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}},e.prototype._getGenericParentMesh=function(e){var t=this;this.rootMesh=new Ae.a(this.profileId+" "+this.handness,this.scene),e.forEach(function(e){e.parent||(e.isPickable=!1,e.setParent(t.rootMesh))}),this.rootMesh.rotationQuaternion=a.b.FromEulerAngles(0,Math.PI,0)},e}(),oa=function(e){function t(i,n,r){var o=e.call(this,i,aa[r],n,r)||this;return o.profileId=t.ProfileId,o}return Object(h.d)(t,e),t.prototype._getFilenameAndPath=function(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}},t.prototype._getModelLoadingConstraints=function(){return!0},t.prototype._processLoadedModel=function(e){},t.prototype._setRootMesh=function(e){var t=this;this.rootMesh=new Ae.a(this.profileId+" "+this.handness,this.scene),e.forEach(function(e){e.isPickable=!1,e.parent||e.setParent(t.rootMesh)}),this.rootMesh.rotationQuaternion=a.b.FromEulerAngles(0,Math.PI,0)},t.prototype._updateModel=function(){},t.ProfileId="generic-trigger",t}(ra),aa={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}},sa=function(e){function t(t,i,n,r){var o=e.call(this,t,n.layouts[i.handedness||"none"],i.gamepad,i.handedness)||this;return o._repositoryUrl=r,o._buttonMeshMapping={},o._touchDots={},o.profileId=n.profileId,o}return Object(h.d)(t,e),t.prototype.dispose=function(){var t=this;e.prototype.dispose.call(this),Object.keys(this._touchDots).forEach(function(e){t._touchDots[e].dispose()})},t.prototype._getFilenameAndPath=function(){return{filename:this.layout.assetPath,path:this._repositoryUrl+"/profiles/"+this.profileId+"/"}},t.prototype._getModelLoadingConstraints=function(){var e=pr.IsPluginForExtensionAvailable(".glb");return e||m.a.Warn("glTF / glb loaded was not registered, using generic controller instead"),e},t.prototype._processLoadedModel=function(e){var t=this;this.getComponentIds().forEach(function(e){var i=t.layout.components[e];t._buttonMeshMapping[e]={mainMesh:t._getChildByName(t.rootMesh,i.rootNodeName),states:{}},Object.keys(i.visualResponses).forEach(function(n){var r=i.visualResponses[n];if("transform"===r.valueNodeProperty)t._buttonMeshMapping[e].states[n]={valueMesh:t._getChildByName(t.rootMesh,r.valueNodeName),minMesh:t._getChildByName(t.rootMesh,r.minNodeName),maxMesh:t._getChildByName(t.rootMesh,r.maxNodeName)};else{var o=i.type===na.TOUCHPAD_TYPE&&i.touchPointNodeName?i.touchPointNodeName:r.valueNodeName;if(t._buttonMeshMapping[e].states[n]={valueMesh:t._getChildByName(t.rootMesh,o)},i.type===na.TOUCHPAD_TYPE&&!t._touchDots[n]){var a=Rr.a.CreateSphere(n+"dot",{diameter:.0015,segments:8},t.scene);a.material=new Ki.a(n+"mat",t.scene),a.material.diffuseColor=s.a.Red(),a.parent=t._buttonMeshMapping[e].states[n].valueMesh,a.isVisible=!1,t._touchDots[n]=a}}})})},t.prototype._setRootMesh=function(e){var t;this.rootMesh=new Ae.a(this.profileId+"-"+this.handness,this.scene),this.rootMesh.isPickable=!1;for(var i=0;i<e.length;i++){var n=e[i];n.isPickable=!1,n.parent||(t=n)}t&&t.setParent(this.rootMesh),this.rootMesh.rotate(Z.a.Y,Math.PI,Z.b.WORLD)},t.prototype._updateModel=function(e){var t=this;this.disableAnimation||this.getComponentIds().forEach(function(e){var i=t.getComponent(e);if(i.hasChanges){var n=t._buttonMeshMapping[e],r=t.layout.components[e];Object.keys(r.visualResponses).forEach(function(e){var o=r.visualResponses[e],a=i.value;"xAxis"===o.componentProperty?a=i.axes.x:"yAxis"===o.componentProperty&&(a=i.axes.y),"transform"===o.valueNodeProperty?t._lerpTransform(n.states[e],a,"button"!==o.componentProperty):(n.states[e].valueMesh.isVisible=i.touched||i.pressed,t._touchDots[e]&&(t._touchDots[e].isVisible=i.touched||i.pressed))})}})},t}(ra),ca=function(){function e(){}return e.ClearProfilesCache=function(){delete this._ProfilesList,this._ProfileLoadingPromises={}},e.DefaultFallbacks=function(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"])},e.FindFallbackWithProfileId=function(e){var t=this._Fallbacks[e]||[];return t.unshift(e),t},e.GetMotionControllerWithXRInput=function(e,t,i){var n=this,r=[];if(i&&r.push(i),r.push.apply(r,e.profiles||[]),r.length&&!r[0]&&r.pop(),e.gamepad&&e.gamepad.id)switch(e.gamepad.id){case e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0:r.push("oculus-touch-v2")}var o=r.indexOf("windows-mixed-reality");if(-1!==o&&r.splice(o,0,"microsoft-mixed-reality"),r.length||r.push("generic-trigger"),this.UseOnlineRepository){var a=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,s=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return a.call(this,r,e,t).catch(function(){return s.call(n,r,e,t)})}return this._LoadProfilesFromAvailableControllers(r,e,t)},e.RegisterController=function(e,t){this._AvailableControllers[e]=t},e.RegisterFallbacksForProfileId=function(e,t){var i;this._Fallbacks[e]?(i=this._Fallbacks[e]).push.apply(i,t):this._Fallbacks[e]=t},e.UpdateProfilesList=function(){return this._ProfilesList=De.b.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(function(e){return JSON.parse(e.toString())}),this._ProfilesList},e._LoadProfileFromRepository=function(e,t,i){var n=this;return Promise.resolve().then(function(){return n._ProfilesList?n._ProfilesList:n.UpdateProfilesList()}).then(function(t){for(var i=0;i<e.length;++i)if(e[i]&&t[e[i]])return e[i];throw new Error("neither controller "+e[0]+" nor all fallbacks were found in the repository,")}).then(function(e){return n._ProfileLoadingPromises[e]||(n._ProfileLoadingPromises[e]=De.b.LoadFileAsync(n.BaseRepositoryUrl+"/profiles/"+e+"/profile.json",!1).then(function(e){return JSON.parse(e)})),n._ProfileLoadingPromises[e]}).then(function(e){return new sa(i,t,e,n.BaseRepositoryUrl)})},e._LoadProfilesFromAvailableControllers=function(e,t,i){for(var n=0;n<e.length;++n)if(e[n])for(var r=this.FindFallbackWithProfileId(e[n]),o=0;o<r.length;++o){var a=this._AvailableControllers[r[o]];if(a)return Promise.resolve(a(t,i))}throw new Error("no controller requested was found in the available controllers list")},e._AvailableControllers={},e._Fallbacks={},e._ProfileLoadingPromises={},e.BaseRepositoryUrl="https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist",e.PrioritizeOnlineRepository=!0,e.UseOnlineRepository=!0,e}();ca.RegisterController(oa.ProfileId,function(e,t){return new oa(t,e.gamepad,e.handedness)}),ca.DefaultFallbacks();var la=0,ua=function(){function e(e,t,i){var n=this;void 0===i&&(i={}),this._scene=e,this.inputSource=t,this._options=i,this._tmpQuaternion=new a.b,this._tmpVector=new a.e,this.onDisposeObservable=new o.c,this.onMeshLoadedObservable=new o.c,this.onMotionControllerInitObservable=new o.c,this._uniqueId="controller-"+la+++"-"+t.targetRayMode+"-"+t.handedness,this.pointer=new Ke.a(this._uniqueId+"-pointer",e),this.pointer.rotationQuaternion=new a.b,this.inputSource.gripSpace&&(this.grip=new Ke.a(this._uniqueId+"-grip",this._scene),this.grip.rotationQuaternion=new a.b),this.inputSource.gamepad&&ca.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then(function(e){n.motionController=e,n.onMotionControllerInitObservable.notifyObservers(e),n._options.doNotLoadControllerMesh||n.motionController.loadModel().then(function(e){e&&(n.onMeshLoadedObservable.notifyObservers(n.motionController.rootMesh),n.motionController.rootMesh.parent=n.grip||n.pointer,n.motionController.disableAnimation=!!n._options.disableMotionControllerAnimation)})})}return Object.defineProperty(e.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this.grip&&this.grip.dispose(),this.motionController&&this.motionController.dispose(),this.pointer.dispose(),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},e.prototype.getWorldPointerRayToRef=function(e,t){void 0===t&&(t=!1);var i=t&&this.grip?this.grip:this.pointer;i.computeWorldMatrix().decompose(void 0,this._tmpQuaternion,void 0),this._tmpVector.set(0,0,1),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),e.origin.copyFrom(i.absolutePosition),e.direction.copyFrom(this._tmpVector),e.length=1e3},e.prototype.updateFromXRFrame=function(e,t){var i=e.getPose(this.inputSource.targetRaySpace,t);if(i&&(this.pointer.position.copyFrom(i.transform.position),this.pointer.rotationQuaternion.copyFrom(i.transform.orientation),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1)),this.inputSource.gripSpace&&this.grip){var n=e.getPose(this.inputSource.gripSpace,t);n&&(this.grip.position.copyFrom(n.transform.position),this.grip.rotationQuaternion.copyFrom(n.transform.orientation),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1))}this.motionController&&this.motionController.updateFromXRFrame(e)},e}(),ha=function(){function e(e,t,i){var n=this;void 0===i&&(i={}),this.xrSessionManager=e,this.xrCamera=t,this.options=i,this.controllers=[],this.onControllerAddedObservable=new o.c,this.onControllerRemovedObservable=new o.c,this._onInputSourcesChange=function(e){n._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add(function(){n._addAndRemoveControllers([],n.controllers.map(function(e){return e.inputSource}))}),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add(function(e){e.addEventListener("inputsourceschange",n._onInputSourcesChange)}),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add(function(e){n.controllers.forEach(function(t){t.updateFromXRFrame(e,n.xrSessionManager.referenceSpace)})}),this.options.customControllersRepositoryURL&&(ca.BaseRepositoryUrl=this.options.customControllersRepositoryURL),this.options.disableOnlineControllerRepository?ca.UseOnlineRepository=!1:(ca.UseOnlineRepository=!0,ca.UpdateProfilesList())}return e.prototype._addAndRemoveControllers=function(e,t){for(var i=this,n=this.controllers.map(function(e){return e.inputSource}),r=0,o=e;r<o.length;r++){var a=o[r];if(-1===n.indexOf(a)){var s=new ua(this.xrSessionManager.scene,a,{forceControllerProfile:this.options.forceInputProfile,doNotLoadControllerMesh:this.options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this.options.disableControllerAnimation});this.controllers.push(s),this.onControllerAddedObservable.notifyObservers(s)}}var c=[],l=[];this.controllers.forEach(function(e){-1===t.indexOf(e.inputSource)?c.push(e):l.push(e)}),this.controllers=c,l.forEach(function(e){i.onControllerRemovedObservable.notifyObservers(e),e.dispose()})},e.prototype.dispose=function(){this.controllers.forEach(function(e){e.dispose()}),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear()},e}(),da=function(){function e(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.disableAutoAttach=!1}return Object.defineProperty(e.prototype,"attached",{get:function(){return this._attached},enumerable:!0,configurable:!0}),e.prototype.attach=function(e){var t=this;if(e)this.attached&&this.detach();else if(this.attached)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,function(e){return t._onXRFrame(e)}),!0},e.prototype.detach=function(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach(function(e){e.observable.remove(e.observer)}),!0):(this.disableAutoAttach=!0,!1)},e.prototype.dispose=function(){this.detach()},e.prototype._addNewAttachObserver=function(e,t){this._removeOnDetach.push({observable:e,observer:e.add(t)})},e}(),fa=function(e){function t(i,n){var r=e.call(this,i)||this;return r._options=n,r._attachController=function(e){if(!r._controllers[e.uniqueId]){var i=r._generateNewMeshPair(e),n=i.laserPointer,o=i.selectionMesh;switch(r._controllers[e.uniqueId]={xrController:e,laserPointer:n,selectionMesh:o,meshUnderPointer:null,pick:null,tmpRay:new Ht.a(new a.e,new a.e),id:t._idCounter++},e.inputSource.targetRayMode){case"tracked-pointer":return r._attachTrackedPointerRayMode(e);case"gaze":return r._attachGazeMode(e);case"screen":return r._attachScreenRayMode(e)}}},r._controllers={},r._tmpVectorForPickCompare=new a.e,r.disablePointerLighting=!0,r.disableSelectionMeshLighting=!0,r.displayLaserPointer=!0,r.displaySelectionMesh=!0,r.laserPointerPickedColor=new s.a(.9,.9,.9),r.lasterPointerDefaultColor=new s.a(.7,.7,.7),r.selectionMeshDefaultColor=new s.a(.8,.8,.8),r.selectionMeshPickedColor=new s.a(.3,.3,1),r._scene=r._xrSessionManager.scene,r}return Object(h.d)(t,e),t.prototype.attach=function(){var t=this;return!!e.prototype.attach.call(this)&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,function(e){t._detachController(e.uniqueId)}),!0)},t.prototype.detach=function(){var t=this;return!!e.prototype.detach.call(this)&&(Object.keys(this._controllers).forEach(function(e){t._detachController(e)}),!0)},t.prototype.getMeshUnderPointer=function(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null},t.prototype.getXRControllerByPointerId=function(e){for(var t=Object.keys(this._controllers),i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].xrController;return null},t.prototype._onXRFrame=function(e){var t=this;Object.keys(this._controllers).forEach(function(e){var i=t._controllers[e];i.xrController.getWorldPointerRayToRef(i.tmpRay),i.pick=t._scene.pickWithRay(i.tmpRay);var n=i.pick;if(n&&n.pickedPoint&&n.hit){t._updatePointerDistance(i.laserPointer,n.distance),i.selectionMesh.position.copyFrom(n.pickedPoint),i.selectionMesh.scaling.x=Math.sqrt(n.distance),i.selectionMesh.scaling.y=Math.sqrt(n.distance),i.selectionMesh.scaling.z=Math.sqrt(n.distance);var r=t._convertNormalToDirectionOfRay(n.getNormal(!0),i.tmpRay);if(i.selectionMesh.position.copyFrom(n.pickedPoint),r){var o=a.e.Cross(Z.a.Y,r),s=a.e.Cross(r,o);a.e.RotationFromAxisToRef(s,r,o,i.selectionMesh.rotation),i.selectionMesh.position.addInPlace(r.scale(.001))}i.selectionMesh.isVisible=t.displaySelectionMesh,i.meshUnderPointer=n.pickedMesh}else i.selectionMesh.isVisible=!1,i.meshUnderPointer=null})},t.prototype._attachGazeMode=function(e){var t=this,i=this._controllers[e.uniqueId],n=this._options.timeToSelect||3e3,r=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Sr.a.DefaultUtilityLayer.utilityLayerScene:this._scene,o=new bn.a,a=on.CreateTorus("selection",{diameter:.0525,thickness:.015,tessellation:20},r);a.isVisible=!1,a.isPickable=!1,a.parent=i.selectionMesh;var s=0,c=!1;i.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(function(){if(i.pick){if(a.isVisible=!1,i.pick.hit)if(t._pickingMoved(o,i.pick))c&&(t._options.disablePointerUpOnTouchOut||t._scene.simulatePointerUp(i.pick,{pointerId:i.id})),c=!1,s=0;else if(s>n/10&&(a.isVisible=!0),(s+=t._scene.getEngine().getDeltaTime())>=n)t._scene.simulatePointerDown(i.pick,{pointerId:i.id}),c=!0,t._options.disablePointerUpOnTouchOut&&t._scene.simulatePointerUp(i.pick,{pointerId:i.id}),a.isVisible=!1;else{var e=1-s/n;a.scaling.set(e,e,e)}else c=!1,s=0;t._scene.simulatePointerMove(i.pick,{pointerId:i.id}),o=i.pick}}),void 0!==this._options.renderingGroupId&&(a.renderingGroupId=this._options.renderingGroupId),e.onDisposeObservable.addOnce(function(){i.pick&&!t._options.disablePointerUpOnTouchOut&&c&&t._scene.simulatePointerUp(i.pick,{pointerId:i.id}),a.dispose()})},t.prototype._attachScreenRayMode=function(e){var t=this,i=this._controllers[e.uniqueId],n=!1;i.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(function(){!i.pick||t._options.disablePointerUpOnTouchOut&&n||(n?t._scene.simulatePointerMove(i.pick,{pointerId:i.id}):(t._scene.simulatePointerDown(i.pick,{pointerId:i.id}),n=!0,t._options.disablePointerUpOnTouchOut&&t._scene.simulatePointerUp(i.pick,{pointerId:i.id})))}),e.onDisposeObservable.addOnce(function(){i.pick&&n&&!t._options.disablePointerUpOnTouchOut&&t._scene.simulatePointerUp(i.pick,{pointerId:i.id})})},t.prototype._attachTrackedPointerRayMode=function(e){var t=this;e.onMotionControllerInitObservable.add(function(i){if(t._options.forceGazeMode)return t._attachGazeMode(e);var n=t._controllers[e.uniqueId];t._options.overrideButtonId&&(n.selectionComponent=i.getComponent(t._options.overrideButtonId)),n.selectionComponent||(n.selectionComponent=i.getMainComponent()),n.onFrameObserver=t._xrSessionManager.onXRFrameObservable.add(function(){n.selectionComponent&&n.selectionComponent.pressed?(n.selectionMesh.material.emissiveColor=t.selectionMeshPickedColor,n.laserPointer.material.emissiveColor=t.laserPointerPickedColor):(n.selectionMesh.material.emissiveColor=t.selectionMeshDefaultColor,n.laserPointer.material.emissiveColor=t.lasterPointerDefaultColor),n.laserPointer.isVisible=t.displayLaserPointer,n.laserPointer.material.disableLighting=t.disablePointerLighting,n.selectionMesh.material.disableLighting=t.disableSelectionMeshLighting,n.pick&&t._scene.simulatePointerMove(n.pick,{pointerId:n.id})}),n.onButtonChangedObserver=n.selectionComponent.onButtonStateChangedObservable.add(function(e){if(e.changes.pressed){var i=e.changes.pressed.current;n.pick&&(i?t._scene.simulatePointerDown(n.pick,{pointerId:n.id}):t._scene.simulatePointerUp(n.pick,{pointerId:n.id}))}})})},t.prototype._convertNormalToDirectionOfRay=function(e,t){e&&(Math.acos(a.e.Dot(e,t.direction))<Math.PI/2&&e.scaleInPlace(-1));return e},t.prototype._detachController=function(e){var t=this._controllers[e];t&&(t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e])},t.prototype._generateNewMeshPair=function(e){var t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Sr.a.DefaultUtilityLayer.utilityLayerScene:this._scene,i=an.a.CreateCylinder("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e.pointer;var n=new Ki.a("laserPointerMat",t);n.emissiveColor=this.lasterPointerDefaultColor,n.alpha=.7,i.material=n,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1;var r=on.CreateTorus("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);r.bakeCurrentTransformIntoVertices(),r.isPickable=!1,r.isVisible=!1;var o=new Ki.a("targetMat",t);return o.specularColor=s.a.Black(),o.emissiveColor=this.selectionMeshDefaultColor,o.backFaceCulling=!1,r.material=o,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:r}},t.prototype._pickingMoved=function(e,t){var i;if(!e.hit||!t.hit)return!0;if(!(e.pickedMesh&&e.pickedPoint&&t.pickedMesh&&t.pickedPoint))return!0;if(e.pickedMesh!==t.pickedMesh)return!0;null===(i=e.pickedPoint)||void 0===i||i.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));var n=.01*(this._options.gazeModePointerMovedFactor||1)/t.distance;return this._tmpVectorForPickCompare.length()>n},t.prototype._updatePointerDistance=function(e,t){void 0===t&&(t=100),e.scaling.y=t,e.position.z=t/2+.05},t._idCounter=0,t.Name=ea.POINTER_SELECTION,t.Version=1,t}(da);ta.AddWebXRFeature(fa.Name,function(e,t){return function(){return new fa(e,t)}},fa.Version,!0);var pa=function(){function e(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}return e.prototype.update=function(e){},e}(),_a=function(){},ma=function(){function e(e,t){var i=this;if(this.scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new o.c,this._overlay=document.createElement("div"),this._overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;",t.customButtons)this._buttons=t.customButtons;else{var n=t.sessionMode||"immersive-vr",r=t.referenceSpaceType||"local-floor",a=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";a+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';var s=document.createElement("style");s.appendChild(document.createTextNode(a)),document.getElementsByTagName("head")[0].appendChild(s);var c=document.createElement("button");c.className="babylonVRicon",c.title=n+" - "+r,this._buttons.push(new pa(c,n,r)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",c.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}var l=e.getEngine().getInputElement();l&&l.parentNode&&(l.parentNode.appendChild(this._overlay),e.onDisposeObservable.addOnce(function(){i.dispose()}))}return e.CreateAsync=function(t,i,n){var r=this,o=new e(t,n),a=o._buttons.map(function(e){return i.sessionManager.isSessionSupportedAsync(e.sessionMode)});return i.onStateChangedObservable.add(function(e){e==rn.NOT_IN_XR&&o._updateButtons(null)}),Promise.all(a).then(function(e){return e.forEach(function(e,t){e&&(o._overlay.appendChild(o._buttons[t].element),o._buttons[t].element.onclick=function(){return Object(h.b)(r,void 0,void 0,function(){var e,r;return Object(h.e)(this,function(a){switch(a.label){case 0:return i.state!=rn.IN_XR?[3,2]:[4,i.exitXRAsync()];case 1:return a.sent(),o._updateButtons(null),[3,6];case 2:if(i.state!=rn.NOT_IN_XR)return[3,6];if(!n.renderTarget)return[3,6];a.label=3;case 3:return a.trys.push([3,5,,6]),[4,i.enterXRAsync(o._buttons[t].sessionMode,o._buttons[t].referenceSpaceType,n.renderTarget)];case 4:return a.sent(),o._updateButtons(o._buttons[t]),[3,6];case 5:return a.sent(),o._updateButtons(null),e=o._buttons[t].element,r=e.title,e.title="Error entering XR session : "+r,e.classList.add("xr-error"),[3,6];case 6:return[2]}})})})}),o})},e.prototype.dispose=function(){var e=this.scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this._overlay)&&e.parentNode.removeChild(this._overlay),this.activeButtonChangedObservable.clear()},e.prototype._updateButtons=function(e){var t=this;this._activeButton=e,this._buttons.forEach(function(e){e.update(t._activeButton)}),this.activeButtonChangedObservable.notifyObservers(this._activeButton)},e}(),ga=function(e){function t(t,i){var n=e.call(this,t)||this;return n._options=i,n._controllers={},n._snappedToPoint=!1,n._tmpRay=new Ht.a(new a.e,new a.e),n._tmpVector=new a.e,n.backwardsMovementEnabled=!0,n.backwardsTeleportationDistance=.7,n.parabolicCheckRadius=5,n.parabolicRayEnabled=!0,n.rotationAngle=Math.PI/8,n.rotationEnabled=!0,n._attachController=function(e){if(!n._controllers[e.uniqueId]){n._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0}};var t=n._controllers[e.uniqueId];e.onMotionControllerInitObservable.addOnce(function(){if(e.motionController){var i=e.motionController.getComponentOfType(na.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(na.TOUCHPAD_TYPE);if(!i||n._options.useMainComponentOnly){var r=e.motionController.getMainComponent();if(!r)return;t.onButtonChangedObserver=r.onButtonStateChangedObservable.add(function(){if(r.changes.pressed)if(r.changes.pressed.current){t.teleportationState.forward=!0,n._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=n._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0;var i=n._options.timeToTeleport||3e3,o=0,a=n._xrSessionManager.onXRFrameObservable.add(function(){r.pressed?((o+=n._xrSessionManager.scene.getEngine().getDeltaTime())>=i&&n._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&n._teleportForward(e.uniqueId),o>=i&&n._xrSessionManager.onXRFrameObservable.remove(a)):n._xrSessionManager.onXRFrameObservable.remove(a)})}else t.teleportationState.forward=!1,n._currentTeleportationControllerId=""})}else t.onButtonChangedObserver=i.onButtonStateChangedObservable.add(function(){n._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&!i.touched&&n._teleportForward(e.uniqueId)}),t.onAxisChangedObserver=i.onAxisValueChangedObservable.add(function(e){if(e.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),e.y>.7&&!t.teleportationState.forward&&n.backwardsMovementEnabled&&!n.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,n._tmpVector.set(0,0,n.backwardsTeleportationDistance),n._tmpVector.rotateByQuaternionToRef(n._options.xrInput.xrCamera.rotationQuaternion,n._tmpVector),n._tmpVector.addInPlace(n._options.xrInput.xrCamera.position),n._options.xrInput.xrCamera.position.subtractToRef(n._tmpVector,n._tmpVector),n._tmpRay.origin.copyFrom(n._tmpVector),n._tmpRay.direction.set(0,-1,0);var i=n._xrSessionManager.scene.pickWithRay(n._tmpRay,function(e){return-1!==n._floorMeshes.indexOf(e)});i&&i.pickedPoint&&n._options.xrInput.xrCamera.position.addInPlace(i.pickedPoint)}if(e.y<-.7&&!n._currentTeleportationControllerId&&!t.teleportationState.rotating&&(t.teleportationState.forward=!0,n._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=n._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),e.x){if(t.teleportationState.forward)n._currentTeleportationControllerId===t.xrController.uniqueId&&(n.rotationEnabled?setTimeout(function(){t.teleportationState.currentRotation=Math.atan2(e.x,-e.y)}):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(e.x)>.7){t.teleportationState.rotating=!0;var r=n.rotationAngle*(e.x>0?1:-1);n._options.xrInput.xrCamera.rotationQuaternion.multiplyInPlace(a.b.FromEulerAngles(0,r,0))}}else t.teleportationState.rotating=!1})}})}},n._options.teleportationTargetMesh||n._createDefaultTargetMesh(),n._floorMeshes=n._options.floorMeshes||[],n._snapToPositions=n._options.snapPositions||[],n._setTargetMeshVisibility(!1),n}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"snapPointsOnly",{get:function(){return!!this._options.snapPointsOnly},set:function(e){this._options.snapPointsOnly=e},enumerable:!0,configurable:!0}),t.prototype.addFloorMesh=function(e){this._floorMeshes.push(e)},t.prototype.addSnapPoint=function(e){this._snapToPositions.push(e)},t.prototype.attach=function(){var t=this;return!!e.prototype.attach.call(this)&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,function(e){t._detachController(e.uniqueId)}),!0)},t.prototype.detach=function(){var t=this;return!!e.prototype.detach.call(this)&&(Object.keys(this._controllers).forEach(function(e){t._detachController(e)}),this._setTargetMeshVisibility(!1),!0)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0)},t.prototype.removeFloorMesh=function(e){var t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)},t.prototype.removeFloorMeshByName=function(e){var t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)},t.prototype.removeSnapPoint=function(e){var t=this._snapToPositions.indexOf(e);if(-1===t)for(var i=0;i<this._snapToPositions.length;++i)if(this._snapToPositions[i].equals(e)){t=i;break}return-1!==t&&(this._snapToPositions.splice(t,1),!0)},t.prototype.setSelectionFeature=function(e){this._selectionFeature=e},t.prototype._onXRFrame=function(e){var t=this,i=this._xrSessionManager.currentFrame,n=this._xrSessionManager.scene;if(this.attach&&i){var r=this._options.teleportationTargetMesh;if(this._currentTeleportationControllerId){if(!r)return;r.rotationQuaternion=r.rotationQuaternion||new a.b;var o=this._controllers[this._currentTeleportationControllerId];if(o.teleportationState.forward){a.b.RotationYawPitchRollToRef(o.teleportationState.currentRotation+o.teleportationState.baseRotation,0,0,r.rotationQuaternion);var s=!1;o.xrController.getWorldPointerRayToRef(this._tmpRay);var c=n.pickWithRay(this._tmpRay,function(e){var i=t._floorMeshes.indexOf(e);return-1!==i&&t._floorMeshes[i].absolutePosition.y<t._options.xrInput.xrCamera.position.y});if(c&&c.pickedPoint)s=!0,this._setTargetMeshPosition(c.pickedPoint),this._setTargetMeshVisibility(!0),this._showParabolicPath(c);else if(this.parabolicRayEnabled){var l=o.xrController.pointer.rotationQuaternion.toEulerAngles().x,u=Math.PI/2-Math.abs(l)+1,h=this.parabolicCheckRadius*u;this._tmpRay.origin.addToRef(this._tmpRay.direction.scale(2*h),this._tmpVector),this._tmpVector.y=this._tmpRay.origin.y,this._tmpRay.origin.addInPlace(this._tmpRay.direction.scale(h)),this._tmpVector.subtractToRef(this._tmpRay.origin,this._tmpRay.direction),this._tmpRay.direction.normalize();var d=n.pickWithRay(this._tmpRay,function(e){return-1!==t._floorMeshes.indexOf(e)});d&&d.pickedPoint&&(s=!0,this._setTargetMeshPosition(d.pickedPoint),this._setTargetMeshVisibility(!0),this._showParabolicPath(d))}this._setTargetMeshVisibility(s)}else this._setTargetMeshVisibility(!1)}else this._setTargetMeshVisibility(!1)}},t.prototype._createDefaultTargetMesh=function(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};var e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Sr.a.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=nn.CreateGround("teleportationTarget",{width:2,height:2,subdivisions:2},e);t.isPickable=!1;var i=new qi("teleportationPlaneDynamicTexture",512,e,!0);i.hasAlpha=!0;var n=i.getContext();n.beginPath(),n.arc(256,256,200,0,2*Math.PI,!1),n.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",n.fill(),n.lineWidth=10,n.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",n.stroke(),n.closePath(),i.update();var r=new Ki.a("teleportationPlaneMaterial",e);r.diffuseTexture=i,t.material=r;var o=on.CreateTorus("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(o.isPickable=!1,o.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){var a=new k("animationInnerCircle","position.y",30,k.ANIMATIONTYPE_FLOAT,k.ANIMATIONLOOPMODE_CYCLE),c=[];c.push({frame:0,value:0}),c.push({frame:30,value:.4}),c.push({frame:60,value:0}),a.setKeys(c);var l=new Ee;l.setEasingMode(he.EASINGMODE_EASEINOUT),a.setEasingFunction(l),o.animations=[],o.animations.push(a),e.beginAnimation(o,0,60,!0)}var u=an.a.CreateCylinder("cone",{diameterTop:0,tessellation:4},e);if(u.isPickable=!1,u.scaling.set(.5,.12,.2),u.rotate(Z.a.X,Math.PI/2),u.position.z=.6,u.parent=o,this._options.defaultTargetMeshOptions.torusArrowMaterial)o.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,u.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{var h=new Ki.a("torusConsMat",e);h.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,h.disableLighting?h.emissiveColor=new s.a(.3,.3,1):h.diffuseColor=new s.a(.3,.3,1),h.alpha=.9,o.material=h,u.material=h,this._teleportationRingMaterial=h}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,o.renderingGroupId=this._options.renderingGroupId,u.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t},t.prototype._detachController=function(e){var t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])},t.prototype._findClosestSnapPointWithRadius=function(e,t){void 0===t&&(t=this._options.snapToPositionRadius||.8);var i=null,n=Number.MAX_VALUE;if(this._snapToPositions.length){var r=t*t;this._snapToPositions.forEach(function(t){var o=a.e.DistanceSquared(t,e);o<=r&&o<n&&(n=o,i=t)})}return i},t.prototype._setTargetMeshPosition=function(e){if(this._options.teleportationTargetMesh){var t=this._findClosestSnapPointWithRadius(e);this._snappedToPoint=!!t,this.snapPointsOnly&&!this._snappedToPoint&&this._teleportationRingMaterial?this._teleportationRingMaterial.diffuseColor.set(1,.3,.3):this.snapPointsOnly&&this._snappedToPoint&&this._teleportationRingMaterial&&this._teleportationRingMaterial.diffuseColor.set(.3,.3,1),this._options.teleportationTargetMesh.position.copyFrom(t||e),this._options.teleportationTargetMesh.position.y+=.01}},t.prototype._setTargetMeshVisibility=function(e){this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible!==e&&(this._options.teleportationTargetMesh.isVisible=e,this._options.teleportationTargetMesh.getChildren(void 0,!1).forEach(function(t){t.isVisible=e}),e?this._selectionFeature&&this._selectionFeature.detach():(this._quadraticBezierCurve&&this._quadraticBezierCurve.dispose(),this._selectionFeature&&this._selectionFeature.attach()))},t.prototype._showParabolicPath=function(e){if(e.pickedPoint){var t=this._controllers[this._currentTeleportationControllerId],i=ue.CreateQuadraticBezier(t.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25);this._quadraticBezierCurve&&this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=Or.a.CreateLines("path line",{points:i.getPoints()}),this._quadraticBezierCurve.isPickable=!1}},t.prototype._teleportForward=function(e){var t=this._controllers[e];if(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",(!this.snapPointsOnly||this._snappedToPoint)&&this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){var i=this._options.xrInput.xrCamera.realWorldHeight;this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=i,this._options.xrInput.xrCamera.rotationQuaternion.multiplyInPlace(a.b.FromEulerAngles(0,t.teleportationState.currentRotation,0))}},t.Name=ea.TELEPORTATION,t.Version=1,t}(da);ta.AddWebXRFeature(ga.Name,function(e,t){return function(){return new ga(e,t)}},ga.Version,!0);var va=function(){},ya=function(){function e(){}return e.CreateAsync=function(t,i){void 0===i&&(i={});var n=new e;return ia.CreateAsync(t).then(function(e){return n.baseExperience=e,i.ignoreNativeCameraTransformation&&(n.baseExperience.camera.compensateOnFirstFrame=!1),n.input=new ha(e.sessionManager,e.camera,i.inputOptions),n.pointerSelection=n.baseExperience.featuresManager.enableFeature(fa.Name,i.useStablePlugins?"stable":"latest",{xrInput:n.input}),i.disableTeleportation||(n.teleportation=n.baseExperience.featuresManager.enableFeature(ga.Name,i.useStablePlugins?"stable":"latest",{floorMeshes:i.floorMeshes,xrInput:n.input}),n.teleportation.setSelectionFeature(n.pointerSelection)),n.renderTarget=n.baseExperience.sessionManager.getWebXRRenderTarget(i.outputCanvasOptions),i.disableDefaultUI?void 0:(i.uiOptions&&(i.uiOptions.renderTarget=i.uiOptions.renderTarget||n.renderTarget),ma.CreateAsync(t,n.baseExperience,i.uiOptions||{renderTarget:n.renderTarget}).then(function(e){n.enterExitUI=e}))}).then(function(){return n}).catch(function(e){return m.a.Error("Error initializing XR"),m.a.Error(e),n})},e.prototype.dispose=function(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()},e}();K.a.prototype.createDefaultLight=function(e){if(void 0===e&&(e=!1),e&&this.lights)for(var t=0;t<this.lights.length;t++)this.lights[t].dispose();0===this.lights.length&&new Wi.a("default light",a.e.Up(),this)},K.a.prototype.createDefaultCamera=function(e,t,i){if(void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1),t&&this.activeCamera&&(this.activeCamera.dispose(),this.activeCamera=null),!this.activeCamera){var n,r=this.getWorldExtends(),o=r.max.subtract(r.min),s=r.min.add(o.scale(.5)),c=1.5*o.length();if(isFinite(c)||(c=1,s.copyFromFloats(0,0,0)),e){var l=new Bt("default camera",-Math.PI/2,Math.PI/2,c,s,this);l.lowerRadiusLimit=.01*c,l.wheelPrecision=100/c,n=l}else{var u=new Nt("default camera",new a.e(s.x,s.y,-c),this);u.setTarget(s),n=u}n.minZ=.01*c,n.maxZ=1e3*c,n.speed=.2*c,this.activeCamera=n;var h=this.getEngine().getInputElement();i&&h&&n.attachControl(h)}},K.a.prototype.createDefaultCameraOrLight=function(e,t,i){void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1),this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},K.a.prototype.createDefaultSkybox=function(e,t,i,n,r){if(void 0===t&&(t=!1),void 0===i&&(i=1e3),void 0===n&&(n=0),void 0===r&&(r=!0),!e)return m.a.Warn("Can not create default skybox without environment texture."),null;r&&e&&(this.environmentTexture=e);var o=Ae.a.CreateBox("hdrSkyBox",i,this);if(t){var a=new zo("skyBox",this);a.backFaceCulling=!1,a.reflectionTexture=e.clone(),a.reflectionTexture&&(a.reflectionTexture.coordinatesMode=et.a.SKYBOX_MODE),a.microSurface=1-n,a.disableLighting=!0,a.twoSidedLighting=!0,o.infiniteDistance=!0,o.material=a}else{var s=new Ki.a("skyBox",this);s.backFaceCulling=!1,s.reflectionTexture=e.clone(),s.reflectionTexture&&(s.reflectionTexture.coordinatesMode=et.a.SKYBOX_MODE),s.disableLighting=!0,o.infiniteDistance=!0,o.material=s}return o.isPickable=!1,o},K.a.prototype.createDefaultEnvironment=function(e){return _o?new _o(e,this):null},K.a.prototype.createDefaultVRExperience=function(e){return void 0===e&&(e={}),new _n(this,e)},K.a.prototype.createDefaultXRExperienceAsync=function(e){return ya.CreateAsync(this,e).then(function(e){return e})},li.a.prototype.updateVideoTexture=function(e,t,i){if(e&&!e._isDisabled){var n=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=Qi.a.CreateCanvas(e.width,e.height);var r=e._workingCanvas.getContext("2d");if(!r)throw new Error("Unable to get 2d context");e._workingContext=r,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}}};var ba=function(e){function t(t,i,n,r,o,a,s){void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===a&&(a=et.a.TRILINEAR_SAMPLINGMODE),void 0===s&&(s={autoPlay:!0,loop:!0,autoUpdateTexture:!0});var c=e.call(this,null,n,!r,o)||this;c._onUserActionRequestedObservable=null,c._stillImageCaptured=!1,c._displayingPosterTexture=!1,c._frameId=-1,c._currentSrc=null,c._createInternalTexture=function(){if(null!=c._texture){if(!c._displayingPosterTexture)return;c._texture.dispose(),c._displayingPosterTexture=!1}if(!c._engine.needPOTTextures||De.b.IsExponentOfTwo(c.video.videoWidth)&&De.b.IsExponentOfTwo(c.video.videoHeight)?(c.wrapU=et.a.WRAP_ADDRESSMODE,c.wrapV=et.a.WRAP_ADDRESSMODE):(c.wrapU=et.a.CLAMP_ADDRESSMODE,c.wrapV=et.a.CLAMP_ADDRESSMODE,c._generateMipMaps=!1),c._texture=c._engine.createDynamicTexture(c.video.videoWidth,c.video.videoHeight,c._generateMipMaps,c.samplingMode),c.video.autoplay||c._settings.poster)c._texture.isReady=!0,c._updateInternalTexture(),c.onLoadObservable.hasObservers()&&c.onLoadObservable.notifyObservers(c);else{var e=c.video.onplaying,t=!1,i=c.video.muted;c.video.muted=!0,c.video.onplaying=function(){c.video.muted=i,c.video.onplaying=e,c._texture.isReady=!0,c._updateInternalTexture(),t||c.video.pause(),c.onLoadObservable.hasObservers()&&c.onLoadObservable.notifyObservers(c)};var n=c.video.play();n?n.then(function(){}).catch(function(){t=!0,c._onUserActionRequestedObservable&&c._onUserActionRequestedObservable.hasObservers()&&c._onUserActionRequestedObservable.notifyObservers(c)}):(c.video.onplaying=e,c._texture.isReady=!0,c._updateInternalTexture(),c.onLoadObservable.hasObservers()&&c.onLoadObservable.notifyObservers(c))}},c.reset=function(){null!=c._texture&&(c._displayingPosterTexture||(c._texture.dispose(),c._texture=null))},c._updateInternalTexture=function(){if(null!=c._texture&&c._texture.isReady&&!(c.video.readyState<c.video.HAVE_CURRENT_DATA||c._displayingPosterTexture)){var e=c.getScene().getFrameId();c._frameId!==e&&(c._frameId=e,c._engine.updateVideoTexture(c._texture,c.video,c._invertY))}},c._engine=c.getScene().getEngine(),c._generateMipMaps=r,c._initialSamplingMode=a,c.autoUpdateTexture=s.autoUpdateTexture,c._currentSrc=i,c.name=t||c._getName(i),c.video=c._getVideo(i),c._settings=s,s.poster&&(c.video.poster=s.poster),void 0!==s.autoPlay&&(c.video.autoplay=s.autoPlay),void 0!==s.loop&&(c.video.loop=s.loop),c.video.setAttribute("playsinline",""),c.video.addEventListener("paused",c._updateInternalTexture),c.video.addEventListener("seeked",c._updateInternalTexture),c.video.addEventListener("emptied",c.reset),c._createInternalTextureOnEvent=s.poster&&!s.autoPlay?"play":"canplay",c.video.addEventListener(c._createInternalTextureOnEvent,c._createInternalTexture);var l=c.video.readyState>=c.video.HAVE_CURRENT_DATA;return!s.poster||s.autoPlay&&l?l&&c._createInternalTexture():(c._texture=c._engine.createTexture(s.poster,!1,!c.invertY,n),c._displayingPosterTexture=!0),c}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"onUserActionRequestedObservable",{get:function(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new o.c),this._onUserActionRequestedObservable},enumerable:!0,configurable:!0}),t.prototype._getName=function(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e},t.prototype._getVideo=function(e){if(e instanceof HTMLVideoElement)return De.b.SetCorsBehavior(e.currentSrc,e),e;var t=document.createElement("video");return"string"==typeof e?(De.b.SetCorsBehavior(e,t),t.src=e):(De.b.SetCorsBehavior(e[0],t),e.forEach(function(e){var i=document.createElement("source");i.src=e,t.appendChild(i)})),t},t.prototype._rebuild=function(){this.update()},t.prototype.update=function(){this.autoUpdateTexture&&this.updateTexture(!0)},t.prototype.updateTexture=function(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))},t.prototype.updateURL=function(e){this.video.src=e,this._currentSrc=e},t.prototype.clone=function(){return new t(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this.reset),this.video.pause()},t.CreateFromStreamAsync=function(e,i){var n=document.createElement("video");return n.setAttribute("autoplay",""),n.setAttribute("muted","true"),n.setAttribute("playsinline",""),n.muted=!0,void 0!==n.mozSrcObject?n.mozSrcObject=i:"object"==typeof n.srcObject?n.srcObject=i:(window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,n.src=window.URL&&window.URL.createObjectURL(i)),new Promise(function(i){var r=function(){i(new t("video",n,e,!0,!0)),n.removeEventListener("playing",r)};n.addEventListener("playing",r),n.play()})},t.CreateFromWebCamAsync=function(e,t,i){var n,r=this;return void 0===i&&(i=!1),t&&t.deviceId&&(n={exact:t.deviceId}),navigator.mediaDevices?navigator.mediaDevices.getUserMedia({video:t,audio:i}).then(function(t){return r.CreateFromStreamAsync(e,t)}):(navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,navigator.getUserMedia&&navigator.getUserMedia({video:{deviceId:n,width:{min:t&&t.minWidth||256,max:t&&t.maxWidth||640},height:{min:t&&t.minHeight||256,max:t&&t.maxHeight||480}},audio:i},function(t){return r.CreateFromStreamAsync(e,t)},function(e){m.a.Error(e.name)}),Promise.reject("No support for userMedia on this device"))},t.CreateFromWebCam=function(e,t,i,n){void 0===n&&(n=!1),this.CreateFromWebCamAsync(e,i,n).then(function(e){t&&t(e)}).catch(function(e){m.a.Error(e.name)})},t}(et.a),Ta=function(){function e(e,t){void 0===e&&(e=a.e.Zero()),void 0===t&&(t=a.e.Up()),this.position=e,this.normal=t}return e.prototype.clone=function(){return new e(this.position.clone(),this.normal.clone())},e}(),Ea=function(){function e(e,t,i){void 0===e&&(e=a.e.Zero()),void 0===t&&(t=a.e.Up()),void 0===i&&(i=a.d.Zero()),this.position=e,this.normal=t,this.uv=i}return e.prototype.clone=function(){return new e(this.position.clone(),this.normal.clone(),this.uv.clone())},e}(),xa=function(e){function t(i,n,r,o){var s=e.call(this,i,o)||this;s._halfDome=!1,s._useDirectMapping=!1,s._videoMode=t.MODE_MONOSCOPIC,s._onBeforeCameraRenderObserver=null,o=s.getScene(),i=i||"videoDome",r.resolution=0|Math.abs(r.resolution)||32,r.clickToPlay=Boolean(r.clickToPlay),r.autoPlay=void 0===r.autoPlay||Boolean(r.autoPlay),r.loop=void 0===r.loop||Boolean(r.loop),r.size=Math.abs(r.size)||(o.activeCamera?.48*o.activeCamera.maxZ:1e3),void 0===r.useDirectMapping?s._useDirectMapping=!0:s._useDirectMapping=r.useDirectMapping,void 0===r.faceForward&&(r.faceForward=!0),s._setReady(!1);var c={loop:r.loop,autoPlay:r.autoPlay,autoUpdateTexture:!0,poster:r.poster},l=s._material=new po(i+"_material",o),u=s._videoTexture=new ba(i+"_texture",n,o,!1,s._useDirectMapping,et.a.TRILINEAR_SAMPLINGMODE,c);if(s._mesh=Ae.a.CreateSphere(i+"_mesh",r.resolution,r.size,o,!1,Ae.a.BACKSIDE),u.anisotropicFilteringLevel=1,u.onLoadObservable.addOnce(function(){s._setReady(!0)}),l.useEquirectangularFOV=!0,l.fovMultiplier=1,l.opacityFresnel=!1,s._useDirectMapping?(u.wrapU=et.a.CLAMP_ADDRESSMODE,u.wrapV=et.a.CLAMP_ADDRESSMODE,l.diffuseTexture=u):(u.coordinatesMode=et.a.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,u.wrapV=et.a.CLAMP_ADDRESSMODE,l.reflectionTexture=u),s._mesh.material=l,s._mesh.parent=s,s._halfDomeMask=Rr.a.CreateSphere("",{slice:.5,diameter:.99*r.size,segments:r.resolution,sideOrientation:Ae.a.BACKSIDE},o),s._halfDomeMask.rotate(Z.a.X,-Math.PI/2),s._halfDomeMask.parent=s._mesh,s._halfDome=!!r.halfDomeMode,s._halfDomeMask.setEnabled(s._halfDome),r.clickToPlay&&(o.onPointerUp=function(){s._videoTexture.video.play()}),r.faceForward&&o.activeCamera){var h=o.activeCamera,d=a.e.Forward(),f=a.e.TransformNormal(d,h.getViewMatrix());f.normalize(),s.rotation.y=Math.acos(a.e.Dot(d,f))}return s}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"videoTexture",{get:function(){return this._videoTexture},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fovMultiplier",{get:function(){return this._material.fovMultiplier},set:function(e){this._material.fovMultiplier=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"videoMode",{get:function(){return this._videoMode},set:function(e){this._videoMode!==e&&this._changeVideoMode(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"halfDome",{get:function(){return this._halfDome},set:function(e){this._halfDome=e,this._halfDomeMask.setEnabled(e)},enumerable:!0,configurable:!0}),t.prototype._changeVideoMode=function(e){var i=this;switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._videoMode=e,this._videoTexture.uScale=1,this._videoTexture.vScale=1,this._videoTexture.uOffset=0,this._videoTexture.vOffset=0,e){case t.MODE_SIDEBYSIDE:this._videoTexture.uScale=this._halfDome?.99999:.5;var n=this._halfDome?0:.5,r=this._halfDome?.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(function(e){i._videoTexture.uOffset=e.isRightCamera?n:r});break;case t.MODE_TOPBOTTOM:this._videoTexture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(function(e){i._videoTexture.vOffset=e.isRightCamera?.5:0})}},t.prototype.dispose=function(t,i){void 0===i&&(i=!1),this._videoTexture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),e.prototype.dispose.call(this,t,i)},t.MODE_MONOSCOPIC=0,t.MODE_TOPBOTTOM=1,t.MODE_SIDEBYSIDE=2,t}(wr.a),Pa=i(51),Aa=function(){function e(e){this.engine=e,this._captureGPUFrameTime=!1,this._gpuFrameTime=new Pa.a,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new Pa.a,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}return Object.defineProperty(e.prototype,"gpuFrameTimeCounter",{get:function(){return this._gpuFrameTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureGPUFrameTime",{get:function(){return this._captureGPUFrameTime},set:function(e){var t=this;e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.engine.onBeginFrameObservable.add(function(){t._gpuFrameTimeToken||(t._gpuFrameTimeToken=t.engine.startTimeQuery())}),this._onEndFrameObserver=this.engine.onEndFrameObservable.add(function(){if(t._gpuFrameTimeToken){var e=t.engine.endTimeQuery(t._gpuFrameTimeToken);e>-1&&(t._gpuFrameTimeToken=null,t._gpuFrameTime.fetchNewFrame(),t._gpuFrameTime.addCount(e,!0))}})):(this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"shaderCompilationTimeCounter",{get:function(){return this._shaderCompilationTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureShaderCompilationTime",{get:function(){return this._captureShaderCompilationTime},set:function(e){var t=this;e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add(function(){t._shaderCompilationTime.fetchNewFrame(),t._shaderCompilationTime.beginMonitoring()}),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add(function(){t._shaderCompilationTime.endMonitoring()})):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null},e}(),Sa=function(){function e(e){var t=this;this.scene=e,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new Pa.a,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new Pa.a,this._captureFrameTime=!1,this._frameTime=new Pa.a,this._captureRenderTime=!1,this._renderTime=new Pa.a,this._captureInterFrameTime=!1,this._interFrameTime=new Pa.a,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new Pa.a,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new Pa.a,this._capturePhysicsTime=!1,this._physicsTime=new Pa.a,this._captureAnimationsTime=!1,this._animationsTime=new Pa.a,this._captureCameraRenderTime=!1,this._cameraRenderTime=new Pa.a,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=e.onBeforeAnimationsObservable.add(function(){t._captureActiveMeshesEvaluationTime&&t._activeMeshesEvaluationTime.fetchNewFrame(),t._captureRenderTargetsRenderTime&&t._renderTargetsRenderTime.fetchNewFrame(),t._captureFrameTime&&(De.b.StartPerformanceCounter("Scene rendering"),t._frameTime.beginMonitoring()),t._captureInterFrameTime&&t._interFrameTime.endMonitoring(),t._captureParticlesRenderTime&&t._particlesRenderTime.fetchNewFrame(),t._captureSpritesRenderTime&&t._spritesRenderTime.fetchNewFrame(),t._captureAnimationsTime&&t._animationsTime.beginMonitoring(),t.scene.getEngine()._drawCalls.fetchNewFrame()}),this._onAfterRenderObserver=e.onAfterRenderObservable.add(function(){t._captureFrameTime&&(De.b.EndPerformanceCounter("Scene rendering"),t._frameTime.endMonitoring()),t._captureRenderTime&&t._renderTime.endMonitoring(!1),t._captureInterFrameTime&&t._interFrameTime.beginMonitoring()})}return Object.defineProperty(e.prototype,"activeMeshesEvaluationTimeCounter",{get:function(){return this._activeMeshesEvaluationTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureActiveMeshesEvaluationTime",{get:function(){return this._captureActiveMeshesEvaluationTime},set:function(e){var t=this;e!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=e,e?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add(function(){De.b.StartPerformanceCounter("Active meshes evaluation"),t._activeMeshesEvaluationTime.beginMonitoring()}),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add(function(){De.b.EndPerformanceCounter("Active meshes evaluation"),t._activeMeshesEvaluationTime.endMonitoring()})):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"renderTargetsRenderTimeCounter",{get:function(){return this._renderTargetsRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureRenderTargetsRenderTime",{get:function(){return this._captureRenderTargetsRenderTime},set:function(e){var t=this;e!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=e,e?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add(function(){De.b.StartPerformanceCounter("Render targets rendering"),t._renderTargetsRenderTime.beginMonitoring()}),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add(function(){De.b.EndPerformanceCounter("Render targets rendering"),t._renderTargetsRenderTime.endMonitoring(!1)})):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"particlesRenderTimeCounter",{get:function(){return this._particlesRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureParticlesRenderTime",{get:function(){return this._captureParticlesRenderTime},set:function(e){var t=this;e!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=e,e?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add(function(){De.b.StartPerformanceCounter("Particles"),t._particlesRenderTime.beginMonitoring()}),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add(function(){De.b.EndPerformanceCounter("Particles"),t._particlesRenderTime.endMonitoring(!1)})):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"spritesRenderTimeCounter",{get:function(){return this._spritesRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureSpritesRenderTime",{get:function(){return this._captureSpritesRenderTime},set:function(e){var t=this;e!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=e,this.scene.spriteManagers&&(e?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add(function(){De.b.StartPerformanceCounter("Sprites"),t._spritesRenderTime.beginMonitoring()}),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add(function(){De.b.EndPerformanceCounter("Sprites"),t._spritesRenderTime.endMonitoring(!1)})):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null)))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"physicsTimeCounter",{get:function(){return this._physicsTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"capturePhysicsTime",{get:function(){return this._capturePhysicsTime},set:function(e){var t=this;e!==this._capturePhysicsTime&&this.scene.onBeforePhysicsObservable&&(this._capturePhysicsTime=e,e?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add(function(){De.b.StartPerformanceCounter("Physics"),t._physicsTime.beginMonitoring()}),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add(function(){De.b.EndPerformanceCounter("Physics"),t._physicsTime.endMonitoring()})):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"animationsTimeCounter",{get:function(){return this._animationsTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureAnimationsTime",{get:function(){return this._captureAnimationsTime},set:function(e){var t=this;e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add(function(){t._animationsTime.endMonitoring()}):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"frameTimeCounter",{get:function(){return this._frameTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureFrameTime",{get:function(){return this._captureFrameTime},set:function(e){this._captureFrameTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"interFrameTimeCounter",{get:function(){return this._interFrameTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureInterFrameTime",{get:function(){return this._captureInterFrameTime},set:function(e){this._captureInterFrameTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"renderTimeCounter",{get:function(){return this._renderTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureRenderTime",{get:function(){return this._captureRenderTime},set:function(e){var t=this;e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add(function(){t._renderTime.beginMonitoring(),De.b.StartPerformanceCounter("Main render")}),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add(function(){t._renderTime.endMonitoring(!1),De.b.EndPerformanceCounter("Main render")})):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cameraRenderTimeCounter",{get:function(){return this._cameraRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureCameraRenderTime",{get:function(){return this._captureCameraRenderTime},set:function(e){var t=this;e!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=e,e?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add(function(e){t._cameraRenderTime.beginMonitoring(),De.b.StartPerformanceCounter("Rendering camera "+e.name)}),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add(function(e){t._cameraRenderTime.endMonitoring(!1),De.b.EndPerformanceCounter("Rendering camera "+e.name)})):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"drawCallsCounter",{get:function(){return this.scene.getEngine()._drawCalls},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver&&(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null),this._onAfterSpritesRenderingObserver&&(this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null),this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this._onBeforePhysicsObserver&&(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null),this._onAfterPhysicsObserver&&(this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null),this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null},e}(),Ca=i(29),Ra="#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;\nuniform sampler2D opacitySampler;\nuniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;\nvoid main(void)\n{\nvec4 finalColor=glowColor;\n\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a<ALPHATESTVALUE)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*finalColor;\n#else\ngl_FragColor=finalColor;\n#endif\n}";ai.a.ShadersStore.glowMapGenerationPixelShader=Ra;var Oa="\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;\nuniform mat4 opacityMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef VERTEXALPHA\nattribute vec4 color;\nvarying vec4 vColor;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef OPACITYUV2\nvUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef VERTEXALPHA\nvColor=color;\n#endif\n}";ai.a.ShadersStore.glowMapGenerationVertexShader=Oa;var Ma=function(){function e(t,i){this._vertexBuffers={},this._maxSize=0,this._mainTextureDesiredSize={width:0,height:0},this._shouldRender=!0,this._postProcesses=[],this._textures=[],this._emissiveTextureAndColor={texture:null,color:new s.b},this.neutralColor=new s.b,this.isEnabled=!0,this.onDisposeObservable=new o.c,this.onBeforeRenderMainTextureObservable=new o.c,this.onBeforeComposeObservable=new o.c,this.onBeforeRenderMeshToEffect=new o.c,this.onAfterRenderMeshToEffect=new o.c,this.onAfterComposeObservable=new o.c,this.onSizeChangedObservable=new o.c,this.name=t,this._scene=i||R.a.LastCreatedScene,e._SceneComponentInitialization(this._scene),this._engine=this._scene.getEngine(),this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.effectLayers.push(this),this._generateIndexBuffer(),this._generateVertexBuffer()}return Object.defineProperty(e.prototype,"camera",{get:function(){return this._effectLayerOptions.camera},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"renderingGroupId",{get:function(){return this._effectLayerOptions.renderingGroupId},set:function(e){this._effectLayerOptions.renderingGroupId=e},enumerable:!0,configurable:!0}),e.prototype._init=function(e){this._effectLayerOptions=Object(h.a)({mainTextureRatio:.5,alphaBlendingMode:g.a.ALPHA_COMBINE,camera:null,renderingGroupId:-1},e),this._setMainTextureSize(),this._createMainTexture(),this._createTextureAndPostProcesses(),this._mergeEffect=this._createMergeEffect()},e.prototype._generateIndexBuffer=function(){var 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)},e.prototype._generateVertexBuffer=function(){var e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1);var t=new en.b(this._engine,e,en.b.PositionKind,!1,!1,2);this._vertexBuffers[en.b.PositionKind]=t},e.prototype._setMainTextureSize=function(){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?Oe.a.GetExponentOfTwo(this._mainTextureDesiredSize.width,this._maxSize):this._mainTextureDesiredSize.width,this._mainTextureDesiredSize.height=this._engine.needPOTTextures?Oe.a.GetExponentOfTwo(this._mainTextureDesiredSize.height,this._maxSize):this._mainTextureDesiredSize.height),this._mainTextureDesiredSize.width=Math.floor(this._mainTextureDesiredSize.width),this._mainTextureDesiredSize.height=Math.floor(this._mainTextureDesiredSize.height)},e.prototype._createMainTexture=function(){var e=this;this._mainTexture=new Fi("HighlightLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,!1,!0,g.a.TEXTURETYPE_UNSIGNED_INT),this._mainTexture.activeCamera=this._effectLayerOptions.camera,this._mainTexture.wrapU=et.a.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=et.a.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(et.a.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._mainTexture.ignoreCameraViewport=!0,this._mainTexture.customRenderFunction=function(t,i,n,r){var o;e.onBeforeRenderMainTextureObservable.notifyObservers(e);var a=e._scene.getEngine();if(r.length){for(a.setColorWrite(!1),o=0;o<r.length;o++)e._renderSubMesh(r.data[o]);a.setColorWrite(!0)}for(o=0;o<t.length;o++)e._renderSubMesh(t.data[o]);for(o=0;o<i.length;o++)e._renderSubMesh(i.data[o]);var s=a.getAlphaMode();for(o=0;o<n.length;o++)e._renderSubMesh(n.data[o],!0);a.setAlphaMode(s)},this._mainTexture.onClearObservable.add(function(t){t.clear(e.neutralColor,!0,!0,!0)})},e.prototype._addCustomEffectDefines=function(e){},e.prototype._isReady=function(e,t,i){var n=e.getMaterial();if(!n)return!1;if(!n.isReadyForSubMesh(e.getMesh(),e,t))return!1;var r=[],o=[en.b.PositionKind],a=e.getMesh(),s=!1,c=!1;if(n){var l=n.needAlphaTesting(),u=n.getAlphaTestTexture(),h=u&&u.hasAlpha&&(n.useAlphaFromDiffuseTexture||n._useAlphaFromAlbedoTexture);u&&(l||h)&&(r.push("#define DIFFUSE"),a.isVerticesDataPresent(en.b.UV2Kind)&&1===u.coordinatesIndex?(r.push("#define DIFFUSEUV2"),c=!0):a.isVerticesDataPresent(en.b.UVKind)&&(r.push("#define DIFFUSEUV1"),s=!0),l&&(r.push("#define ALPHATEST"),r.push("#define ALPHATESTVALUE 0.4")));var d=n.opacityTexture;d&&(r.push("#define OPACITY"),a.isVerticesDataPresent(en.b.UV2Kind)&&1===d.coordinatesIndex?(r.push("#define OPACITYUV2"),c=!0):a.isVerticesDataPresent(en.b.UVKind)&&(r.push("#define OPACITYUV1"),s=!0))}i&&(r.push("#define EMISSIVE"),a.isVerticesDataPresent(en.b.UV2Kind)&&1===i.coordinatesIndex?(r.push("#define EMISSIVEUV2"),c=!0):a.isVerticesDataPresent(en.b.UVKind)&&(r.push("#define EMISSIVEUV1"),s=!0)),a.isVerticesDataPresent(en.b.ColorKind)&&a.hasVertexAlpha&&(o.push(en.b.ColorKind),r.push("#define VERTEXALPHA")),s&&(o.push(en.b.UVKind),r.push("#define UV1")),c&&(o.push(en.b.UV2Kind),r.push("#define UV2"));var f=new ho.a;if(a.useBones&&a.computeBonesUsingShaders){o.push(en.b.MatricesIndicesKind),o.push(en.b.MatricesWeightsKind),a.numBoneInfluencers>4&&(o.push(en.b.MatricesIndicesExtraKind),o.push(en.b.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers);var p=a.skeleton;p&&p.isUsingTextureForMatrices?r.push("#define BONETEXTURE"):r.push("#define BonesPerMesh "+(p?p.bones.length+1:0)),a.numBoneInfluencers>0&&f.addCPUSkinningFallback(0,a)}else r.push("#define NUM_BONE_INFLUENCERS 0");var _=a.morphTargetManager,m=0;_&&_.numInfluencers>0&&(r.push("#define MORPHTARGETS"),m=_.numInfluencers,r.push("#define NUM_MORPH_INFLUENCERS "+m),io.a.PrepareAttributesForMorphTargetsInfluencers(o,a,m)),t&&(r.push("#define INSTANCES"),io.a.PushAttributesForInstances(o)),this._addCustomEffectDefines(r);var g=r.join("\n");return this._cachedDefines!==g&&(this._cachedDefines=g,this._effectLayerMapGenerationEffect=this._scene.getEngine().createEffect("glowMapGeneration",o,["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity"],["diffuseSampler","emissiveSampler","opacitySampler","boneSampler"],g,f,void 0,void 0,{maxSimultaneousMorphTargets:m})),this._effectLayerMapGenerationEffect.isReady()},e.prototype.render=function(){var e=this._mergeEffect;if(e.isReady()){for(var t=0;t<this._postProcesses.length;t++)if(!this._postProcesses[t].isReady())return;var i=this._scene.getEngine();this.onBeforeComposeObservable.notifyObservers(this),i.enableEffect(e),i.setState(!1),i.bindBuffers(this._vertexBuffers,this._indexBuffer,e);var n=i.getAlphaMode();i.setAlphaMode(this._effectLayerOptions.alphaBlendingMode),this._internalRender(e),i.setAlphaMode(n),this.onAfterComposeObservable.notifyObservers(this);var r=this._mainTexture.getSize();this._setMainTextureSize(),r.width===this._mainTextureDesiredSize.width&&r.height===this._mainTextureDesiredSize.height||(this.onSizeChangedObservable.notifyObservers(this),this._disposeTextureAndPostProcesses(),this._createMainTexture(),this._createTextureAndPostProcesses())}},e.prototype.hasMesh=function(e){return-1===this.renderingGroupId||e.renderingGroupId===this.renderingGroupId},e.prototype.shouldRender=function(){return this.isEnabled&&this._shouldRender},e.prototype._shouldRenderMesh=function(e){return!0},e.prototype._canRenderMesh=function(e,t){return!t.needAlphaBlendingForMesh(e)},e.prototype._shouldRenderEmissiveTextureForMesh=function(){return!0},e.prototype._renderSubMesh=function(e,t){var i=this;if(void 0===t&&(t=!1),this.shouldRender()){var n=e.getMaterial(),r=e.getRenderingMesh(),o=this._scene,a=o.getEngine();if(r._internalAbstractMeshDataInfo._isActiveIntermediate=!1,n&&this._canRenderMesh(r,n)){a.setState(n.backFaceCulling);var s=r._getInstancesRenderList(e._id);if(!s.mustReturn&&this._shouldRenderMesh(r)){var c=s.hardwareInstancedRendering[e._id];if(this._setEmissiveTextureAndColor(r,e,n),this.onBeforeRenderMeshToEffect.notifyObservers(r),this._useMeshMaterial(r))r.render(e,c);else if(this._isReady(e,c,this._emissiveTextureAndColor.texture)){a.enableEffect(this._effectLayerMapGenerationEffect),r._bind(e,this._effectLayerMapGenerationEffect,Ca.a.TriangleFillMode),this._effectLayerMapGenerationEffect.setMatrix("viewProjection",o.getTransformMatrix()),this._effectLayerMapGenerationEffect.setFloat4("glowColor",this._emissiveTextureAndColor.color.r,this._emissiveTextureAndColor.color.g,this._emissiveTextureAndColor.color.b,this._emissiveTextureAndColor.color.a);var l=n.needAlphaTesting(),u=n.getAlphaTestTexture(),h=u&&u.hasAlpha&&(n.useAlphaFromDiffuseTexture||n._useAlphaFromAlbedoTexture);if(u&&(l||h))this._effectLayerMapGenerationEffect.setTexture("diffuseSampler",u),(d=u.getTextureMatrix())&&this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix",d);var d,f=n.opacityTexture;if(f)this._effectLayerMapGenerationEffect.setTexture("opacitySampler",f),this._effectLayerMapGenerationEffect.setFloat("opacityIntensity",f.level),(d=f.getTextureMatrix())&&this._effectLayerMapGenerationEffect.setMatrix("opacityMatrix",d);if(this._emissiveTextureAndColor.texture&&(this._effectLayerMapGenerationEffect.setTexture("emissiveSampler",this._emissiveTextureAndColor.texture),this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix",this._emissiveTextureAndColor.texture.getTextureMatrix())),r.useBones&&r.computeBonesUsingShaders&&r.skeleton){var p=r.skeleton;if(p.isUsingTextureForMatrices){var _=p.getTransformMatrixTexture(r);if(!_)return;this._effectLayerMapGenerationEffect.setTexture("boneSampler",_),this._effectLayerMapGenerationEffect.setFloat("boneTextureWidth",4*(p.bones.length+1))}else this._effectLayerMapGenerationEffect.setMatrices("mBones",p.getTransformMatrices(r))}io.a.BindMorphTargetParameters(r,this._effectLayerMapGenerationEffect),t&&a.setAlphaMode(n.alphaMode),r._processRendering(e,this._effectLayerMapGenerationEffect,n.fillMode,s,c,function(e,t){return i._effectLayerMapGenerationEffect.setMatrix("world",t)})}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(r)}}}},e.prototype._useMeshMaterial=function(e){return!1},e.prototype._rebuild=function(){var e=this._vertexBuffers[en.b.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()},e.prototype._disposeTextureAndPostProcesses=function(){this._mainTexture.dispose();for(var e=0;e<this._postProcesses.length;e++)this._postProcesses[e]&&this._postProcesses[e].dispose();this._postProcesses=[];for(e=0;e<this._textures.length;e++)this._textures[e]&&this._textures[e].dispose();this._textures=[]},e.prototype.dispose=function(){var e=this._vertexBuffers[en.b.PositionKind];e&&(e.dispose(),this._vertexBuffers[en.b.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._disposeTextureAndPostProcesses();var t=this._scene.effectLayers.indexOf(this,0);t>-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()},e.prototype.getClassName=function(){return"EffectLayer"},e.Parse=function(e,t,i){return De.b.Instantiate(e.customType).Parse(e,t,i)},e._SceneComponentInitialization=function(e){throw we.a.WarnImport("EffectLayerSceneComponent")},Object(h.c)([Object(N.c)()],e.prototype,"name",void 0),Object(h.c)([Object(N.f)()],e.prototype,"neutralColor",void 0),Object(h.c)([Object(N.c)()],e.prototype,"isEnabled",void 0),Object(h.c)([Object(N.d)()],e.prototype,"camera",null),Object(h.c)([Object(N.c)()],e.prototype,"renderingGroupId",null),e}();n.a.AddParser(Fe.a.NAME_EFFECTLAYER,function(e,t,i,n){if(e.effectLayers){i.effectLayers||(i.effectLayers=new Array);for(var r=0;r<e.effectLayers.length;r++){var o=Ma.Parse(e.effectLayers[r],t,n);i.effectLayers.push(o)}}}),n.a.prototype.removeEffectLayer=function(e){var t=this.effectLayers.indexOf(e);return-1!==t&&this.effectLayers.splice(t,1),t},n.a.prototype.addEffectLayer=function(e){this.effectLayers.push(e)};var Ia=function(){function e(e){this.name=Fe.a.NAME_EFFECTLAYER,this._renderEffects=!1,this._needStencil=!1,this._previousStencilState=!1,this.scene=e,this._engine=e.getEngine(),e.effectLayers=new Array}return e.prototype.register=function(){this.scene._isReadyForMeshStage.registerStep(Fe.a.STEP_ISREADYFORMESH_EFFECTLAYER,this,this._isReadyForMesh),this.scene._cameraDrawRenderTargetStage.registerStep(Fe.a.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER,this,this._renderMainTexture),this.scene._beforeCameraDrawStage.registerStep(Fe.a.STEP_BEFORECAMERADRAW_EFFECTLAYER,this,this._setStencil),this.scene._afterRenderingGroupDrawStage.registerStep(Fe.a.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW,this,this._drawRenderingGroup),this.scene._afterCameraDrawStage.registerStep(Fe.a.STEP_AFTERCAMERADRAW_EFFECTLAYER,this,this._setStencilBack),this.scene._afterCameraDrawStage.registerStep(Fe.a.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW,this,this._drawCamera)},e.prototype.rebuild=function(){for(var e=0,t=this.scene.effectLayers;e<t.length;e++){t[e]._rebuild()}},e.prototype.serialize=function(e){e.effectLayers=[];for(var t=0,i=this.scene.effectLayers;t<i.length;t++){var n=i[t];n.serialize&&e.effectLayers.push(n.serialize())}},e.prototype.addFromContainer=function(e){var t=this;e.effectLayers&&e.effectLayers.forEach(function(e){t.scene.addEffectLayer(e)})},e.prototype.removeFromContainer=function(e,t){var i=this;e.effectLayers&&e.effectLayers.forEach(function(e){i.scene.removeEffectLayer(e),t&&e.dispose()})},e.prototype.dispose=function(){for(var e=this.scene.effectLayers;e.length;)e[0].dispose()},e.prototype._isReadyForMesh=function(e,t){for(var i=0,n=this.scene.effectLayers;i<n.length;i++){var r=n[i];if(r.hasMesh(e))for(var o=0,a=e.subMeshes;o<a.length;o++){var s=a[o];if(!r.isReady(s,t))return!1}}return!0},e.prototype._renderMainTexture=function(e){this._renderEffects=!1,this._needStencil=!1;var t=!1,i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(var n=0,r=i;n<r.length;n++){var o=r[n];if(o.shouldRender()&&(!o.camera||o.camera.cameraRigMode===Qe.a.RIG_MODE_NONE&&e===o.camera||o.camera.cameraRigMode!==Qe.a.RIG_MODE_NONE&&o.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||o.needStencil();var a=o._mainTexture;a._shouldRender()&&(this.scene.incrementRenderId(),a.render(!1,!1),t=!0)}}this.scene.incrementRenderId()}return t},e.prototype._setStencil=function(){this._needStencil&&this._engine.setStencilBuffer(!0)},e.prototype._setStencilBack=function(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)},e.prototype._draw=function(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);for(var t=this.scene.effectLayers,i=0;i<t.length;i++){var n=t[i];n.renderingGroupId===e&&n.shouldRender()&&n.render()}this._engine.setDepthBuffer(!0)}},e.prototype._drawCamera=function(){this._renderEffects&&this._draw(-1)},e.prototype._drawRenderingGroup=function(e){!this.scene._isInIntermediateRendering()&&this._renderEffects&&this._draw(e)},e}();Ma._SceneComponentInitialization=function(e){var t=e._getComponent(Fe.a.NAME_EFFECTLAYER);t||(t=new Ia(e),e._addComponent(t))};var Da="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}";ai.a.ShadersStore.glowMapMergePixelShader=Da;var wa="\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}";ai.a.ShadersStore.glowMapMergeVertexShader=wa;n.a.prototype.getGlowLayerByName=function(e){for(var t=0;t<this.effectLayers.length;t++)if(this.effectLayers[t].name===e&&this.effectLayers[t].getEffectName()===La.EffectName)return this.effectLayers[t];return null};var La=function(e){function t(i,n,r){var o=e.call(this,i,n)||this;return o._intensity=1,o._includedOnlyMeshes=[],o._excludedMeshes=[],o._meshesUsingTheirOwnMaterials=[],o.neutralColor=new s.b(0,0,0,1),o._options=Object(h.a)({mainTextureRatio:t.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1},r),o._init({alphaBlendingMode:g.a.ALPHA_ADD,camera:o._options.camera,mainTextureFixedSize:o._options.mainTextureFixedSize,mainTextureRatio:o._options.mainTextureRatio,renderingGroupId:o._options.renderingGroupId}),o}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"blurKernelSize",{get:function(){return this._horizontalBlurPostprocess1.kernel},set:function(e){this._horizontalBlurPostprocess1.kernel=e,this._verticalBlurPostprocess1.kernel=e,this._horizontalBlurPostprocess2.kernel=e,this._verticalBlurPostprocess2.kernel=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"intensity",{get:function(){return this._intensity},set:function(e){this._intensity=e},enumerable:!0,configurable:!0}),t.prototype.getEffectName=function(){return t.EffectName},t.prototype._createMergeEffect=function(){return this._engine.createEffect("glowMapMerge",[en.b.PositionKind],["offset"],["textureSampler","textureSampler2"],"#define EMISSIVE \n")},t.prototype._createTextureAndPostProcesses=function(){var e=this,t=this._mainTextureDesiredSize.width,i=this._mainTextureDesiredSize.height;t=this._engine.needPOTTextures?Oe.a.GetExponentOfTwo(t,this._maxSize):t,i=this._engine.needPOTTextures?Oe.a.GetExponentOfTwo(i,this._maxSize):i;var n=0;n=this._engine.getCaps().textureHalfFloatRender?g.a.TEXTURETYPE_HALF_FLOAT:g.a.TEXTURETYPE_UNSIGNED_INT,this._blurTexture1=new Fi("GlowLayerBlurRTT",{width:t,height:i},this._scene,!1,!0,n),this._blurTexture1.wrapU=et.a.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=et.a.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(et.a.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;var r=Math.floor(t/2),o=Math.floor(i/2);this._blurTexture2=new Fi("GlowLayerBlurRTT2",{width:r,height:o},this._scene,!1,!0,n),this._blurTexture2.wrapU=et.a.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=et.a.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(et.a.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2],this._horizontalBlurPostprocess1=new Zr("GlowLayerHBP1",new a.d(1,0),this._options.blurKernelSize/2,{width:t,height:i},null,et.a.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,n),this._horizontalBlurPostprocess1.width=t,this._horizontalBlurPostprocess1.height=i,this._horizontalBlurPostprocess1.onApplyObservable.add(function(t){t.setTexture("textureSampler",e._mainTexture)}),this._verticalBlurPostprocess1=new Zr("GlowLayerVBP1",new a.d(0,1),this._options.blurKernelSize/2,{width:t,height:i},null,et.a.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,n),this._horizontalBlurPostprocess2=new Zr("GlowLayerHBP2",new a.d(1,0),this._options.blurKernelSize/2,{width:r,height:o},null,et.a.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,n),this._horizontalBlurPostprocess2.width=r,this._horizontalBlurPostprocess2.height=o,this._horizontalBlurPostprocess2.onApplyObservable.add(function(t){t.setTexture("textureSampler",e._blurTexture1)}),this._verticalBlurPostprocess2=new Zr("GlowLayerVBP2",new a.d(0,1),this._options.blurKernelSize/2,{width:r,height:o},null,et.a.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,n),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(function(){var t=e._blurTexture1.getInternalTexture();t&&(e._scene.postProcessManager.directRender(e._postProcesses1,t,!0),(t=e._blurTexture2.getInternalTexture())&&e._scene.postProcessManager.directRender(e._postProcesses2,t,!0))}),this._postProcesses.map(function(e){e.autoClear=!1})},t.prototype.isReady=function(t,i){var n=t.getMaterial(),r=t.getRenderingMesh();if(!n||!r)return!1;var o=n.emissiveTexture;return e.prototype._isReady.call(this,t,i,o)},t.prototype.needStencil=function(){return!1},t.prototype._canRenderMesh=function(e,t){return!0},t.prototype._internalRender=function(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);var t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(Ca.a.TriangleFillMode,0,6),t.setStencilBuffer(i)},t.prototype._setEmissiveTextureAndColor=function(e,t,i){var n=1;this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(n=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector?this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color):i.emissiveColor?this._emissiveTextureAndColor.color.set(i.emissiveColor.r*n,i.emissiveColor.g*n,i.emissiveColor.b*n,i.alpha):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)},t.prototype._shouldRenderMesh=function(e){return this.hasMesh(e)},t.prototype._addCustomEffectDefines=function(e){e.push("#define GLOW")},t.prototype.addExcludedMesh=function(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)},t.prototype.removeExcludedMesh=function(e){var t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)},t.prototype.addIncludedOnlyMesh=function(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)},t.prototype.removeIncludedOnlyMesh=function(e){var t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)},t.prototype.hasMesh=function(t){return!!e.prototype.hasMesh.call(this,t)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(t.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(t.uniqueId))},t.prototype._useMeshMaterial=function(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1},t.prototype.referenceMeshToUseItsOwnMaterial=function(e){this._meshesUsingTheirOwnMaterials.push(e.uniqueId)},t.prototype.unReferenceMeshFromUsingItsOwnMaterial=function(e){for(var t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);t>0;)this._meshesUsingTheirOwnMaterials.slice(t,t+1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)},t.prototype._disposeMesh=function(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)},t.prototype.getClassName=function(){return"GlowLayer"},t.prototype.serialize=function(){var e,t=N.a.Serialize(this);if(t.customType="BABYLON.GlowLayer",t.includedMeshes=[],this._includedOnlyMeshes.length)for(e=0;e<this._includedOnlyMeshes.length;e++){(i=this._scene.getMeshByUniqueID(this._includedOnlyMeshes[e]))&&t.includedMeshes.push(i.id)}if(t.excludedMeshes=[],this._excludedMeshes.length)for(e=0;e<this._excludedMeshes.length;e++){var i;(i=this._scene.getMeshByUniqueID(this._excludedMeshes[e]))&&t.excludedMeshes.push(i.id)}return t},t.Parse=function(e,i,n){var r,o=N.a.Parse(function(){return new t(e.name,i,e.options)},e,i,n);for(r=0;r<e.excludedMeshes.length;r++){(a=i.getMeshByID(e.excludedMeshes[r]))&&o.addExcludedMesh(a)}for(r=0;r<e.includedMeshes.length;r++){var a;(a=i.getMeshByID(e.includedMeshes[r]))&&o.addIncludedOnlyMesh(a)}return o},t.EffectName="GlowLayer",t.DefaultBlurKernelSize=32,t.DefaultTextureRatio=.5,Object(h.c)([Object(N.c)()],t.prototype,"blurKernelSize",null),Object(h.c)([Object(N.c)()],t.prototype,"intensity",null),Object(h.c)([Object(N.c)("options")],t.prototype,"_options",void 0),t}(Ma);c.a.RegisteredTypes["BABYLON.GlowLayer"]=La;var Na="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}";ai.a.ShadersStore.glowBlurPostProcessPixelShader=Na;n.a.prototype.getHighlightLayerByName=function(e){for(var t=0;t<this.effectLayers.length;t++)if(this.effectLayers[t].name===e&&this.effectLayers[t].getEffectName()===Ba.EffectName)return this.effectLayers[t];return null};var Fa=function(e){function t(t,i,n,r,o,a,s,c){void 0===a&&(a=et.a.BILINEAR_SAMPLINGMODE);var l=e.call(this,t,"glowBlurPostProcess",["screenSize","direction","blurWidth"],null,r,o,a,s,c)||this;return l.direction=i,l.kernel=n,l.onApplyObservable.add(function(e){e.setFloat2("screenSize",l.width,l.height),e.setVector2("direction",l.direction),e.setFloat("blurWidth",l.kernel)}),l}return Object(h.d)(t,e),t}(ui),Ba=function(e){function t(i,n,r){var a=e.call(this,i,n)||this;return a.name=i,a.innerGlow=!0,a.outerGlow=!0,a.onBeforeBlurObservable=new o.c,a.onAfterBlurObservable=new o.c,a._instanceGlowingMeshStencilReference=t.GlowingMeshStencilReference++,a._meshes={},a._excludedMeshes={},a.neutralColor=t.NeutralColor,a._engine.isStencilEnable||m.a.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),a._options=Object(h.a)({mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:g.a.ALPHA_COMBINE,camera:null,renderingGroupId:-1},r),a._init({alphaBlendingMode:a._options.alphaBlendingMode,camera:a._options.camera,mainTextureFixedSize:a._options.mainTextureFixedSize,mainTextureRatio:a._options.mainTextureRatio,renderingGroupId:a._options.renderingGroupId}),a._shouldRender=!1,a}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"blurHorizontalSize",{get:function(){return this._horizontalBlurPostprocess.kernel},set:function(e){this._horizontalBlurPostprocess.kernel=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"blurVerticalSize",{get:function(){return this._verticalBlurPostprocess.kernel},set:function(e){this._verticalBlurPostprocess.kernel=e},enumerable:!0,configurable:!0}),t.prototype.getEffectName=function(){return t.EffectName},t.prototype._createMergeEffect=function(){return this._engine.createEffect("glowMapMerge",[en.b.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)},t.prototype._createTextureAndPostProcesses=function(){var e=this,t=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,i=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;t=this._engine.needPOTTextures?Oe.a.GetExponentOfTwo(t,this._maxSize):t,i=this._engine.needPOTTextures?Oe.a.GetExponentOfTwo(i,this._maxSize):i;var n=0;n=this._engine.getCaps().textureHalfFloatRender?g.a.TEXTURETYPE_HALF_FLOAT:g.a.TEXTURETYPE_UNSIGNED_INT,this._blurTexture=new Fi("HighlightLayerBlurRTT",{width:t,height:i},this._scene,!1,!0,n),this._blurTexture.wrapU=et.a.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=et.a.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(et.a.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._options.alphaBlendingMode===g.a.ALPHA_COMBINE?(this._downSamplePostprocess=new fi("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,et.a.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.onApplyObservable.add(function(t){t.setTexture("textureSampler",e._mainTexture)}),this._horizontalBlurPostprocess=new Fa("HighlightLayerHBP",new a.d(1,0),this._options.blurHorizontalSize,1,null,et.a.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(function(e){e.setFloat2("screenSize",t,i)}),this._verticalBlurPostprocess=new Fa("HighlightLayerVBP",new a.d(0,1),this._options.blurVerticalSize,1,null,et.a.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add(function(e){e.setFloat2("screenSize",t,i)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new Zr("HighlightLayerHBP",new a.d(1,0),this._options.blurHorizontalSize/2,{width:t,height:i},null,et.a.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,n),this._horizontalBlurPostprocess.width=t,this._horizontalBlurPostprocess.height=i,this._horizontalBlurPostprocess.onApplyObservable.add(function(t){t.setTexture("textureSampler",e._mainTexture)}),this._verticalBlurPostprocess=new Zr("HighlightLayerVBP",new a.d(0,1),this._options.blurVerticalSize/2,{width:t,height:i},null,et.a.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,n),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(function(){e.onBeforeBlurObservable.notifyObservers(e);var t=e._blurTexture.getInternalTexture();t&&e._scene.postProcessManager.directRender(e._postProcesses,t,!0),e.onAfterBlurObservable.notifyObservers(e)}),this._postProcesses.map(function(e){e.autoClear=!1})},t.prototype.needStencil=function(){return!0},t.prototype.isReady=function(t,i){var n=t.getMaterial(),r=t.getRenderingMesh();if(!n||!r||!this._meshes)return!1;var o=null,a=this._meshes[r.uniqueId];return a&&a.glowEmissiveOnly&&n&&(o=n.emissiveTexture),e.prototype._isReady.call(this,t,i,o)},t.prototype._internalRender=function(e){e.setTexture("textureSampler",this._blurTexture);var t=this._engine;t.cacheStencilState(),t.setStencilOperationPass(g.a.REPLACE),t.setStencilOperationFail(g.a.KEEP),t.setStencilOperationDepthFail(g.a.KEEP),t.setStencilMask(0),t.setStencilBuffer(!0),t.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&(e.setFloat("offset",0),t.setStencilFunction(g.a.NOTEQUAL),t.drawElementsType(Ca.a.TriangleFillMode,0,6)),this.innerGlow&&(e.setFloat("offset",1),t.setStencilFunction(g.a.EQUAL),t.drawElementsType(Ca.a.TriangleFillMode,0,6)),t.restoreStencilState()},t.prototype.shouldRender=function(){return!!e.prototype.shouldRender.call(this)&&!!this._meshes},t.prototype._shouldRenderMesh=function(t){return(!this._excludedMeshes||!this._excludedMeshes[t.uniqueId])&&!!e.prototype.hasMesh.call(this,t)},t.prototype._setEmissiveTextureAndColor=function(e,t,i){var n=this._meshes[e.uniqueId];n?this._emissiveTextureAndColor.color.set(n.color.r,n.color.g,n.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),n&&n.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null},t.prototype.addExcludedMesh=function(e){this._excludedMeshes&&(this._excludedMeshes[e.uniqueId]||(this._excludedMeshes[e.uniqueId]={mesh:e,beforeBind:e.onBeforeBindObservable.add(function(e){e.getEngine().setStencilBuffer(!1)}),afterRender:e.onAfterRenderObservable.add(function(e){e.getEngine().setStencilBuffer(!0)})}))},t.prototype.removeExcludedMesh=function(e){if(this._excludedMeshes){var t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}},t.prototype.hasMesh=function(t){return!!this._meshes&&(!!e.prototype.hasMesh.call(this,t)&&(void 0!==this._meshes[t.uniqueId]&&null!==this._meshes[t.uniqueId]))},t.prototype.addMesh=function(e,t,i){var n=this;if(void 0===i&&(i=!1),this._meshes){var r=this._meshes[e.uniqueId];r?r.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(function(e){n.isEnabled&&(n._excludedMeshes&&n._excludedMeshes[e.uniqueId]?n._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(n._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(function(e){n.isEnabled&&n._defaultStencilReference(e)}),glowEmissiveOnly:i},e.onDisposeObservable.add(function(){n._disposeMesh(e)})),this._shouldRender=!0}},t.prototype.removeMesh=function(e){if(this._meshes){var t=this._meshes[e.uniqueId];for(var i in t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1,this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}},t.prototype.removeAllMeshes=function(){if(this._meshes)for(var e in this._meshes)if(this._meshes.hasOwnProperty(e)){var t=this._meshes[e];t&&this.removeMesh(t.mesh)}},t.prototype._defaultStencilReference=function(e){e.getScene().getEngine().setStencilFunctionReference(t.NormalMeshStencilReference)},t.prototype._disposeMesh=function(e){this.removeMesh(e),this.removeExcludedMesh(e)},t.prototype.dispose=function(){if(this._meshes){for(var t in this._meshes){(i=this._meshes[t])&&i.mesh&&(i.observerHighlight&&i.mesh.onBeforeBindObservable.remove(i.observerHighlight),i.observerDefault&&i.mesh.onAfterRenderObservable.remove(i.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(var t in this._excludedMeshes){var i;(i=this._excludedMeshes[t])&&(i.beforeBind&&i.mesh.onBeforeBindObservable.remove(i.beforeBind),i.afterRender&&i.mesh.onAfterRenderObservable.remove(i.afterRender))}this._excludedMeshes=null}e.prototype.dispose.call(this)},t.prototype.getClassName=function(){return"HighlightLayer"},t.prototype.serialize=function(){var e=N.a.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(var t in this._meshes){var i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(var n in this._excludedMeshes){var r=this._excludedMeshes[n];r&&e.excludedMeshes.push(r.mesh.id)}return e},t.Parse=function(e,i,n){var r,o=N.a.Parse(function(){return new t(e.name,i,e.options)},e,i,n);for(r=0;r<e.excludedMeshes.length;r++){(a=i.getMeshByID(e.excludedMeshes[r]))&&o.addExcludedMesh(a)}for(r=0;r<e.meshes.length;r++){var a,c=e.meshes[r];(a=i.getMeshByID(c.meshId))&&o.addMesh(a,s.a.FromArray(c.color),c.glowEmissiveOnly)}return o},t.EffectName="HighlightLayer",t.NeutralColor=new s.b(0,0,0,0),t.GlowingMeshStencilReference=2,t.NormalMeshStencilReference=1,Object(h.c)([Object(N.c)()],t.prototype,"innerGlow",void 0),Object(h.c)([Object(N.c)()],t.prototype,"outerGlow",void 0),Object(h.c)([Object(N.c)()],t.prototype,"blurHorizontalSize",null),Object(h.c)([Object(N.c)()],t.prototype,"blurVerticalSize",null),Object(h.c)([Object(N.c)("options")],t.prototype,"_options",void 0),t}(Ma);c.a.RegisteredTypes["BABYLON.HighlightLayer"]=Ba;var Ua=function(){function e(e){this.name=Fe.a.NAME_LAYER,this.scene=e,this._engine=e.getEngine(),e.layers=new Array}return e.prototype.register=function(){this.scene._beforeCameraDrawStage.registerStep(Fe.a.STEP_BEFORECAMERADRAW_LAYER,this,this._drawCameraBackground),this.scene._afterCameraDrawStage.registerStep(Fe.a.STEP_AFTERCAMERADRAW_LAYER,this,this._drawCameraForeground),this.scene._beforeRenderTargetDrawStage.registerStep(Fe.a.STEP_BEFORERENDERTARGETDRAW_LAYER,this,this._drawRenderTargetBackground),this.scene._afterRenderTargetDrawStage.registerStep(Fe.a.STEP_AFTERRENDERTARGETDRAW_LAYER,this,this._drawRenderTargetForeground)},e.prototype.rebuild=function(){for(var e=0,t=this.scene.layers;e<t.length;e++){t[e]._rebuild()}},e.prototype.dispose=function(){for(var e=this.scene.layers;e.length;)e[0].dispose()},e.prototype._draw=function(e){var t=this.scene.layers;if(t.length){this._engine.setDepthBuffer(!1);for(var i=0,n=t;i<n.length;i++){var r=n[i];e(r)&&r.render()}this._engine.setDepthBuffer(!0)}},e.prototype._drawCameraPredicate=function(e,t,i){return!e.renderOnlyInRenderTargetTextures&&e.isBackground===t&&0!=(e.layerMask&i)},e.prototype._drawCameraBackground=function(e){var t=this;this._draw(function(i){return t._drawCameraPredicate(i,!0,e.layerMask)})},e.prototype._drawCameraForeground=function(e){var t=this;this._draw(function(i){return t._drawCameraPredicate(i,!1,e.layerMask)})},e.prototype._drawRenderTargetPredicate=function(e,t,i,n){return e.renderTargetTextures.length>0&&e.isBackground===t&&e.renderTargetTextures.indexOf(n)>-1&&0!=(e.layerMask&i)},e.prototype._drawRenderTargetBackground=function(e){var t=this;this._draw(function(i){return t._drawRenderTargetPredicate(i,!0,t.scene.activeCamera.layerMask,e)})},e.prototype._drawRenderTargetForeground=function(e){var t=this;this._draw(function(i){return t._drawRenderTargetPredicate(i,!1,t.scene.activeCamera.layerMask,e)})},e.prototype.addFromContainer=function(e){var t=this;e.layers&&e.layers.forEach(function(e){t.scene.layers.push(e)})},e.prototype.removeFromContainer=function(e,t){var i=this;void 0===t&&(t=!1),e.layers&&e.layers.forEach(function(e){var n=i.scene.layers.indexOf(e);-1!==n&&i.scene.layers.splice(n,1),t&&e.dispose()})},e}(),Va="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\n\n#include<helperFunctions>\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef LINEAR\nbaseColor.rgb=toGammaSpace(baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}";ai.a.ShadersStore.layerPixelShader=Va;var ka="\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}";ai.a.ShadersStore.layerVertexShader=ka;var za=function(){function e(e,t,i,n,r){this.name=e,this.scale=new a.d(1,1),this.offset=new a.d(0,0),this.alphaBlendingMode=g.a.ALPHA_COMBINE,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this._vertexBuffers={},this.onDisposeObservable=new o.c,this.onBeforeRenderObservable=new o.c,this.onAfterRenderObservable=new o.c,this.texture=t?new et.a(t,i,!0):null,this.isBackground=void 0===n||n,this.color=void 0===r?new s.b(1,1,1,1):r,this._scene=i||R.a.LastCreatedScene;var c=this._scene._getComponent(Fe.a.NAME_LAYER);c||(c=new Ua(this._scene),this._scene._addComponent(c)),this._scene.layers.push(this);var l=this._scene.getEngine(),u=[];u.push(1,1),u.push(-1,1),u.push(-1,-1),u.push(1,-1);var h=new en.b(l,u,en.b.PositionKind,!1,!1,2);this._vertexBuffers[en.b.PositionKind]=h,this._createIndexBuffer()}return Object.defineProperty(e.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),e.prototype._createIndexBuffer=function(){var e=this._scene.getEngine(),t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)},e.prototype._rebuild=function(){var e=this._vertexBuffers[en.b.PositionKind];e&&e._rebuild(),this._createIndexBuffer()},e.prototype.render=function(){var e=this._scene.getEngine(),t="";this.alphaTest&&(t="#define ALPHATEST"),this.texture&&!this.texture.gammaSpace&&(t+="\r\n#define LINEAR"),this._previousDefines!==t&&(this._previousDefines=t,this._effect=e.createEffect("layer",[en.b.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],t));var i=this._effect;if(i&&i.isReady()&&this.texture&&this.texture.isReady()){e=this._scene.getEngine();this.onBeforeRenderObservable.notifyObservers(this),e.enableEffect(i),e.setState(!1),i.setTexture("textureSampler",this.texture),i.setMatrix("textureMatrix",this.texture.getTextureMatrix()),i.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),i.setVector2("offset",this.offset),i.setVector2("scale",this.scale),e.bindBuffers(this._vertexBuffers,this._indexBuffer,i),this.alphaTest?e.drawElementsType(Ca.a.TriangleFillMode,0,6):(e.setAlphaMode(this.alphaBlendingMode),e.drawElementsType(Ca.a.TriangleFillMode,0,6),e.setAlphaMode(g.a.ALPHA_DISABLE)),this.onAfterRenderObservable.notifyObservers(this)}},e.prototype.dispose=function(){var e=this._vertexBuffers[en.b.PositionKind];e&&(e.dispose(),this._vertexBuffers[en.b.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null),this.renderTargetTextures=[];var t=this._scene.layers.indexOf(this);this._scene.layers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()},e}(),Ga=function(){function e(e,t,i,n,r){this.size=e,this.position=t,this.alphaMode=g.a.ALPHA_ONEONE,this.color=i||new s.a(1,1,1),this.texture=n?new et.a(n,r.getScene(),!0):null,this._system=r,r.lensFlares.push(this)}return e.AddFlare=function(t,i,n,r,o){return new e(t,i,n,r,o)},e.prototype.dispose=function(){this.texture&&this.texture.dispose();var e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)},e}(),ja="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}";ai.a.ShadersStore.lensFlarePixelShader=ja;var Wa="\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}";ai.a.ShadersStore.lensFlareVertexShader=Wa;var Xa=function(){function e(t,i,n){this.name=t,this.lensFlares=new Array,this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=n||R.a.LastCreatedScene,e._SceneComponentInitialization(this._scene),this._emitter=i,this.id=t,n.lensFlareSystems.push(this),this.meshesSelectionPredicate=function(e){return n.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&0!=(e.layerMask&n.activeCamera.layerMask)};var r=n.getEngine(),o=[];o.push(1,1),o.push(-1,1),o.push(-1,-1),o.push(1,-1),this._vertexBuffers[en.b.PositionKind]=new en.b(r,o,en.b.PositionKind,!1,!1,2);var a=[];a.push(0),a.push(1),a.push(2),a.push(0),a.push(2),a.push(3),this._indexBuffer=r.createIndexBuffer(a),this._effect=r.createEffect("lensFlare",[en.b.PositionKind],["color","viewportMatrix"],["textureSampler"],"")}return Object.defineProperty(e.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e},enumerable:!0,configurable:!0}),e.prototype.getScene=function(){return this._scene},e.prototype.getEmitter=function(){return this._emitter},e.prototype.setEmitter=function(e){this._emitter=e},e.prototype.getEmitterPosition=function(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position},e.prototype.computeEffectivePosition=function(e){var t=this.getEmitterPosition();return t=a.e.Project(t,a.a.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=a.e.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder),t.z>0&&(this._positionX>e.x&&this._positionX<e.x+e.width&&this._positionY>e.y&&(this._positionY,e.y,e.height),!0)},e.prototype._isVisible=function(){if(!this._isEnabled||!this._scene.activeCamera)return!1;var e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();var i=new Ht.a(this._scene.activeCamera.globalPosition,e),n=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!n||!n.hit||n.distance>t},e.prototype.render=function(){if(!this._effect.isReady()||!this._scene.activeCamera)return!1;var e,t,i=this._scene.getEngine(),n=this._scene.activeCamera.viewport.toGlobal(i.getRenderWidth(!0),i.getRenderHeight(!0));if(!this.computeEffectivePosition(n))return!1;if(!this._isVisible())return!1;var r=(e=this._positionX<this.borderLimit+n.x?this.borderLimit+n.x-this._positionX:this._positionX>n.x+n.width-this.borderLimit?this._positionX-n.x-n.width+this.borderLimit:0)>(t=this._positionY<this.borderLimit+n.y?this.borderLimit+n.y-this._positionY:this._positionY>n.y+n.height-this.borderLimit?this._positionY-n.y-n.height+this.borderLimit:0)?e:t;(r-=this.viewportBorder)>this.borderLimit&&(r=this.borderLimit);var o=1-L.a.Clamp(r/this.borderLimit,0,1);if(o<0)return!1;o>1&&(o=1),this.viewportBorder>0&&(n.x+=this.viewportBorder,n.y+=this.viewportBorder,n.width-=2*this.viewportBorder,n.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);var s=n.x+n.width/2,c=n.y+n.height/2,l=s-this._positionX,u=c-this._positionY;i.enableEffect(this._effect),i.setState(!1),i.setDepthBuffer(!1),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect);for(var h=0;h<this.lensFlares.length;h++){var d=this.lensFlares[h];if(!d.texture||d.texture.isReady()){i.setAlphaMode(d.alphaMode);var f=s-l*d.position,p=c-u*d.position,_=d.size,m=d.size*i.getAspectRatio(this._scene.activeCamera,!0),v=f/(n.width+2*n.x)*2-1,y=1-p/(n.height+2*n.y)*2,b=a.a.FromValues(_/2,0,0,0,0,m/2,0,0,0,0,1,0,v,y,0,1);this._effect.setMatrix("viewportMatrix",b),this._effect.setTexture("textureSampler",d.texture),this._effect.setFloat4("color",d.color.r*o,d.color.g*o,d.color.b*o,1),i.drawElementsType(Ca.a.TriangleFillMode,0,6)}}return i.setDepthBuffer(!0),i.setAlphaMode(g.a.ALPHA_DISABLE),!0},e.prototype.dispose=function(){var e=this._vertexBuffers[en.b.PositionKind];for(e&&(e.dispose(),this._vertexBuffers[en.b.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);this.lensFlares.length;)this.lensFlares[0].dispose();var t=this._scene.lensFlareSystems.indexOf(this);this._scene.lensFlareSystems.splice(t,1)},e.Parse=function(t,i,n){var r=i.getLastEntryByID(t.emitterId),o=t.name||"lensFlareSystem#"+t.emitterId,a=new e(o,r,i);a.id=t.id||o,a.borderLimit=t.borderLimit;for(var c=0;c<t.flares.length;c++){var l=t.flares[c];Ga.AddFlare(l.size,l.position,s.a.FromArray(l.color),l.textureName?n+l.textureName:"",a)}return a},e.prototype.serialize=function(){var e={};e.id=this.id,e.name=this.name,e.emitterId=this.getEmitter().id,e.borderLimit=this.borderLimit,e.flares=[];for(var t=0;t<this.lensFlares.length;t++){var i=this.lensFlares[t];e.flares.push({size:i.size,position:i.position,color:i.color.asArray(),textureName:De.b.GetFilename(i.texture?i.texture.name:"")})}return e},e._SceneComponentInitialization=function(e){throw we.a.WarnImport("LensFlareSystemSceneComponent")},e}();n.a.AddParser(Fe.a.NAME_LENSFLARESYSTEM,function(e,t,i,n){if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=new Array);for(var r=0,o=e.lensFlareSystems.length;r<o;r++){var a=e.lensFlareSystems[r],s=Xa.Parse(a,t,n);i.lensFlareSystems.push(s)}}}),n.a.prototype.getLensFlareSystemByName=function(e){for(var t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].name===e)return this.lensFlareSystems[t];return null},n.a.prototype.getLensFlareSystemByID=function(e){for(var t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].id===e)return this.lensFlareSystems[t];return null},n.a.prototype.removeLensFlareSystem=function(e){var t=this.lensFlareSystems.indexOf(e);return-1!==t&&this.lensFlareSystems.splice(t,1),t},n.a.prototype.addLensFlareSystem=function(e){this.lensFlareSystems.push(e)};var Ha=function(){function e(e){this.name=Fe.a.NAME_LENSFLARESYSTEM,this.scene=e,e.lensFlareSystems=new Array}return e.prototype.register=function(){this.scene._afterCameraDrawStage.registerStep(Fe.a.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM,this,this._draw)},e.prototype.rebuild=function(){},e.prototype.addFromContainer=function(e){var t=this;e.lensFlareSystems&&e.lensFlareSystems.forEach(function(e){t.scene.addLensFlareSystem(e)})},e.prototype.removeFromContainer=function(e,t){var i=this;e.lensFlareSystems&&e.lensFlareSystems.forEach(function(e){i.scene.removeLensFlareSystem(e),t&&e.dispose()})},e.prototype.serialize=function(e){e.lensFlareSystems=[];for(var t=0,i=this.scene.lensFlareSystems;t<i.length;t++){var n=i[t];e.lensFlareSystems.push(n.serialize())}},e.prototype.dispose=function(){for(var e=this.scene.lensFlareSystems;e.length;)e[0].dispose()},e.prototype._draw=function(e){if(this.scene.lensFlaresEnabled){var t=this.scene.lensFlareSystems;De.b.StartPerformanceCounter("Lens flares",t.length>0);for(var i=0,n=t;i<n.length;i++){var r=n[i];0!=(e.layerMask&r.layerMask)&&r.render()}De.b.EndPerformanceCounter("Lens flares",t.length>0)}},e}();Xa._SceneComponentInitialization=function(e){var t=e._getComponent(Fe.a.NAME_LENSFLARESYSTEM);t||(t=new Ha(e),e._addComponent(t))};var Ya="#ifndef FLOAT\n#include<packingFunctions>\n#endif\nvarying float vDepthMetric;\n#ifdef USEDISTANCE\nuniform vec3 lightData;\nvarying vec3 vPositionW;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\n#ifdef DEPTHCLAMP\nvarying float z;\n#endif\n#include<clipPlaneFragmentDeclaration>\nvoid main(void)\n{\n#include<clipPlaneFragment>\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef DEPTHCLAMP\n#ifdef USEDISTANCE\ndepth=clamp(((length(vPositionW-lightData)+depthValues.x)/(depthValues.y))+biasAndScale.x,0.0,1.0);\n#else\ndepth=clamp(((z+depthValues.x)/(depthValues.y))+biasAndScale.x,0.0,1.0);\n#endif\ngl_FragDepth=depth;\n#elif defined(USEDISTANCE)\ndepth=(length(vPositionW-lightData)+depthValues.x)/(depthValues.y)+biasAndScale.x;\n#endif\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}";ai.a.ShadersStore.shadowMapPixelShader=Ya;var Ka="\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef USEDISTANCE\nvarying vec3 vPositionW;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef DEPTHCLAMP\nvarying float z;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n#ifdef USEDISTANCE\nvPositionW=worldPos.xyz;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n#ifdef DEPTHCLAMP\nz=gl_Position.z;\ngl_Position.z=0.0;\n#elif !defined(USEDISTANCE)\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<clipPlaneVertex>\n}";ai.a.ShadersStore.shadowMapVertexShader=Ka;var Qa="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}";ai.a.ShadersStore.depthBoxBlurPixelShader=Qa;var qa=function(){function e(t,i,n){this.onBeforeShadowMapRenderObservable=new o.c,this.onAfterShadowMapRenderObservable=new o.c,this.onBeforeShadowMapRenderMeshObservable=new o.c,this.onAfterShadowMapRenderMeshObservable=new o.c,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=e.FILTER_NONE,this._filteringQuality=e.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=a.e.Zero(),this._viewMatrix=a.a.Zero(),this._projectionMatrix=a.a.Zero(),this._transformMatrix=a.a.Zero(),this._cachedPosition=new a.e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new a.e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=a.a.Identity(),this._mapSize=t,this._light=i,this._scene=i.getScene(),i._shadowGenerator=this,e._SceneComponentInitialization(this._scene);var r=this._scene.getEngine().getCaps();n?r.textureFloatRender&&r.textureFloatLinearFiltering?this._textureType=g.a.TEXTURETYPE_FLOAT:r.textureHalfFloatRender&&r.textureHalfFloatLinearFiltering?this._textureType=g.a.TEXTURETYPE_HALF_FLOAT:this._textureType=g.a.TEXTURETYPE_UNSIGNED_INT:r.textureHalfFloatRender&&r.textureHalfFloatLinearFiltering?this._textureType=g.a.TEXTURETYPE_HALF_FLOAT:r.textureFloatRender&&r.textureFloatLinearFiltering?this._textureType=g.a.TEXTURETYPE_FLOAT:this._textureType=g.a.TEXTURETYPE_UNSIGNED_INT,this._initializeGenerator(),this._applyFilterValues()}return Object.defineProperty(e.prototype,"bias",{get:function(){return this._bias},set:function(e){this._bias=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"normalBias",{get:function(){return this._normalBias},set:function(e){this._normalBias=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"blurBoxOffset",{get:function(){return this._blurBoxOffset},set:function(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"blurScale",{get:function(){return this._blurScale},set:function(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"blurKernel",{get:function(){return this._blurKernel},set:function(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useKernelBlur",{get:function(){return this._useKernelBlur},set:function(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"depthScale",{get:function(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()},set:function(e){this._depthScale=e},enumerable:!0,configurable:!0}),e.prototype._validateFilter=function(e){return e},Object.defineProperty(e.prototype,"filter",{get:function(){return this._filter},set:function(t){if(t=this._validateFilter(t),this._light.needCube()){if(t===e.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(t===e.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(t===e.FILTER_PCF||t===e.FILTER_PCSS)return void(this.usePoissonSampling=!0)}t!==e.FILTER_PCF&&t!==e.FILTER_PCSS||1!==this._scene.getEngine().webGLVersion?this._filter!==t&&(this._filter=t,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"usePoissonSampling",{get:function(){return this.filter===e.FILTER_POISSONSAMPLING},set:function(t){var i=this._validateFilter(e.FILTER_POISSONSAMPLING);(t||this.filter===e.FILTER_POISSONSAMPLING)&&(this.filter=t?i:e.FILTER_NONE)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useExponentialShadowMap",{get:function(){return this.filter===e.FILTER_EXPONENTIALSHADOWMAP},set:function(t){var i=this._validateFilter(e.FILTER_EXPONENTIALSHADOWMAP);(t||this.filter===e.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=t?i:e.FILTER_NONE)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBlurExponentialShadowMap",{get:function(){return this.filter===e.FILTER_BLUREXPONENTIALSHADOWMAP},set:function(t){var i=this._validateFilter(e.FILTER_BLUREXPONENTIALSHADOWMAP);(t||this.filter===e.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=t?i:e.FILTER_NONE)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useCloseExponentialShadowMap",{get:function(){return this.filter===e.FILTER_CLOSEEXPONENTIALSHADOWMAP},set:function(t){var i=this._validateFilter(e.FILTER_CLOSEEXPONENTIALSHADOWMAP);(t||this.filter===e.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=t?i:e.FILTER_NONE)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBlurCloseExponentialShadowMap",{get:function(){return this.filter===e.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP},set:function(t){var i=this._validateFilter(e.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(t||this.filter===e.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=t?i:e.FILTER_NONE)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"usePercentageCloserFiltering",{get:function(){return this.filter===e.FILTER_PCF},set:function(t){var i=this._validateFilter(e.FILTER_PCF);(t||this.filter===e.FILTER_PCF)&&(this.filter=t?i:e.FILTER_NONE)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"filteringQuality",{get:function(){return this._filteringQuality},set:function(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useContactHardeningShadow",{get:function(){return this.filter===e.FILTER_PCSS},set:function(t){var i=this._validateFilter(e.FILTER_PCSS);(t||this.filter===e.FILTER_PCSS)&&(this.filter=t?i:e.FILTER_NONE)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"contactHardeningLightSizeUVRatio",{get:function(){return this._contactHardeningLightSizeUVRatio},set:function(e){this._contactHardeningLightSizeUVRatio=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"darkness",{get:function(){return this._darkness},set:function(e){this.setDarkness(e)},enumerable:!0,configurable:!0}),e.prototype.getDarkness=function(){return this._darkness},e.prototype.setDarkness=function(e){return this._darkness=e>=1?1:e<=0?0:e,this},Object.defineProperty(e.prototype,"transparencyShadow",{get:function(){return this._transparencyShadow},set:function(e){this.setTransparencyShadow(e)},enumerable:!0,configurable:!0}),e.prototype.setTransparencyShadow=function(e){return this._transparencyShadow=e,this},e.prototype.getShadowMap=function(){return this._shadowMap},e.prototype.getShadowMapForRendering=function(){return this._shadowMap2?this._shadowMap2:this._shadowMap},e.prototype.getClassName=function(){return e.CLASSNAME},e.prototype.addShadowCaster=function(e,t){var i;return void 0===t&&(t=!0),this._shadowMap?(this._shadowMap.renderList||(this._shadowMap.renderList=[]),this._shadowMap.renderList.push(e),t&&(i=this._shadowMap.renderList).push.apply(i,e.getChildMeshes()),this):this},e.prototype.removeShadowCaster=function(e,t){if(void 0===t&&(t=!0),!this._shadowMap||!this._shadowMap.renderList)return this;var i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(var n=0,r=e.getChildren();n<r.length;n++){var o=r[n];this.removeShadowCaster(o)}return this},e.prototype.getLight=function(){return this._light},e.prototype._initializeGenerator=function(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()},e.prototype._createTargetRenderTexture=function(){this._scene.getEngine().webGLVersion>1?(this._shadowMap=new Fi(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1),this._shadowMap.createDepthStencilTexture(g.a.LESS,!0)):this._shadowMap=new Fi(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube())},e.prototype._initializeShadowMap=function(){var t=this;if(this._createTargetRenderTexture(),null!==this._shadowMap){this._shadowMap.wrapU=et.a.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=et.a.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(et.a.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=this._renderForShadowMap.bind(this);var i=this._scene.getEngine();this._shadowMap.onBeforeRenderObservable.add(function(n){t._currentFaceIndex=n,t._filter===e.FILTER_PCF&&i.setColorWrite(!1)}),this._shadowMap.onAfterUnbindObservable.add(function(){if(t._filter===e.FILTER_PCF&&i.setColorWrite(!0),t.useBlurExponentialShadowMap||t.useBlurCloseExponentialShadowMap){var n=t.getShadowMapForRendering();n&&t._scene.postProcessManager.directRender(t._blurPostProcesses,n.getInternalTexture(),!0)}});var n=new s.b(0,0,0,0),r=new s.b(1,1,1,1);this._shadowMap.onClearObservable.add(function(i){t._filter===e.FILTER_PCF?i.clear(r,!1,!0,!1):t.useExponentialShadowMap||t.useBlurExponentialShadowMap?i.clear(n,!0,!0,!1):i.clear(r,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(function(e){t._storedUniqueId=t._shadowMap.uniqueId,t._mapSize=e.getRenderSize(),t._light._markMeshesAsLightDirty(),t.recreateShadowMap()});for(var o=Ni.b.MIN_RENDERINGGROUPS;o<Ni.b.MAX_RENDERINGGROUPS;o++)this._shadowMap.setRenderingAutoClearDepthStencil(o,!1)}},e.prototype._initializeBlurRTTAndPostProcesses=function(){var e=this,t=this._scene.getEngine(),i=this._mapSize/this.blurScale;this.useKernelBlur&&1===this.blurScale||(this._shadowMap2=new Fi(this._light.name+"_shadowMap2",i,this._scene,!1,!0,this._textureType),this._shadowMap2.wrapU=et.a.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=et.a.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(et.a.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new Zr(this._light.name+"KernelBlurX",new a.d(1,0),this.blurKernel,1,null,et.a.BILINEAR_SAMPLINGMODE,t,!1,this._textureType),this._kernelBlurXPostprocess.width=i,this._kernelBlurXPostprocess.height=i,this._kernelBlurXPostprocess.onApplyObservable.add(function(t){t.setTexture("textureSampler",e._shadowMap)}),this._kernelBlurYPostprocess=new Zr(this._light.name+"KernelBlurY",new a.d(0,1),this.blurKernel,1,null,et.a.BILINEAR_SAMPLINGMODE,t,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===g.a.TEXTURETYPE_UNSIGNED_INT&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new ui(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,et.a.BILINEAR_SAMPLINGMODE,t,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.onApplyObservable.add(function(t){t.setFloat2("screenSize",i,i),t.setTexture("textureSampler",e._shadowMap)}),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])},e.prototype._renderForShadowMap=function(e,t,i,n){var r,o=this._scene.getEngine(),a=o.getColorWrite();if(n.length){for(o.setColorWrite(!1),r=0;r<n.length;r++)this._renderSubMeshForShadowMap(n.data[r]);o.setColorWrite(a)}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])},e.prototype._bindCustomEffectForRenderSubMeshForShadowMap=function(e,t){},e.prototype._renderSubMeshForShadowMap=function(e){var t=this,i=e.getRenderingMesh(),n=this._scene,r=n.getEngine(),o=e.getMaterial();if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,o&&0!==e.verticesCount){r.setState(o.backFaceCulling);var a=i._getInstancesRenderList(e._id);if(!a.mustReturn){var s=r.getCaps().instancedArrays&&null!==a.visibleInstances[e._id]&&void 0!==a.visibleInstances[e._id];if(this.isReady(e,s)){if(r.enableEffect(this._effect),i._bind(e,this._effect,o.fillMode),this._effect.setFloat3("biasAndScale",this.bias,this.normalBias,this.depthScale),this._effect.setMatrix("viewProjection",this.getTransformMatrix()),this.getLight().getTypeID()===kr.a.LIGHTTYPEID_DIRECTIONALLIGHT?this._effect.setVector3("lightData",this._cachedDirection):this._effect.setVector3("lightData",this._cachedPosition),n.activeCamera&&this._effect.setFloat2("depthValues",this.getLight().getDepthMinZ(n.activeCamera),this.getLight().getDepthMinZ(n.activeCamera)+this.getLight().getDepthMaxZ(n.activeCamera)),o&&o.needAlphaTesting()){var c=o.getAlphaTestTexture();c&&(this._effect.setTexture("diffuseSampler",c),this._effect.setMatrix("diffuseMatrix",c.getTextureMatrix()||this._defaultTextureMatrix))}if(i.useBones&&i.computeBonesUsingShaders&&i.skeleton){var l=i.skeleton;if(l.isUsingTextureForMatrices){var u=l.getTransformMatrixTexture(i);if(!u)return;this._effect.setTexture("boneSampler",u),this._effect.setFloat("boneTextureWidth",4*(l.bones.length+1))}else this._effect.setMatrices("mBones",l.getTransformMatrices(i))}io.a.BindMorphTargetParameters(i,this._effect),io.a.BindClipPlane(this._effect,n),this._bindCustomEffectForRenderSubMeshForShadowMap(e,this._effect),this.forceBackFacesOnly&&r.setState(!0,0,!1,!0),this.onBeforeShadowMapRenderMeshObservable.notifyObservers(i),this.onBeforeShadowMapRenderObservable.notifyObservers(this._effect),i._processRendering(e,this._effect,o.fillMode,a,s,function(e,i){return t._effect.setMatrix("world",i)}),this.forceBackFacesOnly&&r.setState(!0,0,!1,!1),this.onAfterShadowMapRenderObservable.notifyObservers(this._effect),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}}},e.prototype._applyFilterValues=function(){this._shadowMap&&(this.filter===e.FILTER_NONE||this.filter===e.FILTER_PCSS?this._shadowMap.updateSamplingMode(et.a.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(et.a.BILINEAR_SAMPLINGMODE))},e.prototype.forceCompilation=function(e,t){var i=this,n=Object(h.a)({useInstances:!1},t),r=this.getShadowMap();if(r){var o=r.renderList;if(o){for(var a=new Array,s=0,c=o;s<c.length;s++){var l=c[s];a.push.apply(a,l.subMeshes)}if(0!==a.length){var u=0,d=function(){if(i._scene&&i._scene.getEngine()){for(;i.isReady(a[u],n.useInstances);)if(++u>=a.length)return void(e&&e(i));setTimeout(d,16)}};d()}else e&&e(this)}else e&&e(this)}else e&&e(this)},e.prototype.forceCompilationAsync=function(e){var t=this;return new Promise(function(i){t.forceCompilation(function(){i()},e)})},e.prototype._isReadyCustomDefines=function(e,t,i){},e.prototype.isReady=function(e,t){var i=[];this._textureType!==g.a.TEXTURETYPE_UNSIGNED_INT&&i.push("#define FLOAT"),this.useExponentialShadowMap||this.useBlurExponentialShadowMap?i.push("#define ESM"):(this.usePercentageCloserFiltering||this.useContactHardeningShadow)&&i.push("#define DEPTHTEXTURE");var n=[en.b.PositionKind],r=e.getMesh(),o=e.getMaterial();if(this.normalBias&&r.isVerticesDataPresent(en.b.NormalKind)&&(n.push(en.b.NormalKind),i.push("#define NORMAL"),r.nonUniformScaling&&i.push("#define NONUNIFORMSCALING"),this.getLight().getTypeID()===kr.a.LIGHTTYPEID_DIRECTIONALLIGHT&&i.push("#define DIRECTIONINLIGHTDATA")),o&&o.needAlphaTesting()){var a=o.getAlphaTestTexture();a&&(i.push("#define ALPHATEST"),r.isVerticesDataPresent(en.b.UVKind)&&(n.push(en.b.UVKind),i.push("#define UV1")),r.isVerticesDataPresent(en.b.UV2Kind)&&1===a.coordinatesIndex&&(n.push(en.b.UV2Kind),i.push("#define UV2")))}var s=new ho.a;if(r.useBones&&r.computeBonesUsingShaders&&r.skeleton){n.push(en.b.MatricesIndicesKind),n.push(en.b.MatricesWeightsKind),r.numBoneInfluencers>4&&(n.push(en.b.MatricesIndicesExtraKind),n.push(en.b.MatricesWeightsExtraKind));var c=r.skeleton;i.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),r.numBoneInfluencers>0&&s.addCPUSkinningFallback(0,r),c.isUsingTextureForMatrices?i.push("#define BONETEXTURE"):i.push("#define BonesPerMesh "+(c.bones.length+1))}else i.push("#define NUM_BONE_INFLUENCERS 0");var l=r.morphTargetManager,u=0;l&&l.numInfluencers>0&&(i.push("#define MORPHTARGETS"),u=l.numInfluencers,i.push("#define NUM_MORPH_INFLUENCERS "+u),io.a.PrepareAttributesForMorphTargetsInfluencers(n,r,u));var h=this._scene;if(h.clipPlane&&i.push("#define CLIPPLANE"),h.clipPlane2&&i.push("#define CLIPPLANE2"),h.clipPlane3&&i.push("#define CLIPPLANE3"),h.clipPlane4&&i.push("#define CLIPPLANE4"),h.clipPlane5&&i.push("#define CLIPPLANE5"),h.clipPlane6&&i.push("#define CLIPPLANE6"),t&&(i.push("#define INSTANCES"),io.a.PushAttributesForInstances(n)),this.customShaderOptions&&this.customShaderOptions.defines)for(var d=0,f=this.customShaderOptions.defines;d<f.length;d++){var p=f[d];-1===i.indexOf(p)&&i.push(p)}this._light.needCube()&&i.push("#define USEDISTANCE"),this._isReadyCustomDefines(i,e,t);var _=i.join("\n");if(this._cachedDefines!==_){this._cachedDefines=_;var m="shadowMap",v=["world","mBones","viewProjection","diffuseMatrix","lightData","depthValues","biasAndScale","morphTargetInfluences","boneTextureWidth","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6"],y=["diffuseSampler","boneSampler"];if(this.customShaderOptions){if(m=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(var b=0,T=this.customShaderOptions.attributes;b<T.length;b++){var E=T[b];-1===n.indexOf(E)&&n.push(E)}if(this.customShaderOptions.uniforms)for(var x=0,P=this.customShaderOptions.uniforms;x<P.length;x++){var A=P[x];-1===v.indexOf(A)&&v.push(A)}if(this.customShaderOptions.samplers)for(var S=0,C=this.customShaderOptions.samplers;S<C.length;S++){var R=C[S];-1===y.indexOf(R)&&y.push(R)}}this._effect=this._scene.getEngine().createEffect(m,n,v,y,_,s,void 0,void 0,{maxSimultaneousMorphTargets:u})}return!!this._effect.isReady()&&((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())))},e.prototype.prepareDefines=function(t,i){var n=this._scene,r=this._light;n.shadowsEnabled&&r.shadowEnabled&&(t["SHADOW"+i]=!0,this.useContactHardeningShadow?(t["SHADOWPCSS"+i]=!0,this._filteringQuality===e.QUALITY_LOW?t["SHADOWLOWQUALITY"+i]=!0:this._filteringQuality===e.QUALITY_MEDIUM&&(t["SHADOWMEDIUMQUALITY"+i]=!0)):this.usePercentageCloserFiltering?(t["SHADOWPCF"+i]=!0,this._filteringQuality===e.QUALITY_LOW?t["SHADOWLOWQUALITY"+i]=!0:this._filteringQuality===e.QUALITY_MEDIUM&&(t["SHADOWMEDIUMQUALITY"+i]=!0)):this.usePoissonSampling?t["SHADOWPOISSON"+i]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?t["SHADOWESM"+i]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(t["SHADOWCLOSEESM"+i]=!0),r.needCube()&&(t["SHADOWCUBE"+i]=!0))},e.prototype.bindShadowLight=function(t,i){var n=this._light,r=this._scene;if(r.shadowsEnabled&&n.shadowEnabled){var o=r.activeCamera;if(o){var a=this.getShadowMap();a&&(n.needCube()||i.setMatrix("lightMatrix"+t,this.getTransformMatrix()),this._filter===e.FILTER_PCF?(i.setDepthStencilTexture("shadowSampler"+t,this.getShadowMapForRendering()),n._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a.getSize().width,1/a.getSize().width,this.frustumEdgeFalloff,t)):this._filter===e.FILTER_PCSS?(i.setDepthStencilTexture("shadowSampler"+t,this.getShadowMapForRendering()),i.setTexture("depthSampler"+t,this.getShadowMapForRendering()),n._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/a.getSize().width,this._contactHardeningLightSizeUVRatio*a.getSize().width,this.frustumEdgeFalloff,t)):(i.setTexture("shadowSampler"+t,this.getShadowMapForRendering()),n._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/a.getSize().width,this.depthScale,this.frustumEdgeFalloff,t)),n._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(o),this.getLight().getDepthMinZ(o)+this.getLight().getDepthMaxZ(o),t))}}},e.prototype.getTransformMatrix=function(){var e=this._scene;if(this._currentRenderID===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderID=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;var t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),a.e.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(a.e.Dot(this._lightDirection,a.e.Up()))&&(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),a.a.LookAtLHToRef(t,t.add(this._lightDirection),a.e.Up(),this._viewMatrix);var i=this.getShadowMap();if(i){var n=i.renderList;n&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,n)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix},e.prototype.recreateShadowMap=function(){var e=this._shadowMap;if(e){var t=e.renderList;this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this.filter,this._applyFilterValues(),this._shadowMap.renderList=t}},e.prototype._disposeBlurPostProcesses=function(){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=[]},e.prototype._disposeRTTandPostProcesses=function(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()},e.prototype.dispose=function(){this._disposeRTTandPostProcesses(),this._light&&(this._light._shadowGenerator=null,this._light._markMeshesAsLightDirty()),this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()},e.prototype.serialize=function(){var e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.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(var i=0;i<t.renderList.length;i++){var n=t.renderList[i];e.renderList.push(n.id)}return e},e.Parse=function(t,i,n){for(var r=i.getLightByID(t.lightId),o=n?n(t.mapSize,r):new e(t.mapSize,r),a=o.getShadowMap(),s=0;s<t.renderList.length;s++){i.getMeshesByID(t.renderList[s]).forEach(function(e){a&&(a.renderList||(a.renderList=[]),a.renderList.push(e))})}return o.forceBackFacesOnly=!!t.forceBackFacesOnly,void 0!==t.darkness&&o.setDarkness(t.darkness),t.transparencyShadow&&o.setTransparencyShadow(!0),void 0!==t.frustumEdgeFalloff&&(o.frustumEdgeFalloff=t.frustumEdgeFalloff),void 0!==t.bias&&(o.bias=t.bias),void 0!==t.normalBias&&(o.normalBias=t.normalBias),t.usePercentageCloserFiltering?o.usePercentageCloserFiltering=!0:t.useContactHardeningShadow?o.useContactHardeningShadow=!0:t.usePoissonSampling?o.usePoissonSampling=!0:t.useExponentialShadowMap?o.useExponentialShadowMap=!0:t.useBlurExponentialShadowMap?o.useBlurExponentialShadowMap=!0:t.useCloseExponentialShadowMap?o.useCloseExponentialShadowMap=!0:t.useBlurCloseExponentialShadowMap?o.useBlurCloseExponentialShadowMap=!0:t.useVarianceShadowMap?o.useExponentialShadowMap=!0:t.useBlurVarianceShadowMap&&(o.useBlurExponentialShadowMap=!0),void 0!==t.contactHardeningLightSizeUVRatio&&(o.contactHardeningLightSizeUVRatio=t.contactHardeningLightSizeUVRatio),void 0!==t.filteringQuality&&(o.filteringQuality=t.filteringQuality),t.depthScale&&(o.depthScale=t.depthScale),t.blurScale&&(o.blurScale=t.blurScale),t.blurBoxOffset&&(o.blurBoxOffset=t.blurBoxOffset),t.useKernelBlur&&(o.useKernelBlur=t.useKernelBlur),t.blurKernel&&(o.blurKernel=t.blurKernel),o},e.CLASSNAME="ShadowGenerator",e.FILTER_NONE=0,e.FILTER_EXPONENTIALSHADOWMAP=1,e.FILTER_POISSONSAMPLING=2,e.FILTER_BLUREXPONENTIALSHADOWMAP=3,e.FILTER_CLOSEEXPONENTIALSHADOWMAP=4,e.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP=5,e.FILTER_PCF=6,e.FILTER_PCSS=7,e.QUALITY_HIGH=0,e.QUALITY_MEDIUM=1,e.QUALITY_LOW=2,e._SceneComponentInitialization=function(e){throw we.a.WarnImport("ShadowGeneratorSceneComponent")},e}(),Za="#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\n#ifdef PACKED\n#include<packingFunctions>\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\n#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\n#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n}";ai.a.ShadersStore.depthPixelShader=Za;var Ja="\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n";ai.a.ShadersStore.depthVertexShader=Ja;var $a=function(){function e(t,i,n,r){var o=this;void 0===i&&(i=g.a.TEXTURETYPE_FLOAT),void 0===n&&(n=null),void 0===r&&(r=!1),this.enabled=!0,this.useOnlyInActiveCamera=!1,this._scene=t,this._storeNonLinearDepth=r,this.isPacked=i===g.a.TEXTURETYPE_UNSIGNED_BYTE,this.isPacked?this._clearColor=new s.b(1,1,1,1):this._clearColor=new s.b(1,0,0,1),e._SceneComponentInitialization(this._scene),this._camera=n;var a=t.getEngine(),c=this.isPacked||1===a.webGLVersion?g.a.TEXTUREFORMAT_RGBA:g.a.TEXTUREFORMAT_R;this._depthMap=new Fi("depthMap",{width:a.getRenderWidth(),height:a.getRenderHeight()},this._scene,!1,!0,i,!1,void 0,void 0,void 0,void 0,c),this._depthMap.wrapU=et.a.CLAMP_ADDRESSMODE,this._depthMap.wrapV=et.a.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add(function(e){e.clear(o._clearColor,!0,!0,!0)});var l=function(e){var t=e.getRenderingMesh(),i=o._scene,n=i.getEngine(),r=e.getMaterial();if(t._internalAbstractMeshDataInfo._isActiveIntermediate=!1,r){n.setState(r.backFaceCulling,0,!1,i.useRightHandedSystem);var a=t._getInstancesRenderList(e._id);if(!a.mustReturn){var s=n.getCaps().instancedArrays&&null!==a.visibleInstances[e._id],c=o._camera||i.activeCamera;if(o.isReady(e,s)&&c){if(n.enableEffect(o._effect),t._bind(e,o._effect,r.fillMode),o._effect.setMatrix("viewProjection",i.getTransformMatrix()),o._effect.setFloat2("depthValues",c.minZ,c.minZ+c.maxZ),r&&r.needAlphaTesting()){var l=r.getAlphaTestTexture();l&&(o._effect.setTexture("diffuseSampler",l),o._effect.setMatrix("diffuseMatrix",l.getTextureMatrix()))}t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&o._effect.setMatrices("mBones",t.skeleton.getTransformMatrices(t)),io.a.BindMorphTargetParameters(t,o._effect),t._processRendering(e,o._effect,r.fillMode,a,s,function(e,t){return o._effect.setMatrix("world",t)})}}}};this._depthMap.customRenderFunction=function(e,t,i,n){var r;if(n.length){for(a.setColorWrite(!1),r=0;r<n.length;r++)l(n.data[r]);a.setColorWrite(!0)}for(r=0;r<e.length;r++)l(e.data[r]);for(r=0;r<t.length;r++)l(t.data[r])}}return e.prototype.isReady=function(e,t){var i=e.getMaterial();if(i.disableDepthWrite)return!1;var n=[],r=[en.b.PositionKind],o=e.getMesh();i&&i.needAlphaTesting()&&i.getAlphaTestTexture()&&(n.push("#define ALPHATEST"),o.isVerticesDataPresent(en.b.UVKind)&&(r.push(en.b.UVKind),n.push("#define UV1")),o.isVerticesDataPresent(en.b.UV2Kind)&&(r.push(en.b.UV2Kind),n.push("#define UV2"))),o.useBones&&o.computeBonesUsingShaders?(r.push(en.b.MatricesIndicesKind),r.push(en.b.MatricesWeightsKind),o.numBoneInfluencers>4&&(r.push(en.b.MatricesIndicesExtraKind),r.push(en.b.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),n.push("#define BonesPerMesh "+(o.skeleton?o.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0");var a=o.morphTargetManager,s=0;a&&a.numInfluencers>0&&(s=a.numInfluencers,n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+s),io.a.PrepareAttributesForMorphTargetsInfluencers(r,o,s)),t&&(n.push("#define INSTANCES"),io.a.PushAttributesForInstances(r)),this._storeNonLinearDepth&&n.push("#define NONLINEARDEPTH"),this.isPacked&&n.push("#define PACKED");var c=n.join("\n");return this._cachedDefines!==c&&(this._cachedDefines=c,this._effect=this._scene.getEngine().createEffect("depth",r,["world","mBones","viewProjection","diffuseMatrix","depthValues","morphTargetInfluences"],["diffuseSampler"],c,void 0,void 0,void 0,{maxSimultaneousMorphTargets:s})),this._effect.isReady()},e.prototype.getDepthMap=function(){return this._depthMap},e.prototype.dispose=function(){this._depthMap.dispose()},e._SceneComponentInitialization=function(e){throw we.a.WarnImport("DepthRendererSceneComponent")},e}(),es="attribute vec2 vUV;\nuniform sampler2D textureSampler;\n#if defined(INITIAL)\nuniform sampler2D sourceTexture;\nuniform vec2 texSize;\nvoid main(void)\n{\nivec2 coord=ivec2(vUV*(texSize-1.0));\nfloat f1=texelFetch(sourceTexture,coord,0).r;\nfloat f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;\nfloat f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;\nfloat f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;\nfloat minz=min(min(min(f1,f2),f3),f4);\n#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\n#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\n#endif\nglFragColor=vec4(minz,maxz,0.,0.);\n}\n#elif defined(MAIN)\nuniform vec2 texSize;\nvoid main(void)\n{\nivec2 coord=ivec2(vUV*(texSize-1.0));\nvec2 f1=texelFetch(textureSampler,coord,0).rg;\nvec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;\nvec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;\nvec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;\nfloat minz=min(min(min(f1.x,f2.x),f3.x),f4.x);\nfloat maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);\nglFragColor=vec4(minz,maxz,0.,0.);\n}\n#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;\nvoid main(void)\n{\nivec2 coord=ivec2(vUV*vec2(texSize-1));\nvec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;\nvec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;\nvec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;\nvec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;\nfloat minz=min(f1.x,f2.x);\nfloat maxz=max(f1.y,f2.y);\nglFragColor=vec4(minz,maxz,0.,0.);\n}\n#elif defined(LAST)\nvoid main(void)\n{\ndiscard;\nglFragColor=vec4(0.);\n}\n#endif\n";ai.a.ShadersStore.minmaxReduxPixelShader=es;var ts=function(){function e(e){this.onAfterReductionPerformed=new o.c,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new Li.a(e.getScene())}return Object.defineProperty(e.prototype,"sourceTexture",{get:function(){return this._sourceTexture},enumerable:!0,configurable:!0}),e.prototype.setSourceTexture=function(e,t,i,n){var r=this;if(void 0===i&&(i=g.a.TEXTURETYPE_HALF_FLOAT),void 0===n&&(n=!0),e!==this._sourceTexture){this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=n;var o=this._camera.getScene(),a=new ui("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,g.a.TEXTURE_NEAREST_NEAREST,o.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,g.a.TEXTUREFORMAT_RG);a.autoClear=!1,a.forceFullscreenViewport=n;var s=this._sourceTexture.getRenderWidth(),c=this._sourceTexture.getRenderHeight();a.onApply=function(e,t){return function(i){i.setTexture("sourceTexture",r._sourceTexture),i.setFloatArray2("texSize",new Float32Array([e,t]))}}(s,c),this._reductionSteps.push(a);for(var l=1;s>1||c>1;){s=Math.max(Math.round(s/2),1),c=Math.max(Math.round(c/2),1);var u=new ui("Reduction phase "+l,"minmaxRedux",["texSize"],null,{width:s,height:c},null,g.a.TEXTURE_NEAREST_NEAREST,o.getEngine(),!1,"#define "+(1==s&&1==c?"LAST":1==s||1==c?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,g.a.TEXTUREFORMAT_RG);if(u.autoClear=!1,u.forceFullscreenViewport=n,u.onApply=function(e,t){return function(i){1==e||1==t?i.setIntArray2("texSize",new Int32Array([e,t])):i.setFloatArray2("texSize",new Float32Array([e,t]))}}(s,c),this._reductionSteps.push(u),l++,1==s&&1==c){u.onAfterRenderObservable.add(function(e,t,i){var n=new Float32Array(4*e*t),a={min:0,max:0};return function(){o.getEngine()._readTexturePixels(i.inputTexture,e,t,-1,0,n),a.min=n[0],a.max=n[1],r.onAfterReductionPerformed.notifyObservers(a)}}(s,c,u))}}}},Object.defineProperty(e.prototype,"refreshRate",{get:function(){return this._sourceTexture?this._sourceTexture.refreshRate:-1},set:function(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activated",{get:function(){return this._activated},enumerable:!0,configurable:!0}),e.prototype.activate=function(){var e=this;!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add(function(){e._reductionSteps[0].activate(e._camera),e._postProcessManager.directRender(e._reductionSteps,e._reductionSteps[0].inputTexture,e._forceFullscreenViewport),e._camera.getScene().getEngine().unBindFramebuffer(e._reductionSteps[0].inputTexture,!1)}),this._activated=!0)},e.prototype.deactivate=function(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)},e.prototype.dispose=function(e){if(void 0===e&&(e=!0),e&&this.onAfterReductionPerformed.clear(),this.deactivate(),this._reductionSteps){for(var t=0;t<this._reductionSteps.length;++t)this._reductionSteps[t].dispose();this._reductionSteps=null}this._postProcessManager&&e&&this._postProcessManager.dispose(),this._sourceTexture=null},e}(),is=function(e){function t(t){return e.call(this,t)||this}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"depthRenderer",{get:function(){return this._depthRenderer},enumerable:!0,configurable:!0}),t.prototype.setDepthRenderer=function(t,i,n){void 0===t&&(t=null),void 0===i&&(i=g.a.TEXTURETYPE_HALF_FLOAT),void 0===n&&(n=!0);var r=this._camera.getScene();this._depthRenderer&&(delete r._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null),null===t&&(r._depthRenderer||(r._depthRenderer={}),(t=this._depthRenderer=new $a(r,i,this._camera,!1)).enabled=!1,this._depthRendererId="minmax"+this._camera.id,r._depthRenderer[this._depthRendererId]=t),e.prototype.setSourceTexture.call(this,t.getDepthMap(),!0,i,n)},t.prototype.setSourceTexture=function(t,i,n,r){void 0===n&&(n=g.a.TEXTURETYPE_HALF_FLOAT),void 0===r&&(r=!0),e.prototype.setSourceTexture.call(this,t,i,n,r)},t.prototype.activate=function(){this._depthRenderer&&(this._depthRenderer.enabled=!0),e.prototype.activate.call(this)},t.prototype.deactivate=function(){e.prototype.deactivate.call(this),this._depthRenderer&&(this._depthRenderer.enabled=!1)},t.prototype.dispose=function(t){var i;void 0===t&&(t=!0),e.prototype.dispose.call(this,t),this._depthRenderer&&t&&(null===(i=this._depthRenderer.getDepthMap().getScene())||void 0===i||i._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null)},t}(ts),ns=a.e.Up(),rs=a.e.Zero(),os=new a.e,as=new a.e,ss=new a.a,cs=function(e){function t(t,i,n){var r=e.call(this,t,i,n)||this;if(1==r._scene.getEngine().webGLVersion)throw"CSM can only be used in WebGL2";return r.usePercentageCloserFiltering=!0,r}return Object(h.d)(t,e),t.prototype._validateFilter=function(e){return e===qa.FILTER_NONE||e===qa.FILTER_PCF||e===qa.FILTER_PCSS?e:(console.error('Unsupported filter "'+e+'"!'),qa.FILTER_NONE)},Object.defineProperty(t.prototype,"numCascades",{get:function(){return this._numCascades},set:function(e){(e=Math.min(Math.max(e,t.MIN_CASCADES_COUNT),t.MAX_CASCADES_COUNT))!==this._numCascades&&(this._numCascades=e,this.recreateShadowMap())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"freezeShadowCastersBoundingInfo",{get:function(){return this._freezeShadowCastersBoundingInfo},set:function(e){this._freezeShadowCastersBoundingInfoObservable&&e&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._freezeShadowCastersBoundingInfoObservable||e||(this._freezeShadowCastersBoundingInfoObservable=this._scene.onBeforeRenderObservable.add(this._computeShadowCastersBoundingInfo.bind(this))),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()},enumerable:!0,configurable:!0}),t.prototype._computeShadowCastersBoundingInfo=function(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(Number.MIN_VALUE,Number.MIN_VALUE,Number.MIN_VALUE),this._shadowMap&&this._shadowMap.renderList){for(var e=this._shadowMap.renderList,t=0;t<e.length;t++){if(r=e[t]){var i=r.getBoundingInfo().boundingBox;this._scbiMin.minimizeInPlace(i.minimumWorld),this._scbiMax.maximizeInPlace(i.maximumWorld)}}var n=this._scene.meshes;for(t=0;t<n.length;t++){var r;if((r=n[t])&&r.isVisible&&r.isEnabled&&r.receiveShadows){i=r.getBoundingInfo().boundingBox;this._scbiMin.minimizeInPlace(i.minimumWorld),this._scbiMax.maximizeInPlace(i.maximumWorld)}}}this._shadowCastersBoundingInfo.reConstruct(this._scbiMin,this._scbiMax)},Object.defineProperty(t.prototype,"shadowCastersBoundingInfo",{get:function(){return this._shadowCastersBoundingInfo},set:function(e){this._shadowCastersBoundingInfo=e},enumerable:!0,configurable:!0}),t.prototype.setMinMaxDistance=function(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)},Object.defineProperty(t.prototype,"minDistance",{get:function(){return this._minDistance},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxDistance",{get:function(){return this._maxDistance},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return t.CLASSNAME},t.prototype.getCascadeMinExtents=function(e){return e>=0&&e<this._numCascades?this._cascadeMinExtents[e]:null},t.prototype.getCascadeMaxExtents=function(e){return e>=0&&e<this._numCascades?this._cascadeMaxExtents[e]:null},Object.defineProperty(t.prototype,"shadowMaxZ",{get:function(){return this._scene&&this._scene.activeCamera?this._shadowMaxZ:0},set:function(e){this._scene&&this._scene.activeCamera?this._shadowMaxZ===e||e<this._scene.activeCamera.minZ||e>this._scene.activeCamera.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"debug",{get:function(){return this._debug},set:function(e){this._debug=e,this._light._markMeshesAsLightDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"depthClamp",{get:function(){return this._depthClamp},set:function(e){this._depthClamp=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cascadeBlendPercentage",{get:function(){return this._cascadeBlendPercentage},set:function(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"lambda",{get:function(){return this._lambda},set:function(e){var t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)},enumerable:!0,configurable:!0}),t.prototype.getCascadeViewMatrix=function(e){return e>=0&&e<this._numCascades?this._viewMatrices[e]:null},t.prototype.getCascadeProjectionMatrix=function(e){return e>=0&&e<this._numCascades?this._projectionMatrices[e]:null},t.prototype.getCascadeTransformMatrix=function(e){return e>=0&&e<this._numCascades?this._transformMatrices[e]:null},t.prototype.setDepthRenderer=function(e){this._depthRenderer=e,this._depthReducer&&this._depthReducer.setDepthRenderer(this._depthRenderer)},Object.defineProperty(t.prototype,"autoCalcDepthBounds",{get:function(){return this._autoCalcDepthBounds},set:function(e){var t=this,i=this._scene.activeCamera;if(i){if(this._autoCalcDepthBounds=e,!e)return this._depthReducer&&this._depthReducer.deactivate(),void this.setMinMaxDistance(0,1);this._depthReducer||(this._depthReducer=new is(i),this._depthReducer.onAfterReductionPerformed.add(function(e){var i=e.min,n=e.max;i>=n&&(i=0,n=1),i==t._minDistance&&n==t._maxDistance||t.setMinMaxDistance(i,n)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"autoCalcDepthBoundsRefreshRate",{get:function(){var e,t,i;return null!=(i=null===(t=null===(e=this._depthReducer)||void 0===e?void 0:e.depthRenderer)||void 0===t?void 0:t.getDepthMap().refreshRate)?i:-1},set:function(e){var t;(null===(t=this._depthReducer)||void 0===t?void 0:t.depthRenderer)&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)},enumerable:!0,configurable:!0}),t.prototype.splitFrustum=function(){this._breaksAreDirty=!0},t.prototype._splitFrustum=function(){var e=this._scene.activeCamera;if(e){for(var t=e.minZ,i=e.maxZ,n=i-t,r=this._minDistance,o=t+r*n,a=t+(this._shadowMaxZ<i&&this._shadowMaxZ>=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance)*n,s=a-o,c=a/o,l=0;l<this._cascades.length;++l){var u=(l+1)/this._numCascades,h=o*Math.pow(c,u),d=o+s*u,f=this._lambda*(h-d)+d;this._cascades[l].prevBreakDistance=0===l?r:this._cascades[l-1].breakDistance,this._cascades[l].breakDistance=(f-t)/n,this._viewSpaceFrustumsZ[l]=t+this._cascades[l].breakDistance*n,this._frustumLengths[l]=(this._cascades[l].breakDistance-this._cascades[l].prevBreakDistance)*n}this._breaksAreDirty=!1}},t.prototype._computeMatrices=function(){if(this._scene.activeCamera){a.e.NormalizeToRef(this._light.getShadowDirection(0),this._lightDirection),1===Math.abs(a.e.Dot(this._lightDirection,a.e.Up()))&&(this._lightDirection.z=1e-13),this._cachedDirection.copyFrom(this._lightDirection);for(var e=0;e<this._numCascades;++e){this._computeFrustumInWorldSpace(e),this._computeCascadeFrustum(e),this._cascadeMaxExtents[e].subtractToRef(this._cascadeMinExtents[e],os),this._frustumCenter[e].addToRef(this._lightDirection.scale(this._cascadeMinExtents[e].z),this._shadowCameraPos[e]),a.a.LookAtLHToRef(this._shadowCameraPos[e],this._frustumCenter[e],ns,this._viewMatrices[e]);var t=0,i=os.z,n=this._shadowCastersBoundingInfo;n.update(this._viewMatrices[e]),i=Math.min(i,n.boundingBox.maximumWorld.z),t=this._depthClamp&&this.filter!==qa.FILTER_PCSS?Math.max(t,n.boundingBox.minimumWorld.z):Math.min(t,n.boundingBox.minimumWorld.z),a.a.OrthoOffCenterLHToRef(this._cascadeMinExtents[e].x,this._cascadeMaxExtents[e].x,this._cascadeMinExtents[e].y,this._cascadeMaxExtents[e].y,t,i,this._projectionMatrices[e]),this._cascadeMinExtents[e].z=t,this._cascadeMaxExtents[e].z=i,this._viewMatrices[e].multiplyToRef(this._projectionMatrices[e],this._transformMatrices[e]),a.e.TransformCoordinatesToRef(rs,this._transformMatrices[e],os),os.scaleInPlace(this._mapSize/2),as.copyFromFloats(Math.round(os.x),Math.round(os.y),Math.round(os.z)),as.subtractInPlace(os).scaleInPlace(2/this._mapSize),a.a.TranslationToRef(as.x,as.y,0,ss),this._projectionMatrices[e].multiplyToRef(ss,this._projectionMatrices[e]),this._viewMatrices[e].multiplyToRef(this._projectionMatrices[e],this._transformMatrices[e]),this._transformMatrices[e].copyToArray(this._transformMatricesAsArray,16*e)}}},t.prototype._computeFrustumInWorldSpace=function(e){if(this._scene.activeCamera){var i=this._cascades[e].prevBreakDistance,n=this._cascades[e].breakDistance;this._scene.activeCamera.getViewMatrix();for(var r=a.a.Invert(this._scene.activeCamera.getTransformationMatrix()),o=0;o<t.frustumCornersNDCSpace.length;++o)a.e.TransformCoordinatesToRef(t.frustumCornersNDCSpace[o],r,this._frustumCornersWorldSpace[e][o]);for(o=0;o<t.frustumCornersNDCSpace.length/2;++o)os.copyFrom(this._frustumCornersWorldSpace[e][o+4]).subtractInPlace(this._frustumCornersWorldSpace[e][o]),as.copyFrom(os).scaleInPlace(i),os.scaleInPlace(n),os.addInPlace(this._frustumCornersWorldSpace[e][o]),this._frustumCornersWorldSpace[e][o+4].copyFrom(os),this._frustumCornersWorldSpace[e][o].addInPlace(as)}},t.prototype._computeCascadeFrustum=function(e){if(this._cascadeMinExtents[e].copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cascadeMaxExtents[e].copyFromFloats(Number.MIN_VALUE,Number.MIN_VALUE,Number.MIN_VALUE),this._frustumCenter[e].copyFromFloats(0,0,0),this._scene.activeCamera){for(var t=0;t<this._frustumCornersWorldSpace[e].length;++t)this._frustumCenter[e].addInPlace(this._frustumCornersWorldSpace[e][t]);if(this._frustumCenter[e].scaleInPlace(1/this._frustumCornersWorldSpace[e].length),this.stabilizeCascades){var i=0;for(t=0;t<this._frustumCornersWorldSpace[e].length;++t){var n=this._frustumCornersWorldSpace[e][t].subtractToRef(this._frustumCenter[e],os).length();i=Math.max(i,n)}i=Math.ceil(16*i)/16,this._cascadeMaxExtents[e].copyFromFloats(i,i,i),this._cascadeMinExtents[e].copyFromFloats(-i,-i,-i)}else{var r=this._frustumCenter[e];this._frustumCenter[e].addToRef(this._lightDirection,os),a.a.LookAtLHToRef(r,os,ns,ss);for(t=0;t<this._frustumCornersWorldSpace[e].length;++t)a.e.TransformCoordinatesToRef(this._frustumCornersWorldSpace[e][t],ss,os),this._cascadeMinExtents[e].minimizeInPlace(os),this._cascadeMaxExtents[e].maximizeInPlace(os)}}},t.prototype._initializeGenerator=function(){var i,n,r,o,s,c,l,u,h,d,f,p,_,m,g,v,y,b,T,E;this.penumbraDarkness=null!=(i=this.penumbraDarkness)?i:1,this._numCascades=null!=(n=this._numCascades)?n:t.DEFAULT_CASCADES_COUNT,this.stabilizeCascades=null!=(r=this.stabilizeCascades)&&r,this._freezeShadowCastersBoundingInfoObservable=null!=(o=this._freezeShadowCastersBoundingInfoObservable)?o:null,this.freezeShadowCastersBoundingInfo=null!=(s=this.freezeShadowCastersBoundingInfo)&&s,this._scbiMin=null!=(c=this._scbiMin)?c:new a.e(0,0,0),this._scbiMax=null!=(l=this._scbiMax)?l:new a.e(0,0,0),this._shadowCastersBoundingInfo=null!=(u=this._shadowCastersBoundingInfo)?u:new Pn.a(new a.e(0,0,0),new a.e(0,0,0)),this._breaksAreDirty=null==(h=this._breaksAreDirty)||h,this._minDistance=null!=(d=this._minDistance)?d:0,this._maxDistance=null!=(f=this._maxDistance)?f:1,this._currentLayer=null!=(p=this._currentLayer)?p:0,this._shadowMaxZ=null!=(g=null!=(_=this._shadowMaxZ)?_:null===(m=this._scene.activeCamera)||void 0===m?void 0:m.maxZ)?g:1e4,this._debug=null!=(v=this._debug)&&v,this._depthClamp=null==(y=this._depthClamp)||y,this._cascadeBlendPercentage=null!=(b=this._cascadeBlendPercentage)?b:.1,this._lambda=null!=(T=this._lambda)?T:.5,this._autoCalcDepthBounds=null!=(E=this._autoCalcDepthBounds)&&E,e.prototype._initializeGenerator.call(this)},t.prototype._createTargetRenderTexture=function(){var e={width:this._mapSize,height:this._mapSize,layers:this.numCascades};this._shadowMap=new Fi(this._light.name+"_shadowMap",e,this._scene,!1,!0,this._textureType,!1,void 0,!1,!1,void 0),this._shadowMap.createDepthStencilTexture(g.a.LESS,!0)},t.prototype._initializeShadowMap=function(){var i=this;if(e.prototype._initializeShadowMap.call(this),null!==this._shadowMap){this._transformMatricesAsArray=new Float32Array(16*this._numCascades),this._viewSpaceFrustumsZ=new Array(this._numCascades),this._frustumLengths=new Array(this._numCascades),this._lightSizeUVCorrection=new Array(2*this._numCascades),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(var n=0;n<this._numCascades;++n){this._cascades[n]={prevBreakDistance:0,breakDistance:0},this._viewMatrices[n]=a.a.Zero(),this._projectionMatrices[n]=a.a.Zero(),this._transformMatrices[n]=a.a.Zero(),this._cascadeMinExtents[n]=new a.e,this._cascadeMaxExtents[n]=new a.e,this._frustumCenter[n]=new a.e,this._shadowCameraPos[n]=new a.e,this._frustumCornersWorldSpace[n]=new Array(t.frustumCornersNDCSpace.length);for(var r=0;r<t.frustumCornersNDCSpace.length;++r)this._frustumCornersWorldSpace[n][r]=new a.e}this._shadowMap.onBeforeRenderObservable.add(function(e){i._currentLayer=e}),this._shadowMap.onBeforeBindObservable.add(function(){i._breaksAreDirty&&i._splitFrustum(),i._computeMatrices()}),this._splitFrustum()}},t.prototype._bindCustomEffectForRenderSubMeshForShadowMap=function(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))},t.prototype._isReadyCustomDefines=function(e,t,i){this._depthClamp&&this._filter!==qa.FILTER_PCSS&&e.push("#define DEPTHCLAMP")},t.prototype.prepareDefines=function(t,i){e.prototype.prepareDefines.call(this,t,i);var n=this._scene,r=this._light;if(n.shadowsEnabled&&r.shadowEnabled){t["SHADOWCSM"+i]=!0,t["SHADOWCSMDEBUG"+i]=this.debug,t["SHADOWCSMNUM_CASCADES"+i]=this.numCascades,t["SHADOWCSM_RIGHTHANDED"+i]=n.useRightHandedSystem;var o=n.activeCamera;o&&this._shadowMaxZ<o.maxZ&&(t["SHADOWCSMUSESHADOWMAXZ"+i]=!0),0===this.cascadeBlendPercentage&&(t["SHADOWCSMNOBLEND"+i]=!0)}},t.prototype.bindShadowLight=function(e,t){var i=this._light,n=this._scene;if(n.shadowsEnabled&&i.shadowEnabled){var r=n.activeCamera;if(r){var o=this.getShadowMap();if(o){var a=o.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===qa.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,o),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a,1/a,this.frustumEdgeFalloff,e);else if(this._filter===qa.FILTER_PCSS){for(var s=0;s<this._numCascades;++s)this._lightSizeUVCorrection[2*s+0]=0===s?1:(this._cascadeMaxExtents[0].x-this._cascadeMinExtents[0].x)/(this._cascadeMaxExtents[s].x-this._cascadeMinExtents[s].x),this._lightSizeUVCorrection[2*s+1]=0===s?1:(this._cascadeMaxExtents[0].y-this._cascadeMinExtents[0].y)/(this._cascadeMaxExtents[s].y-this._cascadeMinExtents[s].y),this._depthCorrection[s]=0===s?1:(this._cascadeMaxExtents[s].z-this._cascadeMinExtents[s].z)/(this._cascadeMaxExtents[0].z-this._cascadeMinExtents[0].z);t.setDepthStencilTexture("shadowSampler"+e,o),t.setTexture("depthSampler"+e,o),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("shadowSampler"+e,o),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)}}}},t.prototype.getTransformMatrix=function(){return this.getCascadeTransformMatrix(0)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._freezeShadowCastersBoundingInfoObservable&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._depthReducer&&(this._depthReducer.dispose(),this._depthReducer=null)},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this),i=this.getShadowMap();if(!i)return t;if(t.numCascades=this._numCascades,t.debug=this._debug,t.stabilizeCascades=this.stabilizeCascades,t.lambda=this._lambda,t.cascadeBlendPercentage=this.cascadeBlendPercentage,t.depthClamp=this._depthClamp,t.autoCalcDepthBounds=this.autoCalcDepthBounds,t.shadowMaxZ=this._shadowMaxZ,t.penumbraDarkness=this.penumbraDarkness,t.freezeShadowCastersBoundingInfo=this._freezeShadowCastersBoundingInfo,t.minDistance=this.minDistance,t.maxDistance=this.maxDistance,t.renderList=[],i.renderList)for(var n=0;n<i.renderList.length;n++){var r=i.renderList[n];t.renderList.push(r.id)}return t},t.Parse=function(e,i){var n=qa.Parse(e,i,function(e,i){return new t(e,i)});return void 0!==e.numCascades&&(n.numCascades=e.numCascades),void 0!==e.debug&&(n.debug=e.debug),void 0!==e.stabilizeCascades&&(n.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(n.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(n.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(n.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(n.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(n.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(n.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(n.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&n.setMinMaxDistance(e.minDistance,e.maxDistance),n},t.frustumCornersNDCSpace=[new a.e(-1,1,-1),new a.e(1,1,-1),new a.e(1,-1,-1),new a.e(-1,-1,-1),new a.e(-1,1,1),new a.e(1,1,1),new a.e(1,-1,1),new a.e(-1,-1,1)],t.CLASSNAME="CascadedShadowGenerator",t.DEFAULT_CASCADES_COUNT=4,t.MIN_CASCADES_COUNT=2,t.MAX_CASCADES_COUNT=4,t._SceneComponentInitialization=function(e){throw we.a.WarnImport("ShadowGeneratorSceneComponent")},t}(qa);n.a.AddParser(Fe.a.NAME_SHADOWGENERATOR,function(e,t){if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(var i=0,n=e.shadowGenerators.length;i<n;i++){var r=e.shadowGenerators[i];r.className===cs.CLASSNAME?cs.Parse(r,t):qa.Parse(r,t)}});var ls=function(){function e(e){this.name=Fe.a.NAME_SHADOWGENERATOR,this.scene=e}return e.prototype.register=function(){this.scene._gatherRenderTargetsStage.registerStep(Fe.a.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR,this,this._gatherRenderTargets)},e.prototype.rebuild=function(){},e.prototype.serialize=function(e){e.shadowGenerators=[];for(var t=0,i=this.scene.lights;t<i.length;t++){var n=i[t].getShadowGenerator();n&&e.shadowGenerators.push(n.serialize())}},e.prototype.addFromContainer=function(e){},e.prototype.removeFromContainer=function(e,t){},e.prototype.dispose=function(){},e.prototype._gatherRenderTargets=function(e){var t=this.scene;if(this.scene.shadowsEnabled)for(var i=0;i<t.lights.length;i++){var n=t.lights[i],r=n.getShadowGenerator();if(n.isEnabled()&&n.shadowEnabled&&r){var o=r.getShadowMap();-1!==t.textures.indexOf(o)&&e.push(o)}}},e}();qa._SceneComponentInitialization=function(e){var t=e._getComponent(Fe.a.NAME_SHADOWGENERATOR);t||(t=new ls(e),e._addComponent(t))},B.a.AddNodeConstructor("Light_Type_0",function(e,t){return function(){return new us(e,a.e.Zero(),t)}});var us=function(e){function t(t,i,n){var r=e.call(this,t,n)||this;return r._shadowAngle=Math.PI/2,r.position=i,r}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"shadowAngle",{get:function(){return this._shadowAngle},set:function(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"direction",{get:function(){return this._direction},set:function(e){var t=this.needCube();this._direction=e,this.needCube()!==t&&this._shadowGenerator&&this._shadowGenerator.recreateShadowMap()},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"PointLight"},t.prototype.getTypeID=function(){return kr.a.LIGHTTYPEID_POINTLIGHT},t.prototype.needCube=function(){return!this.direction},t.prototype.getShadowDirection=function(t){if(this.direction)return e.prototype.getShadowDirection.call(this,t);switch(t){case 0:return new a.e(1,0,0);case 1:return new a.e(-1,0,0);case 2:return new a.e(0,-1,0);case 3:return new a.e(0,1,0);case 4:return new a.e(0,0,1);case 5:return new a.e(0,0,-1)}return a.e.Zero()},t.prototype._setDefaultShadowProjectionMatrix=function(e,t,i){var n=this.getScene().activeCamera;n&&a.a.PerspectiveFovLHToRef(this.shadowAngle,1,this.getDepthMinZ(n),this.getDepthMaxZ(n),e)},t.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},t.prototype.transferToEffect=function(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this},t.prototype.transferToNodeMaterialEffect=function(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this},t.prototype.prepareLightSpecificDefines=function(e,t){e["POINTLIGHT"+t]=!0},Object(h.c)([Object(N.c)()],t.prototype,"shadowAngle",null),t}(zr),hs=function(){function e(e,t,i){var n=this;void 0===t&&(t=""),void 0===i&&(i="black"),this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=function(){var e=n._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(n._renderingCanvas).position;n._loadingDiv&&(n._loadingDiv.style.position="fixed"===t?"fixed":"absolute",n._loadingDiv.style.left=e.left+"px",n._loadingDiv.style.top=e.top+"px",n._loadingDiv.style.width=e.width+"px",n._loadingDiv.style.height=e.height+"px")}}return e.prototype.displayLoadingUI=function(){if(!this._loadingDiv){this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText;var t=document.createElement("style");t.type="text/css";t.innerHTML="@-webkit-keyframes spin1 {                    0% { -webkit-transform: rotate(0deg);}\n                    100% { -webkit-transform: rotate(360deg);}\n                }                @keyframes spin1 {                    0% { transform: rotate(0deg);}\n                    100% { transform: rotate(360deg);}\n                }",document.getElementsByTagName("head")[0].appendChild(t);var i=!!window.SVGSVGElement,n=new Image;e.DefaultLogoUrl?n.src=e.DefaultLogoUrl:n.src=i?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",n.style.position="absolute",n.style.left="40%",n.style.top="40%",n.style.width="20%",n.style.height="20%";var r=new Image;if(e.DefaultSpinnerUrl?r.src=e.DefaultSpinnerUrl:r.src=i?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",r.style.position="absolute",r.style.left="30%",r.style.top="30%",r.style.width="40%",r.style.height="40%",r.style.animation="spin1 0.75s infinite linear",r.style.webkitAnimation="spin1 0.75s infinite linear",r.style.transformOrigin="50% 50%",r.style.webkitTransformOrigin="50% 50%",!i){var o={w:16,h:18.5},a={w:30,h:30};n.style.width=o.w+"vh",n.style.height=o.h+"vh",n.style.left="calc(50% - "+o.w/2+"vh)",n.style.top="calc(50% - "+o.h/2+"vh)",r.style.width=a.w+"vh",r.style.height=a.h+"vh",r.style.left="calc(50% - "+a.w/2+"vh)",r.style.top="calc(50% - "+a.h/2+"vh)"}this._loadingDiv.appendChild(n),this._loadingDiv.appendChild(r),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}},e.prototype.hideLoadingUI=function(){var e=this;if(this._loadingDiv){this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",function(){e._loadingDiv&&(e._loadingDiv.parentElement&&e._loadingDiv.parentElement.removeChild(e._loadingDiv),window.removeEventListener("resize",e._resizeLoadingUI),e._loadingDiv=null)})}},Object.defineProperty(e.prototype,"loadingUIText",{get:function(){return this._loadingText},set:function(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"loadingUIBackgroundColor",{get:function(){return this._loadingDivBackgroundColor},set:function(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)},enumerable:!0,configurable:!0}),e.DefaultLogoUrl="",e.DefaultSpinnerUrl="",e}();Oe.a.DefaultLoadingScreenFactory=function(e){return new hs(e)};var ds=i(69),fs=i(71),ps=function(){function e(){}return e.ConvertPanoramaToCubemap=function(e,t,i,n){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(n,this.FACE_FRONT,e,t,i),back:this.CreateCubemapTexture(n,this.FACE_BACK,e,t,i),left:this.CreateCubemapTexture(n,this.FACE_LEFT,e,t,i),right:this.CreateCubemapTexture(n,this.FACE_RIGHT,e,t,i),up:this.CreateCubemapTexture(n,this.FACE_UP,e,t,i),down:this.CreateCubemapTexture(n,this.FACE_DOWN,e,t,i),size:n,type:g.a.TEXTURETYPE_FLOAT,format:g.a.TEXTUREFORMAT_RGB,gammaSpace:!1}},e.CreateCubemapTexture=function(e,t,i,n,r){for(var o=new ArrayBuffer(e*e*4*3),a=new Float32Array(o),s=t[1].subtract(t[0]).scale(1/e),c=t[3].subtract(t[2]).scale(1/e),l=1/e,u=0,h=0;h<e;h++){for(var d=t[0],f=t[2],p=0;p<e;p++){var _=f.subtract(d).scale(u).add(d);_.normalize();var m=this.CalcProjectionSpherical(_,i,n,r);a[h*e*3+3*p+0]=m.r,a[h*e*3+3*p+1]=m.g,a[h*e*3+3*p+2]=m.b,d=d.add(s),f=f.add(c)}u+=l}return a},e.CalcProjectionSpherical=function(e,t,i,n){for(var r=Math.atan2(e.z,e.x),o=Math.acos(e.y);r<-Math.PI;)r+=2*Math.PI;for(;r>Math.PI;)r-=2*Math.PI;var a=r/Math.PI,s=o/Math.PI;a=.5*a+.5;var c=Math.round(a*i);c<0?c=0:c>=i&&(c=i-1);var l=Math.round(s*n);l<0?l=0:l>=n&&(l=n-1);var u=n-l-1;return{r:t[u*i*3+3*c+0],g:t[u*i*3+3*c+1],b:t[u*i*3+3*c+2]}},e.FACE_FRONT=[new a.e(-1,-1,-1),new a.e(1,-1,-1),new a.e(-1,1,-1),new a.e(1,1,-1)],e.FACE_BACK=[new a.e(1,-1,1),new a.e(-1,-1,1),new a.e(1,1,1),new a.e(-1,1,1)],e.FACE_RIGHT=[new a.e(1,-1,-1),new a.e(1,-1,1),new a.e(1,1,-1),new a.e(1,1,1)],e.FACE_LEFT=[new a.e(-1,-1,1),new a.e(-1,-1,-1),new a.e(-1,1,1),new a.e(-1,1,-1)],e.FACE_DOWN=[new a.e(-1,1,-1),new a.e(1,1,-1),new a.e(-1,1,1),new a.e(1,1,1)],e.FACE_UP=[new a.e(-1,-1,1),new a.e(1,-1,1),new a.e(-1,-1,-1),new a.e(1,-1,-1)],e}(),_s=function(){function e(){}return e.Ldexp=function(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)},e.Rgbe2float=function(e,t,i,n,r,o){r>0?(r=this.Ldexp(1,r-136),e[o+0]=t*r,e[o+1]=i*r,e[o+2]=n*r):(e[o+0]=0,e[o+1]=0,e[o+2]=0)},e.readStringLine=function(e,t){for(var i="",n="",r=t;r<e.length-t&&"\n"!=(n=String.fromCharCode(e[r]));r++)i+=n;return i},e.RGBE_ReadHeader=function(e){var t,i,n=this.readStringLine(e,0);if("#"!=n[0]||"?"!=n[1])throw"Bad HDR Format.";var r=!1,o=!1,a=0;do{a+=n.length+1,"FORMAT=32-bit_rle_rgbe"==(n=this.readStringLine(e,a))?o=!0:0==n.length&&(r=!0)}while(!r);if(!o)throw"HDR Bad header format, unsupported FORMAT";a+=n.length+1,n=this.readStringLine(e,a);var s=/^\-Y (.*) \+X (.*)$/g.exec(n);if(!s||s.length<3)throw"HDR Bad header format, no size";if(i=parseInt(s[2]),t=parseInt(s[1]),i<8||i>32767)throw"HDR Bad header format, unsupported size";return{height:t,width:i,dataPosition:a+=n.length+1}},e.GetCubeMapTextureData=function(e,t){var i=new Uint8Array(e),n=this.RGBE_ReadHeader(i),r=this.RGBE_ReadPixels_RLE(i,n);return ps.ConvertPanoramaToCubemap(r,n.width,n.height,t)},e.RGBE_ReadPixels=function(e,t){return this.RGBE_ReadPixels_RLE(e,t)},e.RGBE_ReadPixels_RLE=function(e,t){for(var i,n,r,o,a,s=t.height,c=t.width,l=t.dataPosition,u=0,h=0,d=0,f=new ArrayBuffer(4*c),p=new Uint8Array(f),_=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(_);s>0;){if(i=e[l++],n=e[l++],r=e[l++],o=e[l++],2!=i||2!=n||128&r)throw"HDR Bad header format, not RLE";if((r<<8|o)!=c)throw"HDR Bad header format, wrong scan line width";for(u=0,d=0;d<4;d++)for(h=(d+1)*c;u<h;)if(i=e[l++],n=e[l++],i>128){if(0==(a=i-128)||a>h-u)throw"HDR Bad Format, bad scanline data (run)";for(;a-- >0;)p[u++]=n}else{if(0==(a=i)||a>h-u)throw"HDR Bad Format, bad scanline data (non-run)";if(p[u++]=n,--a>0)for(var g=0;g<a;g++)p[u++]=e[l++]}for(d=0;d<c;d++)i=p[d],n=p[d+c],r=p[d+2*c],o=p[d+3*c],this.Rgbe2float(m,i,n,r,o,(t.height-s)*c*3+3*d);s--}return m},e}(),ms=function(e){function t(t,i,n,r,o,s,c,l,u){void 0===r&&(r=!1),void 0===o&&(o=!0),void 0===s&&(s=!1),void 0===c&&(c=!1),void 0===l&&(l=null),void 0===u&&(u=null);var h=e.call(this,i)||this;return h._generateHarmonics=!0,h._onLoad=null,h._onError=null,h.coordinatesMode=et.a.CUBIC_MODE,h._isBlocking=!0,h._rotationY=0,h.boundingBoxPosition=a.e.Zero(),t?(h.name=t,h.url=t,h.hasAlpha=!1,h.isCube=!0,h._textureMatrix=a.a.Identity(),h._onLoad=l,h._onError=u,h.gammaSpace=s,h._noMipmap=r,h._size=n,h._generateHarmonics=o,h._texture=h._getFromCache(t,h._noMipmap),h._texture?l&&(h._texture.isReady?De.b.SetImmediate(function(){return l()}):h._texture.onLoadedObservable.add(l)):i.useDelayedTextureLoading?h.delayLoadState=g.a.DELAYLOADSTATE_NOTLOADED:h.loadTexture(),h):h}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"isBlocking",{get:function(){return this._isBlocking},set:function(e){this._isBlocking=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationY",{get:function(){return this._rotationY},set:function(e){this._rotationY=e,this.setReflectionTextureMatrix(a.a.RotationY(this._rotationY))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"boundingBoxSize",{get:function(){return this._boundingBoxSize},set:function(e){if(!this._boundingBoxSize||!this._boundingBoxSize.equals(e)){this._boundingBoxSize=e;var t=this.getScene();t&&t.markAllMaterialsAsDirty(g.a.MATERIAL_TextureDirtyFlag)}},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"HDRCubeTexture"},t.prototype.loadTexture=function(){var e=this,i=this.getScene();i&&(this._texture=i.getEngine().createRawCubeTextureFromUrl(this.url,i,this._size,g.a.TEXTUREFORMAT_RGB,i.getEngine().getCaps().textureFloat?g.a.TEXTURETYPE_FLOAT:g.a.TEXTURETYPE_UNSIGNED_INT,this._noMipmap,function(i){e.lodGenerationOffset=0,e.lodGenerationScale=.8;var n=e.getScene();if(!n)return null;var r=_s.GetCubeMapTextureData(i,e._size);if(e._generateHarmonics){var o=Xn.ConvertCubeMapToSphericalPolynomial(r);e.sphericalPolynomial=o}for(var a=[],s=null,c=0;c<6;c++){if(!n.getEngine().getCaps().textureFloat){var l=new ArrayBuffer(e._size*e._size*3);s=new Uint8Array(l)}var u=r[t._facesMapping[c]];if(e.gammaSpace||s)for(var h=0;h<e._size*e._size;h++)if(e.gammaSpace&&(u[3*h+0]=Math.pow(u[3*h+0],re.b),u[3*h+1]=Math.pow(u[3*h+1],re.b),u[3*h+2]=Math.pow(u[3*h+2],re.b)),s){var d=Math.max(255*u[3*h+0],0),f=Math.max(255*u[3*h+1],0),p=Math.max(255*u[3*h+2],0),_=Math.max(Math.max(d,f),p);if(_>255){var m=255/_;d*=m,f*=m,p*=m}s[3*h+0]=d,s[3*h+1]=f,s[3*h+2]=p}s?a.push(s):a.push(u)}return a},null,this._onLoad,this._onError))},t.prototype.clone=function(){var e=this.getScene();if(!e)return this;var i=new t(this.url,e,this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i.coordinatesIndex=this.coordinatesIndex,i.coordinatesMode=this.coordinatesMode,i},t.prototype.delayLoad=function(){this.delayLoadState===g.a.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=g.a.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this.loadTexture())},t.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},t.prototype.setReflectionTextureMatrix=function(e){var t=this;this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&this.getScene().markAllMaterialsAsDirty(g.a.MATERIAL_TextureDirtyFlag,function(e){return-1!==e.getActiveTextures().indexOf(t)})},t.Parse=function(e,i,n){var r=null;return e.name&&!e.isRenderTarget&&((r=new t(n+e.name,i,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace)).name=e.name,r.hasAlpha=e.hasAlpha,r.level=e.level,r.coordinatesMode=e.coordinatesMode,r.isBlocking=e.isBlocking),r&&(e.boundingBoxPosition&&(r.boundingBoxPosition=a.e.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=a.e.FromArray(e.boundingBoxSize)),e.rotationY&&(r.rotationY=e.rotationY)),r},t.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e},t._facesMapping=["right","left","up","down","front","back"],t}(jn.a);c.a.RegisteredTypes["BABYLON.HDRCubeTexture"]=ms;var gs=function(){function e(e,t,i){void 0===t&&(t=0),void 0===i&&(i=null),this.name=e,this.animations=new Array,this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new o.c,this._onDataLayoutChanged=new o.c,this._animationPropertiesOverride=null,this._scene=i||R.a.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}return Object.defineProperty(e.prototype,"influence",{get:function(){return this._influence},set:function(e){if(this._influence!==e){var t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"animationPropertiesOverride",{get:function(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasPositions",{get:function(){return!!this._positions},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasNormals",{get:function(){return!!this._normals},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasTangents",{get:function(){return!!this._tangents},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasUVs",{get:function(){return!!this._uvs},enumerable:!0,configurable:!0}),e.prototype.setPositions=function(e){var t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)},e.prototype.getPositions=function(){return this._positions},e.prototype.setNormals=function(e){var t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)},e.prototype.getNormals=function(){return this._normals},e.prototype.setTangents=function(e){var t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)},e.prototype.getTangents=function(){return this._tangents},e.prototype.setUVs=function(e){var t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)},e.prototype.getUVs=function(){return this._uvs},e.prototype.clone=function(){var t=this,i=N.a.Clone(function(){return new e(t.name,t.influence,t._scene)},this);return i._positions=this._positions,i._normals=this._normals,i._tangents=this._tangents,i._uvs=this._uvs,i},e.prototype.serialize=function(){var e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),null!=this.id&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),N.a.AppendSerializedAnimations(this,e),e},e.prototype.getClassName=function(){return"MorphTarget"},e.Parse=function(t){var i=new e(t.name,t.influence);if(i.setPositions(t.positions),null!=t.id&&(i.id=t.id),t.normals&&i.setNormals(t.normals),t.tangents&&i.setTangents(t.tangents),t.uvs&&i.setUVs(t.uvs),t.animations)for(var n=0;n<t.animations.length;n++){var r=t.animations[n],o=c.a.GetClass("BABYLON.Animation");o&&i.animations.push(o.Parse(r))}return i},e.FromMesh=function(t,i,n){i||(i=t.name);var r=new e(i,n,t.getScene());return r.setPositions(t.getVerticesData(en.b.PositionKind)),t.isVerticesDataPresent(en.b.NormalKind)&&r.setNormals(t.getVerticesData(en.b.NormalKind)),t.isVerticesDataPresent(en.b.TangentKind)&&r.setTangents(t.getVerticesData(en.b.TangentKind)),t.isVerticesDataPresent(en.b.UVKind)&&r.setUVs(t.getVerticesData(en.b.UVKind)),r},Object(h.c)([Object(N.c)()],e.prototype,"id",void 0),e}(),vs=function(){function e(e){void 0===e&&(e=null),this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new oi.a(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._uniqueId=0,this._tempInfluences=new Array,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,e||(e=R.a.LastCreatedScene),this._scene=e,this._scene&&(this._scene.morphTargetManagers.push(this),this._uniqueId=this._scene.getUniqueId())}return Object.defineProperty(e.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"vertexCount",{get:function(){return this._vertexCount},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"supportsNormals",{get:function(){return this._supportsNormals&&this.enableNormalMorphing},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"supportsTangents",{get:function(){return this._supportsTangents&&this.enableTangentMorphing},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"supportsUVs",{get:function(){return this._supportsUVs&&this.enableUVMorphing},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"numTargets",{get:function(){return this._targets.length},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"numInfluencers",{get:function(){return this._activeTargets.length},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"influences",{get:function(){return this._influences},enumerable:!0,configurable:!0}),e.prototype.getActiveTarget=function(e){return this._activeTargets.data[e]},e.prototype.getTarget=function(e){return this._targets[e]},e.prototype.addTarget=function(e){var t=this;this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add(function(e){t._syncActiveTargets(e)})),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add(function(){t._syncActiveTargets(!0)})),this._syncActiveTargets(!0)},e.prototype.removeTarget=function(e){var t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0))},e.prototype.clone=function(){for(var t=new e(this._scene),i=0,n=this._targets;i<n.length;i++){var r=n[i];t.addTarget(r.clone())}return t.enableNormalMorphing=this.enableNormalMorphing,t.enableTangentMorphing=this.enableTangentMorphing,t.enableUVMorphing=this.enableUVMorphing,t},e.prototype.serialize=function(){var e={};e.id=this.uniqueId,e.targets=[];for(var t=0,i=this._targets;t<i.length;t++){var n=i[t];e.targets.push(n.serialize())}return e},e.prototype._syncActiveTargets=function(e){var t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0;for(var i=0,n=this._targets;i<n.length;i++){var r=n[i];if(0!==r.influence){this._activeTargets.push(r),this._tempInfluences[t++]=r.influence,this._supportsNormals=this._supportsNormals&&r.hasNormals,this._supportsTangents=this._supportsTangents&&r.hasTangents,this._supportsUVs=this._supportsUVs&&r.hasUVs;var o=r.getPositions();if(o){var a=o.length/3;if(0===this._vertexCount)this._vertexCount=a;else if(this._vertexCount!==a)return void m.a.Error("Incompatible target. Targets must all have the same vertices count.")}}}this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(var s=0;s<t;s++)this._influences[s]=this._tempInfluences[s];e&&this.synchronize()},e.prototype.synchronize=function(){if(this._scene)for(var e=0,t=this._scene.meshes;e<t.length;e++){var i=t[e];i.morphTargetManager===this&&i._syncGeometryWithMorphTargetManager()}},e.Parse=function(t,i){var n=new e(i);n._uniqueId=t.id;for(var r=0,o=t.targets;r<o.length;r++){var a=o[r];n.addTarget(gs.Parse(a))}return n},e}(),ys=i(30),bs=i(47),Ts=function(){function e(t,i){if(void 0===i&&(i=e.DefaultPluginFactory()),this._physicsPlugin=i,this._impostors=[],this._joints=[],this._subTimeStep=0,!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");t=t||new a.e(0,-9.807,0),this.setGravity(t),this.setTimeStep()}return e.DefaultPluginFactory=function(){throw we.a.WarnImport("CannonJSPlugin")},e.prototype.setGravity=function(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)},e.prototype.setTimeStep=function(e){void 0===e&&(e=1/60),this._physicsPlugin.setTimeStep(e)},e.prototype.getTimeStep=function(){return this._physicsPlugin.getTimeStep()},e.prototype.setSubTimeStep=function(e){void 0===e&&(e=0),this._subTimeStep=e},e.prototype.getSubTimeStep=function(){return this._subTimeStep},e.prototype.dispose=function(){this._impostors.forEach(function(e){e.dispose()}),this._physicsPlugin.dispose()},e.prototype.getPhysicsPluginName=function(){return this._physicsPlugin.name},e.prototype.addImpostor=function(e){e.uniqueId=this._impostors.push(e),e.parent||this._physicsPlugin.generatePhysicsBody(e)},e.prototype.removeImpostor=function(e){var t=this._impostors.indexOf(e);t>-1&&(this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e))},e.prototype.addJoint=function(e,t,i){var n={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(n),this._physicsPlugin.generateJoint(n)},e.prototype.removeJoint=function(e,t,i){var n=this._joints.filter(function(n){return n.connectedImpostor===t&&n.joint===i&&n.mainImpostor===e});n.length&&this._physicsPlugin.removeJoint(n[0])},e.prototype._step=function(e){var t=this;this._impostors.forEach(function(e){e.isBodyInitRequired()&&t._physicsPlugin.generatePhysicsBody(e)}),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)},e.prototype.getPhysicsPlugin=function(){return this._physicsPlugin},e.prototype.getImpostors=function(){return this._impostors},e.prototype.getImpostorForPhysicsObject=function(e){for(var t=0;t<this._impostors.length;++t)if(this._impostors[t].object===e)return this._impostors[t];return null},e.prototype.getImpostorWithPhysicsBody=function(e){for(var t=0;t<this._impostors.length;++t)if(this._impostors[t].physicsBody===e)return this._impostors[t];return null},e.prototype.raycast=function(e,t){return this._physicsPlugin.raycast(e,t)},e.Epsilon=.001,e}(),Es=function(){function e(){this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=a.e.Zero(),this._hitPointWorld=a.e.Zero(),this._rayFromWorld=a.e.Zero(),this._rayToWorld=a.e.Zero()}return Object.defineProperty(e.prototype,"hasHit",{get:function(){return this._hasHit},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hitDistance",{get:function(){return this._hitDistance},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hitNormalWorld",{get:function(){return this._hitNormalWorld},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hitPointWorld",{get:function(){return this._hitPointWorld},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rayFromWorld",{get:function(){return this._rayFromWorld},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rayToWorld",{get:function(){return this._rayToWorld},enumerable:!0,configurable:!0}),e.prototype.setHitData=function(e,t){this._hasHit=!0,this._hitNormalWorld=new a.e(e.x,e.y,e.z),this._hitPointWorld=new a.e(t.x,t.y,t.z)},e.prototype.setHitDistance=function(e){this._hitDistance=e},e.prototype.calculateHitDistance=function(){this._hitDistance=a.e.Distance(this._rayFromWorld,this._hitPointWorld)},e.prototype.reset=function(e,t){void 0===e&&(e=a.e.Zero()),void 0===t&&(t=a.e.Zero()),this._rayFromWorld=e,this._rayToWorld=t,this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=a.e.Zero(),this._hitPointWorld=a.e.Zero()},e}(),xs=function(){function e(e,t,i){void 0===e&&(e=!0),void 0===t&&(t=10),void 0===i&&(i=CANNON),this._useDeltaForWorldStep=e,this.name="CannonJSPlugin",this._physicsMaterials=new Array,this._fixedTimeStep=1/60,this._physicsBodysToRemoveAfterStep=new Array,this._minus90X=new a.b(-.7071067811865475,0,0,.7071067811865475),this._plus90X=new a.b(.7071067811865475,0,0,.7071067811865475),this._tmpPosition=a.e.Zero(),this._tmpDeltaPosition=a.e.Zero(),this._tmpUnityRotation=new a.b,this.BJSCANNON=i,this.isSupported()?(this._extendNamespace(),this.world=new this.BJSCANNON.World,this.world.broadphase=new this.BJSCANNON.NaiveBroadphase,this.world.solver.iterations=t,this._cannonRaycastResult=new this.BJSCANNON.RaycastResult,this._raycastResult=new Es):m.a.Error("CannonJS is not available. Please make sure you included the js file.")}return e.prototype.setGravity=function(e){this.world.gravity.copy(e)},e.prototype.setTimeStep=function(e){this._fixedTimeStep=e},e.prototype.getTimeStep=function(){return this._fixedTimeStep},e.prototype.executeStep=function(e){this.world.step(this._fixedTimeStep,this._useDeltaForWorldStep?e:0,3),this._removeMarkedPhysicsBodiesFromWorld()},e.prototype._removeMarkedPhysicsBodiesFromWorld=function(){var e=this;this._physicsBodysToRemoveAfterStep.length>0&&(this._physicsBodysToRemoveAfterStep.forEach(function(t){e.world.remove(t)}),this._physicsBodysToRemoveAfterStep=[])},e.prototype.applyImpulse=function(e,t,i){var n=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(r,n)},e.prototype.applyForce=function(e,t,i){var n=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(r,n)},e.prototype.generatePhysicsBody=function(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){var t=this._createShape(e),i=e.physicsBody;i&&this.removePhysicsBody(e);var n=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),r={mass:e.getParam("mass"),material:n},o=e.getParam("nativeOptions");for(var a in o)o.hasOwnProperty(a)&&(r[a]=o[a]);e.physicsBody=new this.BJSCANNON.Body(r),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach(function(t){e.physicsBody[t].copy(i[t])}),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}},e.prototype._processChildMeshes=function(e){var t=this,i=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],n=e.object.rotationQuaternion;if(i.length){var r=function(i,o){if(n&&o.rotationQuaternion){var s=o.getPhysicsImpostor();if(s)if(s.parent!==e){var c=o.position.clone(),l=o.rotationQuaternion.multiply(a.b.Inverse(n));s.physicsBody&&(t.removePhysicsBody(s),s.physicsBody=null),s.parent=e,s.resetUpdateFlags(),e.physicsBody.addShape(t._createShape(s),new t.BJSCANNON.Vec3(c.x,c.y,c.z),new t.BJSCANNON.Quaternion(l.x,l.y,l.z,l.w)),e.physicsBody.mass+=s.getParam("mass")}n.multiplyInPlace(o.rotationQuaternion),o.getChildMeshes(!0).filter(function(e){return!!e.physicsImpostor}).forEach(r.bind(t,o.getAbsolutePosition()))}};i.filter(function(e){return!!e.physicsImpostor}).forEach(r.bind(this,e.object.getAbsolutePosition()))}},e.prototype.removePhysicsBody=function(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodysToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodysToRemoveAfterStep.push(e.physicsBody)},e.prototype.generateJoint=function(e){var t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(t&&i){var n,r=e.joint.jointData,o={pivotA:r.mainPivot?(new this.BJSCANNON.Vec3).copy(r.mainPivot):null,pivotB:r.connectedPivot?(new this.BJSCANNON.Vec3).copy(r.connectedPivot):null,axisA:r.mainAxis?(new this.BJSCANNON.Vec3).copy(r.mainAxis):null,axisB:r.connectedAxis?(new this.BJSCANNON.Vec3).copy(r.connectedAxis):null,maxForce:r.nativeParams.maxForce,collideConnected:!!r.collision};switch(e.joint.type){case bs.e.HingeJoint:case bs.e.Hinge2Joint:n=new this.BJSCANNON.HingeConstraint(t,i,o);break;case bs.e.DistanceJoint:n=new this.BJSCANNON.DistanceConstraint(t,i,r.maxDistance||2);break;case bs.e.SpringJoint:var a=r;n=new this.BJSCANNON.Spring(t,i,{restLength:a.length,stiffness:a.stiffness,damping:a.damping,localAnchorA:o.pivotA,localAnchorB:o.pivotB});break;case bs.e.LockJoint:n=new this.BJSCANNON.LockConstraint(t,i,o);break;case bs.e.PointToPointJoint:case bs.e.BallAndSocketJoint:default:n=new this.BJSCANNON.PointToPointConstraint(t,o.pivotA,i,o.pivotB,o.maxForce)}n.collideConnected=!!r.collision,e.joint.physicsJoint=n,e.joint.type!==bs.e.SpringJoint?this.world.addConstraint(n):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){n.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}},e.prototype.removeJoint=function(e){e.joint.type!==bs.e.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)},e.prototype._addMaterial=function(e,t,i){var n,r;for(n=0;n<this._physicsMaterials.length;n++)if((r=this._physicsMaterials[n]).friction===t&&r.restitution===i)return r;var o=new this.BJSCANNON.Material(e);return o.friction=t,o.restitution=i,this._physicsMaterials.push(o),o},e.prototype._checkWithEpsilon=function(e){return e<Ts.Epsilon?Ts.Epsilon:e},e.prototype._createShape=function(e){var t,i=e.object,n=e.getObjectExtendSize();switch(e.type){case ys.a.SphereImpostor:var r=n.x,o=n.y,s=n.z;t=new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(r),this._checkWithEpsilon(o),this._checkWithEpsilon(s))/2);break;case ys.a.CylinderImpostor:var c=e.getParam("nativeOptions");c||(c={});var l=void 0!==c.radiusTop?c.radiusTop:this._checkWithEpsilon(n.x)/2,u=void 0!==c.radiusBottom?c.radiusBottom:this._checkWithEpsilon(n.x)/2,h=void 0!==c.height?c.height:this._checkWithEpsilon(n.y),d=void 0!==c.numSegments?c.numSegments:16;t=new this.BJSCANNON.Cylinder(l,u,h,d);var f=new this.BJSCANNON.Quaternion;f.setFromAxisAngle(new this.BJSCANNON.Vec3(1,0,0),-Math.PI/2);var p=new this.BJSCANNON.Vec3(0,0,0);t.transformAllPoints(p,f);break;case ys.a.BoxImpostor:var _=n.scale(.5);t=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(_.x),this._checkWithEpsilon(_.y),this._checkWithEpsilon(_.z)));break;case ys.a.PlaneImpostor:m.a.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead"),t=new this.BJSCANNON.Plane;break;case ys.a.MeshImpostor:var g=i.getVerticesData?i.getVerticesData(en.b.PositionKind):[],v=i.getIndices?i.getIndices():[];if(!g)return;var y=i.position.clone(),b=i.rotation&&i.rotation.clone(),T=i.rotationQuaternion&&i.rotationQuaternion.clone();i.position.copyFromFloats(0,0,0),i.rotation&&i.rotation.copyFromFloats(0,0,0),i.rotationQuaternion&&i.rotationQuaternion.copyFrom(e.getParentsRotation()),i.rotationQuaternion&&i.parent&&i.rotationQuaternion.conjugateInPlace();var E,x=i.computeWorldMatrix(!0),P=new Array;for(E=0;E<g.length;E+=3)a.e.TransformCoordinates(a.e.FromArray(g,E),x).toArray(P,E);m.a.Warn("MeshImpostor only collides against spheres."),t=new this.BJSCANNON.Trimesh(P,v),i.position.copyFrom(y),b&&i.rotation&&i.rotation.copyFrom(b),T&&i.rotationQuaternion&&i.rotationQuaternion.copyFrom(T);break;case ys.a.HeightmapImpostor:var A=i.position.clone(),S=i.rotation&&i.rotation.clone(),C=i.rotationQuaternion&&i.rotationQuaternion.clone();i.position.copyFromFloats(0,0,0),i.rotation&&i.rotation.copyFromFloats(0,0,0),i.rotationQuaternion&&i.rotationQuaternion.copyFrom(e.getParentsRotation()),i.rotationQuaternion&&i.parent&&i.rotationQuaternion.conjugateInPlace(),i.rotationQuaternion&&i.rotationQuaternion.multiplyInPlace(this._minus90X),t=this._createHeightmap(i),i.position.copyFrom(A),S&&i.rotation&&i.rotation.copyFrom(S),C&&i.rotationQuaternion&&i.rotationQuaternion.copyFrom(C),i.computeWorldMatrix(!0);break;case ys.a.ParticleImpostor:t=new this.BJSCANNON.Particle;break;case ys.a.NoImpostor:t=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0,0,0))}return t},e.prototype._createHeightmap=function(e,t){var i,n=e.getVerticesData(en.b.PositionKind),r=e.computeWorldMatrix(!0),o=new Array;for(i=0;i<n.length;i+=3)a.e.TransformCoordinates(a.e.FromArray(n,i),r).toArray(o,i);n=o;for(var s=new Array,c=t||~~(Math.sqrt(n.length/3)-1),l=e.getBoundingInfo(),u=Math.min(l.boundingBox.extendSizeWorld.x,l.boundingBox.extendSizeWorld.y),h=l.boundingBox.extendSizeWorld.z,d=2*u/c,f=0;f<n.length;f+=3){var p=Math.round(n[f+0]/d+c/2),_=Math.round(-1*(n[f+1]/d-c/2)),m=-n[f+2]+h;s[p]||(s[p]=[]),s[p][_]||(s[p][_]=m),s[p][_]=Math.max(m,s[p][_])}for(p=0;p<=c;++p){if(!s[p]){for(var g=1;!s[(p+g)%c];)g++;s[p]=s[(p+g)%c].slice()}for(_=0;_<=c;++_)if(!s[p][_]){var v;for(g=1;void 0===v;)v=s[p][(_+g++)%c];s[p][_]=v}}var y=new this.BJSCANNON.Heightfield(s,{elementSize:d});return y.minY=h,y},e.prototype._updatePhysicsBodyTransformation=function(e){var t=e.object;if(t.computeWorldMatrix&&t.computeWorldMatrix(!0),t.getBoundingInfo()){var i=e.getObjectCenter();this._tmpDeltaPosition.copyFrom(t.getAbsolutePivotPoint().subtract(i)),this._tmpDeltaPosition.divideInPlace(e.object.scaling),this._tmpPosition.copyFrom(i);var n=t.rotationQuaternion;if(n){if(e.type!==ys.a.PlaneImpostor&&e.type!==ys.a.HeightmapImpostor||(n=n.multiply(this._minus90X),e.setDeltaRotation(this._plus90X)),e.type===ys.a.HeightmapImpostor){var r=t,o=r.getBoundingInfo(),s=r.rotationQuaternion;r.rotationQuaternion=this._tmpUnityRotation,r.computeWorldMatrix(!0);var c=i.clone(),l=r.getPivotMatrix();l=l?l.clone():a.a.Identity();var u=a.a.Translation(o.boundingBox.extendSizeWorld.x,0,-o.boundingBox.extendSizeWorld.z);r.setPreTransformMatrix(u),r.computeWorldMatrix(!0);var h=o.boundingBox.centerWorld.subtract(i).subtract(r.position).negate();this._tmpPosition.copyFromFloats(h.x,h.y-o.boundingBox.extendSizeWorld.y,h.z),this._tmpDeltaPosition.copyFrom(o.boundingBox.centerWorld.subtract(c)),this._tmpDeltaPosition.y+=o.boundingBox.extendSizeWorld.y,r.rotationQuaternion=s,r.setPreTransformMatrix(l),r.computeWorldMatrix(!0)}else e.type===ys.a.MeshImpostor&&this._tmpDeltaPosition.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpDeltaPosition),e.physicsBody.position.copy(this._tmpPosition),e.physicsBody.quaternion.copy(n)}}},e.prototype.setTransformationFromPhysicsBody=function(e){e.object.position.copyFrom(e.physicsBody.position),e.object.rotationQuaternion&&e.object.rotationQuaternion.copyFrom(e.physicsBody.quaternion)},e.prototype.setPhysicsBodyTransformation=function(e,t,i){e.physicsBody.position.copy(t),e.physicsBody.quaternion.copy(i)},e.prototype.isSupported=function(){return void 0!==this.BJSCANNON},e.prototype.setLinearVelocity=function(e,t){e.physicsBody.velocity.copy(t)},e.prototype.setAngularVelocity=function(e,t){e.physicsBody.angularVelocity.copy(t)},e.prototype.getLinearVelocity=function(e){var t=e.physicsBody.velocity;return t?new a.e(t.x,t.y,t.z):null},e.prototype.getAngularVelocity=function(e){var t=e.physicsBody.angularVelocity;return t?new a.e(t.x,t.y,t.z):null},e.prototype.setBodyMass=function(e,t){e.physicsBody.mass=t,e.physicsBody.updateMassProperties()},e.prototype.getBodyMass=function(e){return e.physicsBody.mass},e.prototype.getBodyFriction=function(e){return e.physicsBody.material.friction},e.prototype.setBodyFriction=function(e,t){e.physicsBody.material.friction=t},e.prototype.getBodyRestitution=function(e){return e.physicsBody.material.restitution},e.prototype.setBodyRestitution=function(e,t){e.physicsBody.material.restitution=t},e.prototype.sleepBody=function(e){e.physicsBody.sleep()},e.prototype.wakeUpBody=function(e){e.physicsBody.wakeUp()},e.prototype.updateDistanceJoint=function(e,t){e.physicsJoint.distance=t},e.prototype.setMotor=function(e,t,i,n){n||(e.physicsJoint.enableMotor(),e.physicsJoint.setMotorSpeed(t),i&&this.setLimit(e,i))},e.prototype.setLimit=function(e,t,i){e.physicsJoint.motorEquation.maxForce=t,e.physicsJoint.motorEquation.minForce=void 0===i?-t:i},e.prototype.syncMeshWithImpostor=function(e,t){var i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.quaternion.x,e.rotationQuaternion.y=i.quaternion.y,e.rotationQuaternion.z=i.quaternion.z,e.rotationQuaternion.w=i.quaternion.w)},e.prototype.getRadius=function(e){return e.physicsBody.shapes[0].boundingSphereRadius},e.prototype.getBoxSizeToRef=function(e,t){var i=e.physicsBody.shapes[0];t.x=2*i.halfExtents.x,t.y=2*i.halfExtents.y,t.z=2*i.halfExtents.z},e.prototype.dispose=function(){},e.prototype._extendNamespace=function(){var e=new this.BJSCANNON.Vec3,t=this.BJSCANNON;this.BJSCANNON.World.prototype.step=function(i,n,r){if(r=r||10,0===(n=n||0))this.internalStep(i),this.time+=i;else{var o=Math.floor((this.time+n)/i)-Math.floor(this.time/i);o=Math.min(o,r)||1;for(var a=performance.now(),s=0;s!==o&&(this.internalStep(i),!(performance.now()-a>1e3*i));s++);this.time+=n;for(var c=this.time%i/i,l=e,u=this.bodies,h=0;h!==u.length;h++){var d=u[h];d.type!==t.Body.STATIC&&d.sleepState!==t.Body.SLEEPING?(d.position.vsub(d.previousPosition,l),l.scale(c,l),d.position.vadd(l,d.interpolatedPosition)):(d.interpolatedPosition.copy(d.position),d.interpolatedQuaternion.copy(d.quaternion))}}}},e.prototype.raycast=function(e,t){return this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),this._raycastResult.reset(e,t),this._cannonRaycastResult.hasHit&&(this._raycastResult.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),this._raycastResult.setHitDistance(this._cannonRaycastResult.distance)),this._raycastResult},e}();Ts.DefaultPluginFactory=function(){return new xs};var Ps=function(){function e(e,t){void 0===t&&(t=OIMO),this.name="OimoJSPlugin",this._tmpImpostorsArray=[],this._tmpPositionVector=a.e.Zero(),this.BJSOIMO=t,this.world=new this.BJSOIMO.World({iterations:e}),this.world.clear(),this._raycastResult=new Es}return e.prototype.setGravity=function(e){this.world.gravity.copy(e)},e.prototype.setTimeStep=function(e){this.world.timeStep=e},e.prototype.getTimeStep=function(){return this.world.timeStep},e.prototype.executeStep=function(e,t){var i=this;t.forEach(function(e){e.beforeStep()}),this.world.step(),t.forEach(function(e){e.afterStep(),i._tmpImpostorsArray[e.uniqueId]=e});for(var n=this.world.contacts;null!==n;)if(!n.touching||n.body1.sleeping||n.body2.sleeping){var r=this._tmpImpostorsArray[+n.body1.name],o=this._tmpImpostorsArray[+n.body2.name];r&&o?(r.onCollide({body:o.physicsBody}),o.onCollide({body:r.physicsBody}),n=n.next):n=n.next}else n=n.next},e.prototype.applyImpulse=function(e,t,i){var n=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*n))},e.prototype.applyForce=function(e,t,i){m.a.Warn("Oimo doesn't support applying force. Using impule instead."),this.applyImpulse(e,t,i)},e.prototype.generatePhysicsBody=function(e){var t=this;if(e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){var i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},n=[e];(s=e.object).getChildMeshes&&s.getChildMeshes().forEach(function(e){e.physicsImpostor&&n.push(e.physicsImpostor)});var r=function(e){return Math.max(e,Ts.Epsilon)},o=new a.b;n.forEach(function(n){if(n.object.rotationQuaternion){var a=n.object.rotationQuaternion;o=a.clone(),n.object.rotationQuaternion.set(0,0,0,1),n.object.computeWorldMatrix(!0);var s=a.toEulerAngles(),c=n.getObjectExtendSize();if(n===e){var l=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(l,t._tmpPositionVector),t._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(l.x),i.pos.push(l.y),i.pos.push(l.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{var u=n.object.position.clone();i.posShape.push(u.x),i.posShape.push(u.y),i.posShape.push(u.z),i.rotShape.push(57.29577951308232*s.x),i.rotShape.push(57.29577951308232*s.y),i.rotShape.push(57.29577951308232*s.z)}switch(n.object.rotationQuaternion.copyFrom(o),n.type){case ys.a.ParticleImpostor:m.a.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case ys.a.SphereImpostor:var h=c.x,d=c.y,f=c.z,p=Math.max(r(h),r(d),r(f))/2;i.type.push("sphere"),i.size.push(p),i.size.push(p),i.size.push(p);break;case ys.a.CylinderImpostor:var _=r(c.x)/2,g=r(c.y);i.type.push("cylinder"),i.size.push(_),i.size.push(g),i.size.push(g);break;case ys.a.PlaneImpostor:case ys.a.BoxImpostor:default:_=r(c.x),g=r(c.y);var v=r(c.z);i.type.push("box"),i.size.push(_),i.size.push(g),i.size.push(v)}n.object.rotationQuaternion=a}}),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(o),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);var s;e.setDeltaPosition(this._tmpPositionVector)}},e.prototype.removePhysicsBody=function(e){this.world.removeRigidBody(e.physicsBody)},e.prototype.generateJoint=function(e){var t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(t&&i){var n,r=e.joint.jointData,o=r.nativeParams||{},a={body1:t,body2:i,axe1:o.axe1||(r.mainAxis?r.mainAxis.asArray():null),axe2:o.axe2||(r.connectedAxis?r.connectedAxis.asArray():null),pos1:o.pos1||(r.mainPivot?r.mainPivot.asArray():null),pos2:o.pos2||(r.connectedPivot?r.connectedPivot.asArray():null),min:o.min,max:o.max,collision:o.collision||r.collision,spring:o.spring,world:this.world};switch(e.joint.type){case bs.e.BallAndSocketJoint:n="jointBall";break;case bs.e.SpringJoint:m.a.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");var s=r;a.min=s.length||a.min,a.max=Math.max(a.min,a.max);case bs.e.DistanceJoint:n="jointDistance",a.max=r.maxDistance;break;case bs.e.PrismaticJoint:n="jointPrisme";break;case bs.e.SliderJoint:n="jointSlide";break;case bs.e.WheelJoint:n="jointWheel";break;case bs.e.HingeJoint:default:n="jointHinge"}a.type=n,e.joint.physicsJoint=this.world.add(a)}},e.prototype.removeJoint=function(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){m.a.Warn(e)}},e.prototype.isSupported=function(){return void 0!==this.BJSOIMO},e.prototype.setTransformationFromPhysicsBody=function(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){for(var t=e.physicsBody.shapes;t.next;)t=t.next;e.object.position.copyFrom(t.position)}else e.object.position.copyFrom(e.physicsBody.getPosition());e.object.rotationQuaternion&&e.object.rotationQuaternion.copyFrom(e.physicsBody.getQuaternion())}},e.prototype.setPhysicsBodyTransformation=function(e,t,i){var n=e.physicsBody;e.physicsBody.shapes.next||(n.position.copy(t),n.orientation.copy(i),n.syncShapes(),n.awake())},e.prototype.setLinearVelocity=function(e,t){e.physicsBody.linearVelocity.copy(t)},e.prototype.setAngularVelocity=function(e,t){e.physicsBody.angularVelocity.copy(t)},e.prototype.getLinearVelocity=function(e){var t=e.physicsBody.linearVelocity;return t?new a.e(t.x,t.y,t.z):null},e.prototype.getAngularVelocity=function(e){var t=e.physicsBody.angularVelocity;return t?new a.e(t.x,t.y,t.z):null},e.prototype.setBodyMass=function(e,t){var i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)},e.prototype.getBodyMass=function(e){return e.physicsBody.shapes.density},e.prototype.getBodyFriction=function(e){return e.physicsBody.shapes.friction},e.prototype.setBodyFriction=function(e,t){e.physicsBody.shapes.friction=t},e.prototype.getBodyRestitution=function(e){return e.physicsBody.shapes.restitution},e.prototype.setBodyRestitution=function(e,t){e.physicsBody.shapes.restitution=t},e.prototype.sleepBody=function(e){e.physicsBody.sleep()},e.prototype.wakeUpBody=function(e){e.physicsBody.awake()},e.prototype.updateDistanceJoint=function(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)},e.prototype.setMotor=function(e,t,i,n){void 0!==i?m.a.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;var r=n?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setMotor(t,i)},e.prototype.setLimit=function(e,t,i,n){var r=n?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setLimit(t,void 0===i?-t:i)},e.prototype.syncMeshWithImpostor=function(e,t){var i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.s)},e.prototype.getRadius=function(e){return e.physicsBody.shapes.radius},e.prototype.getBoxSizeToRef=function(e,t){var i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth},e.prototype.dispose=function(){this.world.clear()},e.prototype.raycast=function(e,t){return m.a.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult},e}();$i.a.CreateRibbon=function(e){var t=e.pathArray,i=e.closeArray||!1,n=e.closePath||!1,r=e.invertUV||!1,o=Math.floor(t[0].length/2),a=e.offset||o;a=a>o?o:Math.floor(a);var s,c,l,u,h=0===e.sideOrientation?0:e.sideOrientation||$i.a.DEFAULTSIDE,d=e.uvs,f=e.colors,p=[],_=[],m=[],g=[],v=[],y=[],b=[],T=[],E=[],x=[];if(t.length<2){var P=[],A=[];for(l=0;l<t[0].length-a;l++)P.push(t[0][l]),A.push(t[0][l+a]);t=[P,A]}var S,C,R,O,M,I=0,D=n?1:0;for(s=t[0].length,c=0;c<t.length;c++){for(b[c]=0,v[c]=[0],s=s<(C=(S=t[c]).length)?s:C,u=0;u<C;)p.push(S[u].x,S[u].y,S[u].z),u>0&&(R=S[u].subtract(S[u-1]).length()+b[c],v[c].push(R),b[c]=R),u++;n&&(u--,p.push(S[0].x,S[0].y,S[0].z),R=S[u].subtract(S[0]).length()+b[c],v[c].push(R),b[c]=R),E[c]=C+D,x[c]=I,I+=C+D}var w,L,N=null,F=null;for(l=0;l<s+D;l++){for(T[l]=0,y[l]=[0],c=0;c<t.length-1;c++)O=t[c],M=t[c+1],l===s?(N=O[0],F=M[0]):(N=O[l],F=M[l]),R=F.subtract(N).length()+T[l],y[l].push(R),T[l]=R;i&&F&&N&&(O=t[c],M=t[0],l===s&&(F=M[0]),R=F.subtract(N).length()+T[l],T[l]=R)}if(d)for(c=0;c<d.length;c++)g.push(d[c].x,d[c].y);else for(c=0;c<t.length;c++)for(l=0;l<s+D;l++)w=0!=b[c]?v[c][l]/b[c]:0,L=0!=T[l]?y[l][c]/T[l]:0,r?g.push(L,w):g.push(w,L);for(var B=0,U=E[c=0]-1,V=E[c+1]-1,k=U<V?U:V,z=x[1]-x[0],G=i?E.length:E.length-1;B<=k&&c<G;)_.push(B,B+z,B+1),_.push(B+z+1,B+1,B+z),(B+=1)===k&&(++c===E.length-1?(z=x[0]-x[c],U=E[c]-1,V=E[0]-1):(z=x[c+1]-x[c],U=E[c]-1,V=E[c+1]-1),B=x[c],k=U<V?U+B:V+B);if($i.a.ComputeNormals(p,_,m),n){var j=0,W=0;for(c=0;c<t.length;c++)j=3*x[c],W=c+1<t.length?3*(x[c+1]-1):m.length-3,m[j]=.5*(m[j]+m[W]),m[j+1]=.5*(m[j+1]+m[W+1]),m[j+2]=.5*(m[j+2]+m[W+2]),m[W]=m[j],m[W+1]=m[j+1],m[W+2]=m[j+2]}$i.a._ComputeSides(h,p,_,m,g,e.frontUVs,e.backUVs);var X=null;if(f){X=new Float32Array(4*f.length);for(var H=0;H<f.length;H++)X[4*H]=f[H].r,X[4*H+1]=f[H].g,X[4*H+2]=f[H].b,X[4*H+3]=f[H].a}var Y=new $i.a,K=new Float32Array(p),Q=new Float32Array(m),q=new Float32Array(g);return Y.indices=_,Y.positions=K,Y.normals=Q,Y.uvs=q,X&&Y.set(X,en.b.ColorKind),n&&(Y._idx=x),Y},Ae.a.CreateRibbon=function(e,t,i,n,r,o,a,s,c){return void 0===i&&(i=!1),void 0===a&&(a=!1),As.CreateRibbon(e,{pathArray:t,closeArray:i,closePath:n,offset:r,updatable:a,sideOrientation:s,instance:c},o)};var As=function(){function e(){}return e.CreateRibbon=function(e,t,i){void 0===i&&(i=null);var n=t.pathArray,r=t.closeArray,o=t.closePath,s=Ae.a._GetDefaultSideOrientation(t.sideOrientation),c=t.instance,l=t.updatable;if(c){var u=a.c.Vector3[0].setAll(Number.MAX_VALUE),h=a.c.Vector3[1].setAll(-Number.MAX_VALUE),d=c.getVerticesData(en.b.PositionKind);if(function(e){for(var t=n[0].length,i=c,r=0,o=i._originalBuilderSideOrientation===Ae.a.DOUBLESIDE?2:1,a=1;a<=o;++a)for(var s=0;s<n.length;++s){var l=n[s],d=l.length;t=t<d?t:d;for(var f=0;f<t;++f){var p=l[f];e[r]=p.x,e[r+1]=p.y,e[r+2]=p.z,u.minimizeInPlaceFromFloats(p.x,p.y,p.z),h.maximizeInPlaceFromFloats(p.x,p.y,p.z),r+=3}i._creationDataStorage&&i._creationDataStorage.closePath&&(p=l[0],e[r]=p.x,e[r+1]=p.y,e[r+2]=p.z,r+=3)}}(d),c._boundingInfo?c._boundingInfo.reConstruct(u,h,c._worldMatrix):c._boundingInfo=new Pn.a(u,h,c._worldMatrix),c.updateVerticesData(en.b.PositionKind,d,!1,!1),t.colors){for(var f=c.getVerticesData(en.b.ColorKind),p=0,_=0;p<t.colors.length;p++,_+=4){var m=t.colors[p];f[_]=m.r,f[_+1]=m.g,f[_+2]=m.b,f[_+3]=m.a}c.updateVerticesData(en.b.ColorKind,f,!1,!1)}if(t.uvs){for(var g=c.getVerticesData(en.b.UVKind),v=0;v<t.uvs.length;v++)g[2*v]=t.uvs[v].x,g[2*v+1]=t.uvs[v].y;c.updateVerticesData(en.b.UVKind,g,!1,!1)}if(!c.areNormalsFrozen||c.isFacetDataEnabled){var y=c.getIndices(),b=c.getVerticesData(en.b.NormalKind),T=c.isFacetDataEnabled?c.getFacetDataParameters():null;if($i.a.ComputeNormals(d,y,b,T),c._creationDataStorage&&c._creationDataStorage.closePath)for(var E=0,x=0,P=0;P<n.length;P++)E=3*c._creationDataStorage.idx[P],x=P+1<n.length?3*(c._creationDataStorage.idx[P+1]-1):b.length-3,b[E]=.5*(b[E]+b[x]),b[E+1]=.5*(b[E+1]+b[x+1]),b[E+2]=.5*(b[E+2]+b[x+2]),b[x]=b[E],b[x+1]=b[E+1],b[x+2]=b[E+2];c.areNormalsFrozen||c.updateVerticesData(en.b.NormalKind,b,!1,!1)}return c}var A=new Ae.a(e,i);A._originalBuilderSideOrientation=s,A._creationDataStorage=new Ae.b;var S=$i.a.CreateRibbon(t);return o&&(A._creationDataStorage.idx=S._idx),A._creationDataStorage.closePath=o,A._creationDataStorage.closeArray=r,S.applyToMesh(A,l),A},e}();Ae.a.ExtrudeShape=function(e,t,i,n,r,o,a,s,c,l){void 0===a&&(a=null);var u={shape:t,path:i,scale:n,rotation:r,cap:0===o?0:o||Ae.a.NO_CAP,sideOrientation:c,instance:l,updatable:s};return Ss.ExtrudeShape(e,u,a)},Ae.a.ExtrudeShapeCustom=function(e,t,i,n,r,o,a,s,c,l,u,h){var d={shape:t,path:i,scaleFunction:n,rotationFunction:r,ribbonCloseArray:o,ribbonClosePath:a,cap:0===s?0:s||Ae.a.NO_CAP,sideOrientation:u,instance:h,updatable:l};return Ss.ExtrudeShapeCustom(e,d,c)};var Ss=function(){function e(){}return e.ExtrudeShape=function(t,i,n){void 0===n&&(n=null);var r=i.path,o=i.shape,a=i.scale||1,s=i.rotation||0,c=0===i.cap?0:i.cap||Ae.a.NO_CAP,l=i.updatable,u=Ae.a._GetDefaultSideOrientation(i.sideOrientation),h=i.instance||null,d=i.invertUV||!1;return e._ExtrudeShapeGeneric(t,o,r,a,s,null,null,!1,!1,c,!1,n,!!l,u,h,d,i.frontUVs||null,i.backUVs||null)},e.ExtrudeShapeCustom=function(t,i,n){void 0===n&&(n=null);var r=i.path,o=i.shape,a=i.scaleFunction||function(){return 1},s=i.rotationFunction||function(){return 0},c=i.ribbonCloseArray||!1,l=i.ribbonClosePath||!1,u=0===i.cap?0:i.cap||Ae.a.NO_CAP,h=i.updatable,d=Ae.a._GetDefaultSideOrientation(i.sideOrientation),f=i.instance,p=i.invertUV||!1;return e._ExtrudeShapeGeneric(t,o,r,null,null,a,s,c,l,u,!0,n,!!h,d,f||null,p,i.frontUVs||null,i.backUVs||null)},e._ExtrudeShapeGeneric=function(e,t,i,n,r,o,s,c,l,u,h,d,f,p,_,m,g,v){var y,b,T=function(e,t,i,n,r,o,s,c,l,u){for(var h=i.getTangents(),d=i.getNormals(),f=i.getBinormals(),p=i.getDistances(),_=0,m=u&&c?c:function(){return null!==o?o:0},g=u&&s?s:function(){return null!==r?r:1},v=l===Ae.a.NO_CAP||l===Ae.a.CAP_END?0:2,y=a.c.Matrix[0],b=0;b<t.length;b++){for(var T=new Array,E=m(b,p[b]),x=g(b,p[b]),P=0;P<e.length;P++){a.a.RotationAxisToRef(h[b],_,y);var A=h[b].scale(e[P].z).add(d[b].scale(e[P].x)).add(f[b].scale(e[P].y)),S=T[P]?T[P]:a.e.Zero();a.e.TransformCoordinatesToRef(A,y,S),S.scaleInPlace(x).addInPlace(t[b]),T[P]=S}n[v]=T,_+=E,v++}var C=function(e){var t,i=Array(),n=a.e.Zero();for(t=0;t<e.length;t++)n.addInPlace(e[t]);for(n.scaleInPlace(1/e.length),t=0;t<e.length;t++)i.push(n);return i};switch(l){case Ae.a.NO_CAP:break;case Ae.a.CAP_START:n[0]=C(n[2]),n[1]=n[2];break;case Ae.a.CAP_END:n[v]=n[v-1],n[v+1]=C(n[v-1]);break;case Ae.a.CAP_ALL:n[0]=C(n[2]),n[1]=n[2],n[v]=n[v-1],n[v+1]=C(n[v-1])}return n};if(_){var E=_._creationDataStorage;return y=E.path3D.update(i),b=T(t,i,E.path3D,E.pathArray,n,r,o,s,E.cap,h),_=Ae.a.CreateRibbon("",b,!1,!1,0,d||void 0,!1,0,_)}b=T(t,i,y=new le(i),new Array,n,r,o,s,u=u<0||u>3?0:u,h);var x=As.CreateRibbon(e,{pathArray:b,closeArray:c,closePath:l,updatable:f,sideOrientation:p,invertUV:m,frontUVs:g||void 0,backUVs:v||void 0},d);return x._creationDataStorage.pathArray=b,x._creationDataStorage.path3D=y,x._creationDataStorage.cap=u,x},e}(),Cs=function(){function e(e,t,i){var n=this;void 0===e&&(e=!0),void 0===t&&(t=Ammo),void 0===i&&(i=null),this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new a.b,this._tmpContactCallbackResult=!1,this._tmpVector=new a.e,this._tmpMatrix=new a.a,"function"==typeof t?t(this.bjsAMMO):this.bjsAMMO=t,this.isSupported()?(this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=function(){n._tmpContactCallbackResult=!0},this._raycastResult=new Es,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)):m.a.Error("AmmoJS is not available. Please make sure you included the js file.")}return e.prototype.setGravity=function(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)},e.prototype.setTimeStep=function(e){this._timeStep=e},e.prototype.setFixedTimeStep=function(e){this._fixedTimeStep=e},e.prototype.setMaxSteps=function(e){this._maxSteps=e},e.prototype.getTimeStep=function(){return this._timeStep},e.prototype._isImpostorInContact=function(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult},e.prototype._isImpostorPairInContact=function(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult},e.prototype._stepSimulation=function(e,t,i){if(void 0===e&&(e=1/60),void 0===t&&(t=10),void 0===i&&(i=1/60),0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i<i?(this.world.stepSimulation(e,0),e=0):(e-=i,this.world.stepSimulation(i,0)),t--},e.prototype.executeStep=function(e,t){for(var i=0,n=t;i<n.length;i++){var r=n[i];r.soft||r.beforeStep()}this._stepSimulation(this._useDeltaForWorldStep?e:this._timeStep,this._maxSteps,this._fixedTimeStep);for(var o=0,a=t;o<a.length;o++){var s=a[o];if(s.soft?this._afterSoftStep(s):s.afterStep(),s._onPhysicsCollideCallbacks.length>0&&this._isImpostorInContact(s))for(var c=0,l=s._onPhysicsCollideCallbacks;c<l.length;c++)for(var u=0,h=l[c].otherImpostors;u<h.length;u++){var d=h[u];(s.physicsBody.isActive()||d.physicsBody.isActive())&&this._isImpostorPairInContact(s,d)&&(s.onCollide({body:d.physicsBody}),d.onCollide({body:s.physicsBody}))}}},e.prototype._afterSoftStep=function(e){e.type===ys.a.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)},e.prototype._ropeStep=function(e){for(var t,i,n,r,o=e.physicsBody.get_m_nodes(),s=o.size(),c=new Array,l=0;l<s;l++)i=(t=o.at(l).get_m_x()).x(),n=t.y(),r=t.z(),c.push(new a.e(i,n,r));var u=e.object,h=e.getParam("shape");e._isFromLine?e.object=Or.a.CreateLines("lines",{points:c,instance:u}):e.object=Ss.ExtrudeShape("ext",{shape:h,path:c,instance:u})},e.prototype._softbodyOrClothStep=function(e){var t=e.type===ys.a.ClothImpostor?1:-1,i=e.object,n=i.getVerticesData(en.b.PositionKind);n||(n=[]);var r=i.getVerticesData(en.b.NormalKind);r||(r=[]);for(var o,a,s,c,l,u,h,d,f=n.length/3,p=e.physicsBody.get_m_nodes(),_=0;_<f;_++){var m;s=(a=(o=p.at(_)).get_m_x()).x(),c=a.y(),l=a.z()*t,u=(m=o.get_m_n()).x(),h=m.y(),d=m.z()*t,n[3*_]=s,n[3*_+1]=c,n[3*_+2]=l,r[3*_]=u,r[3*_+1]=h,r[3*_+2]=d}var g=new $i.a;g.positions=n,g.normals=r,g.uvs=i.getVerticesData(en.b.UVKind),g.colors=i.getVerticesData(en.b.ColorKind),i&&i.getIndices&&(g.indices=i.getIndices()),g.applyToMesh(i)},e.prototype.applyImpulse=function(e,t,i){if(e.soft)m.a.Warn("Cannot be applied to a soft body");else{e.physicsBody.activate();var n=this._tmpAmmoVectorA,r=this._tmpAmmoVectorB;e.object&&e.object.getWorldMatrix&&(e.object.getWorldMatrix().invertToRef(this._tmpMatrix),a.e.TransformCoordinatesToRef(i,this._tmpMatrix,this._tmpVector),i=this._tmpVector),n.setValue(i.x,i.y,i.z),r.setValue(t.x,t.y,t.z),e.physicsBody.applyImpulse(r,n)}},e.prototype.applyForce=function(e,t,i){if(e.soft)m.a.Warn("Cannot be applied to a soft body");else{e.physicsBody.activate();var n=this._tmpAmmoVectorA,r=this._tmpAmmoVectorB;e.object&&e.object.getWorldMatrix&&(e.object.getWorldMatrix().invertToRef(this._tmpMatrix),a.e.TransformCoordinatesToRef(i,this._tmpMatrix,this._tmpVector),i=this._tmpVector),n.setValue(i.x,i.y,i.z),r.setValue(t.x,t.y,t.z),e.physicsBody.applyForce(r,n)}},e.prototype.generatePhysicsBody=function(t){if(t._pluginData.toDispose=[],t.parent)t.physicsBody&&(this.removePhysicsBody(t),t.forceUpdate());else if(t.isBodyInitRequired()){var i=this._createShape(t),n=t.getParam("mass");if(t._pluginData.mass=n,t.soft)i.get_m_cfg().set_collisions(17),i.get_m_cfg().set_kDP(t.getParam("damping")),this.bjsAMMO.castObject(i,this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(t.getParam("margin")),i.setActivationState(e.DISABLE_DEACTIVATION_FLAG),this.world.addSoftBody(i,1,-1),t.physicsBody=i,t._pluginData.toDispose.push(i),this.setBodyPressure(t,0),t.type===ys.a.SoftbodyImpostor&&this.setBodyPressure(t,t.getParam("pressure")),this.setBodyStiffness(t,t.getParam("stiffness")),this.setBodyVelocityIterations(t,t.getParam("velocityIterations")),this.setBodyPositionIterations(t,t.getParam("positionIterations"));else{var r=new this.bjsAMMO.btVector3(0,0,0),o=new this.bjsAMMO.btTransform;o.setIdentity(),0!==n&&i.calculateLocalInertia(n,r),this._tmpAmmoVectorA.setValue(t.object.position.x,t.object.position.y,t.object.position.z),this._tmpAmmoQuaternion.setValue(t.object.rotationQuaternion.x,t.object.rotationQuaternion.y,t.object.rotationQuaternion.z,t.object.rotationQuaternion.w),o.setOrigin(this._tmpAmmoVectorA),o.setRotation(this._tmpAmmoQuaternion);var a=new this.bjsAMMO.btDefaultMotionState(o),s=new this.bjsAMMO.btRigidBodyConstructionInfo(n,a,i,r),c=new this.bjsAMMO.btRigidBody(s);0===n&&(c.setCollisionFlags(c.getCollisionFlags()|e.KINEMATIC_FLAG),c.setActivationState(e.DISABLE_DEACTIVATION_FLAG)),t.type!=ys.a.NoImpostor||i.getChildShape||c.setCollisionFlags(c.getCollisionFlags()|e.DISABLE_COLLISION_FLAG),this.world.addRigidBody(c),t.physicsBody=c,t._pluginData.toDispose=t._pluginData.toDispose.concat([c,s,a,o,r,i])}this.setBodyRestitution(t,t.getParam("restitution")),this.setBodyFriction(t,t.getParam("friction"))}},e.prototype.removePhysicsBody=function(e){var t=this;this.world&&(e.soft?this.world.removeSoftBody(e.physicsBody):this.world.removeRigidBody(e.physicsBody),e._pluginData&&(e._pluginData.toDispose.forEach(function(e){t.bjsAMMO.destroy(e)}),e._pluginData.toDispose=[]))},e.prototype.generateJoint=function(e){var t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(t&&i){var n,r=e.joint.jointData;switch(r.mainPivot||(r.mainPivot=new a.e(0,0,0)),r.connectedPivot||(r.connectedPivot=new a.e(0,0,0)),e.joint.type){case bs.e.DistanceJoint:var o=r.maxDistance;o&&(r.mainPivot=new a.e(0,-o/2,0),r.connectedPivot=new a.e(0,o/2,0)),n=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z),new this.bjsAMMO.btVector3(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z));break;case bs.e.HingeJoint:r.mainAxis||(r.mainAxis=new a.e(0,0,0)),r.connectedAxis||(r.connectedAxis=new a.e(0,0,0));var s=new this.bjsAMMO.btVector3(r.mainAxis.x,r.mainAxis.y,r.mainAxis.z),c=new this.bjsAMMO.btVector3(r.connectedAxis.x,r.connectedAxis.y,r.connectedAxis.z);n=new this.bjsAMMO.btHingeConstraint(t,i,new this.bjsAMMO.btVector3(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z),new this.bjsAMMO.btVector3(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z),s,c);break;case bs.e.BallAndSocketJoint:n=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z),new this.bjsAMMO.btVector3(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z));break;default:m.a.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),n=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z),new this.bjsAMMO.btVector3(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z))}this.world.addConstraint(n,!e.joint.jointData.collision),e.joint.physicsJoint=n}},e.prototype.removeJoint=function(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)},e.prototype._addMeshVerts=function(e,t,i){var n=this,r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){var o=i.getIndices();o||(o=[]);var s=i.getVerticesData(en.b.PositionKind);s||(s=[]),i.computeWorldMatrix(!1);for(var c=o.length/3,l=0;l<c;l++){for(var u=[],h=0;h<3;h++){var d,f=new a.e(s[3*o[3*l+h]+0],s[3*o[3*l+h]+1],s[3*o[3*l+h]+2]);a.a.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),f=a.e.TransformCoordinates(f,this._tmpMatrix),(d=0==h?this._tmpAmmoVectorA:1==h?this._tmpAmmoVectorB:this._tmpAmmoVectorC).setValue(f.x,f.y,f.z),u.push(d)}e.addTriangle(u[0],u[1],u[2]),r++}i.getChildMeshes().forEach(function(i){r+=n._addMeshVerts(e,t,i)})}return r},e.prototype._softVertexData=function(e){var t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){var i=t.getIndices();i||(i=[]);var n=t.getVerticesData(en.b.PositionKind);n||(n=[]);var r=t.getVerticesData(en.b.NormalKind);r||(r=[]),t.computeWorldMatrix(!1);for(var o=[],s=[],c=0;c<n.length;c+=3){var l=new a.e(n[c],n[c+1],n[c+2]),u=new a.e(r[c],r[c+1],r[c+2]);l=a.e.TransformCoordinates(l,t.getWorldMatrix()),u=a.e.TransformNormal(u,t.getWorldMatrix()),o.push(l.x,l.y,l.z),s.push(u.x,u.y,u.z)}var h=new $i.a;return h.positions=o,h.normals=s,h.uvs=t.getVerticesData(en.b.UVKind),h.colors=t.getVerticesData(en.b.ColorKind),t&&t.getIndices&&(h.indices=t.getIndices()),h.applyToMesh(t),t.position=a.e.Zero(),t.rotationQuaternion=null,t.rotation=a.e.Zero(),t.computeWorldMatrix(!0),h}return $i.a.ExtractFromMesh(t)},e.prototype._createSoftbody=function(e){var t=e.object;if(t&&t.getIndices){var i=t.getIndices();i||(i=[]);var n=this._softVertexData(e),r=n.positions,o=n.normals;if(null===r||null===o)return new this.bjsAMMO.btCompoundShape;for(var s=[],c=[],l=0;l<r.length;l+=3){var u=new a.e(r[l],r[l+1],r[l+2]),h=new a.e(o[l],o[l+1],o[l+2]);s.push(u.x,u.y,-u.z),c.push(h.x,h.y,-h.z)}var d=(new this.bjsAMMO.btSoftBodyHelpers).CreateFromTriMesh(this.world.getWorldInfo(),s,t.getIndices(),i.length/3,!0),f=r.length/3,p=d.get_m_nodes();for(l=0;l<f;l++){var _;(_=p.at(l).get_m_n()).setX(c[3*l]),_.setY(c[3*l+1]),_.setZ(c[3*l+2])}return d}},e.prototype._createCloth=function(e){var t=e.object;if(t&&t.getIndices){var i=t.getIndices();i||(i=[]);var n=this._softVertexData(e),r=n.positions,o=n.normals;if(null===r||null===o)return new this.bjsAMMO.btCompoundShape;var a=r.length,s=Math.sqrt(a/3);e.segments=s;var c=s-1;return this._tmpAmmoVectorA.setValue(r[0],r[1],r[2]),this._tmpAmmoVectorB.setValue(r[3*c],r[3*c+1],r[3*c+2]),this._tmpAmmoVectorD.setValue(r[a-3],r[a-2],r[a-1]),this._tmpAmmoVectorC.setValue(r[a-3-3*c],r[a-2-3*c],r[a-1-3*c]),(new this.bjsAMMO.btSoftBodyHelpers).CreatePatch(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,this._tmpAmmoVectorC,this._tmpAmmoVectorD,s,s,e.getParam("fixedPoints"),!0)}},e.prototype._createRope=function(e){var t,i,n=this._softVertexData(e),r=n.positions,o=n.normals;if(null===r||null===o)return new this.bjsAMMO.btCompoundShape;n.applyToMesh(e.object,!0),e._isFromLine=!0;if(0===o.map(function(e){return e*e}).reduce(function(e,t){return e+t}))i=(t=r.length)/3-1,this._tmpAmmoVectorA.setValue(r[0],r[1],r[2]),this._tmpAmmoVectorB.setValue(r[t-3],r[t-2],r[t-1]);else{e._isFromLine=!1;var a=e.getParam("path");if(null===e.getParam("shape"))return m.a.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;if(r.length%(3*a.length)!=0)return m.a.Warn("Path does not match extrusion"),new this.bjsAMMO.btCompoundShape;i=(t=a.length)-1,this._tmpAmmoVectorA.setValue(a[0].x,a[0].y,a[0].z),this._tmpAmmoVectorB.setValue(a[t-1].x,a[t-1].y,a[t-1].z)}e.segments=i;var s=e.getParam("fixedPoints");s=s>3?3:s;var c=(new this.bjsAMMO.btSoftBodyHelpers).CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,s);return c.get_m_cfg().set_collisions(17),c},e.prototype._createCustom=function(e){var t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t},e.prototype._addHullVerts=function(e,t,i){var n=this,r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){var o=i.getIndices();o||(o=[]);var s=i.getVerticesData(en.b.PositionKind);s||(s=[]),i.computeWorldMatrix(!1);for(var c=o.length/3,l=0;l<c;l++){for(var u=[],h=0;h<3;h++){var d,f=new a.e(s[3*o[3*l+h]+0],s[3*o[3*l+h]+1],s[3*o[3*l+h]+2]);a.a.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),f=a.e.TransformCoordinates(f,this._tmpMatrix),(d=0==h?this._tmpAmmoVectorA:1==h?this._tmpAmmoVectorB:this._tmpAmmoVectorC).setValue(f.x,f.y,f.z),u.push(d)}e.addPoint(u[0],!0),e.addPoint(u[1],!0),e.addPoint(u[2],!0),r++}i.getChildMeshes().forEach(function(i){r+=n._addHullVerts(e,t,i)})}return r},e.prototype._createShape=function(e,t){var i=this;void 0===t&&(t=!1);var n,r=e.object,o=e.getObjectExtendSize();if(!t){var s=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];n=new this.bjsAMMO.btCompoundShape;var c=0;if(s.forEach(function(e){var t=e.getPhysicsImpostor();if(t){if(t.type==ys.a.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";var r=i._createShape(t),o=e.parent.getWorldMatrix().clone(),s=new a.e;o.decompose(s),i._tmpAmmoTransform.getOrigin().setValue(e.position.x*s.x,e.position.y*s.y,e.position.z*s.z),i._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),i._tmpAmmoTransform.setRotation(i._tmpAmmoQuaternion),n.addChildShape(i._tmpAmmoTransform,r),t.dispose(),c++}}),c>0){if(e.type!=ys.a.NoImpostor){var l=this._createShape(e,!0);l&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),n.addChildShape(this._tmpAmmoTransform,l))}return n}this.bjsAMMO.destroy(n),n=null}switch(e.type){case ys.a.SphereImpostor:if(L.a.WithinEpsilon(o.x,o.y,1e-4)&&L.a.WithinEpsilon(o.x,o.z,1e-4))n=new this.bjsAMMO.btSphereShape(o.x/2);else{var u=[new this.bjsAMMO.btVector3(0,0,0)];(n=new this.bjsAMMO.btMultiSphereShape(u,[1],1)).setLocalScaling(new this.bjsAMMO.btVector3(o.x/2,o.y/2,o.z/2))}break;case ys.a.CapsuleImpostor:n=new this.bjsAMMO.btCapsuleShape(o.x/2,o.y/2);break;case ys.a.CylinderImpostor:this._tmpAmmoVectorA.setValue(o.x/2,o.y/2,o.z/2),n=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case ys.a.PlaneImpostor:case ys.a.BoxImpostor:this._tmpAmmoVectorA.setValue(o.x/2,o.y/2,o.z/2),n=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case ys.a.MeshImpostor:if(0==e.getParam("mass")){var h=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(h);var d=this._addMeshVerts(h,r,r);n=0==d?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(h);break}case ys.a.ConvexHullImpostor:var f=new this.bjsAMMO.btConvexHullShape;0==(d=this._addHullVerts(f,r,r))?(e._pluginData.toDispose.push(f),n=new this.bjsAMMO.btCompoundShape):n=f;break;case ys.a.NoImpostor:n=new this.bjsAMMO.btSphereShape(o.x/2);break;case ys.a.CustomImpostor:n=this._createCustom(e);break;case ys.a.SoftbodyImpostor:n=this._createSoftbody(e);break;case ys.a.ClothImpostor:n=this._createCloth(e);break;case ys.a.RopeImpostor:n=this._createRope(e);break;default:m.a.Warn("The impostor type is not currently supported by the ammo plugin.")}return n},e.prototype.setTransformationFromPhysicsBody=function(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))},e.prototype.setPhysicsBodyTransformation=function(e,t,i){var n=e.physicsBody.getWorldTransform();if(n.getOrigin().x()!=t.x||n.getOrigin().y()!=t.y||n.getOrigin().z()!=t.z||n.getRotation().x()!=i.x||n.getRotation().y()!=i.y||n.getRotation().z()!=i.z||n.getRotation().w()!=i.w)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),n.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),n.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(n),0==e.mass){var r=e.physicsBody.getMotionState();r&&r.setWorldTransform(n)}else e.physicsBody.activate()},e.prototype.isSupported=function(){return void 0!==this.bjsAMMO},e.prototype.setLinearVelocity=function(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)},e.prototype.setAngularVelocity=function(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)},e.prototype.getLinearVelocity=function(e){if(e.soft)var t=e.physicsBody.linearVelocity();else t=e.physicsBody.getLinearVelocity();if(!t)return null;var i=new a.e(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i},e.prototype.getAngularVelocity=function(e){if(e.soft)var t=e.physicsBody.angularVelocity();else t=e.physicsBody.getAngularVelocity();if(!t)return null;var i=new a.e(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i},e.prototype.setBodyMass=function(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t},e.prototype.getBodyMass=function(e){return e._pluginData.mass||0},e.prototype.getBodyFriction=function(e){return e._pluginData.friction||0},e.prototype.setBodyFriction=function(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t},e.prototype.getBodyRestitution=function(e){return e._pluginData.restitution||0},e.prototype.setBodyRestitution=function(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t},e.prototype.getBodyPressure=function(e){return e.soft?e._pluginData.pressure||0:(m.a.Warn("Pressure is not a property of a rigid body"),0)},e.prototype.setBodyPressure=function(e,t){e.soft?e.type===ys.a.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):m.a.Warn("Pressure can only be applied to a softbody")},e.prototype.getBodyStiffness=function(e){return e.soft?e._pluginData.stiffness||0:(m.a.Warn("Stiffness is not a property of a rigid body"),0)},e.prototype.setBodyStiffness=function(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):m.a.Warn("Stiffness cannot be applied to a rigid body")},e.prototype.getBodyVelocityIterations=function(e){return e.soft?e._pluginData.velocityIterations||0:(m.a.Warn("Velocity iterations is not a property of a rigid body"),0)},e.prototype.setBodyVelocityIterations=function(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):m.a.Warn("Velocity iterations cannot be applied to a rigid body")},e.prototype.getBodyPositionIterations=function(e){return e.soft?e._pluginData.positionIterations||0:(m.a.Warn("Position iterations is not a property of a rigid body"),0)},e.prototype.setBodyPositionIterations=function(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):m.a.Warn("Position iterations cannot be applied to a rigid body")},e.prototype.appendAnchor=function(e,t,i,n,r,o){void 0===r&&(r=1),void 0===o&&(o=!1);var a=e.segments,s=Math.round((a-1)*i)+a*(a-1-Math.round((a-1)*n));e.physicsBody.appendAnchor(s,t.physicsBody,o,r)},e.prototype.appendHook=function(e,t,i,n,r){void 0===n&&(n=1),void 0===r&&(r=!1);var o=Math.round(e.segments*i);e.physicsBody.appendAnchor(o,t.physicsBody,r,n)},e.prototype.sleepBody=function(e){m.a.Warn("sleepBody is not currently supported by the Ammo physics plugin")},e.prototype.wakeUpBody=function(e){e.physicsBody.activate()},e.prototype.updateDistanceJoint=function(e,t,i){m.a.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")},e.prototype.setMotor=function(e,t,i,n){e.physicsJoint.enableAngularMotor(!0,t,i)},e.prototype.setLimit=function(e,t,i){m.a.Warn("setLimit is not currently supported by the Ammo physics plugin")},e.prototype.syncMeshWithImpostor=function(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())},e.prototype.getRadius=function(e){return e.getObjectExtendSize().x/2},e.prototype.getBoxSizeToRef=function(e,t){var i=e.getObjectExtendSize();t.x=i.x,t.y=i.y,t.z=i.z},e.prototype.dispose=function(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null},e.prototype.raycast=function(e,t){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);var i=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);return this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,i),this._raycastResult.reset(e,t),i.hasHit()&&(this._raycastResult.setHitData({x:i.get_m_hitNormalWorld().x(),y:i.get_m_hitNormalWorld().y(),z:i.get_m_hitNormalWorld().z()},{x:i.get_m_hitPointWorld().x(),y:i.get_m_hitPointWorld().y(),z:i.get_m_hitPointWorld().z()}),this._raycastResult.calculateHitDistance()),this.bjsAMMO.destroy(i),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB),this._raycastResult},e.DISABLE_COLLISION_FLAG=4,e.KINEMATIC_FLAG=2,e.DISABLE_DEACTIVATION_FLAG=4,e}();n.a.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return-1;var t=this.reflectionProbes.indexOf(e);return-1!==t&&this.reflectionProbes.splice(t,1),t},n.a.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};var Rs=function(){function e(e,t,i,n,r){var o=this;void 0===n&&(n=!0),void 0===r&&(r=!1),this.name=e,this._viewMatrix=a.a.Identity(),this._target=a.e.Zero(),this._add=a.e.Zero(),this._invertYAxis=!1,this.position=a.e.Zero(),this._scene=i,this._scene.reflectionProbes||(this._scene.reflectionProbes=new Array),this._scene.reflectionProbes.push(this),this._renderTargetTexture=new Fi(e,t,i,n,!0,r?g.a.TEXTURETYPE_FLOAT:g.a.TEXTURETYPE_UNSIGNED_INT,!0),this._renderTargetTexture.onBeforeRenderObservable.add(function(e){switch(e){case 0:o._add.copyFromFloats(1,0,0);break;case 1:o._add.copyFromFloats(-1,0,0);break;case 2:o._add.copyFromFloats(0,o._invertYAxis?1:-1,0);break;case 3:o._add.copyFromFloats(0,o._invertYAxis?-1:1,0);break;case 4:o._add.copyFromFloats(0,0,1);break;case 5:o._add.copyFromFloats(0,0,-1)}o._attachedMesh&&o.position.copyFrom(o._attachedMesh.getAbsolutePosition()),o.position.addToRef(o._add,o._target),a.a.LookAtLHToRef(o.position,o._target,a.e.Up(),o._viewMatrix),i.activeCamera&&(o._projectionMatrix=a.a.PerspectiveFovLH(Math.PI/2,1,i.activeCamera.minZ,i.activeCamera.maxZ),i.setTransformMatrix(o._viewMatrix,o._projectionMatrix)),i._forcedViewPosition=o.position}),this._renderTargetTexture.onAfterUnbindObservable.add(function(){i._forcedViewPosition=null,i.updateTransformMatrix(!0)})}return Object.defineProperty(e.prototype,"samples",{get:function(){return this._renderTargetTexture.samples},set:function(e){this._renderTargetTexture.samples=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"refreshRate",{get:function(){return this._renderTargetTexture.refreshRate},set:function(e){this._renderTargetTexture.refreshRate=e},enumerable:!0,configurable:!0}),e.prototype.getScene=function(){return this._scene},Object.defineProperty(e.prototype,"cubeTexture",{get:function(){return this._renderTargetTexture},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"renderList",{get:function(){return this._renderTargetTexture.renderList},enumerable:!0,configurable:!0}),e.prototype.attachToMesh=function(e){this._attachedMesh=e},e.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)},e.prototype.dispose=function(){var e=this._scene.reflectionProbes.indexOf(this);-1!==e&&this._scene.reflectionProbes.splice(e,1),this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null)},e.prototype.toString=function(e){var t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t},e.prototype.getClassName=function(){return"ReflectionProbe"},e.prototype.serialize=function(){var e=N.a.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e},e.Parse=function(t,i,n){var r=null;if(i.reflectionProbes)for(var o=0;o<i.reflectionProbes.length;o++){var a=i.reflectionProbes[o];if(a.name===t.name){r=a;break}}return(r=N.a.Parse(function(){return r||new e(t.name,t.renderTargetSize,i,t._generateMipMaps)},t,i,n)).cubeTexture._waitingRenderList=t.renderList,t._attachedMesh&&r.attachToMesh(i.getMeshByID(t._attachedMesh)),r},Object(h.c)([Object(N.k)()],e.prototype,"_attachedMesh",void 0),Object(h.c)([Object(N.o)()],e.prototype,"position",void 0),e}(),Os=function(){function e(){}return e.LoaderInjectedPhysicsEngine=void 0,e}(),Ms=function(e,t,i,n){for(var r=0,o=t.materials.length;r<o;r++){var a=t.materials[r];if(a.id===e)return Ca.a.Parse(a,i,n)}return null},Is=function(e,t,i){for(var n in t)if(e.name===t[n])return i.push(e.id),!0;return!(!e.parentId||-1===i.indexOf(e.parentId))&&(i.push(e.id),!0)},Ds=function(e,t){return e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown")},ws=function(e,t){var i=t;if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){var n=t._waitingData.lods.ids,r=i.isEnabled(!1);if(t._waitingData.lods.distances){var o=t._waitingData.lods.distances;if(o.length>=n.length){var a=o.length>n.length?o[o.length-1]:0;i.setEnabled(!1);for(var s=0;s<n.length;s++){var c=n[s],l=e.getMeshByID(c);null!=l&&i.addLODLevel(o[s],l)}a>0&&i.addLODLevel(a,null),!0===r&&i.setEnabled(!0)}else De.b.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},Ls=function(e,t,i,r,o){void 0===o&&(o=!1);var a=new Re(e),s="importScene has failed JSON parse";try{var l=JSON.parse(t);s="";var u,h,d=pr.loggingLevel===pr.DETAILED_LOGGING;if(void 0!==l.environmentTexture&&null!==l.environmentTexture){var f=void 0===l.isPBR||l.isPBR;if(l.environmentTextureType&&"BABYLON.HDRCubeTexture"===l.environmentTextureType){var p=l.environmentTextureSize?l.environmentTextureSize:128,_=new ms((l.environmentTexture.match(/https?:\/\//g)?"":i)+l.environmentTexture,e,p,!0,!f);l.environmentTextureRotationY&&(_.rotationY=l.environmentTextureRotationY),e.environmentTexture=_}else if(eo.a.EndsWith(l.environmentTexture,".env")){var g=new to((l.environmentTexture.match(/https?:\/\//g)?"":i)+l.environmentTexture,e);l.environmentTextureRotationY&&(g.rotationY=l.environmentTextureRotationY),e.environmentTexture=g}else{var v=to.CreateFromPrefilteredData((l.environmentTexture.match(/https?:\/\//g)?"":i)+l.environmentTexture,e);l.environmentTextureRotationY&&(v.rotationY=l.environmentTextureRotationY),e.environmentTexture=v}if(!0===l.createDefaultSkybox){var y=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,b=l.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,f,y,b)}a.environmentTexture=e.environmentTexture}if(void 0!==l.environmentIntensity&&null!==l.environmentIntensity&&(e.environmentIntensity=l.environmentIntensity),void 0!==l.lights&&null!==l.lights)for(u=0,h=l.lights.length;u<h;u++){var T=l.lights[u],E=kr.a.Parse(T,e);E&&(a.lights.push(E),s+=0===u?"\n\tLights:":"",s+="\n\t\t"+E.toString(d))}if(void 0!==l.reflectionProbes&&null!==l.reflectionProbes)for(u=0,h=l.reflectionProbes.length;u<h;u++){var x=l.reflectionProbes[u],P=Rs.Parse(x,e,i);P&&(a.reflectionProbes.push(P),s+=0===u?"\n\tReflection Probes:":"",s+="\n\t\t"+P.toString(d))}if(void 0!==l.animations&&null!==l.animations)for(u=0,h=l.animations.length;u<h;u++){var A=l.animations[u],S=c.a.GetClass("BABYLON.Animation");if(S){var C=S.Parse(A);e.animations.push(C),a.animations.push(C),s+=0===u?"\n\tAnimations:":"",s+="\n\t\t"+C.toString(d)}}if(void 0!==l.materials&&null!==l.materials)for(u=0,h=l.materials.length;u<h;u++){var R=l.materials[u],O=Ca.a.Parse(R,e,i);if(O)a.materials.push(O),s+=0===u?"\n\tMaterials:":"",s+="\n\t\t"+O.toString(d),O.getActiveTextures().forEach(function(e){-1==a.textures.indexOf(e)&&a.textures.push(e)})}if(void 0!==l.multiMaterials&&null!==l.multiMaterials)for(u=0,h=l.multiMaterials.length;u<h;u++){var I=l.multiMaterials[u],D=fs.a.ParseMultiMaterial(I,e);a.multiMaterials.push(D),s+=0===u?"\n\tMultiMaterials:":"",s+="\n\t\t"+D.toString(d),D.getActiveTextures().forEach(function(e){-1==a.textures.indexOf(e)&&a.textures.push(e)})}if(void 0!==l.morphTargetManagers&&null!==l.morphTargetManagers)for(var w=0,L=l.morphTargetManagers;w<L.length;w++){var N=L[w];a.morphTargetManagers.push(vs.Parse(N,e))}if(void 0!==l.skeletons&&null!==l.skeletons)for(u=0,h=l.skeletons.length;u<h;u++){var F=l.skeletons[u],B=ot.Parse(F,e);a.skeletons.push(B),s+=0===u?"\n\tSkeletons:":"",s+="\n\t\t"+B.toString(d)}var U=l.geometries;if(null!=U){var V=new Array,k=U.vertexData;if(null!=k)for(u=0,h=k.length;u<h;u++){var z=k[u];V.push(ds.a.Parse(z,e,i))}V.forEach(function(e){e&&a.geometries.push(e)})}if(void 0!==l.transformNodes&&null!==l.transformNodes)for(u=0,h=l.transformNodes.length;u<h;u++){var G=l.transformNodes[u],j=wr.a.Parse(G,e,i);a.transformNodes.push(j)}if(void 0!==l.meshes&&null!==l.meshes)for(u=0,h=l.meshes.length;u<h;u++){var W=l.meshes[u],X=Ae.a.Parse(W,e,i);a.meshes.push(X),s+=0===u?"\n\tMeshes:":"",s+="\n\t\t"+X.toString(d)}if(void 0!==l.cameras&&null!==l.cameras)for(u=0,h=l.cameras.length;u<h;u++){var H=l.cameras[u],Y=Qe.a.Parse(H,e);a.cameras.push(Y),s+=0===u?"\n\tCameras:":"",s+="\n\t\t"+Y.toString(d)}if(void 0!==l.animationGroups&&null!==l.animationGroups)for(u=0,h=l.animationGroups.length;u<h;u++){var K=l.animationGroups[u],Q=ie.Parse(K,e);a.animationGroups.push(Q),s+=0===u?"\n\tAnimationGroups:":"",s+="\n\t\t"+Q.toString(d)}for(u=0,h=e.cameras.length;u<h;u++){(Y=e.cameras[u])._waitingParentId&&(Y.parent=e.getLastEntryByID(Y._waitingParentId),Y._waitingParentId=null)}for(u=0,h=e.lights.length;u<h;u++){var q=e.lights[u];q&&q._waitingParentId&&(q.parent=e.getLastEntryByID(q._waitingParentId),q._waitingParentId=null)}for(u=0,h=e.transformNodes.length;u<h;u++){var Z=e.transformNodes[u];Z._waitingParentId&&(Z.parent=e.getLastEntryByID(Z._waitingParentId),Z._waitingParentId=null)}for(u=0,h=e.meshes.length;u<h;u++){(X=e.meshes[u])._waitingParentId&&(X.parent=e.getLastEntryByID(X._waitingParentId),X._waitingParentId=null),X._waitingData.lods&&ws(e,X)}for(u=0,h=e.skeletons.length;u<h;u++){(B=e.skeletons[u])._hasWaitingData&&(null!=B.bones&&B.bones.forEach(function(t){if(t._waitingTransformNodeId){var i=e.getLastEntryByID(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}}),B._hasWaitingData=null)}for(u=0,h=e.meshes.length;u<h;u++){var J=e.meshes[u];J._waitingData.freezeWorldMatrix?(J.freezeWorldMatrix(),J._waitingData.freezeWorldMatrix=null):J.computeWorldMatrix(!0)}for(u=0,h=e.lights.length;u<h;u++){var $=e.lights[u];if($._excludedMeshesIds.length>0){for(var ee=0;ee<$._excludedMeshesIds.length;ee++){var te=e.getMeshByID($._excludedMeshesIds[ee]);te&&$.excludedMeshes.push(te)}$._excludedMeshesIds=[]}if($._includedOnlyMeshesIds.length>0){for(var ne=0;ne<$._includedOnlyMeshesIds.length;ne++){var re=e.getMeshByID($._includedOnlyMeshesIds[ne]);re&&$.includedOnlyMeshes.push(re)}$._includedOnlyMeshesIds=[]}}for(n.a.Parse(l,e,a,i),u=0,h=e.meshes.length;u<h;u++){(X=e.meshes[u])._waitingData.actions&&(M.Parse(X._waitingData.actions,X,e),X._waitingData.actions=null)}void 0!==l.actions&&null!==l.actions&&M.Parse(l.actions,null,e)}catch(e){var oe=Ds("loadAssets",l?l.producer:"Unknown")+s;if(!r)throw m.a.Log(oe),e;r(oe,e)}finally{o||a.removeAllFromScene(),null!==s&&pr.loggingLevel!==pr.NO_LOGGING&&m.a.Log(Ds("loadAssets",l?l.producer:"Unknown")+(pr.loggingLevel!==pr.MINIMAL_LOGGING?s:""))}return a};pr.RegisterPlugin({name:"babylon.js",extensions:".babylon",canDirectLoad:function(e){return-1!==e.indexOf("babylon")},importMesh:function(e,t,i,r,o,a,s,c){var l="importMesh has failed JSON parse";try{var u=JSON.parse(i);l="";var h=pr.loggingLevel===pr.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;var d=new Array;if(void 0!==u.meshes&&null!==u.meshes){var f,p,_,g=[],v=[];for(f=0,p=u.meshes.length;f<p;f++){var y=u.meshes[f];if(null===e||Is(y,e,d)){if(null!==e&&delete e[e.indexOf(y.name)],void 0!==y.geometryId&&null!==y.geometryId&&void 0!==u.geometries&&null!==u.geometries){var b=!1;["boxes","spheres","cylinders","toruses","grounds","planes","torusKnots","vertexData"].forEach(function(e){!0!==b&&u.geometries[e]&&Array.isArray(u.geometries[e])&&u.geometries[e].forEach(function(i){if(i.id===y.geometryId){switch(e){case"vertexData":ds.a.Parse(i,t,r)}b=!0}})}),!1===b&&m.a.Warn("Geometry not found for mesh "+y.id)}if(y.materialId){var T=-1!==v.indexOf(y.materialId);if(!1===T&&void 0!==u.multiMaterials&&null!==u.multiMaterials)for(var E=0,x=u.multiMaterials.length;E<x;E++){var P=u.multiMaterials[E];if(P.id===y.materialId){for(var A=0,S=P.materials.length;A<S;A++){var C,R=P.materials[A];v.push(R),(C=Ms(R,u,t,r))&&(l+="\n\tMaterial "+C.toString(h))}v.push(P.id);var O=fs.a.ParseMultiMaterial(P,t);O&&(T=!0,l+="\n\tMulti-Material "+O.toString(h));break}}if(!1===T)v.push(y.materialId),(C=Ms(y.materialId,u,t,r))?l+="\n\tMaterial "+C.toString(h):m.a.Warn("Material not found for mesh "+y.id)}if(y.skeletonId>-1&&void 0!==u.skeletons&&null!==u.skeletons)if(!1===g.indexOf(y.skeletonId)>-1)for(var M=0,I=u.skeletons.length;M<I;M++){var D=u.skeletons[M];if(D.id===y.skeletonId){var w=ot.Parse(D,t);s.push(w),g.push(D.id),l+="\n\tSkeleton "+w.toString(h)}}if(void 0!==u.morphTargetManagers&&null!==u.morphTargetManagers)for(var L=0,N=u.morphTargetManagers;L<N.length;L++){var F=N[L];vs.Parse(F,t)}var B=Ae.a.Parse(y,t,r);o.push(B),l+="\n\tMesh "+B.toString(h)}}for(f=0,p=t.meshes.length;f<p;f++)(_=t.meshes[f])._waitingParentId&&(_.parent=t.getLastEntryByID(_._waitingParentId),_._waitingParentId=null),_._waitingData.lods&&ws(t,_);for(f=0,p=t.skeletons.length;f<p;f++){(w=t.skeletons[f])._hasWaitingData&&(null!=w.bones&&w.bones.forEach(function(e){if(e._waitingTransformNodeId){var i=t.getLastEntryByID(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}}),w._hasWaitingData=null)}for(f=0,p=t.meshes.length;f<p;f++)(_=t.meshes[f])._waitingData.freezeWorldMatrix?(_.freezeWorldMatrix(),_._waitingData.freezeWorldMatrix=null):_.computeWorldMatrix(!0)}if(void 0!==u.particleSystems&&null!==u.particleSystems){var U=n.a.GetIndividualParser(Fe.a.NAME_PARTICLESYSTEM);if(U)for(f=0,p=u.particleSystems.length;f<p;f++){var V=u.particleSystems[f];-1!==d.indexOf(V.emitterId)&&a.push(U(V,t,r))}}return!0}catch(e){var k=Ds("importMesh",u?u.producer:"Unknown")+l;if(!c)throw m.a.Log(k),e;c(k,e)}finally{null!==l&&pr.loggingLevel!==pr.NO_LOGGING&&m.a.Log(Ds("importMesh",u?u.producer:"Unknown")+(pr.loggingLevel!==pr.MINIMAL_LOGGING?l:""))}return!1},load:function(e,t,i,n){var r="importScene has failed JSON parse";try{var o=JSON.parse(t);if(r="",void 0!==o.useDelayedTextureLoading&&null!==o.useDelayedTextureLoading&&(e.useDelayedTextureLoading=o.useDelayedTextureLoading&&!pr.ForceFullSceneLoadingForIncremental),void 0!==o.autoClear&&null!==o.autoClear&&(e.autoClear=o.autoClear),void 0!==o.clearColor&&null!==o.clearColor&&(e.clearColor=s.b.FromArray(o.clearColor)),void 0!==o.ambientColor&&null!==o.ambientColor&&(e.ambientColor=s.a.FromArray(o.ambientColor)),void 0!==o.gravity&&null!==o.gravity&&(e.gravity=a.e.FromArray(o.gravity)),o.fogMode&&0!==o.fogMode)switch(e.fogMode=o.fogMode,e.fogColor=s.a.FromArray(o.fogColor),e.fogStart=o.fogStart,e.fogEnd=o.fogEnd,e.fogDensity=o.fogDensity,r+="\tFog mode for scene:  ",e.fogMode){case 1:r+="exp\n";break;case 2:r+="exp2\n";break;case 3:r+="linear\n"}if(o.physicsEnabled){var c;"cannon"===o.physicsEngine?c=new xs(void 0,void 0,Os.LoaderInjectedPhysicsEngine):"oimo"===o.physicsEngine?c=new Ps(void 0,Os.LoaderInjectedPhysicsEngine):"ammo"===o.physicsEngine&&(c=new Cs(void 0,Os.LoaderInjectedPhysicsEngine,void 0)),r="\tPhysics engine "+(o.physicsEngine?o.physicsEngine:"oimo")+" enabled\n";var l=o.physicsGravity?a.e.FromArray(o.physicsGravity):null;e.enablePhysics(l,c)}if(void 0!==o.metadata&&null!==o.metadata&&(e.metadata=o.metadata),void 0!==o.collisionsEnabled&&null!==o.collisionsEnabled&&(e.collisionsEnabled=o.collisionsEnabled),!Ls(e,t,i,n,!0))return!1;if(o.autoAnimate&&e.beginAnimation(e,o.autoAnimateFrom,o.autoAnimateTo,o.autoAnimateLoop,o.autoAnimateSpeed||1),void 0!==o.activeCameraID&&null!==o.activeCameraID&&e.setActiveCameraByID(o.activeCameraID),void 0!==o.environmentTexture&&null!==o.environmentTexture){var u=void 0===o.isPBR||o.isPBR;if(o.environmentTextureType&&"BABYLON.HDRCubeTexture"===o.environmentTextureType){var h=o.environmentTextureSize?o.environmentTextureSize:128,d=new ms(i+o.environmentTexture,e,h,!0,!u);o.environmentTextureRotationY&&(d.rotationY=o.environmentTextureRotationY),e.environmentTexture=d}else if(eo.a.EndsWith(o.environmentTexture,".env")){var f=new to(i+o.environmentTexture,e);o.environmentTextureRotationY&&(f.rotationY=o.environmentTextureRotationY),e.environmentTexture=f}else{var p=to.CreateFromPrefilteredData(i+o.environmentTexture,e);o.environmentTextureRotationY&&(p.rotationY=o.environmentTextureRotationY),e.environmentTexture=p}if(!0===o.createDefaultSkybox){var _=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,g=o.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,u,_,g)}}return!0}catch(e){var v=Ds("importScene",o?o.producer:"Unknown")+r;if(!n)throw m.a.Log(v),e;n(v,e)}finally{null!==r&&pr.loggingLevel!==pr.NO_LOGGING&&m.a.Log(Ds("importScene",o?o.producer:"Unknown")+(pr.loggingLevel!==pr.MINIMAL_LOGGING?r:""))}return!1},loadAssetContainer:function(e,t,i,n){return Ls(e,t,i,n)}});var Ns=i(111),Fs=function(){function e(){this._isEnabled=!0,this.leftColor=s.a.White(),this.rightColor=s.a.Black(),this.bias=0,this.power=1}return Object.defineProperty(e.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled!==e&&(this._isEnabled=e,Oe.a.MarkAllMaterialsAsDirty(g.a.MATERIAL_FresnelDirtyFlag|g.a.MATERIAL_MiscDirtyFlag))},enumerable:!0,configurable:!0}),e.prototype.clone=function(){var t=new e;return O.a.DeepCopy(this,t),t},e.prototype.serialize=function(){var e={};return e.isEnabled=this.isEnabled,e.leftColor=this.leftColor.asArray(),e.rightColor=this.rightColor.asArray(),e.bias=this.bias,e.power=this.power,e},e.Parse=function(t){var i=new e;return i.isEnabled=t.isEnabled,i.leftColor=s.a.FromArray(t.leftColor),i.rightColor=s.a.FromArray(t.rightColor),i.bias=t.bias,i.power=t.power||1,i},e}();N.a._FresnelParametersParser=Fs.Parse;var Bs=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.maxSimultaneousLights=4,n.disableLighting=!1,n.invertNormalMapX=!1,n.invertNormalMapY=!1,n.emissiveColor=new s.a(0,0,0),n.occlusionStrength=1,n.useLightmapAsShadowmap=!1,n._useAlphaFromAlbedoTexture=!0,n._useAmbientInGrayScale=!0,n}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"doubleSided",{get:function(){return this._twoSidedLighting},set:function(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"PBRBaseSimpleMaterial"},Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],t.prototype,"environmentTexture",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapX",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapY",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],t.prototype,"normalTexture",void 0),Object(h.c)([Object(N.e)("emissive"),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveColor",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveTexture",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],t.prototype,"occlusionStrength",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],t.prototype,"occlusionTexture",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],t.prototype,"alphaCutOff",void 0),Object(h.c)([Object(N.c)()],t.prototype,"doubleSided",null),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty",null)],t.prototype,"lightmapTexture",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useLightmapAsShadowmap",void 0),t}(ko),Us=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n._useRoughnessFromMetallicTextureAlpha=!1,n._useRoughnessFromMetallicTextureGreen=!0,n._useMetallnessFromMetallicTextureBlue=!0,n.metallic=1,n.roughness=1,n}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"PBRMetallicRoughnessMaterial"},t.prototype.clone=function(e){var i=this,n=N.a.Clone(function(){return new t(e,i.getScene())},this);return n.id=e,n.name=e,this.clearCoat.copyTo(n.clearCoat),this.anisotropy.copyTo(n.anisotropy),this.brdf.copyTo(n.brdf),this.sheen.copyTo(n.sheen),this.subSurface.copyTo(n.subSurface),n},t.prototype.serialize=function(){var e=N.a.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e},t.Parse=function(e,i,n){var r=N.a.Parse(function(){return new t(e.name,i)},e,i,n);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,i,n),e.anisotropy&&r.anisotropy.parse(e.anisotropy,i,n),e.brdf&&r.brdf.parse(e.brdf,i,n),e.sheen&&r.sheen.parse(e.sheen,i,n),e.subSurface&&r.subSurface.parse(e.subSurface,i,n),r},Object(h.c)([Object(N.e)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],t.prototype,"baseColor",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],t.prototype,"baseTexture",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallic",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"roughness",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],t.prototype,"metallicRoughnessTexture",void 0),t}(Bs);c.a.RegisteredTypes["BABYLON.PBRMetallicRoughnessMaterial"]=Us;var Vs=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n._useMicroSurfaceFromReflectivityMapAlpha=!0,n}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"PBRSpecularGlossinessMaterial"},t.prototype.clone=function(e){var i=this,n=N.a.Clone(function(){return new t(e,i.getScene())},this);return n.id=e,n.name=e,this.clearCoat.copyTo(n.clearCoat),this.anisotropy.copyTo(n.anisotropy),this.brdf.copyTo(n.brdf),this.sheen.copyTo(n.sheen),this.subSurface.copyTo(n.subSurface),n},t.prototype.serialize=function(){var e=N.a.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e},t.Parse=function(e,i,n){var r=N.a.Parse(function(){return new t(e.name,i)},e,i,n);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,i,n),e.anisotropy&&r.anisotropy.parse(e.anisotropy,i,n),e.brdf&&r.brdf.parse(e.brdf,i,n),e.sheen&&r.sheen.parse(e.sheen,i,n),e.subSurface&&r.subSurface.parse(e.subSurface,i,n),r},Object(h.c)([Object(N.e)("diffuse"),Object(N.b)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],t.prototype,"diffuseColor",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],t.prototype,"diffuseTexture",void 0),Object(h.c)([Object(N.e)("specular"),Object(N.b)("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],t.prototype,"specularColor",void 0),Object(h.c)([Object(N.c)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty","_microSurface")],t.prototype,"glossiness",void 0),Object(h.c)([Object(N.m)(),Object(N.b)("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],t.prototype,"specularGlossinessTexture",void 0),t}(Bs);c.a.RegisteredTypes["BABYLON.PBRSpecularGlossinessMaterial"]=Vs;var ks=i(82),zs=function(e){function t(t,i){var n=e.call(this,i)||this;return t?(n._engine=i.getEngine(),n._textureMatrix=a.a.Identity(),n.name=t,n.url=t,n.hasAlpha=!1,n.isCube=!1,n.is3D=n._engine.webGLVersion>1,n.wrapU=g.a.TEXTURE_CLAMP_ADDRESSMODE,n.wrapV=g.a.TEXTURE_CLAMP_ADDRESSMODE,n.wrapR=g.a.TEXTURE_CLAMP_ADDRESSMODE,n.anisotropicFilteringLevel=1,n._texture=n._getFromCache(t,!0),n._texture||(i.useDelayedTextureLoading?n.delayLoadState=g.a.DELAYLOADSTATE_NOTLOADED:n.loadTexture()),n):n}return Object(h.d)(t,e),t.prototype.getTextureMatrix=function(){return this._textureMatrix},t.prototype.load3dlTexture=function(){var e,i=this._engine;e=1===i.webGLVersion?i.createRawTexture(null,1,1,g.a.TEXTUREFORMAT_RGBA,!1,!1,g.a.TEXTURE_BILINEAR_SAMPLINGMODE,null,g.a.TEXTURETYPE_UNSIGNED_INT):i.createRawTexture3D(null,1,1,1,g.a.TEXTUREFORMAT_RGBA,!1,!1,g.a.TEXTURE_BILINEAR_SAMPLINGMODE,null,g.a.TEXTURETYPE_UNSIGNED_INT),this._texture=e;var n=function(n){if("string"==typeof n){for(var r,o=null,a=null,s=n.split("\n"),c=0,l=0,u=0,h=0,d=0,f=0;f<s.length;f++)if(r=s[f],t._noneEmptyLineRegex.test(r)&&0!==r.indexOf("#")){var p=r.split(" ");if(0!==c){if(0!=c){var _=Math.max(parseInt(p[0]),0),m=Math.max(parseInt(p[1]),0),v=Math.max(parseInt(p[2]),0);d=Math.max(_,d),d=Math.max(m,d),d=Math.max(v,d);var y=4*(l+h*c+u*c*c);a&&(a[y+0]=_,a[y+1]=m,a[y+2]=v),++u%c==0&&(u=0,++h%c==0&&(l++,h=0))}}else c=p.length,o=new Uint8Array(c*c*c*4),a=new Float32Array(c*c*c*4)}if(a&&o)for(f=0;f<a.length;f++)if(f>0&&(f+1)%4==0)o[f]=255;else{var b=a[f];o[f]=b/d*255}e.is3D?(e.updateSize(c,c,c),i.updateRawTexture3D(e,o,g.a.TEXTUREFORMAT_RGBA,!1)):(e.updateSize(c*c,c),i.updateRawTexture(e,o,g.a.TEXTUREFORMAT_RGBA,!1))}},r=this.getScene();return r?r._loadFile(this.url,n):this._engine._loadFile(this.url,n),this._texture},t.prototype.loadTexture=function(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this.load3dlTexture()},t.prototype.clone=function(){var e=new t(this.url,this.getScene());return e.level=this.level,e},t.prototype.delayLoad=function(){this.delayLoadState===g.a.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=g.a.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,!0),this._texture||this.loadTexture())},t.Parse=function(e,i){var n=null;return e.name&&!e.isRenderTarget&&((n=new t(e.name,i)).name=e.name,n.level=e.level),n},t.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e},t._noneEmptyLineRegex=/\S+/,t}(jn.a);c.a.RegisteredTypes["BABYLON.ColorGradingTexture"]=zs;var Gs=function(e){function t(t,i,n,r,o,a,s){void 0===r&&(r=!1),void 0===o&&(o=!0),void 0===a&&(a=null),void 0===s&&(s=null);var c=e.call(this,i)||this;if(c._onLoad=null,c._onError=null,c.coordinatesMode=et.a.CUBIC_MODE,!t)throw new Error("Image url is not set");return c.name=t,c.url=t,c._size=n,c._noMipmap=r,c.gammaSpace=o,c._onLoad=a,c._onError=s,c.hasAlpha=!1,c.isCube=!0,c._texture=c._getFromCache(t,c._noMipmap),c._texture?a&&(c._texture.isReady?De.b.SetImmediate(function(){return a()}):c._texture.onLoadedObservable.add(a)):i.useDelayedTextureLoading?c.delayLoadState=g.a.DELAYLOADSTATE_NOTLOADED:c.loadImage(c.loadTexture.bind(c),c._onError),c}return Object(h.d)(t,e),t.prototype.loadImage=function(e,t){var i=this,n=document.createElement("canvas"),r=new Image;r.addEventListener("load",function(){i._width=r.width,i._height=r.height,n.width=i._width,n.height=i._height;var t=n.getContext("2d");t.drawImage(r,0,0);var o=t.getImageData(0,0,r.width,r.height);i._buffer=o.data.buffer,n.remove(),e()}),r.addEventListener("error",function(e){t&&t(i.getClassName()+" could not be loaded",e)}),r.src=this.url},t.prototype.loadTexture=function(){var e=this,i=this.getScene();i&&(this._texture=i.getEngine().createRawCubeTextureFromUrl(this.url,i,this._size,g.a.TEXTUREFORMAT_RGB,i.getEngine().getCaps().textureFloat?g.a.TEXTURETYPE_FLOAT:g.a.TEXTURETYPE_UNSIGNED_INTEGER,this._noMipmap,function(){for(var i=e.getFloat32ArrayFromArrayBuffer(e._buffer),n=ps.ConvertPanoramaToCubemap(i,e._width,e._height,e._size),r=[],o=0;o<6;o++){var a=n[t._FacesMapping[o]];r.push(a)}return r},null,this._onLoad,this._onError))},t.prototype.getFloat32ArrayFromArrayBuffer=function(e){for(var t=new DataView(e),i=new Float32Array(3*e.byteLength/4),n=0,r=0;r<e.byteLength;r++)(r+1)%4!=0&&(i[n++]=t.getUint8(r)/255);return i},t.prototype.getClassName=function(){return"EquiRectangularCubeTexture"},t.prototype.clone=function(){var e=this.getScene();if(!e)return this;var i=new t(this.url,e,this._size,this._noMipmap,this.gammaSpace);return i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i.coordinatesIndex=this.coordinatesIndex,i.coordinatesMode=this.coordinatesMode,i},t._FacesMapping=["right","left","up","down","front","back"],t}(jn.a),js=function(){function e(){}return e.GetTGAHeader=function(e){var t=0;return{id_length:e[t++],colormap_type:e[t++],image_type:e[t++],colormap_index:e[t++]|e[t++]<<8,colormap_length:e[t++]|e[t++]<<8,colormap_size:e[t++],origin:[e[t++]|e[t++]<<8,e[t++]|e[t++]<<8],width:e[t++]|e[t++]<<8,height:e[t++]|e[t++]<<8,pixel_size:e[t++],flags:e[t++]}},e.UploadContent=function(t,i){if(i.length<19)m.a.Error("Unable to load TGA file - Not enough data to contain header");else{var n=18,r=e.GetTGAHeader(i);if(r.id_length+n>i.length)m.a.Error("Unable to load TGA file - Not enough data");else{n+=r.id_length;var o,a=!1,s=!1,c=!1;switch(r.image_type){case e._TYPE_RLE_INDEXED:a=!0;case e._TYPE_INDEXED:s=!0;break;case e._TYPE_RLE_RGB:a=!0;case e._TYPE_RGB:break;case e._TYPE_RLE_GREY:a=!0;case e._TYPE_GREY:c=!0}var l,u,h,d,f,p,_,g=r.pixel_size>>3,v=r.width*r.height*g;if(s&&(l=i.subarray(n,n+=r.colormap_length*(r.colormap_size>>3))),a){var y,b,T;o=new Uint8Array(v);for(var E=0,x=new Uint8Array(g);n<v&&E<v;)if(b=1+(127&(y=i[n++])),128&y){for(T=0;T<g;++T)x[T]=i[n++];for(T=0;T<b;++T)o.set(x,E+T*g);E+=g*b}else{for(b*=g,T=0;T<b;++T)o[E+T]=i[n++];E+=b}}else o=i.subarray(n,n+=s?r.width*r.height:v);switch((r.flags&e._ORIGIN_MASK)>>e._ORIGIN_SHIFT){default:case e._ORIGIN_UL:u=0,d=1,_=r.width,h=0,f=1,p=r.height;break;case e._ORIGIN_BL:u=0,d=1,_=r.width,h=r.height-1,f=-1,p=-1;break;case e._ORIGIN_UR:u=r.width-1,d=-1,_=-1,h=0,f=1,p=r.height;break;case e._ORIGIN_BR:u=r.width-1,d=-1,_=-1,h=r.height-1,f=-1,p=-1}var P=e["_getImageData"+(c?"Grey":"")+r.pixel_size+"bits"](r,l,o,h,f,p,u,d,_);t.getEngine()._uploadDataToTextureDirectly(t,P)}}},e._getImageData8bits=function(e,t,i,n,r,o,a,s,c){var l,u,h,d=i,f=t,p=e.width,_=e.height,m=0,g=new Uint8Array(p*_*4);for(h=n;h!==o;h+=r)for(u=a;u!==c;u+=s,m++)l=d[m],g[4*(u+p*h)+3]=255,g[4*(u+p*h)+2]=f[3*l+0],g[4*(u+p*h)+1]=f[3*l+1],g[4*(u+p*h)+0]=f[3*l+2];return g},e._getImageData16bits=function(e,t,i,n,r,o,a,s,c){var l,u,h,d=i,f=e.width,p=e.height,_=0,m=new Uint8Array(f*p*4);for(h=n;h!==o;h+=r)for(u=a;u!==c;u+=s,_+=2){var g=255*((31744&(l=d[_+0]+(d[_+1]<<8)))>>10)/31|0,v=255*((992&l)>>5)/31|0,y=255*(31&l)/31|0;m[4*(u+f*h)+0]=g,m[4*(u+f*h)+1]=v,m[4*(u+f*h)+2]=y,m[4*(u+f*h)+3]=32768&l?0:255}return m},e._getImageData24bits=function(e,t,i,n,r,o,a,s,c){var l,u,h=i,d=e.width,f=e.height,p=0,_=new Uint8Array(d*f*4);for(u=n;u!==o;u+=r)for(l=a;l!==c;l+=s,p+=3)_[4*(l+d*u)+3]=255,_[4*(l+d*u)+2]=h[p+0],_[4*(l+d*u)+1]=h[p+1],_[4*(l+d*u)+0]=h[p+2];return _},e._getImageData32bits=function(e,t,i,n,r,o,a,s,c){var l,u,h=i,d=e.width,f=e.height,p=0,_=new Uint8Array(d*f*4);for(u=n;u!==o;u+=r)for(l=a;l!==c;l+=s,p+=4)_[4*(l+d*u)+2]=h[p+0],_[4*(l+d*u)+1]=h[p+1],_[4*(l+d*u)+0]=h[p+2],_[4*(l+d*u)+3]=h[p+3];return _},e._getImageDataGrey8bits=function(e,t,i,n,r,o,a,s,c){var l,u,h,d=i,f=e.width,p=e.height,_=0,m=new Uint8Array(f*p*4);for(h=n;h!==o;h+=r)for(u=a;u!==c;u+=s,_++)l=d[_],m[4*(u+f*h)+0]=l,m[4*(u+f*h)+1]=l,m[4*(u+f*h)+2]=l,m[4*(u+f*h)+3]=255;return m},e._getImageDataGrey16bits=function(e,t,i,n,r,o,a,s,c){var l,u,h=i,d=e.width,f=e.height,p=0,_=new Uint8Array(d*f*4);for(u=n;u!==o;u+=r)for(l=a;l!==c;l+=s,p+=2)_[4*(l+d*u)+0]=h[p+0],_[4*(l+d*u)+1]=h[p+0],_[4*(l+d*u)+2]=h[p+0],_[4*(l+d*u)+3]=h[p+1];return _},e._TYPE_INDEXED=1,e._TYPE_RGB=2,e._TYPE_GREY=3,e._TYPE_RLE_INDEXED=9,e._TYPE_RLE_RGB=10,e._TYPE_RLE_GREY=11,e._ORIGIN_MASK=48,e._ORIGIN_SHIFT=4,e._ORIGIN_BL=0,e._ORIGIN_BR=1,e._ORIGIN_UL=2,e._ORIGIN_UR=3,e}(),Ws=function(){function e(){this.supportCascades=!1}return e.prototype.canLoad=function(e){return eo.a.EndsWith(e,".tga")},e.prototype.loadCubeData=function(e,t,i,n,r){throw".env not supported in Cube."},e.prototype.loadData=function(e,t,i){var n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=js.GetTGAHeader(n);i(r.width,r.height,t.generateMipMaps,!1,function(){js.UploadContent(t,n)})},e}();Oe.a._TextureLoaders.push(new Ws);var Xs,Hs=function(){};!function(e){e[e.cTFETC1=0]="cTFETC1",e[e.cTFBC1=1]="cTFBC1",e[e.cTFBC4=2]="cTFBC4",e[e.cTFPVRTC1_4_OPAQUE_ONLY=3]="cTFPVRTC1_4_OPAQUE_ONLY",e[e.cTFBC7_M6_OPAQUE_ONLY=4]="cTFBC7_M6_OPAQUE_ONLY",e[e.cTFETC2=5]="cTFETC2",e[e.cTFBC3=6]="cTFBC3",e[e.cTFBC5=7]="cTFBC5"}(Xs||(Xs={}));var Ys=function(){function e(){}return e.GetInternalFormatFromBasisFormat=function(e){if(e===Xs.cTFETC1)return 36196;if(e===Xs.cTFBC1)return 33776;if(e===Xs.cTFBC3)return 33779;throw"The chosen Basis transcoder format is not currently supported"},e._CreateWorkerAsync=function(){var t=this;return this._WorkerPromise||(this._WorkerPromise=new Promise(function(i){t._Worker?i(t._Worker):De.b.LoadFileAsync(e.WasmModuleURL).then(function(n){var r=URL.createObjectURL(new Blob(["("+Ks+")()"],{type:"application/javascript"}));t._Worker=new Worker(r);var o=function(e){"init"===e.data.action&&(t._Worker.removeEventListener("message",o),i(t._Worker))};t._Worker.addEventListener("message",o),t._Worker.postMessage({action:"init",url:e.JSModuleURL,wasmBinary:n})})})),this._WorkerPromise},e.TranscodeAsync=function(e,t){var i=this,n=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise(function(e,r){i._CreateWorkerAsync().then(function(){var o=i._actionId++,a=function(t){"transcode"===t.data.action&&t.data.id===o&&(i._Worker.removeEventListener("message",a),t.data.success?e(t.data):r("Transcode is not supported on this device"))};i._Worker.addEventListener("message",a);var s=new Uint8Array(n.byteLength);s.set(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),i._Worker.postMessage({action:"transcode",id:o,imageData:s,config:t,ignoreSupportedFormats:i._IgnoreSupportedFormats},[s.buffer])})})},e.LoadTextureFromTranscodeResult=function(t,i){for(var n,r=t.getEngine(),o=function(){if(n=i.fileInfo.images[a].levels[0],t._invertVScale=t.invertY,-1===i.format)if(t.type=g.a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,t.format=g.a.TEXTUREFORMAT_RGB,r.webGLVersion<2&&(L.a.Log2(n.width)%1!=0||L.a.Log2(n.height)%1!=0)){var o=new tt.a(r,tt.b.Temp);t._invertVScale=t.invertY,o.type=g.a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,o.format=g.a.TEXTUREFORMAT_RGB,o.width=n.width+3&-4,o.height=n.height+3&-4,r._bindTextureDirectly(r._gl.TEXTURE_2D,o,!0),r._uploadDataToTextureDirectly(o,n.transcodedPixels,a,0,g.a.TEXTUREFORMAT_RGB,!0),r._rescaleTexture(o,t,r.scenes[0],r._getInternalFormat(g.a.TEXTUREFORMAT_RGB),function(){r._releaseTexture(o),r._bindTextureDirectly(r._gl.TEXTURE_2D,t,!0)})}else t._invertVScale=!t.invertY,t.width=n.width+3&-4,t.height=n.height+3&-4,r._uploadDataToTextureDirectly(t,n.transcodedPixels,a,0,g.a.TEXTUREFORMAT_RGB,!0);else t.width=n.width,t.height=n.height,i.fileInfo.images[a].levels.forEach(function(n,o){r._uploadCompressedDataToTextureDirectly(t,e.GetInternalFormatFromBasisFormat(i.format),n.width,n.height,n.transcodedPixels,a,o)}),r.webGLVersion<2&&(L.a.Log2(t.width)%1!=0||L.a.Log2(t.height)%1!=0)&&(De.b.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),t._cachedWrapU=et.a.CLAMP_ADDRESSMODE,t._cachedWrapV=et.a.CLAMP_ADDRESSMODE)},a=0;a<i.fileInfo.images.length;a++)o()},e._IgnoreSupportedFormats=!1,e.JSModuleURL="https://preview.babylonjs.com/basisTranscoder/basis_transcoder.js",e.WasmModuleURL="https://preview.babylonjs.com/basisTranscoder/basis_transcoder.wasm",e._WorkerPromise=null,e._Worker=null,e._actionId=0,e}();function Ks(){var e={cTFETC1:0,cTFBC1:1,cTFBC4:2,cTFPVRTC1_4_OPAQUE_ONLY:3,cTFBC7_M6_OPAQUE_ONLY:4,cTFETC2:5,cTFBC3:6,cTFBC5:7},t=null;function i(e,t,i,n,r){var o=e.getImageTranscodedSizeInBytes(t,i,n),a=new Uint8Array(o);if(!e.transcodeImage(a,t,i,n,1,0))return null;r&&(a=function(e,t,i,n){for(var r=new Uint16Array(4),o=new Uint16Array(i*n),a=i/4,s=n/4,c=0;c<s;c++)for(var l=0;l<a;l++){var u=t+8*(c*a+l);r[0]=e[u]|e[u+1]<<8,r[1]=e[u+2]|e[u+3]<<8,r[2]=(2*(31&r[0])+1*(31&r[1]))/3|(2*(2016&r[0])+1*(2016&r[1]))/3&2016|(2*(63488&r[0])+1*(63488&r[1]))/3&63488,r[3]=(2*(31&r[1])+1*(31&r[0]))/3|(2*(2016&r[1])+1*(2016&r[0]))/3&2016|(2*(63488&r[1])+1*(63488&r[0]))/3&63488;for(var h=0;h<4;h++){var d=e[u+4+h],f=(4*c+h)*i+4*l;o[f++]=r[3&d],o[f++]=r[d>>2&3],o[f++]=r[d>>4&3],o[f++]=r[d>>6&3]}}return o}(a,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4));return a}onmessage=function(n){if("init"===n.data.action)t||(Module={wasmBinary:n.data.wasmBinary},importScripts(n.data.url),t=new Promise(function(e){Module.onRuntimeInitialized=function(){Module.initializeBasis(),e()}})),t.then(function(){postMessage({action:"init"})});else if("transcode"===n.data.action){var r=n.data.config,o=n.data.imageData,a=new Module.BasisFile(o),s=function(e){for(var t=e.getHasAlpha(),i=e.getNumImages(),n=[],r=0;r<i;r++){for(var o={levels:[]},a=e.getNumLevels(r),s=0;s<a;s++){var c={width:e.getImageWidth(r,s),height:e.getImageHeight(r,s)};o.levels.push(c)}n.push(o)}return{hasAlpha:t,images:n}}(a),c=n.data.ignoreSupportedFormats?null:function(t,i){var n=null;t.supportedCompressionFormats&&(t.supportedCompressionFormats.etc1?n=e.cTFETC1:t.supportedCompressionFormats.s3tc?n=i.hasAlpha?e.cTFBC3:e.cTFBC1:t.supportedCompressionFormats.pvrtc||t.supportedCompressionFormats.etc2&&(n=e.cTFETC2));return n}(n.data.config,s),l=!1;null===c&&(l=!0,c=s.hasAlpha?e.cTFBC3:e.cTFBC1);var u=!0;a.startTranscoding()||(u=!1);for(var h=[],d=0;d<s.images.length&&u;d++){var f=s.images[d];if(void 0===r.loadSingleImage||r.loadSingleImage===d){var p=f.levels.length;!1===r.loadMipmapLevels&&(p=1);for(var _=0;_<p;_++){var m=f.levels[_],g=i(a,d,_,c,l);if(!g){u=!1;break}m.transcodedPixels=g,h.push(m.transcodedPixels.buffer)}}}a.close(),a.delete(),l&&(c=-1),u?postMessage({action:"transcode",success:u,id:n.data.id,fileInfo:s,format:c},h):postMessage({action:"transcode",success:u,id:n.data.id})}}}var Qs=function(){function e(){this.supportCascades=!0}return e.prototype.canLoad=function(e){return eo.a.EndsWith(e,".basis")},e.prototype.loadCubeData=function(e,t,i,n,r){if(!Array.isArray(e)){var o=t.getEngine().getCaps(),a={supportedCompressionFormats:{etc1:!!o.etc1,s3tc:!!o.s3tc,pvrtc:!!o.pvrtc,etc2:!!o.etc2}};Ys.TranscodeAsync(e,a).then(function(e){var i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;Ys.LoadTextureFromTranscodeResult(t,e),t.getEngine()._setCubeMapTextureParams(i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()}).catch(function(e){De.b.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0})}},e.prototype.loadData=function(e,t,i){var n=t.getEngine().getCaps(),r={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2}};Ys.TranscodeAsync(e,r).then(function(e){var n=e.fileInfo.images[0].levels[0],r=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(n.width,n.height,r,-1!==e.format,function(){Ys.LoadTextureFromTranscodeResult(t,e)})}).catch(function(e){De.b.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),i(0,0,!1,!1,function(){})})},e}();Oe.a._TextureLoaders.push(new Qs),li.a.prototype.unBindMultiColorAttachmentFramebuffer=function(e,t,i){void 0===t&&(t=!1),this._currentRenderTarget=null;var n=this._gl;if(e[0]._MSAAFramebuffer){n.bindFramebuffer(n.READ_FRAMEBUFFER,e[0]._MSAAFramebuffer),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,e[0]._framebuffer);var r=e[0]._attachments;r||(r=new Array(e.length),e[0]._attachments=r);for(var o=0;o<e.length;o++){for(var a=e[o],s=0;s<r.length;s++)r[s]=n.NONE;r[o]=n[this.webGLVersion>1?"COLOR_ATTACHMENT"+o:"COLOR_ATTACHMENT"+o+"_WEBGL"],n.readBuffer(r[o]),n.drawBuffers(r),n.blitFramebuffer(0,0,a.width,a.height,0,0,a.width,a.height,n.COLOR_BUFFER_BIT,n.NEAREST)}for(o=0;o<r.length;o++)r[o]=n[this.webGLVersion>1?"COLOR_ATTACHMENT"+o:"COLOR_ATTACHMENT"+o+"_WEBGL"];n.drawBuffers(r)}for(o=0;o<e.length;o++){!(a=e[o]).generateMipMaps||t||a.isCube||(this._bindTextureDirectly(n.TEXTURE_2D,a,!0),n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null))}i&&(e[0]._MSAAFramebuffer&&this._bindUnboundFramebuffer(e[0]._framebuffer),i()),this._bindUnboundFramebuffer(null)},li.a.prototype.createMultipleRenderTarget=function(e,t){var i=!1,n=!0,r=!1,o=!1,a=1,s=g.a.TEXTURETYPE_UNSIGNED_INT,c=g.a.TEXTURE_TRILINEAR_SAMPLINGMODE,l=new Array,u=new Array;void 0!==t&&(i=void 0!==t.generateMipMaps&&t.generateMipMaps,n=void 0===t.generateDepthBuffer||t.generateDepthBuffer,r=void 0!==t.generateStencilBuffer&&t.generateStencilBuffer,o=void 0!==t.generateDepthTexture&&t.generateDepthTexture,a=t.textureCount||1,t.types&&(l=t.types),t.samplingModes&&(u=t.samplingModes));var h=this._gl,d=h.createFramebuffer();this._bindUnboundFramebuffer(d);for(var f=e.width||e,p=e.height||e,_=[],v=[],y=this._setupFramebufferDepthAttachments(r,n,f,p),b=0;b<a;b++){var T=u[b]||c,E=l[b]||s;(E!==g.a.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(E!==g.a.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(T=g.a.TEXTURE_NEAREST_SAMPLINGMODE);var x=this._getSamplingParameters(T,i);E!==g.a.TEXTURETYPE_FLOAT||this._caps.textureFloat||(E=g.a.TEXTURETYPE_UNSIGNED_INT,m.a.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"));var P=new tt.a(this,tt.b.MultiRenderTarget),A=h[this.webGLVersion>1?"COLOR_ATTACHMENT"+b:"COLOR_ATTACHMENT"+b+"_WEBGL"];_.push(P),v.push(A),h.activeTexture(h["TEXTURE"+b]),h.bindTexture(h.TEXTURE_2D,P._webGLTexture),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MAG_FILTER,x.mag),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MIN_FILTER,x.min),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.texImage2D(h.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(E),f,p,0,h.RGBA,this._getWebGLTextureType(E),null),h.framebufferTexture2D(h.DRAW_FRAMEBUFFER,A,h.TEXTURE_2D,P._webGLTexture,0),i&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(h.TEXTURE_2D,null),P._framebuffer=d,P._depthStencilBuffer=y,P.baseWidth=f,P.baseHeight=p,P.width=f,P.height=p,P.isReady=!0,P.samples=1,P.generateMipMaps=i,P.samplingMode=T,P.type=E,P._generateDepthBuffer=n,P._generateStencilBuffer=r,P._attachments=v,this._internalTexturesCache.push(P)}if(o&&this._caps.depthTextureExtension){var S=new tt.a(this,tt.b.MultiRenderTarget);h.activeTexture(h.TEXTURE0),h.bindTexture(h.TEXTURE_2D,S._webGLTexture),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MAG_FILTER,h.NEAREST),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MIN_FILTER,h.NEAREST),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.texImage2D(h.TEXTURE_2D,0,this.webGLVersion<2?h.DEPTH_COMPONENT:h.DEPTH_COMPONENT16,f,p,0,h.DEPTH_COMPONENT,h.UNSIGNED_SHORT,null),h.framebufferTexture2D(h.FRAMEBUFFER,h.DEPTH_ATTACHMENT,h.TEXTURE_2D,S._webGLTexture,0),S._framebuffer=d,S.baseWidth=f,S.baseHeight=p,S.width=f,S.height=p,S.isReady=!0,S.samples=1,S.generateMipMaps=i,S.samplingMode=h.NEAREST,S._generateDepthBuffer=n,S._generateStencilBuffer=r,_.push(S),this._internalTexturesCache.push(S)}return h.drawBuffers(v),this._bindUnboundFramebuffer(null),this.resetTextureCache(),_},li.a.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||0==e.length)return 1;if(e[0].samples===t)return t;var i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e[0]._depthStencilBuffer&&(i.deleteRenderbuffer(e[0]._depthStencilBuffer),e[0]._depthStencilBuffer=null),e[0]._MSAAFramebuffer&&(i.deleteFramebuffer(e[0]._MSAAFramebuffer),e[0]._MSAAFramebuffer=null);for(var n=0;n<e.length;n++)e[n]._MSAARenderBuffer&&(i.deleteRenderbuffer(e[n]._MSAARenderBuffer),e[n]._MSAARenderBuffer=null);if(t>1&&i.renderbufferStorageMultisample){var r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");this._bindUnboundFramebuffer(r);var o=this._setupFramebufferDepthAttachments(e[0]._generateStencilBuffer,e[0]._generateDepthBuffer,e[0].width,e[0].height,t),a=[];for(n=0;n<e.length;n++){var s=e[n],c=i[this.webGLVersion>1?"COLOR_ATTACHMENT"+n:"COLOR_ATTACHMENT"+n+"_WEBGL"],l=i.createRenderbuffer();if(!l)throw new Error("Unable to create multi sampled framebuffer");i.bindRenderbuffer(i.RENDERBUFFER,l),i.renderbufferStorageMultisample(i.RENDERBUFFER,t,this._getRGBAMultiSampleBufferFormat(s.type),s.width,s.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,c,i.RENDERBUFFER,l),s._MSAAFramebuffer=r,s._MSAARenderBuffer=l,s.samples=t,s._depthStencilBuffer=o,i.bindRenderbuffer(i.RENDERBUFFER,null),a.push(c)}i.drawBuffers(a)}else this._bindUnboundFramebuffer(e[0]._framebuffer);return this._bindUnboundFramebuffer(null),t};var qs=function(e){function t(t,i,n,r,o){var a=this,s=!(!o||!o.generateMipMaps)&&o.generateMipMaps,c=!(!o||!o.generateDepthTexture)&&o.generateDepthTexture,l=!o||void 0===o.doNotChangeAspectRatio||o.doNotChangeAspectRatio;if((a=e.call(this,t,i,r,s,l)||this)._engine=r.getEngine(),a.isSupported){for(var u=[],h=[],d=0;d<n;d++)o&&o.types&&void 0!==o.types[d]?u.push(o.types[d]):u.push(o&&o.defaultType?o.defaultType:g.a.TEXTURETYPE_UNSIGNED_INT),o&&o.samplingModes&&void 0!==o.samplingModes[d]?h.push(o.samplingModes[d]):h.push(et.a.BILINEAR_SAMPLINGMODE);var f=!o||void 0===o.generateDepthBuffer||o.generateDepthBuffer,p=!(!o||void 0===o.generateStencilBuffer)&&o.generateStencilBuffer;return a._size=i,a._multiRenderTargetOptions={samplingModes:h,generateMipMaps:s,generateDepthBuffer:f,generateStencilBuffer:p,generateDepthTexture:c,types:u,textureCount:n},a._createInternalTextures(),a._createTextures(),a}a.dispose()}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"isSupported",{get:function(){return this._engine.webGLVersion>1||this._engine.getCaps().drawBuffersExtension},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"textures",{get:function(){return this._textures},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"depthTexture",{get:function(){return this._textures[this._textures.length-1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"wrapU",{set:function(e){if(this._textures)for(var t=0;t<this._textures.length;t++)this._textures[t].wrapU=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"wrapV",{set:function(e){if(this._textures)for(var t=0;t<this._textures.length;t++)this._textures[t].wrapV=e},enumerable:!0,configurable:!0}),t.prototype._rebuild=function(){this.releaseInternalTextures(),this._createInternalTextures();for(var e=0;e<this._internalTextures.length;e++){this._textures[e]._texture=this._internalTextures[e]}this._texture=this._internalTextures[0]},t.prototype._createInternalTextures=function(){this._internalTextures=this._engine.createMultipleRenderTarget(this._size,this._multiRenderTargetOptions)},t.prototype._createTextures=function(){this._textures=[];for(var e=0;e<this._internalTextures.length;e++){var t=new et.a(null,this.getScene());t._texture=this._internalTextures[e],this._textures.push(t)}this._texture=this._internalTextures[0]},Object.defineProperty(t.prototype,"samples",{get:function(){return this._samples},set:function(e){this._samples!==e&&(this._samples=this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures,e))},enumerable:!0,configurable:!0}),t.prototype.resize=function(e){this.releaseInternalTextures(),this._size=e,this._createInternalTextures()},t.prototype.unbindFrameBuffer=function(e,t){var i=this;e.unBindMultiColorAttachmentFramebuffer(this._internalTextures,this.isCube,function(){i.onAfterRenderObservable.notifyObservers(t)})},t.prototype.dispose=function(){this.releaseInternalTextures(),e.prototype.dispose.call(this)},t.prototype.releaseInternalTextures=function(){if(this._internalTextures)for(var e=this._internalTextures.length-1;e>=0;e--)void 0!==this._internalTextures[e]&&(this._internalTextures[e].dispose(),this._internalTextures.splice(e,1))},t}(Fi),Zs=function(){function e(e){this.name=Fe.a.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=new Array}return e.prototype.register=function(){this.scene._beforeClearStage.registerStep(Fe.a.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){},e.prototype._beforeClear=function(){if(this.scene.proceduralTexturesEnabled){De.b.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(var e=0;e<this.scene.proceduralTextures.length;e++){var t=this.scene.proceduralTextures[e];t._shouldRender()&&t.render()}De.b.EndPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0)}},e}(),Js="\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}";ai.a.ShadersStore.proceduralVertexShader=Js;var $s=function(e){function t(t,i,n,r,a,s,c){void 0===a&&(a=null),void 0===s&&(s=!0),void 0===c&&(c=!1);var l=e.call(this,null,r,!s)||this;l.isCube=c,l.isEnabled=!0,l.autoClear=!0,l.onGeneratedObservable=new o.c,l._textures={},l._currentRefreshId=-1,l._frameId=-1,l._refreshRate=1,l._vertexBuffers={},l._uniforms=new Array,l._samplers=new Array,l._floats={},l._ints={},l._floatsArrays={},l._colors3={},l._colors4={},l._vectors2={},l._vectors3={},l._matrices={},l._fallbackTextureUsed=!1,l._cachedDefines="",l._contentUpdateId=-1;var u=(r=l.getScene())._getComponent(Fe.a.NAME_PROCEDURALTEXTURE);u||(u=new Zs(r),r._addComponent(u)),r.proceduralTextures.push(l),l._engine=r.getEngine(),l.name=t,l.isRenderTarget=!0,l._size=i,l._generateMipMaps=s,l.setFragment(n),l._fallbackTexture=a,c?(l._texture=l._engine.createRenderTargetCubeTexture(i,{generateMipMaps:s,generateDepthBuffer:!1,generateStencilBuffer:!1}),l.setFloat("face",0)):l._texture=l._engine.createRenderTargetTexture(i,{generateMipMaps:s,generateDepthBuffer:!1,generateStencilBuffer:!1});var h=[];return h.push(1,1),h.push(-1,1),h.push(-1,-1),h.push(1,-1),l._vertexBuffers[en.b.PositionKind]=new en.b(l._engine,h,en.b.PositionKind,!1,!1,2),l._createIndexBuffer(),l}return Object(h.d)(t,e),t.prototype.getEffect=function(){return this._effect},t.prototype.getContent=function(){return this._contentData&&this._frameId===this._contentUpdateId?this._contentData:(this._contentData=this.readPixels(0,0,this._contentData),this._contentUpdateId=this._frameId,this._contentData)},t.prototype._createIndexBuffer=function(){var e=this._engine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)},t.prototype._rebuild=function(){var e=this._vertexBuffers[en.b.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===Fi.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=Fi.REFRESHRATE_RENDER_ONCE)},t.prototype.reset=function(){void 0!==this._effect&&this._effect.dispose()},t.prototype._getDefines=function(){return""},t.prototype.isReady=function(){var e,t=this,i=this._engine;if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;var n=this._getDefines();return!(!this._effect||n!==this._cachedDefines||!this._effect.isReady())||(e=void 0!==this._fragment.fragmentElement?{vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:{vertex:"procedural",fragment:this._fragment},this._cachedDefines=n,this._effect=i.createEffect(e,[en.b.PositionKind],this._uniforms,this._samplers,n,void 0,void 0,function(){t.releaseInternalTexture(),t._fallbackTexture&&(t._texture=t._fallbackTexture._texture,t._texture&&t._texture.incrementReferences()),t._fallbackTextureUsed=!0}),this._effect.isReady())},t.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},t.prototype.setFragment=function(e){this._fragment=e},Object.defineProperty(t.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!0,configurable:!0}),t.prototype._shouldRender=function(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)},t.prototype.getRenderSize=function(){return this._size},t.prototype.resize=function(e,t){this._fallbackTextureUsed||(this.releaseInternalTexture(),this._texture=this._engine.createRenderTargetTexture(e,t),this._size=e,this._generateMipMaps=t)},t.prototype._checkUniform=function(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)},t.prototype.setTexture=function(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this},t.prototype.setFloat=function(e,t){return this._checkUniform(e),this._floats[e]=t,this},t.prototype.setInt=function(e,t){return this._checkUniform(e),this._ints[e]=t,this},t.prototype.setFloats=function(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this},t.prototype.setColor3=function(e,t){return this._checkUniform(e),this._colors3[e]=t,this},t.prototype.setColor4=function(e,t){return this._checkUniform(e),this._colors4[e]=t,this},t.prototype.setVector2=function(e,t){return this._checkUniform(e),this._vectors2[e]=t,this},t.prototype.setVector3=function(e,t){return this._checkUniform(e),this._vectors3[e]=t,this},t.prototype.setMatrix=function(e,t){return this._checkUniform(e),this._matrices[e]=t,this},t.prototype.render=function(e){var t=this.getScene();if(t){var i=this._engine;for(var n in i.enableEffect(this._effect),i.setState(!1),this._textures)this._effect.setTexture(n,this._textures[n]);for(n in this._ints)this._effect.setInt(n,this._ints[n]);for(n in this._floats)this._effect.setFloat(n,this._floats[n]);for(n in this._floatsArrays)this._effect.setArray(n,this._floatsArrays[n]);for(n in this._colors3)this._effect.setColor3(n,this._colors3[n]);for(n in this._colors4){var r=this._colors4[n];this._effect.setFloat4(n,r.r,r.g,r.b,r.a)}for(n in this._vectors2)this._effect.setVector2(n,this._vectors2[n]);for(n in this._vectors3)this._effect.setVector3(n,this._vectors3[n]);for(n in this._matrices)this._effect.setMatrix(n,this._matrices[n]);if(this._texture){if(this.isCube)for(var o=0;o<6;o++)i.bindFramebuffer(this._texture,o,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),this._effect.setFloat("face",o),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(Ca.a.TriangleFillMode,0,6),5===o&&i.generateMipMapsForCubemap(this._texture);else i.bindFramebuffer(this._texture,0,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(Ca.a.TriangleFillMode,0,6);i.unBindFramebuffer(this._texture,this.isCube),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}}},t.prototype.clone=function(){var e=this.getSize(),i=new t(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.coordinatesMode=this.coordinatesMode,i},t.prototype.dispose=function(){var t=this.getScene();if(t){var i=t.proceduralTextures.indexOf(this);i>=0&&t.proceduralTextures.splice(i,1);var n=this._vertexBuffers[en.b.PositionKind];n&&(n.dispose(),this._vertexBuffers[en.b.PositionKind]=null),this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),e.prototype.dispose.call(this)}},Object(h.c)([Object(N.c)()],t.prototype,"isEnabled",void 0),Object(h.c)([Object(N.c)()],t.prototype,"autoClear",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_generateMipMaps",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_size",void 0),Object(h.c)([Object(N.c)()],t.prototype,"refreshRate",null),t}(et.a),ec=i(65),tc=function(e){function t(t,i,n,r,o,a){var s=e.call(this,t,n,null,r,o,a)||this;return s._animate=!0,s._time=0,s._texturePath=i,s._loadJson(i),s.refreshRate=1,s}return Object(h.d)(t,e),t.prototype._loadJson=function(e){var t=this,i=function(){m.a.Log("No config file found in "+e+" trying to use ShadersStore or DOM element");try{t.setFragment(t._texturePath)}catch(e){m.a.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},n=e+"/config.json",r=new ec.a;r.open("GET",n),r.addEventListener("load",function(){if(200===r.status||r.responseText&&r.responseText.length>0)try{t._config=JSON.parse(r.response),t.updateShaderUniforms(),t.updateTextures(),t.setFragment(t._texturePath+"/custom"),t._animate=t._config.animate,t.refreshRate=t._config.refreshrate}catch(e){i()}else i()},!1),r.addEventListener("error",function(){i()},!1);try{r.send()}catch(e){m.a.Error("CustomProceduralTexture: Error on XHR send request.")}},t.prototype.isReady=function(){if(!e.prototype.isReady.call(this))return!1;for(var t in this._textures){if(!this._textures[t].isReady())return!1}return!0},t.prototype.render=function(t){var i=this.getScene();this._animate&&i&&(this._time+=.03*i.getAnimationRatio(),this.updateShaderUniforms()),e.prototype.render.call(this,t)},t.prototype.updateTextures=function(){for(var e=0;e<this._config.sampler2Ds.length;e++)this.setTexture(this._config.sampler2Ds[e].sample2Dname,new et.a(this._texturePath+"/"+this._config.sampler2Ds[e].textureRelativeUrl,this.getScene()))},t.prototype.updateShaderUniforms=function(){if(this._config)for(var e=0;e<this._config.uniforms.length;e++){var t=this._config.uniforms[e];switch(t.type){case"float":this.setFloat(t.name,t.value);break;case"color3":this.setColor3(t.name,new s.a(t.r,t.g,t.b));break;case"color4":this.setColor4(t.name,new s.b(t.r,t.g,t.b,t.a));break;case"vector2":this.setVector2(t.name,new a.d(t.x,t.y));break;case"vector3":this.setVector3(t.name,new a.e(t.x,t.y,t.z))}}this.setFloat("time",this._time)},Object.defineProperty(t.prototype,"animate",{get:function(){return this._animate},set:function(e){this._animate=e},enumerable:!0,configurable:!0}),t}($s),ic="\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y);\nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n";ai.a.ShadersStore.noisePixelShader=ic;var nc=function(e){function t(t,i,n,r,o){void 0===i&&(i=256),void 0===n&&(n=R.a.LastCreatedScene);var a=e.call(this,t,i,"noise",n,r,o)||this;return a._time=0,a.brightness=.2,a.octaves=3,a.persistence=.8,a.animationSpeedFactor=1,a.autoClear=!1,a._updateShaderUniforms(),a}return Object(h.d)(t,e),t.prototype._updateShaderUniforms=function(){var e=this.getScene();e&&(this._time+=e.getAnimationRatio()*this.animationSpeedFactor*.01,this.setFloat("brightness",this.brightness),this.setFloat("persistence",this.persistence),this.setFloat("timeScale",this._time))},t.prototype._getDefines=function(){return"#define OCTAVES "+(0|this.octaves)},t.prototype.render=function(t){this._updateShaderUniforms(),e.prototype.render.call(this,t)},t.prototype.serialize=function(){var e={customType:"BABYLON.NoiseProceduralTexture"};return e.brightness=this.brightness,e.octaves=this.octaves,e.persistence=this.persistence,e.animationSpeedFactor=this.animationSpeedFactor,e.size=this.getSize().width,e.generateMipMaps=this._generateMipMaps,e},t.Parse=function(e,i){var n=new t(e.name,e.size,i,void 0,e.generateMipMaps);return n.brightness=e.brightness,n.octaves=e.octaves,n.persistence=e.persistence,n.animationSpeedFactor=e.animationSpeedFactor,n},t}($s);c.a.RegisteredTypes["BABYLON.NoiseProceduralTexture"]=nc;var rc,oc,ac,sc,cc,lc,uc=function(e){function t(t,i,n,r,o,a,s,c,l){void 0===r&&(r=g.a.TEXTUREFORMAT_RGBA),void 0===o&&(o=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===a&&(a=!1),void 0===s&&(s=!1),void 0===c&&(c=g.a.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===l&&(l=null);var u=e.call(this,"",t)||this;return u._texture=t.getEngine().createRawCubeTexture(i,n,r,o,a,s,c,l),u}return Object(h.d)(t,e),t.prototype.update=function(e,t,i,n,r){void 0===r&&(r=null),this._texture.getEngine().updateRawCubeTexture(this._texture,e,t,i,n,r)},t.prototype.updateRGBDAsync=function(e,i,n,r){return void 0===i&&(i=null),void 0===n&&(n=.8),void 0===r&&(r=0),t._UpdateRGBDAsync(this._texture,e,i,n,r)},t.prototype.clone=function(){var e=this;return N.a.Clone(function(){var i=e.getScene(),n=e._texture,r=new t(i,n._bufferViewArray,n.width,n.format,n.type,n.generateMipMaps,n.invertY,n.samplingMode,n._compression);return n.source===tt.b.CubeRawRGBD&&r.updateRGBDAsync(n._bufferViewArrayArray,n._sphericalPolynomial,n._lodGenerationScale,n._lodGenerationOffset),r},this)},t._UpdateRGBDAsync=function(e,t,i,n,r){return e._source=tt.b.CubeRawRGBD,e._bufferViewArrayArray=t,e._lodGenerationScale=n,e._lodGenerationOffset=r,e._sphericalPolynomial=i,qn.UploadLevelsAsync(e,t).then(function(){e.isReady=!0})},t}(to),hc=function(e){function t(t,i,n,r,o,a,s,c,l,u){void 0===s&&(s=!0),void 0===c&&(c=!1),void 0===l&&(l=et.a.TRILINEAR_SAMPLINGMODE),void 0===u&&(u=g.a.TEXTURETYPE_UNSIGNED_INT);var h=e.call(this,null,a,!s,c)||this;return h.format=o,h._engine=a.getEngine(),h._texture=a.getEngine().createRawTexture3D(t,i,n,r,o,s,c,l,null,u),h.is3D=!0,h}return Object(h.d)(t,e),t.prototype.update=function(e){this._texture&&this._engine.updateRawTexture3D(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)},t}(et.a),dc=function(e){function t(t,i,n,r,o,a,s,c,l,u){void 0===s&&(s=!0),void 0===c&&(c=!1),void 0===l&&(l=et.a.TRILINEAR_SAMPLINGMODE),void 0===u&&(u=g.a.TEXTURETYPE_UNSIGNED_INT);var h=e.call(this,null,a,!s,c)||this;return h.format=o,h._engine=a.getEngine(),h._texture=a.getEngine().createRawTexture2DArray(t,i,n,r,o,s,c,l,null,u),h.is2DArray=!0,h}return Object(h.d)(t,e),t.prototype.update=function(e){this._texture&&this._engine.updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)},t}(et.a),fc=function(e){function t(t,i,n,r){var o=e.call(this,t,i,n,r,!0)||this;return o.refractionPlane=new mn.a(0,1,0,1),o.depth=2,o.onBeforeRenderObservable.add(function(){n.clipPlane=o.refractionPlane}),o.onAfterRenderObservable.add(function(){n.clipPlane=null}),o}return Object(h.d)(t,e),t.prototype.clone=function(){var e=this.getScene();if(!e)return this;var i=this.getSize(),n=new t(this.name,i.width,e,this._generateMipMaps);return n.hasAlpha=this.hasAlpha,n.level=this.level,n.refractionPlane=this.refractionPlane.clone(),this.renderList&&(n.renderList=this.renderList.slice(0)),n.depth=this.depth,n},t.prototype.serialize=function(){if(!this.name)return null;var t=e.prototype.serialize.call(this);return t.mirrorPlane=this.refractionPlane.asArray(),t.depth=this.depth,t},t}(Fi),pc=function(e){function t(i,n,r){var o=e.call(this,r.scene)||this;return n&&(r.engine||r.scene)?(r=Object(h.a)(Object(h.a)({},t.DefaultOptions),r),o._engine=r.engine||r.scene.getEngine(),o._generateMipMaps=r.generateMipMaps,o._samplingMode=r.samplingMode,o._textureMatrix=a.a.Identity(),o.name=i,o.element=n,o._isVideo=n instanceof HTMLVideoElement,o.anisotropicFilteringLevel=1,o._createInternalTexture(),o):o}return Object(h.d)(t,e),t.prototype._createInternalTexture=function(){var e=0,t=0;this._isVideo?(e=this.element.videoWidth,t=this.element.videoHeight):(e=this.element.width,t=this.element.height),this._texture=this._engine.createDynamicTexture(e,t,this._generateMipMaps,this._samplingMode),this.update()},t.prototype.getTextureMatrix=function(){return this._textureMatrix},t.prototype.update=function(e){if(void 0===e&&(e=null),null!=this._texture)if(this._isVideo){var t=this.element;if(t.readyState<t.HAVE_CURRENT_DATA)return;this._engine.updateVideoTexture(this._texture,t,null===e||e)}else{var i=this.element;this._engine.updateDynamicTexture(this._texture,i,null===e||e,!1)}},t.DefaultOptions={generateMipMaps:!1,samplingMode:g.a.TEXTURE_BILINEAR_SAMPLINGMODE,engine:null,scene:null},t}(jn.a),_c=function(e,t,i){this.id=e,this.scale=t,this.offset=i},mc=function(){function e(t,i,n,r){return this.name=t,this.meshes=i,this.scene=r,this.options=n,this.options.map=this.options.map||["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=this.options.uvsIn||en.b.UVKind,this.options.uvsOut=this.options.uvsOut||en.b.UVKind,this.options.layout=this.options.layout||e.LAYOUT_STRIP,this.options.layout===e.LAYOUT_COLNUM&&(this.options.colnum=this.options.colnum||8),this.options.updateInputMeshes=this.options.updateInputMeshes||!0,this.options.disposeSources=this.options.disposeSources||!0,this._expecting=0,this.options.fillBlanks=this.options.fillBlanks||!0,!0===this.options.fillBlanks&&(this.options.customFillColor=this.options.customFillColor||"black"),this.options.frameSize=this.options.frameSize||256,this.options.paddingRatio=this.options.paddingRatio||.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=this.options.paddingMode||e.SUBUV_WRAP,this.options.paddingMode===e.SUBUV_COLOR&&(this.options.paddingColor=this.options.paddingColor||new s.b(0,0,0,1)),this.sets={},this.frames=[],this}return e.prototype._createFrames=function(e){for(var t=this,i=this._calculateSize(),n=new a.d(1,1).divide(i),r=0,o=this._expecting,c=this.meshes.length,l=Object.keys(this.sets),u=0;u<l.length;u++){var h=l[u],d=new qi(this.name+".TexturePack."+h+"Set",{width:i.x,height:i.y},this.scene,!0,et.a.TRILINEAR_SAMPLINGMODE,Oe.a.TEXTUREFORMAT_RGBA),f=d.getContext();f.fillStyle="rgba(0,0,0,0)",f.fillRect(0,0,i.x,i.y),d.update(!1),this.sets[h]=d}var p=this.options.frameSize||256,_=this._paddingValue,m=p+2*_;for(u=0;u<c;u++)for(var g=this.meshes[u].material,v=function(a){var c=new qi("temp",m,y.scene,!0),h=c.getContext(),d=y._getFrameOffset(u),f=function(){r++,c.update(!1);var a=h.getImageData(0,0,m,m),s=t.sets[v];if(s.getContext().putImageData(a,i.x*d.x,i.y*d.y),c.dispose(),s.update(!1),r==o)return t._calculateMeshUVFrames(p,_,i,n,t.options.updateInputMeshes||!1),void e()},v=l[a]||"_blank";if(g&&null!==g[v]){var b=g[v],T=new Image;T.src=b instanceof qi?b.getContext().canvas.toDataURL("image/png"):b.url,T.onload=function(){h.fillStyle="rgba(0,0,0,0)",h.fillRect(0,0,m,m),c.update(!1),h.setTransform(1,0,0,-1,0,0);var e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(t.options.paddingMode){case 0:for(var i=0;i<9;i++)h.drawImage(T,0,0,T.width,T.height,_+p*e[i],_+p*e[i+1]-m,p,p);break;case 1:for(var n=0;n<_;n++)h.drawImage(T,0,0,T.width,T.height,n+p*e[0],_-m,p,p),h.drawImage(T,0,0,T.width,T.height,2*_-n,_-m,p,p),h.drawImage(T,0,0,T.width,T.height,_,n-m,p,p),h.drawImage(T,0,0,T.width,T.height,_,2*_-n-m,p,p);h.drawImage(T,0,0,T.width,T.height,_+p*e[0],_+p*e[1]-m,p,p);break;case 2:h.fillStyle=(t.options.paddingColor||s.a.Black()).toHexString(),h.fillRect(0,0,m,-m),h.clearRect(_,_,p,p),h.drawImage(T,0,0,T.width,T.height,_+p*e[0],_+p*e[1]-m,p,p)}h.setTransform(1,0,0,1,0,0),f()}}else h.fillStyle="rgba(0,0,0,0)",y.options.fillBlanks&&(h.fillStyle=y.options.customFillColor),h.fillRect(0,0,m,m),f()},y=this,b=0;b<l.length;b++)v(b)},e.prototype._calculateSize=function(){var e=this.meshes.length||0,t=this.options.frameSize||0,i=this._paddingValue||0;switch(this.options.layout){case 0:return new a.d(t*e+2*i*e,t+2*i);case 1:var n=Math.max(2,Math.ceil(Math.sqrt(e))),r=t*n+2*i*n;return new a.d(r,r);case 2:var o=this.options.colnum||1,s=Math.max(1,Math.ceil(e/o));return new a.d(t*o+2*i*o,t*s+2*i*s)}return a.d.Zero()},e.prototype._calculateMeshUVFrames=function(e,t,i,n,r){for(var o=this.meshes.length,s=0;s<o;s++){var c=this.meshes[s],l=new a.d(e/i.x,e/i.y),u=n.clone().scale(t),h=this._getFrameOffset(s).add(u),d=new _c(s,l,h);this.frames.push(d),r&&(this._updateMeshUV(c,s),this._updateTextureReferences(c))}},e.prototype._getFrameOffset=function(e){var t,i,n,r=this.meshes.length;switch(this.options.layout){case 0:return t=1/r,new a.d(e*t,0);case 1:var o=Math.max(2,Math.ceil(Math.sqrt(r)));return n=e-(i=Math.floor(e/o))*o,t=1/o,new a.d(n*t,i*t);case 2:var s=this.options.colnum||1,c=Math.max(1,Math.ceil(r/s));return i=e-(n=Math.floor(e/c))*c,t=new a.d(1/s,1/c),new a.d(n*t.x,i*t.y)}return a.d.Zero()},e.prototype._updateMeshUV=function(e,t){var i=this.frames[t],n=e.getVerticesData(this.options.uvsIn||en.b.UVKind),r=[],o=0;n.length&&(o=n.length||0);for(var a=0;a<o;a+=2)r.push(n[a]*i.scale.x+i.offset.x,n[a+1]*i.scale.y+i.offset.y);e.setVerticesData(this.options.uvsOut||en.b.UVKind,r)},e.prototype._updateTextureReferences=function(e,t){void 0===t&&(t=!1);for(var i=e.material,n=Object.keys(this.sets),r=function(e){e.dispose&&e.dispose()},o=0;o<n.length;o++){var a=n[o];if(t)null!==i[a]&&r(i[a]),i[a]=this.sets[a];else{if(!i)return;null!==i[a]&&(r(i[a]),i[a]=this.sets[a])}}},e.prototype.setMeshToFrame=function(e,t,i){void 0===i&&(i=!1),this._updateMeshUV(e,t),i&&this._updateTextureReferences(e,!0)},e.prototype.processAsync=function(){var e=this;return new Promise(function(t,i){try{if(0===e.meshes.length)return void t();for(var n=0,r=function(i){var r=e.meshes[i],o=r.material;if(!o)return++n===e.meshes.length?{value:e._createFrames(t)}:"continue";o.forceCompilationAsync(r).then(function(){!function(i){if(n++,e.options.map){for(var r=0;r<e.options.map.length;r++)null!==i[e.options.map[r]]&&(e.sets[e.options.map[r]]||(e.sets[e.options.map[r]]=!0),e._expecting++);n===e.meshes.length&&e._createFrames(t)}}(o)})},o=0;o<e.meshes.length;o++){var a=r(o);if("object"==typeof a)return a.value}}catch(e){return i(e)}})},e.prototype.dispose=function(){for(var e=Object.keys(this.sets),t=0;t<e.length;t++){var i=e[t];this.sets[i].dispose()}},e.prototype.download=function(e,t){var i=this;void 0===e&&(e="png"),void 0===t&&(t=1),setTimeout(function(){var n={name:i.name,sets:{},options:{},frames:[]},r=Object.keys(i.sets),o=Object.keys(i.options);try{for(var a=0;a<r.length;a++){var s=r[a],c=i.sets[s];n.sets[s]=c.getContext().canvas.toDataURL("image/"+e,t)}for(a=0;a<o.length;a++){var l=o[a];n.options[l]=i.options[l]}for(a=0;a<i.frames.length;a++){var u=i.frames[a];n.frames.push(u.scale.x,u.scale.y,u.offset.x,u.offset.y)}}catch(e){return void m.a.Warn("Unable to download: "+e)}var h="data:text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(n,null,4)),d=document.createElement("a");d.setAttribute("href",h),d.setAttribute("download",i.name+"_texurePackage.json"),document.body.appendChild(d),d.click(),d.remove()},0)},e.prototype.updateFromJSON=function(e){try{var t=JSON.parse(e);this.name=t.name;for(var i=Object.keys(t.options),n=0;n<i.length;n++)this.options[i[n]]=t.options[i[n]];for(n=0;n<t.frames.length;n+=4){var r=new _c(n/4,new a.d(t.frames[n],t.frames[n+1]),new a.d(t.frames[n+2],t.frames[n+3]));this.frames.push(r)}var o=Object.keys(t.sets);for(n=0;n<o.length;n++){var s=new et.a(t.sets[o[n]],this.scene,!1,!1);this.sets[o[n]]=s}}catch(e){m.a.Warn("Unable to update from JSON: "+e)}},e.LAYOUT_STRIP=0,e.LAYOUT_POWER2=1,e.LAYOUT_COLNUM=2,e.SUBUV_WRAP=0,e.SUBUV_EXTEND=1,e.SUBUV_COLOR=2,e}();!function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(rc||(rc={})),function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput"}(oc||(oc={})),function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(ac||(ac={})),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime"}(sc||(sc={})),function(e){e[e.Compatible=0]="Compatible",e[e.TypeIncompatible=1]="TypeIncompatible",e[e.TargetIncompatible=2]="TargetIncompatible"}(cc||(cc={})),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(lc||(lc={}));var gc=function(){function e(e,t,i){this._connectedPoint=null,this._endpoints=new Array,this._typeConnectionSource=null,this._linkedConnectionSource=null,this._type=oc.Float,this._enforceAssociatedVariableName=!1,this.acceptedConnectionPointTypes=new Array,this.excludedConnectionPointTypes=new Array,this.onConnectionObservable=new o.c,this._prioritizeVertex=!1,this._target=rc.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}return Object.defineProperty(e.prototype,"direction",{get:function(){return this._direction},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"associatedVariableName",{get:function(){return this._ownerBlock.isInput?this._ownerBlock.associatedVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.associatedVariableName},set:function(e){this._associatedVariableName=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"innerType",{get:function(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"type",{get:function(){if(this._type===oc.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}return this._type===oc.BasedOnInput&&this._typeConnectionSource?this._typeConnectionSource.type:this._type},set:function(e){this._type=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"target",{get:function(){return this._prioritizeVertex&&this._ownerBlock?this._target!==rc.VertexAndFragment?this._target:this._ownerBlock.target===rc.Fragment?rc.Fragment:rc.Vertex:this._target},set:function(e){this._target=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isConnected",{get:function(){return null!==this.connectedPoint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isConnectedToInputBlock",{get:function(){return null!==this.connectedPoint&&this.connectedPoint.ownerBlock.isInput},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"connectInputBlock",{get:function(){return this.isConnectedToInputBlock?this.connectedPoint.ownerBlock:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"connectedPoint",{get:function(){return this._connectedPoint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"ownerBlock",{get:function(){return this._ownerBlock},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"sourceBlock",{get:function(){return this._connectedPoint?this._connectedPoint.ownerBlock:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"connectedBlocks",{get:function(){return 0===this._endpoints.length?[]:this._endpoints.map(function(e){return e.ownerBlock})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"endpoints",{get:function(){return this._endpoints},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasEndpoints",{get:function(){return this._endpoints&&this._endpoints.length>0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isConnectedInVertexShader",{get:function(){if(this.target===rc.Vertex)return!0;if(!this.hasEndpoints)return!1;for(var e=0,t=this._endpoints;e<t.length;e++){var i=t[e];if(i.ownerBlock.target===rc.Vertex)return!0;if(i.target===rc.Vertex)return!0;if((i.ownerBlock.target===rc.Neutral||i.ownerBlock.target===rc.VertexAndFragment)&&i.ownerBlock.outputs.some(function(e){return e.isConnectedInVertexShader}))return!0}return!1},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isConnectedInFragmentShader",{get:function(){if(this.target===rc.Fragment)return!0;if(!this.hasEndpoints)return!1;for(var e=0,t=this._endpoints;e<t.length;e++){var i=t[e];if(i.ownerBlock.target===rc.Fragment)return!0;if((i.ownerBlock.target===rc.Neutral||i.ownerBlock.target===rc.VertexAndFragment)&&i.ownerBlock.outputs.some(function(e){return e.isConnectedInFragmentShader}))return!0}return!1},enumerable:!0,configurable:!0}),e.prototype.getClassName=function(){return"NodeMaterialConnectionPoint"},e.prototype.canConnectTo=function(e){return this.checkCompatibilityState(e)===cc.Compatible},e.prototype.checkCompatibilityState=function(e){if(this._ownerBlock.target===rc.Fragment){var t=e.ownerBlock;if(t.target===rc.Vertex)return cc.TargetIncompatible;for(var i=0,n=t.outputs;i<n.length;i++){if(n[i].isConnectedInVertexShader)return cc.TargetIncompatible}}if(this.type!==e.type&&e.innerType!==oc.AutoDetect){switch(this.type){case oc.Vector3:if(e.type===oc.Color3)return cc.Compatible;break;case oc.Vector4:if(e.type===oc.Color4)return cc.Compatible;break;case oc.Color3:if(e.type===oc.Vector3)return cc.Compatible;break;case oc.Color4:if(e.type===oc.Vector4)return cc.Compatible}return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?cc.Compatible:cc.TypeIncompatible}return e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type)?1:cc.Compatible},e.prototype.connectTo=function(e,t){if(void 0===t&&(t=!1),!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this},e.prototype.disconnectFrom=function(e){var t=this._endpoints.indexOf(e);return-1===t?this:(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1,this)},e.prototype.serialize=function(){var e={};return e.name=this.name,this.connectedPoint&&(e.inputName=this.name,e.targetBlockId=this.connectedPoint.ownerBlock.uniqueId,e.targetConnectionName=this.connectedPoint.name),e},e.prototype.dispose=function(){this.onConnectionObservable.clear()},e}(),vc=i(138),yc=function(){function e(e,t,i,n){void 0===t&&(t=rc.Vertex),void 0===i&&(i=!1),void 0===n&&(n=!1),this._isFinalMerger=!1,this._isInput=!1,this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.name=e,this._target=t,this._isFinalMerger=i,this._isInput=n,this.uniqueId=vc.a.UniqueId}return Object.defineProperty(e.prototype,"isUnique",{get:function(){return this._isUnique},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isFinalMerger",{get:function(){return this._isFinalMerger},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isInput",{get:function(){return this._isInput},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"buildId",{get:function(){return this._buildId},set:function(e){this._buildId=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"target",{get:function(){return this._target},set:function(e){0==(this._target&e)&&(this._target=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputs",{get:function(){return this._inputs},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){return this._outputs},enumerable:!0,configurable:!0}),e.prototype.getInputByName=function(e){var t=this._inputs.filter(function(t){return t.name===e});return t.length?t[0]:null},e.prototype.getOutputByName=function(e){var t=this._outputs.filter(function(t){return t.name===e});return t.length?t[0]:null},e.prototype.initialize=function(e){},e.prototype.bind=function(e,t,i){},e.prototype._declareOutput=function(e,t){return t._getGLType(e.type)+" "+e.associatedVariableName},e.prototype._writeVariable=function(e){return e.connectedPoint?""+e.associatedVariableName:"0."},e.prototype._writeFloat=function(e){var t=e.toString();return-1===t.indexOf(".")&&(t+=".0"),""+t},e.prototype.getClassName=function(){return"NodeMaterialBlock"},e.prototype.registerInput=function(e,t,i,n){void 0===i&&(i=!1);var r=new gc(e,this,lc.Input);return r.type=t,r.isOptional=i,n&&(r.target=n),this._inputs.push(r),this},e.prototype.registerOutput=function(e,t,i){var n=new gc(e,this,lc.Output);return n.type=t,i&&(n.target=i),this._outputs.push(n),this},e.prototype.getFirstAvailableInput=function(e){void 0===e&&(e=null);for(var t=0,i=this._inputs;t<i.length;t++){var n=i[t];if(!(n.connectedPoint||e&&e.type!==n.type&&n.type!==oc.AutoDetect))return n}return null},e.prototype.getFirstAvailableOutput=function(e){void 0===e&&(e=null);for(var t=0,i=this._outputs;t<i.length;t++){var n=i[t];if(!e||!e.target||e.target===rc.Neutral||0!=(e.target&n.target))return n}return null},e.prototype.getSiblingOutput=function(e){var t=this._outputs.indexOf(e);return-1===t||t>=this._outputs.length?null:this._outputs[t+1]},e.prototype.connectTo=function(e,t){if(0!==this._outputs.length){for(var i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),n=!0;n;){var r=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&r&&i.canConnectTo(r))i.connectTo(r),n=!1;else{if(!i)throw"Unable to find a compatible match";i=this.getSiblingOutput(i)}}return this}},e.prototype._buildBlock=function(e){},e.prototype.updateUniformsAndSamples=function(e,t,i,n){},e.prototype.provideFallbacks=function(e,t){},e.prototype.initializeDefines=function(e,t,i,n){void 0===n&&(n=!1)},e.prototype.prepareDefines=function(e,t,i,n){void 0===n&&(n=!1)},e.prototype.autoConfigure=function(e){},e.prototype.replaceRepeatableContent=function(e,t,i,n){},e.prototype.isReady=function(e,t,i,n){return void 0===n&&(n=!1),!0},e.prototype._linkConnectionTypes=function(e,t){this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]},e.prototype._processBuild=function(e,t,i,n){e.build(t,n);var r=null!=t._vertexState,o=e._buildTarget===rc.Vertex&&e.target!==rc.VertexAndFragment;if(r&&(0==(e.target&e._buildTarget)||0==(e.target&i.target)||this.target!==rc.VertexAndFragment&&o)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute)){var a=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+a.associatedVariableName,t._getGLType(a.type))&&(t._vertexState.compilationString+="v_"+a.associatedVariableName+" = "+a.associatedVariableName+";\r\n"),i.associatedVariableName="v_"+a.associatedVariableName,i._enforceAssociatedVariableName=!0}},e.prototype.build=function(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(var i=0,n=this._outputs;i<n.length;i++){(l=n[i]).associatedVariableName||(l.associatedVariableName=e._getFreeVariableName(l.name))}for(var r=0,o=this._inputs;r<o.length;r++){var a=o[r];if(a.connectedPoint){if(this.target!==rc.Neutral){if(0==(a.target&this.target))continue;if(0==(a.target&e.target))continue}(d=a.connectedPoint.ownerBlock)&&d!==this&&this._processBuild(d,e,a,t)}else a.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(a)}if(this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&console.log((e.target===rc.Vertex?"Vertex shader":"Fragment shader")+": Building "+this.name+" ["+this.getClassName()+"]"),this.isFinalMerger)switch(e.target){case rc.Vertex:e.sharedData.checks.emitVertex=!0;break;case rc.Fragment:e.sharedData.checks.emitFragment=!0}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+="\r\n//"+this.name+"\r\n"),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(var s=0,c=this._outputs;s<c.length;s++){var l;if(0!=((l=c[s]).target&e.target))for(var u=0,h=l.endpoints;u<h.length;u++){var d,f=h[u];(d=f.ownerBlock)&&0!=(d.target&e.target)&&-1!==t.indexOf(d)&&this._processBuild(d,e,f,t)}}return!1},e.prototype._inputRename=function(e){return e},e.prototype._outputRename=function(e){return e},e.prototype._dumpPropertiesCode=function(){return""},e.prototype._dumpCode=function(e,t){var i;t.push(this);var n=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=n||this.getClassName()+"_"+this.uniqueId,-1!==e.indexOf(this._codeVariableName)){var r=0;do{r++,this._codeVariableName=n+r}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName),i="\r\n// "+this.getClassName()+"\r\n",this.comments&&(i+="// "+this.comments+"\r\n"),i+="var "+this._codeVariableName+" = new BABYLON."+this.getClassName()+'("'+this.name+'");\r\n',i+=this._dumpPropertiesCode();for(var o=0,a=this.inputs;o<a.length;o++){var s=a[o];if(s.isConnected){var c=s.connectedPoint.ownerBlock;-1===t.indexOf(c)&&(i+=c._dumpCode(e,t))}}for(var l=0,u=this.outputs;l<u.length;l++){var h=u[l];if(h.hasEndpoints)for(var d=0,f=h.endpoints;d<f.length;d++){(c=f[d].ownerBlock)&&-1===t.indexOf(c)&&(i+=c._dumpCode(e,t))}}return i},e.prototype._dumpCodeForOutputConnections=function(e){var t="";if(-1!==e.indexOf(this))return t;e.push(this);for(var i=0,n=this.inputs;i<n.length;i++){var r=n[i];if(r.isConnected){var o=r.connectedPoint,a=o.ownerBlock;t+=a._dumpCodeForOutputConnections(e),t+=a._codeVariableName+"."+a._outputRename(o.name)+".connectTo("+this._codeVariableName+"."+this._inputRename(r.name)+");\r\n"}}return t},e.prototype.clone=function(e,t){void 0===t&&(t="");var i=this.serialize(),n=c.a.GetClass(i.customType);if(n){var r=new n;return r._deserialize(i,e,t),r}return null},e.prototype.serialize=function(){var e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.inputs=[];for(var t=0,i=this.inputs;t<i.length;t++){var n=i[t];e.inputs.push(n.serialize())}return e},e.prototype._deserialize=function(e,t,i){this.name=e.name,this.comments=e.comments},e.prototype.dispose=function(){for(var e=0,t=this.inputs;e<t.length;e++){t[e].dispose()}for(var i=0,n=this.outputs;i<n.length;i++){n[i].dispose()}},e}(),bc=function(){function e(){this.supportUniformBuffers=!1,this.attributes=new Array,this.uniforms=new Array,this.constants=new Array,this.samplers=new Array,this.functions={},this.extensions={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}return e.prototype.finalize=function(e){var t=e.sharedData.emitComments,i=this.target===rc.Fragment;this.compilationString="\r\n"+(t?"//Entry point\r\n":"")+"void main(void) {\r\n"+this.compilationString,this._constantDeclaration&&(this.compilationString="\r\n"+(t?"//Constants\r\n":"")+this._constantDeclaration+"\r\n"+this.compilationString);var n="";for(var r in this.functions)n+=this.functions[r]+"\r\n";for(var o in this.compilationString="\r\n"+n+"\r\n"+this.compilationString,!i&&this._varyingTransfer&&(this.compilationString=this.compilationString+"\r\n"+this._varyingTransfer),this.compilationString=this.compilationString+"\r\n}",this.sharedData.varyingDeclaration&&(this.compilationString="\r\n"+(t?"//Varyings\r\n":"")+this.sharedData.varyingDeclaration+"\r\n"+this.compilationString),this._samplerDeclaration&&(this.compilationString="\r\n"+(t?"//Samplers\r\n":"")+this._samplerDeclaration+"\r\n"+this.compilationString),this._uniformDeclaration&&(this.compilationString="\r\n"+(t?"//Uniforms\r\n":"")+this._uniformDeclaration+"\r\n"+this.compilationString),this._attributeDeclaration&&!i&&(this.compilationString="\r\n"+(t?"//Attributes\r\n":"")+this._attributeDeclaration+"\r\n"+this.compilationString),this.extensions){var a=this.extensions[o];this.compilationString="\r\n"+a+"\r\n"+this.compilationString}this._builtCompilationString=this.compilationString},Object.defineProperty(e.prototype,"_repeatableContentAnchor",{get:function(){return"###___ANCHOR"+this._repeatableContentAnchorIndex+++"___###"},enumerable:!0,configurable:!0}),e.prototype._getFreeVariableName=function(e){return e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e]?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])},e.prototype._getFreeDefineName=function(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]},e.prototype._excludeVariableName=function(e){this.sharedData.variableNames[e]=0},e.prototype._emit2DSampler=function(e){this._samplerDeclaration+="uniform sampler2D "+e+";\r\n",this.samplers.push(e)},e.prototype._getGLType=function(e){switch(e){case oc.Float:return"float";case oc.Int:return"int";case oc.Vector2:return"vec2";case oc.Color3:case oc.Vector3:return"vec3";case oc.Color4:case oc.Vector4:return"vec4";case oc.Matrix:return"mat4"}return""},e.prototype._emitExtension=function(e,t){this.extensions[e]||(this.extensions[e]=t)},e.prototype._emitFunction=function(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+"\r\n"+t),this.functions[e]=t)},e.prototype._emitCodeFromInclude=function(e,t,i){if(i&&i.repeatKey)return"#include<"+e+">[0.."+i.repeatKey+"]\r\n";var n=ai.a.IncludesShadersStore[e]+"\r\n";if(this.sharedData.emitComments&&(n=t+"\r\n"+n),!i)return n;if(i.replaceStrings)for(var r=0;r<i.replaceStrings.length;r++){var o=i.replaceStrings[r];n=n.replace(o.search,o.replace)}return n},e.prototype._emitFunctionFromInclude=function(e,t,i,n){void 0===n&&(n="");var r=e+n;if(!this.functions[r]){if(!(i&&(i.removeAttributes||i.removeUniforms||i.removeVaryings||i.removeIfDef||i.replaceStrings)))return i&&i.repeatKey?this.functions[r]="#include<"+e+">[0.."+i.repeatKey+"]\r\n":this.functions[r]="#include<"+e+">\r\n",void(this.sharedData.emitComments&&(this.functions[r]=t+"\r\n"+this.functions[r]));if(this.functions[r]=ai.a.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[r]=t+"\r\n"+this.functions[r]),i.removeIfDef&&(this.functions[r]=this.functions[r].replace(/^\s*?#ifdef.+$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#endif.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#else.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[r]=this.functions[r].replace(/^\s*?attribute.+$/gm,"")),i.removeUniforms&&(this.functions[r]=this.functions[r].replace(/^\s*?uniform.+$/gm,"")),i.removeVaryings&&(this.functions[r]=this.functions[r].replace(/^\s*?varying.+$/gm,"")),i.replaceStrings)for(var o=0;o<i.replaceStrings.length;o++){var a=i.replaceStrings[o];this.functions[r]=this.functions[r].replace(a.search,a.replace)}}},e.prototype._registerTempVariable=function(e){return-1===this.sharedData.temps.indexOf(e)&&(this.sharedData.temps.push(e),!0)},e.prototype._emitVaryingFromString=function(e,t,i,n){return void 0===i&&(i=""),void 0===n&&(n=!1),-1===this.sharedData.varyings.indexOf(e)&&(this.sharedData.varyings.push(e),i&&(eo.a.StartsWith(i,"defined(")?this.sharedData.varyingDeclaration+="#if "+i+"\r\n":this.sharedData.varyingDeclaration+=(n?"#ifndef":"#ifdef")+" "+i+"\r\n"),this.sharedData.varyingDeclaration+="varying "+t+" "+e+";\r\n",i&&(this.sharedData.varyingDeclaration+="#endif\r\n"),!0)},e.prototype._emitUniformFromString=function(e,t,i,n){void 0===i&&(i=""),void 0===n&&(n=!1),-1===this.uniforms.indexOf(e)&&(this.uniforms.push(e),i&&(this._uniformDeclaration+=(n?"#ifndef":"#ifdef")+" "+i+"\r\n"),this._uniformDeclaration+="uniform "+t+" "+e+";\r\n",i&&(this._uniformDeclaration+="#endif\r\n"))},e.prototype._emitFloat=function(e){return e.toString()===e.toFixed(0)?e+".0":e.toString()},e}(),Tc=function(){function e(){this.temps=new Array,this.varyings=new Array,this.varyingDeclaration="",this.inputBlocks=new Array,this.textureBlocks=new Array,this.bindableBlocks=new Array,this.blocksWithFallbacks=new Array,this.blocksWithDefines=new Array,this.repeatableContentBlocks=new Array,this.dynamicUniformBlocks=new Array,this.blockingBlocks=new Array,this.animatedInputs=new Array,this.variableNames={},this.defineNames={},this.hints={needWorldViewMatrix:!1,needWorldViewProjectionMatrix:!1,needAlphaBlending:!1,needAlphaTesting:!1},this.checks={emitVertex:!1,emitFragment:!1,notConnectedNonOptionalInputs:new Array},this.variableNames.position=0,this.variableNames.normal=0,this.variableNames.tangent=0,this.variableNames.uv=0,this.variableNames.uv2=0,this.variableNames.uv3=0,this.variableNames.uv4=0,this.variableNames.uv4=0,this.variableNames.uv5=0,this.variableNames.uv6=0,this.variableNames.color=0,this.variableNames.matricesIndices=0,this.variableNames.matricesWeights=0,this.variableNames.matricesIndicesExtra=0,this.variableNames.matricesWeightsExtra=0,this.variableNames.diffuseBase=0,this.variableNames.specularBase=0,this.variableNames.worldPos=0,this.variableNames.shadow=0,this.variableNames.vTBN=0,this.defineNames.MAINUV0=0,this.defineNames.MAINUV1=0,this.defineNames.MAINUV2=0,this.defineNames.MAINUV3=0,this.defineNames.MAINUV4=0,this.defineNames.MAINUV5=0,this.defineNames.MAINUV6=0,this.defineNames.MAINUV7=0}return e.prototype.emitErrors=function(){var e="";this.checks.emitVertex||(e+="NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.\r\n"),this.checks.emitFragment||(e+="NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\r\n");for(var t=0,i=this.checks.notConnectedNonOptionalInputs;t<i.length;t++){var n=i[t];e+="input "+n.name+" from block "+n.ownerBlock.name+"["+n.ownerBlock.getClassName()+"] is not connected and is not optional.\r\n"}if(e)throw"Build of NodeMaterial failed:\r\n"+e},e}(),Ec=function(e){function t(t){var i=e.call(this,t,rc.Vertex)||this;return i.complementW=1,i.complementZ=0,i.registerInput("vector",oc.AutoDetect),i.registerInput("transform",oc.Matrix),i.registerOutput("output",oc.Vector4),i.registerOutput("xyz",oc.Vector3),i._inputs[0].onConnectionObservable.add(function(e){if(e.ownerBlock.isInput){var t=e.ownerBlock;"normal"!==t.name&&"tangent"!==t.name||(i.complementW=0)}}),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"TransformBlock"},Object.defineProperty(t.prototype,"vector",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"xyz",{get:function(){return this._outputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transform",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.vector,n=this.transform;if(i.connectedPoint){switch(i.connectedPoint.type){case oc.Vector2:t.compilationString+=this._declareOutput(this.output,t)+" = "+n.associatedVariableName+" * vec4("+i.associatedVariableName+", "+this._writeFloat(this.complementZ)+", "+this._writeFloat(this.complementW)+");\r\n";break;case oc.Vector3:case oc.Color3:t.compilationString+=this._declareOutput(this.output,t)+" = "+n.associatedVariableName+" * vec4("+i.associatedVariableName+", "+this._writeFloat(this.complementW)+");\r\n";break;default:t.compilationString+=this._declareOutput(this.output,t)+" = "+n.associatedVariableName+" * "+i.associatedVariableName+";\r\n"}this.xyz.hasEndpoints&&(t.compilationString+=this._declareOutput(this.xyz,t)+" = "+this.output.associatedVariableName+".xyz;\r\n")}return this},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.complementZ=this.complementZ,t.complementW=this.complementW,t},t.prototype._deserialize=function(t,i,n){e.prototype._deserialize.call(this,t,i,n),this.complementZ=void 0!==t.complementZ?t.complementZ:0,this.complementW=void 0!==t.complementW?t.complementW:1},t.prototype._dumpPropertiesCode=function(){var e=this._codeVariableName+".complementZ = "+this.complementZ+";\r\n";return e+=this._codeVariableName+".complementW = "+this.complementW+";\r\n"},t}(yc);c.a.RegisteredTypes["BABYLON.TransformBlock"]=Ec;var xc=function(e){function t(t){var i=e.call(this,t,rc.Vertex,!0)||this;return i.registerInput("vector",oc.Vector4),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"VertexOutputBlock"},Object.defineProperty(t.prototype,"vector",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.vector;return t.compilationString+="gl_Position = "+i.associatedVariableName+";\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.VertexOutputBlock"]=xc;var Pc,Ac=function(e){function t(t){var i=e.call(this,t,rc.Fragment,!0)||this;return i.registerInput("rgba",oc.Color4,!0),i.registerInput("rgb",oc.Color3,!0),i.registerInput("a",oc.Float,!0),i.rgb.acceptedConnectionPointTypes.push(oc.Float),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"FragmentOutputBlock"},Object.defineProperty(t.prototype,"rgba",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rgb",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"a",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.rgba,n=this.rgb,r=this.a;if(t.sharedData.hints.needAlphaBlending=i.isConnected||r.isConnected,i.connectedPoint)r.isConnected?t.compilationString+="gl_FragColor = vec4("+i.associatedVariableName+".rgb, "+r.associatedVariableName+");\r\n":t.compilationString+="gl_FragColor = "+i.associatedVariableName+";\r\n";else if(n.connectedPoint){var o="1.0";r.connectedPoint&&(o=r.associatedVariableName),n.connectedPoint.type===oc.Float?t.compilationString+="gl_FragColor = vec4("+n.associatedVariableName+", "+n.associatedVariableName+", "+n.associatedVariableName+", "+o+");\r\n":t.compilationString+="gl_FragColor = vec4("+n.associatedVariableName+", "+o+");\r\n"}else t.sharedData.checks.notConnectedNonOptionalInputs.push(i);return this},t}(yc);c.a.RegisteredTypes["BABYLON.FragmentOutputBlock"]=Ac,function(e){e[e.None=0]="None",e[e.Time=1]="Time"}(Pc||(Pc={}));var Sc=function(e){function t(t,i,n){void 0===i&&(i=rc.Vertex),void 0===n&&(n=oc.AutoDetect);var r=e.call(this,t,i,!1,!0)||this;return r._mode=ac.Undefined,r._animationType=Pc.None,r.min=0,r.max=0,r.isBoolean=!1,r.matrixMode=0,r._systemValue=null,r.visibleInInspector=!1,r.isConstant=!1,r.groupInInspector="",r.onValueChangedObservable=new o.c,r._type=n,r.setDefaultValue(),r.registerOutput("output",n),r}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"type",{get:function(){if(this._type===oc.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=oc.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=oc.Vector2,this._type;case"Vector3":return this._type=oc.Vector3,this._type;case"Vector4":return this._type=oc.Vector4,this._type;case"Color3":return this._type=oc.Color3,this._type;case"Color4":return this._type=oc.Color4,this._type;case"Matrix":return this._type=oc.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"tangent":return this._type=oc.Vector3,this._type;case"uv":case"uv2":return this._type=oc.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"world0":case"world1":case"world2":case"world3":return this._type=oc.Vector4,this._type;case"color":return this._type=oc.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case sc.World:case sc.WorldView:case sc.WorldViewProjection:case sc.View:case sc.ViewProjection:case sc.Projection:return this._type=oc.Matrix,this._type;case sc.CameraPosition:return this._type=oc.Vector3,this._type;case sc.FogColor:return this._type=oc.Color3,this._type;case sc.DeltaTime:return this._type=oc.Float,this._type}}return this._type},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype.setAsAttribute=function(e){return e&&(this.name=e),this._mode=ac.Attribute,this},t.prototype.setAsSystemValue=function(e){return this.systemValue=e,this},Object.defineProperty(t.prototype,"value",{get:function(){return this._storedValue},set:function(e){this.type===oc.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=ac.Uniform,this.onValueChangedObservable.notifyObservers(this)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"valueCallback",{get:function(){return this._valueCallback},set:function(e){this._valueCallback=e,this._mode=ac.Uniform},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"associatedVariableName",{get:function(){return this._associatedVariableName},set:function(e){this._associatedVariableName=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationType",{get:function(){return this._animationType},set:function(e){this._animationType=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isUndefined",{get:function(){return this._mode===ac.Undefined},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isUniform",{get:function(){return this._mode===ac.Uniform},set:function(e){this._mode=e?ac.Uniform:ac.Undefined,this.associatedVariableName=""},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isAttribute",{get:function(){return this._mode===ac.Attribute},set:function(e){this._mode=e?ac.Attribute:ac.Undefined,this.associatedVariableName=""},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isVarying",{get:function(){return this._mode===ac.Varying},set:function(e){this._mode=e?ac.Varying:ac.Undefined,this.associatedVariableName=""},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isSystemValue",{get:function(){return null!=this._systemValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"systemValue",{get:function(){return this._systemValue},set:function(e){this._mode=ac.Uniform,this.associatedVariableName="",this._systemValue=e},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"InputBlock"},t.prototype.animate=function(e){switch(this._animationType){case Pc.Time:this.type===oc.Float&&(this.value+=.01*e.getAnimationRatio())}},t.prototype._emitDefine=function(e){return"!"===e[0]?"#ifndef "+e.substring(1)+"\r\n":"#ifdef "+e+"\r\n"},t.prototype.initialize=function(e){this.associatedVariableName=""},t.prototype.setDefaultValue=function(){switch(this.type){case oc.Float:this.value=0;break;case oc.Vector2:this.value=a.d.Zero();break;case oc.Vector3:this.value=a.e.Zero();break;case oc.Vector4:this.value=a.f.Zero();break;case oc.Color3:this.value=s.a.White();break;case oc.Color4:this.value=new s.b(1,1,1,1);break;case oc.Matrix:this.value=a.a.Identity()}},t.prototype._emitConstant=function(e){switch(this.type){case oc.Float:return""+e._emitFloat(this.value);case oc.Vector2:return"vec2("+this.value.x+", "+this.value.y+")";case oc.Vector3:return"vec3("+this.value.x+", "+this.value.y+", "+this.value.z+")";case oc.Vector4:return"vec4("+this.value.x+", "+this.value.y+", "+this.value.z+", "+this.value.w+")";case oc.Color3:return"vec3("+this.value.r+", "+this.value.g+", "+this.value.b+")";case oc.Color4:return"vec4("+this.value.r+", "+this.value.g+", "+this.value.b+", "+this.value.a+")"}return""},t.prototype._emit=function(e,t){if(this.isUniform){if(this.associatedVariableName||(this.associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;return e.constants.push(this.associatedVariableName),void(e._constantDeclaration+=this._declareOutput(this.output,e)+" = "+this._emitConstant(e)+";\r\n")}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t)),e._uniformDeclaration+="uniform "+e._getGLType(this.type)+" "+this.associatedVariableName+";\r\n",t&&(e._uniformDeclaration+="#endif\r\n");var i=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case sc.WorldView:i.needWorldViewMatrix=!0;break;case sc.WorldViewProjection:i.needWorldViewProjectionMatrix=!0}else this._animationType!==Pc.None&&e.sharedData.animatedInputs.push(this)}else if(this.isAttribute){if(this.associatedVariableName=this.name,this.target===rc.Vertex&&e._vertexState)return void this._emit(e._vertexState,t);if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),t&&(e._attributeDeclaration+=this._emitDefine(t)),e._attributeDeclaration+="attribute "+e._getGLType(this.type)+" "+this.associatedVariableName+";\r\n",t&&(e._attributeDeclaration+="#endif\r\n")}},t.prototype._transmitWorld=function(e,t,i,n){if(this._systemValue){var r=this.associatedVariableName;switch(this._systemValue){case sc.World:e.setMatrix(r,t);break;case sc.WorldView:e.setMatrix(r,i);break;case sc.WorldViewProjection:e.setMatrix(r,n)}}},t.prototype._transmit=function(e,t){if(!this.isAttribute){var i=this.associatedVariableName;if(this._systemValue)switch(this._systemValue){case sc.World:case sc.WorldView:case sc.WorldViewProjection:return;case sc.View:e.setMatrix(i,t.getViewMatrix());break;case sc.Projection:e.setMatrix(i,t.getProjectionMatrix());break;case sc.ViewProjection:e.setMatrix(i,t.getTransformMatrix());break;case sc.CameraPosition:e.setVector3(i,t.activeCamera.globalPosition);break;case sc.FogColor:e.setColor3(i,t.fogColor);break;case sc.DeltaTime:e.setFloat(i,t.deltaTime/1e3)}else{var n=this._valueCallback?this._valueCallback():this._storedValue;if(null!==n)switch(this.type){case oc.Float:e.setFloat(i,n);break;case oc.Int:e.setInt(i,n);break;case oc.Color3:e.setColor3(i,n);break;case oc.Color4:e.setDirectColor4(i,n);break;case oc.Vector2:e.setVector2(i,n);break;case oc.Vector3:e.setVector3(i,n);break;case oc.Vector4:e.setVector4(i,n);break;case oc.Matrix:e.setMatrix(i,n)}}}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t),(this.isUniform||this.isSystemValue)&&t.sharedData.inputBlocks.push(this),this._emit(t)},t.prototype._dumpPropertiesCode=function(){var e=this._codeVariableName;if(this.isAttribute)return e+'.setAsAttribute("'+this.name+'");\r\n';if(this.isSystemValue)return e+".setAsSystemValue(BABYLON.NodeMaterialSystemValues."+sc[this._systemValue]+");\r\n";if(this.isUniform){var t="";switch(this.type){case oc.Float:var i=e+".value = "+this.value+";\r\n";return i+=e+".min = "+this.min+";\r\n",i+=e+".max = "+this.max+";\r\n",i+=e+".isBoolean = "+this.isBoolean+";\r\n",i+=e+".matrixMode = "+this.matrixMode+";\r\n",i+=e+".animationType  = BABYLON.AnimatedInputBlockTypes."+Pc[this.animationType]+";\r\n";case oc.Vector2:t="new BABYLON.Vector2("+this.value.x+", "+this.value.y+")";break;case oc.Vector3:t="new BABYLON.Vector3("+this.value.x+", "+this.value.y+", "+this.value.z+")";break;case oc.Vector4:t="new BABYLON.Vector4("+this.value.x+", "+this.value.y+", "+this.value.z+", "+this.value.w+")";break;case oc.Color3:t="new BABYLON.Color3("+this.value.r+", "+this.value.g+", "+this.value.b+")";break;case oc.Color4:t="new BABYLON.Color4("+this.value.r+", "+this.value.g+", "+this.value.b+", "+this.value.a+")";break;case oc.Matrix:t="BABYLON.Matrix.FromArray(["+this.value.m.toString()+"])"}var n=e+".value = "+t+";\r\n";return n+=e+".isConstant = "+(this.isConstant?"true":"false")+";\r\n",n+=e+".visibleInInspector = "+(this.visibleInInspector?"true":"false")+";\r\n"}return""},t.prototype.dispose=function(){this.onValueChangedObservable.clear(),e.prototype.dispose.call(this)},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.type=this.type,t.mode=this._mode,t.systemValue=this._systemValue,t.animationType=this._animationType,t.visibleInInspector=this.visibleInInspector,t.min=this.min,t.max=this.max,t.isBoolean=this.isBoolean,t.matrixMode=this.matrixMode,t.isConstant=this.isConstant,t.groupInInspector=this.groupInInspector,null!=this._storedValue&&this._mode===ac.Uniform&&(this._storedValue.asArray?(t.valueType="BABYLON."+this._storedValue.getClassName(),t.value=this._storedValue.asArray()):(t.valueType="number",t.value=this._storedValue)),t},t.prototype._deserialize=function(t,i,n){if(e.prototype._deserialize.call(this,t,i,n),this._type=t.type,this._mode=t.mode,this._systemValue=t.systemValue||t.wellKnownValue,this._animationType=t.animationType,this.visibleInInspector=t.visibleInInspector,this.min=t.min||0,this.max=t.max||0,this.isBoolean=!!t.isBoolean,this.matrixMode=t.matrixMode||0,this.isConstant=!!t.isConstant,this.groupInInspector=t.groupInInspector||"",t.valueType)if("number"===t.valueType)this._storedValue=t.value;else{var r=c.a.GetClass(t.valueType);r&&(this._storedValue=r.FromArray(t.value))}},t}(yc);c.a.RegisteredTypes["BABYLON.InputBlock"]=Sc;var Cc=function(e){function t(){var t=e.call(this)||this;return t.NORMAL=!1,t.TANGENT=!1,t.UV1=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.BONETEXTURE=!1,t.MORPHTARGETS=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_UV=!1,t.NUM_MORPH_INFLUENCERS=0,t.IMAGEPROCESSING=!1,t.VIGNETTE=!1,t.VIGNETTEBLENDMODEMULTIPLY=!1,t.VIGNETTEBLENDMODEOPAQUE=!1,t.TONEMAPPING=!1,t.TONEMAPPING_ACES=!1,t.CONTRAST=!1,t.EXPOSURE=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=!1,t.SAMPLER3DBGRMAP=!1,t.IMAGEPROCESSINGPOSTPROCESS=!1,t.BUMPDIRECTUV=0,t.rebuild(),t}return Object(h.d)(t,e),t.prototype.setValue=function(e,t){void 0===this[e]&&this._keys.push(e),this[e]=t},t}(no.a),Rc=function(e){function t(i,n,r){void 0===r&&(r={});var s=e.call(this,i,n||Oe.a.LastCreatedScene)||this;return s._buildId=t._BuildIdGenerator++,s._buildWasSuccessful=!1,s._cachedWorldViewMatrix=new a.a,s._cachedWorldViewProjectionMatrix=new a.a,s._optimizers=new Array,s._animationFrame=-1,s.BJSNODEMATERIALEDITOR=s._getGlobalNodeMaterialEditor(),s.editorData=null,s.ignoreAlpha=!1,s.maxSimultaneousLights=4,s.onBuildObservable=new o.c,s._vertexOutputNodes=new Array,s._fragmentOutputNodes=new Array,s.attachedBlocks=new Array,s._options=Object(h.a)({emitComments:!1},r),s._attachImageProcessingConfiguration(null),s}return Object(h.d)(t,e),t.prototype._getGlobalNodeMaterialEditor=function(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0},Object.defineProperty(t.prototype,"options",{get:function(){return this._options},set:function(e){this._options=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"NodeMaterial"},t.prototype._attachImageProcessingConfiguration=function(e){var t=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(function(){t._markAllSubMeshesAsImageProcessingDirty()})))},t.prototype.getBlockByName=function(e){for(var t=0,i=this.attachedBlocks;t<i.length;t++){var n=i[t];if(n.name===e)return n}return null},t.prototype.getBlockByPredicate=function(e){for(var t=0,i=this.attachedBlocks;t<i.length;t++){var n=i[t];if(e(n))return n}return null},t.prototype.getInputBlockByPredicate=function(e){for(var t=0,i=this.attachedBlocks;t<i.length;t++){var n=i[t];if(n.isInput&&e(n))return n}return null},t.prototype.getInputBlocks=function(){for(var e=[],t=0,i=this.attachedBlocks;t<i.length;t++){var n=i[t];n.isInput&&e.push(n)}return e},t.prototype.registerOptimizer=function(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this},t.prototype.unregisterOptimizer=function(e){var t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this},t.prototype.addOutputNode=function(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return 0!=(e.target&rc.Vertex)&&this._addVertexOutputNode(e),0!=(e.target&rc.Fragment)&&this._addFragmentOutputNode(e),this},t.prototype.removeOutputNode=function(e){return null===e.target?this:(0!=(e.target&rc.Vertex)&&this._removeVertexOutputNode(e),0!=(e.target&rc.Fragment)&&this._removeFragmentOutputNode(e),this)},t.prototype._addVertexOutputNode=function(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=rc.Vertex,this._vertexOutputNodes.push(e),this},t.prototype._removeVertexOutputNode=function(e){var t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this},t.prototype._addFragmentOutputNode=function(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=rc.Fragment,this._fragmentOutputNodes.push(e),this},t.prototype._removeFragmentOutputNode=function(e){var t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this},t.prototype.needAlphaBlending=function(){return!this.ignoreAlpha&&(this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)},t.prototype.needAlphaTesting=function(){return this._sharedData&&this._sharedData.hints.needAlphaTesting},t.prototype._initializeBlock=function(e,t,i){if(e.initialize(t),e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique)for(var n=e.getClassName(),r=0,o=this.attachedBlocks;r<o.length;r++){if(o[r].getClassName()===n)throw"Cannot have multiple blocks of type "+n+" in the same NodeMaterial"}this.attachedBlocks.push(e)}for(var a=0,s=e.inputs;a<s.length;a++){var c=s[a];c.associatedVariableName="";var l=c.connectedPoint;if(l){var u=l.ownerBlock;u!==e&&(u.target===rc.VertexAndFragment?i.push(u):t.target===rc.Fragment&&u.target===rc.Vertex&&u._preparationId!==this._buildId&&i.push(u),this._initializeBlock(u,t,i))}}for(var h=0,d=e.outputs;h<d.length;h++){d[h].associatedVariableName=""}},t.prototype._resetDualBlocks=function(e,t){e.target===rc.VertexAndFragment&&(e.buildId=t);for(var i=0,n=e.inputs;i<n.length;i++){var r=n[i].connectedPoint;if(r){var o=r.ownerBlock;o!==e&&this._resetDualBlocks(o,t)}}},t.prototype.removeBlock=function(e){var t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)},t.prototype.build=function(e){void 0===e&&(e=!1),this._buildWasSuccessful=!1;var i=this.getScene().getEngine();if(0===this._vertexOutputNodes.length)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new bc,this._vertexCompilationState.supportUniformBuffers=i.supportsUniformBuffers,this._vertexCompilationState.target=rc.Vertex,this._fragmentCompilationState=new bc,this._fragmentCompilationState.supportUniformBuffers=i.supportsUniformBuffers,this._fragmentCompilationState.target=rc.Fragment,this._sharedData=new Tc,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene();for(var n=[],r=[],o=0,a=this._vertexOutputNodes;o<a.length;o++){var s=a[o];n.push(s),this._initializeBlock(s,this._vertexCompilationState,r)}for(var c=0,l=this._fragmentOutputNodes;c<l.length;c++){var u=l[c];r.push(u),this._initializeBlock(u,this._fragmentCompilationState,n)}this.optimize();for(var h=0,d=n;h<d.length;h++){(s=d[h]).build(this._vertexCompilationState,n)}this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(var f=0,p=r;f<p.length;f++){u=p[f];this._resetDualBlocks(u,this._buildId-1)}for(var _=0,m=r;_<m.length;_++){(u=m[_]).build(this._fragmentCompilationState,r)}this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),this._buildId=t._BuildIdGenerator++,this._sharedData.emitErrors(),e&&(console.log("Vertex shader:"),console.log(this._vertexCompilationState.compilationString),console.log("Fragment shader:"),console.log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);for(var g=0,v=this.getScene().meshes;g<v.length;g++){var y=v[g];if(y.subMeshes)for(var b=0,T=y.subMeshes;b<T.length;b++){var E=T[b];if(E.getMaterial()===this&&E._materialDefines){var x=E._materialDefines;x.markAllAsDirty(),x.reset()}}}},t.prototype.optimize=function(){for(var e=0,t=this._optimizers;e<t.length;e++){t[e].optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}},t.prototype._prepareDefinesForAttributes=function(e,t){var i=t.NORMAL,n=t.TANGENT,r=t.UV1;t.NORMAL=e.isVerticesDataPresent(en.b.NormalKind),t.TANGENT=e.isVerticesDataPresent(en.b.TangentKind),t.UV1=e.isVerticesDataPresent(en.b.UVKind),i===t.NORMAL&&n===t.TANGENT&&r===t.UV1||t.markAsAttributesDirty()},t.prototype.isReadyForSubMesh=function(e,t,i){var n=this;if(void 0===i&&(i=!1),!this._buildWasSuccessful)return!1;var r=this.getScene();if(this._sharedData.animatedInputs){var o=r.getFrameId();if(this._animationFrame!==o){for(var a=0,s=this._sharedData.animatedInputs;a<s.length;a++){s[a].animate(r)}this._animationFrame=o}}if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new Cc);var c=t._materialDefines;if(!this.checkReadyOnEveryCall&&t.effect&&c._renderId===r.getRenderId())return!0;var l=r.getEngine();if(this._prepareDefinesForAttributes(e,c),this._sharedData.blockingBlocks.some(function(t){return!t.isReady(e,n,c,i)}))return!1;if(this._sharedData.blocksWithDefines.forEach(function(t){t.initializeDefines(e,n,c,i)}),this._sharedData.blocksWithDefines.forEach(function(t){t.prepareDefines(e,n,c,i)}),c.isDirty){c.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach(function(t){t.replaceRepeatableContent(n._vertexCompilationState,n._fragmentCompilationState,e,c)});var u=[];this._sharedData.dynamicUniformBlocks.forEach(function(e){e.updateUniformsAndSamples(n._vertexCompilationState,n,c,u)});var h=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach(function(e){-1===h.indexOf(e)&&h.push(e)});var d=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach(function(e){-1===d.indexOf(e)&&d.push(e)});var f=new ho.a;this._sharedData.blocksWithFallbacks.forEach(function(t){t.provideFallbacks(e,f)});var p=t.effect,_=c.toString(),m=l.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:h,uniformBuffersNames:u,samplers:d,defines:_,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:c.NUM_MORPH_INFLUENCERS}},l);m&&(this.allowShaderHotSwapping&&p&&!m.isReady()?(m=p,c.markAsUnprocessed()):(r.resetCachedMaterial(),t.setEffect(m,c)))}return!(!t.effect||!t.effect.isReady())&&(c._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},Object.defineProperty(t.prototype,"compiledShaders",{get:function(){return"// Vertex shader\r\n"+this._vertexCompilationState.compilationString+"\r\n\r\n// Fragment shader\r\n"+this._fragmentCompilationState.compilationString},enumerable:!0,configurable:!0}),t.prototype.bindOnlyWorldMatrix=function(e){var t=this.getScene();if(this._activeEffect){var i=this._sharedData.hints;i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(var n=0,r=this._sharedData.inputBlocks;n<r.length;n++){r[n]._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}}},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),r=i.effect;if(r){if(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._mustRebind(n,r,t.visibility)){var o=this._sharedData;if(r&&n.getCachedEffect()!==r){for(var a=0,s=o.bindableBlocks;a<s.length;a++){s[a].bind(r,this,t)}for(var c=0,l=o.inputBlocks;c<l.length;c++){l[c]._transmit(r,n)}}}this._afterBind(t,this._activeEffect)}},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._sharedData&&t.push.apply(t,this._sharedData.textureBlocks.filter(function(e){return e.texture}).map(function(e){return e.texture})),t},t.prototype.getTextureBlocks=function(){return this._sharedData?this._sharedData.textureBlocks:[]},t.prototype.hasTexture=function(t){if(e.prototype.hasTexture.call(this,t))return!0;if(!this._sharedData)return!1;for(var i=0,n=this._sharedData.textureBlocks;i<n.length;i++){if(n[i].texture===t)return!0}return!1},t.prototype.dispose=function(t,i,n){if(i)for(var r=0,o=this._sharedData.textureBlocks.filter(function(e){return e.texture}).map(function(e){return e.texture});r<o.length;r++){o[r].dispose()}for(var a=0,s=this.attachedBlocks;a<s.length;a++){s[a].dispose()}this.onBuildObservable.clear(),e.prototype.dispose.call(this,t,i,n)},t.prototype._createNodeEditor=function(){this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this.BJSNODEMATERIALEDITOR.NodeEditor.Show({nodeMaterial:this})},t.prototype.edit=function(e){var i=this;return new Promise(function(n,r){if(void 0===i.BJSNODEMATERIALEDITOR){var o=e&&e.editorURL?e.editorURL:t.EditorURL;De.b.LoadScript(o,function(){i._createNodeEditor(),n()})}else i._createNodeEditor(),n()})},t.prototype.clear=function(){this._vertexOutputNodes=[],this._fragmentOutputNodes=[],this.attachedBlocks=[]},t.prototype.setToDefault=function(){this.clear(),this.editorData=null;var e=new Sc("Position");e.setAsAttribute("position");var t=new Sc("World");t.setAsSystemValue(BABYLON.NodeMaterialSystemValues.World);var i=new Ec("WorldPos");e.connectTo(i),t.connectTo(i);var n=new Sc("ViewProjection");n.setAsSystemValue(BABYLON.NodeMaterialSystemValues.ViewProjection);var r=new Ec("WorldPos * ViewProjectionTransform");i.connectTo(r),n.connectTo(r);var o=new xc("VertexOutput");r.connectTo(o);var a=new Sc("color");a.value=new s.b(.8,.8,.8,1);var c=new Ac("FragmentOutput");a.connectTo(c),this.addOutputNode(o),this.addOutputNode(c)},t.prototype.loadAsync=function(e){var t=this;return this.getScene()._loadFileAsync(e).then(function(e){var i=JSON.parse(e);t.loadFromSerialization(i,"")})},t.prototype._gatherBlocks=function(e,t){if(-1===t.indexOf(e)){t.push(e);for(var i=0,n=e.inputs;i<n.length;i++){var r=n[i].connectedPoint;if(r){var o=r.ownerBlock;o!==e&&this._gatherBlocks(o,t)}}}},t.prototype.generateCode=function(){for(var e=[],t=[],i=[],n=0,r=this._vertexOutputNodes;n<r.length;n++){var o=r[n];this._gatherBlocks(o,t)}for(var a=[],s=0,c=this._fragmentOutputNodes;s<c.length;s++){o=c[s];this._gatherBlocks(o,a)}for(var l='var nodeMaterial = new BABYLON.NodeMaterial("'+(this.name||"node material")+'");\r\n',u=0,h=t;u<h.length;u++){(E=h[u]).isInput&&-1===e.indexOf(E)&&(l+=E._dumpCode(i,e))}for(var d=0,f=a;d<f.length;d++){(E=f[d]).isInput&&-1===e.indexOf(E)&&(l+=E._dumpCode(i,e))}e=[],l+="\r\n// Connections\r\n";for(var p=0,_=this._vertexOutputNodes;p<_.length;p++){l+=(E=_[p])._dumpCodeForOutputConnections(e)}for(var m=0,g=this._fragmentOutputNodes;m<g.length;m++){l+=(E=g[m])._dumpCodeForOutputConnections(e)}l+="\r\n// Output nodes\r\n";for(var v=0,y=this._vertexOutputNodes;v<y.length;v++){l+="nodeMaterial.addOutputNode("+(E=y[v])._codeVariableName+");\r\n"}for(var b=0,T=this._fragmentOutputNodes;b<T.length;b++){var E;l+="nodeMaterial.addOutputNode("+(E=T[b])._codeVariableName+");\r\n"}return l+="nodeMaterial.build();\r\n"},t.prototype.serialize=function(e){var t=e?{}:N.a.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));var i=[];if(e)i=e;else{t.customType="BABYLON.NodeMaterial",t.outputNodes=[];for(var n=0,r=this._vertexOutputNodes;n<r.length;n++){var o=r[n];this._gatherBlocks(o,i),t.outputNodes.push(o.uniqueId)}for(var a=0,s=this._fragmentOutputNodes;a<s.length;a++){o=s[a];this._gatherBlocks(o,i),-1===t.outputNodes.indexOf(o.uniqueId)&&t.outputNodes.push(o.uniqueId)}}t.blocks=[];for(var c=0,l=i;c<l.length;c++){var u=l[c];t.blocks.push(u.serialize())}if(!e)for(var h=0,d=this.attachedBlocks;h<d.length;h++){u=d[h];-1===i.indexOf(u)&&t.blocks.push(u.serialize())}return t},t.prototype._restoreConnections=function(e,t,i){for(var n=0,r=e.outputs;n<r.length;n++)for(var o=r[n],a=0,s=t.blocks;a<s.length;a++)for(var c=s[a],l=i[c.id],u=0,h=c.inputs;u<h.length;u++){var d=h[u];if(i[d.targetBlockId]!==e||d.targetConnectionName!==o.name);else{var f=l.getInputByName(d.inputName);if(!f||f.isConnected)continue;o.connectTo(f,!0),this._restoreConnections(l,t,i)}}},t.prototype.loadFromSerialization=function(e,t){void 0===t&&(t=""),this.clear();for(var i={},n=0,r=e.blocks;n<r.length;n++){var o=r[n],a=c.a.GetClass(o.customType);if(a)(l=new a)._deserialize(o,this.getScene(),t),i[o.id]=l,this.attachedBlocks.push(l)}for(var s=0;s<e.blocks.length;s++){var l;(l=i[e.blocks[s].id]).inputs.length||this._restoreConnections(l,e,i)}for(var u=0,h=e.outputNodes;u<h.length;u++){var d=h[u];this.addOutputNode(i[d])}if(e.locations||e.editorData&&e.editorData.locations){for(var f=e.locations||e.editorData.locations,p=0,_=f;p<_.length;p++){var m=_[p];i[m.blockId]&&(m.blockId=i[m.blockId].uniqueId)}e.locations?this.editorData={locations:f}:(this.editorData=e.editorData,this.editorData.locations=f);var g=[];for(var v in i)g[v]=i[v].uniqueId;this.editorData.map=g}},t.Parse=function(e,i,n){void 0===n&&(n="");var r=N.a.Parse(function(){return new t(e.name,i)},e,i,n);return r.loadFromSerialization(e,n),r.build(),r},t.ParseFromFileAsync=function(e,i,n){var r=new t(e,n);return new Promise(function(e,t){return r.loadAsync(i).then(function(){return e(r)}).catch(t)})},t.ParseFromSnippetAsync=function(e,i,n){var r=this;return void 0===n&&(n=""),new Promise(function(o,a){var s=new ec.a;s.addEventListener("readystatechange",function(){if(4==s.readyState)if(200==s.status){var r=JSON.parse(JSON.parse(s.responseText).jsonPayload),c=JSON.parse(r.nodeMaterial),l=N.a.Parse(function(){return new t(e,i)},c,i,n);l.loadFromSerialization(c);try{l.build(!0),o(l)}catch(e){a(e)}}else a("Unable to load the snippet "+e)}),s.open("GET",r.SnippetUrl+"/"+e.replace("#","/")),s.send()})},t.CreateDefault=function(e,i){var n=new t(e,i);return n.setToDefault(),n.build(),n},t._BuildIdGenerator=0,t.EditorURL="https://unpkg.com/babylonjs-node-editor@"+Oe.a.Version+"/babylon.nodeEditor.js",t.SnippetUrl="https://snippet.babylonjs.com",t}(ro.a);c.a.RegisteredTypes["BABYLON.NodeMaterial"]=Rc;var Oc=function(e){function t(t){var i=e.call(this,t,rc.Vertex)||this;return i.registerInput("matricesIndices",oc.Vector4),i.registerInput("matricesWeights",oc.Vector4),i.registerInput("matricesIndicesExtra",oc.Vector4,!0),i.registerInput("matricesWeightsExtra",oc.Vector4,!0),i.registerInput("world",oc.Matrix),i.registerOutput("output",oc.Matrix),i}return Object(h.d)(t,e),t.prototype.initialize=function(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh")},t.prototype.getClassName=function(){return"BonesBlock"},Object.defineProperty(t.prototype,"matricesIndices",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"matricesWeights",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"matricesIndicesExtra",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"matricesWeightsExtra",{get:function(){return this._inputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"world",{get:function(){return this._inputs[4]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype.autoConfigure=function(e){if(!this.matricesIndices.isConnected){var t=e.getInputBlockByPredicate(function(e){return e.isAttribute&&"matricesIndices"===e.name});t||(t=new Sc("matricesIndices")).setAsAttribute("matricesIndices"),t.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){var i=e.getInputBlockByPredicate(function(e){return e.isAttribute&&"matricesWeights"===e.name});i||(i=new Sc("matricesWeights")).setAsAttribute("matricesWeights"),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){var n=e.getInputBlockByPredicate(function(e){return e.systemValue===sc.World});n||(n=new Sc("world")).setAsSystemValue(sc.World),n.output.connectTo(this.world)}},t.prototype.provideFallbacks=function(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)},t.prototype.bind=function(e,t,i){io.a.BindBonesParameters(i,e)},t.prototype.prepareDefines=function(e,t,i){i._areAttributesDirty&&io.a.PrepareDefinesForBones(e,i)},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t),t.sharedData.blocksWithFallbacks.push(this),t.sharedData.bindableBlocks.push(this),t.sharedData.blocksWithDefines.push(this),t.uniforms.push("boneTextureWidth"),t.uniforms.push("mBones"),t.samplers.push("boneSampler");var i="//"+this.name;t._emitFunctionFromInclude("bonesDeclaration",i,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});var n=t._getFreeVariableName("influence");t.compilationString+=t._emitCodeFromInclude("bonesVertex",i,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:n}]});var r=this._outputs[0],o=this.world;return t.compilationString+="#if NUM_BONE_INFLUENCERS>0\r\n",t.compilationString+=this._declareOutput(r,t)+" = "+o.associatedVariableName+" * "+n+";\r\n",t.compilationString+="#else\r\n",t.compilationString+=this._declareOutput(r,t)+" = "+o.associatedVariableName+";\r\n",t.compilationString+="#endif\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.BonesBlock"]=Oc;var Mc=function(e){function t(t){var i=e.call(this,t,rc.Vertex)||this;return i.registerInput("world0",oc.Vector4),i.registerInput("world1",oc.Vector4),i.registerInput("world2",oc.Vector4),i.registerInput("world3",oc.Vector4),i.registerInput("world",oc.Matrix,!0),i.registerOutput("output",oc.Matrix),i.registerOutput("instanceID",oc.Float),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"InstancesBlock"},Object.defineProperty(t.prototype,"world0",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"world1",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"world2",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"world3",{get:function(){return this._inputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"world",{get:function(){return this._inputs[4]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"instanceID",{get:function(){return this._outputs[1]},enumerable:!0,configurable:!0}),t.prototype.autoConfigure=function(e){if(!this.world0.connectedPoint){var t=e.getInputBlockByPredicate(function(e){return e.isAttribute&&"world0"===e.name});t||(t=new Sc("world0")).setAsAttribute("world0"),t.output.connectTo(this.world0)}if(!this.world1.connectedPoint){var i=e.getInputBlockByPredicate(function(e){return e.isAttribute&&"world1"===e.name});i||(i=new Sc("world1")).setAsAttribute("world1"),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){var n=e.getInputBlockByPredicate(function(e){return e.isAttribute&&"world2"===e.name});n||(n=new Sc("world2")).setAsAttribute("world2"),n.output.connectTo(this.world2)}if(!this.world3.connectedPoint){var r=e.getInputBlockByPredicate(function(e){return e.isAttribute&&"world3"===e.name});r||(r=new Sc("world3")).setAsAttribute("world3"),r.output.connectTo(this.world3)}if(!this.world.connectedPoint){var o=e.getInputBlockByPredicate(function(e){return e.isAttribute&&"world"===e.name});o||(o=new Sc("world")).setAsSystemValue(sc.World),o.output.connectTo(this.world)}this.world.define="!INSTANCES"},t.prototype.prepareDefines=function(e,t,i,n){void 0===n&&(n=!1);var r=!1;i.INSTANCES!==n&&(i.setValue("INSTANCES",n),r=!0),r&&i.markAsUnprocessed()},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t),t.sharedData.blocksWithDefines.push(this);var i=this._outputs[0],n=this._outputs[1],r=this.world0,o=this.world1,a=this.world2,s=this.world3;return t.compilationString+="#ifdef INSTANCES\r\n",t.compilationString+=this._declareOutput(i,t)+" = mat4("+r.associatedVariableName+", "+o.associatedVariableName+", "+a.associatedVariableName+", "+s.associatedVariableName+");\r\n",t.compilationString+=this._declareOutput(n,t)+" = float(gl_InstanceID);\r\n",t.compilationString+="#else\r\n",t.compilationString+=this._declareOutput(i,t)+" = "+this.world.associatedVariableName+";\r\n",t.compilationString+=this._declareOutput(n,t)+" = 0.0;\r\n",t.compilationString+="#endif\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.InstancesBlock"]=Mc;var Ic=function(e){function t(t){var i=e.call(this,t,rc.Vertex)||this;return i.registerInput("position",oc.Vector3),i.registerInput("normal",oc.Vector3),i.registerInput("tangent",oc.Vector3),i.registerInput("uv",oc.Vector2),i.registerOutput("positionOutput",oc.Vector3),i.registerOutput("normalOutput",oc.Vector3),i.registerOutput("tangentOutput",oc.Vector3),i.registerOutput("uvOutput",oc.Vector2),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"MorphTargetsBlock"},Object.defineProperty(t.prototype,"position",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"normal",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"tangent",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"uv",{get:function(){return this._inputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"positionOutput",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"normalOutput",{get:function(){return this._outputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"tangentOutput",{get:function(){return this._outputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"uvOutput",{get:function(){return this._outputs[3]},enumerable:!0,configurable:!0}),t.prototype.initialize=function(e){e._excludeVariableName("morphTargetInfluences")},t.prototype.autoConfigure=function(e){if(!this.position.isConnected){var t=e.getInputBlockByPredicate(function(e){return e.isAttribute&&"position"===e.name});t||(t=new Sc("position")).setAsAttribute(),t.output.connectTo(this.position)}if(!this.normal.isConnected){var i=e.getInputBlockByPredicate(function(e){return e.isAttribute&&"normal"===e.name});i||(i=new Sc("normal")).setAsAttribute("normal"),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){var n=e.getInputBlockByPredicate(function(e){return e.isAttribute&&"tangent"===e.name});n||(n=new Sc("tangent")).setAsAttribute("tangent"),n.output.connectTo(this.tangent)}if(!this.uv.isConnected){var r=e.getInputBlockByPredicate(function(e){return e.isAttribute&&"uv"===e.name});r||(r=new Sc("uv")).setAsAttribute("uv"),r.output.connectTo(this.uv)}},t.prototype.prepareDefines=function(e,t,i){i._areAttributesDirty&&io.a.PrepareDefinesForMorphTargets(e,i)},t.prototype.bind=function(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&io.a.BindMorphTargetParameters(i,e)},t.prototype.replaceRepeatableContent=function(e,t,i,n){for(var r=this.position,o=this.normal,a=this.tangent,s=this.uv,c=this.positionOutput,l=this.normalOutput,u=this.tangentOutput,h=this.uvOutput,d=e,f=n.NUM_MORPH_INFLUENCERS,p=i.morphTargetManager,_=p&&p.supportsNormals&&n.NORMAL,m=p&&p.supportsTangents&&n.TANGENT,g=p&&p.supportsUVs&&n.UV1,v="",y=0;y<f;y++)v+="#ifdef MORPHTARGETS\r\n",v+=c.associatedVariableName+" += (position"+y+" - "+r.associatedVariableName+") * morphTargetInfluences["+y+"];\r\n",_&&(v+="#ifdef MORPHTARGETS_NORMAL\r\n",v+=l.associatedVariableName+" += (normal"+y+" - "+o.associatedVariableName+") * morphTargetInfluences["+y+"];\r\n",v+="#endif\r\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\r\n",v+=u.associatedVariableName+".xyz += (tangent"+y+" - "+a.associatedVariableName+".xyz) * morphTargetInfluences["+y+"];\r\n",v+="#endif\r\n"),g&&(v+="#ifdef MORPHTARGETS_UV\r\n",v+=h.associatedVariableName+".xy += (uv_"+y+" - "+s.associatedVariableName+".xy) * morphTargetInfluences["+y+"];\r\n",v+="#endif\r\n"),v+="#endif\r\n";if(d.compilationString=d.compilationString.replace(this._repeatableContentAnchor,v),f>0)for(y=0;y<f;y++)d.attributes.push(en.b.PositionKind+y),_&&d.attributes.push(en.b.NormalKind+y),m&&d.attributes.push(en.b.TangentKind+y),g&&d.attributes.push(en.b.UVKind+"_"+y)},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t),t.sharedData.blocksWithDefines.push(this),t.sharedData.bindableBlocks.push(this),t.sharedData.repeatableContentBlocks.push(this);var i=this.position,n=this.normal,r=this.tangent,o=this.uv,a=this.positionOutput,s=this.normalOutput,c=this.tangentOutput,l=this.uvOutput,u="//"+this.name;return t.uniforms.push("morphTargetInfluences"),t._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration",u),t._emitFunctionFromInclude("morphTargetsVertexDeclaration",u,{repeatKey:"maxSimultaneousMorphTargets"}),t.compilationString+=this._declareOutput(a,t)+" = "+i.associatedVariableName+";\r\n",t.compilationString+="#ifdef NORMAL\r\n",t.compilationString+=this._declareOutput(s,t)+" = "+n.associatedVariableName+";\r\n",t.compilationString+="#else\r\n",t.compilationString+=this._declareOutput(s,t)+" = vec3(0., 0., 0.);\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#ifdef TANGENT\r\n",t.compilationString+=this._declareOutput(c,t)+" = "+r.associatedVariableName+";\r\n",t.compilationString+="#else\r\n",t.compilationString+=this._declareOutput(c,t)+" = vec3(0., 0., 0.);\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#ifdef UV1\r\n",t.compilationString+=this._declareOutput(l,t)+" = "+o.associatedVariableName+";\r\n",t.compilationString+="#else\r\n",t.compilationString+=this._declareOutput(l,t)+" = vec2(0., 0.);\r\n",t.compilationString+="#endif\r\n",this._repeatableContentAnchor=t._repeatableContentAnchor,t.compilationString+=this._repeatableContentAnchor,this},t}(yc);c.a.RegisteredTypes["BABYLON.MorphTargetsBlock"]=Ic;var Dc=function(e){function t(t){var i=e.call(this,t,rc.Vertex)||this;return i.registerInput("worldPosition",oc.Vector4,!1,rc.Vertex),i.registerOutput("direction",oc.Vector3),i.registerOutput("color",oc.Color3),i.registerOutput("intensity",oc.Float),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"LightInformationBlock"},Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"direction",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"color",{get:function(){return this._outputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"intensity",{get:function(){return this._outputs[2]},enumerable:!0,configurable:!0}),t.prototype.bind=function(e,t,i){if(i){this.light&&this.light.isDisposed&&(this.light=null);var n=this.light,r=t.getScene();if(!n&&r.lights.length&&(n=r.lights[0]),!n||!n.isEnabled)return e.setFloat3(this._lightDataUniformName,0,0,0),void e.setFloat4(this._lightColorUniformName,0,0,0,0);n.transferToNodeMaterialEffect(e,this._lightDataUniformName),e.setColor4(this._lightColorUniformName,n.diffuse,n.intensity)}},t.prototype.prepareDefines=function(e,t,i){if(i._areLightsDirty){var n=this.light;i.setValue(this._lightTypeDefineName,!!(n&&n instanceof us))}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t),t.sharedData.bindableBlocks.push(this),t.sharedData.blocksWithDefines.push(this);var i=this.direction,n=this.color,r=this.intensity;return this._lightDataUniformName=t._getFreeVariableName("lightData"),this._lightColorUniformName=t._getFreeVariableName("lightColor"),this._lightTypeDefineName=t._getFreeDefineName("LIGHTPOINTTYPE"),t._emitUniformFromString(this._lightDataUniformName,"vec3"),t._emitUniformFromString(this._lightColorUniformName,"vec4"),t.compilationString+="#ifdef "+this._lightTypeDefineName+"\r\n",t.compilationString+=this._declareOutput(i,t)+" = normalize("+this.worldPosition.associatedVariableName+".xyz - "+this._lightDataUniformName+");\r\n",t.compilationString+="#else\r\n",t.compilationString+=this._declareOutput(i,t)+" = "+this._lightDataUniformName+";\r\n",t.compilationString+="#endif\r\n",t.compilationString+=this._declareOutput(n,t)+" = "+this._lightColorUniformName+".rgb;\r\n",t.compilationString+=this._declareOutput(r,t)+" = "+this._lightColorUniformName+".a;\r\n",this},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return this.light&&(t.lightId=this.light.id),t},t.prototype._deserialize=function(t,i,n){e.prototype._deserialize.call(this,t,i,n),t.lightId&&(this.light=i.getLightByID(t.lightId))},t}(yc);c.a.RegisteredTypes["BABYLON.LightInformationBlock"]=Dc;var wc=function(e){function t(t){var i=e.call(this,t,rc.Fragment)||this;return i.registerInput("color",oc.Color4),i.registerOutput("output",oc.Color4),i._inputs[0].acceptedConnectionPointTypes.push(oc.Color3),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"ImageProcessingBlock"},Object.defineProperty(t.prototype,"color",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype.initialize=function(e){e._excludeVariableName("exposureLinear"),e._excludeVariableName("contrast"),e._excludeVariableName("vInverseScreenSize"),e._excludeVariableName("vignetteSettings1"),e._excludeVariableName("vignetteSettings2"),e._excludeVariableName("vCameraColorCurveNegative"),e._excludeVariableName("vCameraColorCurveNeutral"),e._excludeVariableName("vCameraColorCurvePositive"),e._excludeVariableName("txColorTransform"),e._excludeVariableName("colorTransformSettings")},t.prototype.isReady=function(e,t,i){return!(i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())},t.prototype.prepareDefines=function(e,t,i){i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i)},t.prototype.bind=function(e,t,i){i&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t),t.sharedData.blocksWithDefines.push(this),t.sharedData.blockingBlocks.push(this),t.sharedData.bindableBlocks.push(this),t.uniforms.push("exposureLinear"),t.uniforms.push("contrast"),t.uniforms.push("vInverseScreenSize"),t.uniforms.push("vignetteSettings1"),t.uniforms.push("vignetteSettings2"),t.uniforms.push("vCameraColorCurveNegative"),t.uniforms.push("vCameraColorCurveNeutral"),t.uniforms.push("vCameraColorCurvePositive"),t.uniforms.push("txColorTransform"),t.uniforms.push("colorTransformSettings");var i=this.color,n=this._outputs[0],r="//"+this.name;return t._emitFunctionFromInclude("helperFunctions",r),t._emitFunctionFromInclude("imageProcessingDeclaration",r),t._emitFunctionFromInclude("imageProcessingFunctions",r),i.connectedPoint.type===oc.Color4||i.connectedPoint.type===oc.Vector4?t.compilationString+=this._declareOutput(n,t)+" = "+i.associatedVariableName+";\r\n":t.compilationString+=this._declareOutput(n,t)+" = vec4("+i.associatedVariableName+", 1.0);\r\n",t.compilationString+="#ifdef IMAGEPROCESSINGPOSTPROCESS\r\n",t.compilationString+=n.associatedVariableName+".rgb = toLinearSpace("+i.associatedVariableName+".rgb);\r\n",t.compilationString+="#else\r\n",t.compilationString+="#ifdef IMAGEPROCESSING\r\n",t.compilationString+=n.associatedVariableName+".rgb = toLinearSpace("+i.associatedVariableName+".rgb);\r\n",t.compilationString+=n.associatedVariableName+" = applyImageProcessing("+n.associatedVariableName+");\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#endif\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.ImageProcessingBlock"]=wc;var Lc=function(e){function t(t){var i=e.call(this,t,rc.Fragment)||this;return i._tangentSpaceParameterName="",i.invertX=!1,i.invertY=!1,i.registerInput("worldPosition",oc.Vector4,!1),i.registerInput("worldNormal",oc.Vector4,!1),i.registerInput("worldTangent",oc.Vector4,!0),i.registerInput("uv",oc.Vector2,!1),i.registerInput("normalMapColor",oc.Color3,!1),i.registerInput("strength",oc.Float,!1),i.registerOutput("output",oc.Vector4),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"PerturbNormalBlock"},Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"worldNormal",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"worldTangent",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"uv",{get:function(){return this._inputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"normalMapColor",{get:function(){return this._inputs[4]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"strength",{get:function(){return this._inputs[5]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype.prepareDefines=function(e,t,i){i.setValue("BUMP",!0)},t.prototype.bind=function(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1)},t.prototype.autoConfigure=function(e){if(!this.uv.isConnected){var t=e.getInputBlockByPredicate(function(e){return e.isAttribute&&"uv"===e.name});t||(t=new Sc("uv")).setAsAttribute(),t.output.connectTo(this.uv)}if(!this.strength.isConnected){var i=new Sc("strength");i.value=1,i.output.connectTo(this.strength)}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i="//"+this.name,n=this.uv,r=this.worldPosition,o=this.worldNormal,a=this.worldTangent;t.sharedData.blocksWithDefines.push(this),t.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=t._getFreeDefineName("tangentSpaceParameter"),t._emitUniformFromString(this._tangentSpaceParameterName,"vec2");var s=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?""+t._emitFloat(1/this.strength.connectInputBlock.value):"1.0 / "+this.strength.associatedVariableName;t._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");var c={search:/defined\(TANGENT\)/g,replace:a.isConnected?"defined(TANGENT)":"defined(IGNORE)"};return a.isConnected&&(t.compilationString+="vec3 tbnNormal = normalize("+o.associatedVariableName+".xyz);\r\n",t.compilationString+="vec3 tbnTangent = normalize("+a.associatedVariableName+".xyz);\r\n",t.compilationString+="vec3 tbnBitangent = cross(tbnNormal, tbnTangent);\r\n",t.compilationString+="mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r\n"),t._emitFunctionFromInclude("bumpFragmentFunctions",i,{replaceStrings:[{search:/vBumpInfos.y/g,replace:s},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vPositionW/g,replace:r.associatedVariableName+".xyz"},c]}),t.compilationString+=this._declareOutput(this.output,t)+" = vec4(0.);\r\n",t.compilationString+=t._emitCodeFromInclude("bumpFragment",i,{replaceStrings:[{search:/perturbNormal\(TBN,vBumpUV\+uvOffset\)/g,replace:"perturbNormal(TBN, "+this.normalMapColor.associatedVariableName+")"},{search:/vBumpInfos.y/g,replace:s},{search:/vBumpUV/g,replace:n.associatedVariableName},{search:/vPositionW/g,replace:r.associatedVariableName+".xyz"},{search:/normalW=/g,replace:this.output.associatedVariableName+".xyz = "},{search:/normalW/g,replace:o.associatedVariableName+".xyz"},c]}),this},t.prototype._dumpPropertiesCode=function(){var e=this._codeVariableName+".invertX = "+this.invertX+";\r\n";return e+=this._codeVariableName+".invertY = "+this.invertY+";\r\n"},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.invertX=this.invertX,t.invertY=this.invertY,t},t.prototype._deserialize=function(t,i,n){e.prototype._deserialize.call(this,t,i,n),this.invertX=t.invertX,this.invertY=t.invertY},t}(yc);c.a.RegisteredTypes["BABYLON.PerturbNormalBlock"]=Lc;var Nc=function(e){function t(t){var i=e.call(this,t,rc.Fragment,!0)||this;return i.registerInput("value",oc.Float,!0),i.registerInput("cutoff",oc.Float,!0),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"DiscardBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cutoff",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){return e.prototype._buildBlock.call(this,t),t.sharedData.hints.needAlphaTesting=!0,t.compilationString+="if ("+this.value.associatedVariableName+" < "+this.cutoff.associatedVariableName+") discard;\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.DiscardBlock"]=Nc;var Fc=function(e){function t(t){var i=e.call(this,t,rc.Fragment)||this;return i.registerOutput("output",oc.Float,rc.Fragment),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"FrontFacingBlock"},Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),t.target===rc.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = gl_FrontFacing ? 1.0 : 0.0;\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.FrontFacingBlock"]=Fc;var Bc=function(e){function t(t){var i=e.call(this,t,rc.Fragment)||this;return i.registerInput("input",oc.AutoDetect,!1),i.registerOutput("dx",oc.BasedOnInput),i.registerOutput("dy",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._outputs[1]._typeConnectionSource=i._inputs[0],i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"DerivativeBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dx",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dy",{get:function(){return this._outputs[1]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],n=this._outputs[1];return t._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),i.hasEndpoints&&(t.compilationString+=this._declareOutput(i,t)+" = dFdx("+this.input.associatedVariableName+");\r\n"),n.hasEndpoints&&(t.compilationString+=this._declareOutput(n,t)+" = dFdy("+this.input.associatedVariableName+");\r\n"),this},t}(yc);c.a.RegisteredTypes["BABYLON.DerivativeBlock"]=Bc;var Uc=function(e){function t(t){var i=e.call(this,t,rc.VertexAndFragment,!0)||this;return i.registerInput("worldPosition",oc.Vector4,!1,rc.Vertex),i.registerInput("view",oc.Matrix,!1,rc.Vertex),i.registerInput("input",oc.Color3,!1,rc.Fragment),i.registerInput("fogColor",oc.Color3,!1,rc.Fragment),i.registerOutput("output",oc.Color3,rc.Fragment),i.input.acceptedConnectionPointTypes.push(oc.Color4),i.fogColor.acceptedConnectionPointTypes.push(oc.Color4),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"FogBlock"},Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"view",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fogColor",{get:function(){return this._inputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype.autoConfigure=function(e){if(!this.view.isConnected){var t=e.getInputBlockByPredicate(function(e){return e.systemValue===sc.View});t||(t=new Sc("view")).setAsSystemValue(sc.View),t.output.connectTo(this.view)}if(!this.fogColor.isConnected){var i=e.getInputBlockByPredicate(function(e){return e.systemValue===sc.FogColor});i||(i=new Sc("fogColor",void 0,oc.Color3)).setAsSystemValue(sc.FogColor),i.output.connectTo(this.fogColor)}},t.prototype.prepareDefines=function(e,t,i){var n=e.getScene();i.setValue("FOG",t.fogEnabled&&io.a.GetFogState(e,n))},t.prototype.bind=function(e,t,i){if(i){var n=i.getScene();e.setFloat4(this._fogParameters,n.fogMode,n.fogStart,n.fogEnd,n.fogDensity)}},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),t.target===rc.Fragment){t.sharedData.blocksWithDefines.push(this),t.sharedData.bindableBlocks.push(this),t._emitFunctionFromInclude("fogFragmentDeclaration","//"+this.name,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}]});var i=t._getFreeVariableName("fog"),n=this.input,r=this.fogColor;this._fogParameters=t._getFreeVariableName("fogParameters");var o=this._outputs[0];t._emitUniformFromString(this._fogParameters,"vec4"),t.compilationString+="#ifdef FOG\r\n",t.compilationString+="float "+i+" = CalcFogFactor("+this._fogDistanceName+", "+this._fogParameters+");\r\n",t.compilationString+=this._declareOutput(o,t)+" = "+i+" * "+n.associatedVariableName+".rgb + (1.0 - "+i+") * "+r.associatedVariableName+".rgb;\r\n",t.compilationString+="#else\r\n"+this._declareOutput(o,t)+" =  "+n.associatedVariableName+".rgb;\r\n",t.compilationString+="#endif\r\n"}else{var a=this.worldPosition,s=this.view;this._fogDistanceName=t._getFreeVariableName("vFogDistance"),t._emitVaryingFromString(this._fogDistanceName,"vec3"),t.compilationString+=this._fogDistanceName+" = ("+s.associatedVariableName+" * "+a.associatedVariableName+").xyz;\r\n"}return this},t}(yc);c.a.RegisteredTypes["BABYLON.FogBlock"]=Uc;var Vc=function(e){function t(t){var i=e.call(this,t,rc.VertexAndFragment)||this;return i._isUnique=!0,i.registerInput("worldPosition",oc.Vector4,!1,rc.Vertex),i.registerInput("worldNormal",oc.Vector4,!1,rc.Fragment),i.registerInput("cameraPosition",oc.Vector3,!1,rc.Fragment),i.registerInput("glossiness",oc.Float,!0,rc.Fragment),i.registerInput("glossPower",oc.Float,!0,rc.Fragment),i.registerInput("diffuseColor",oc.Color3,!0,rc.Fragment),i.registerInput("specularColor",oc.Color3,!0,rc.Fragment),i.registerOutput("diffuseOutput",oc.Color3,rc.Fragment),i.registerOutput("specularOutput",oc.Color3,rc.Fragment),i.registerOutput("shadow",oc.Float,rc.Fragment),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"LightBlock"},Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"worldNormal",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraPosition",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"glossiness",{get:function(){return this._inputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"glossPower",{get:function(){return this._inputs[4]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"diffuseColor",{get:function(){return this._inputs[5]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"specularColor",{get:function(){return this._inputs[6]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"diffuseOutput",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"specularOutput",{get:function(){return this._outputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadow",{get:function(){return this._outputs[2]},enumerable:!0,configurable:!0}),t.prototype.autoConfigure=function(e){if(!this.cameraPosition.isConnected){var t=e.getInputBlockByPredicate(function(e){return e.systemValue===sc.CameraPosition});t||(t=new Sc("cameraPosition")).setAsSystemValue(sc.CameraPosition),t.output.connectTo(this.cameraPosition)}},t.prototype.prepareDefines=function(e,t,i){if(i._areLightsDirty){var n=e.getScene();if(this.light){var r={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};io.a.PrepareDefinesForLight(n,e,this.light,this._lightId,i,!0,r),r.needRebuild&&i.rebuild()}else io.a.PrepareDefinesForLights(n,e,i,!0,t.maxSimultaneousLights)}},t.prototype.updateUniformsAndSamples=function(e,t,i,n){for(var r=0;r<t.maxSimultaneousLights&&i["LIGHT"+r];r++)io.a.PrepareUniformsAndSamplersForLight(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],n)},t.prototype.bind=function(e,t,i){if(i){var n=i.getScene();this.light?io.a.BindLight(this.light,this._lightId,n,e,!0):io.a.BindLights(n,i,e,!0,t.maxSimultaneousLights)}},t.prototype._injectVertexCode=function(e){var t=this.worldPosition,i="//"+this.name;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));var n="v_"+t.associatedVariableName;e._emitVaryingFromString(n,"vec4")&&(e.compilationString+=n+" = "+t.associatedVariableName+";\r\n"),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+="vec4 worldPos = "+t.associatedVariableName+";\r\n",e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),t.target===rc.Fragment){t.sharedData.bindableBlocks.push(this),t.sharedData.blocksWithDefines.push(this);var i="//"+this.name,n=this.worldPosition;t._emitFunctionFromInclude("helperFunctions",i),t._emitFunctionFromInclude("lightsFragmentFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:"v_"+n.associatedVariableName+".xyz"}]}),t._emitFunctionFromInclude("shadowsFragmentFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:"v_"+n.associatedVariableName+".xyz"}]}),this.light?t._emitFunctionFromInclude(t.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):t._emitFunctionFromInclude(t.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),0===this._lightId&&(t._registerTempVariable("viewDirectionW")&&(t.compilationString+="vec3 viewDirectionW = normalize("+this.cameraPosition.associatedVariableName+" - v_"+n.associatedVariableName+".xyz);\r\n"),t.compilationString+="lightingInfo info;\r\n",t.compilationString+="float shadow = 1.;\r\n",t.compilationString+="float glossiness = "+(this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0")+" * "+(this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0")+";\r\n",t.compilationString+="vec3 diffuseBase = vec3(0., 0., 0.);\r\n",t.compilationString+="vec3 specularBase = vec3(0., 0., 0.);\r\n",t.compilationString+="vec3 normalW = "+this.worldNormal.associatedVariableName+".xyz;\r\n"),this.light?t.compilationString+=t._emitCodeFromInclude("lightFragment",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]}):t.compilationString+=t._emitCodeFromInclude("lightFragment",i,{repeatKey:"maxSimultaneousLights"});var r=this.diffuseOutput,o=this.specularOutput;return t.compilationString+=this._declareOutput(r,t)+" = diffuseBase"+(this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:"")+";\r\n",o.hasEndpoints&&(t.compilationString+=this._declareOutput(o,t)+" = specularBase"+(this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:"")+";\r\n"),this.shadow.hasEndpoints&&(t.compilationString+=this._declareOutput(this.shadow,t)+" = shadow;\r\n"),this}this._injectVertexCode(t)},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return this.light&&(t.lightId=this.light.id),t},t.prototype._deserialize=function(t,i,n){e.prototype._deserialize.call(this,t,i,n),t.lightId&&(this.light=i.getLightByID(t.lightId))},t}(yc);c.a.RegisteredTypes["BABYLON.LightBlock"]=Vc;var kc=function(e){function t(t){var i=e.call(this,t,rc.VertexAndFragment)||this;return i.convertToGammaSpace=!1,i.registerInput("uv",oc.Vector2,!1,rc.VertexAndFragment),i.registerOutput("rgba",oc.Color4,rc.Neutral),i.registerOutput("rgb",oc.Color3,rc.Neutral),i.registerOutput("r",oc.Float,rc.Neutral),i.registerOutput("g",oc.Float,rc.Neutral),i.registerOutput("b",oc.Float,rc.Neutral),i.registerOutput("a",oc.Float,rc.Neutral),i._inputs[0].acceptedConnectionPointTypes.push(oc.Vector3),i._inputs[0].acceptedConnectionPointTypes.push(oc.Vector4),i._inputs[0]._prioritizeVertex=!0,i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"TextureBlock"},Object.defineProperty(t.prototype,"uv",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rgba",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rgb",{get:function(){return this._outputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"r",{get:function(){return this._outputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"g",{get:function(){return this._outputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"b",{get:function(){return this._outputs[4]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"a",{get:function(){return this._outputs[5]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){if(!this.uv.isConnected)return rc.VertexAndFragment;if(this.uv.sourceBlock.isInput)return rc.VertexAndFragment;for(var e=this.uv.connectedPoint;e;){if(e.target===rc.Fragment)return rc.Fragment;if(e.target===rc.Vertex)return rc.VertexAndFragment;if(e.target===rc.Neutral||e.target===rc.VertexAndFragment){var t=e.ownerBlock;e=null;for(var i=0,n=t.inputs;i<n.length;i++){var r=n[i];if(r.connectedPoint){e=r.connectedPoint;break}}}}return rc.VertexAndFragment},enumerable:!0,configurable:!0}),t.prototype.autoConfigure=function(e){if(!this.uv.isConnected){var t=e.getInputBlockByPredicate(function(e){return e.isAttribute&&"uv"===e.name});t||(t=new Sc("uv")).setAsAttribute(),t.output.connectTo(this.uv)}},t.prototype.initializeDefines=function(e,t,i,n){void 0===n&&(n=!1),i._areTexturesDirty&&i.setValue(this._mainUVDefineName,!1)},t.prototype.prepareDefines=function(e,t,i){if(i._areTexturesDirty){if(!this.texture||!this.texture.getTextureMatrix)return i.setValue(this._defineName,!1),void i.setValue(this._mainUVDefineName,!0);i.setValue(this._linearDefineName,this.convertToGammaSpace),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1),i.setValue(this._mainUVDefineName,!0)):i.setValue(this._defineName,!0))}},t.prototype.isReady=function(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())},t.prototype.bind=function(e,t,i){i&&this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),e.setTexture(this._samplerName,this.texture))},Object.defineProperty(t.prototype,"_isMixed",{get:function(){return this.target!==rc.Fragment},enumerable:!0,configurable:!0}),t.prototype._injectVertexCode=function(e){var t=this.uv;(this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.associatedVariableName.toUpperCase(),t.connectedPoint.ownerBlock.isInput)&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec2"));if(this._mainUVName="vMain"+t.associatedVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),e._emitVaryingFromString(this._transformedUVName,"vec2",this._defineName),e._emitVaryingFromString(this._mainUVName,"vec2",this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,"mat4",this._defineName),e.compilationString+="#ifdef "+this._defineName+"\r\n",e.compilationString+=this._transformedUVName+" = vec2("+this._textureTransformName+" * vec4("+t.associatedVariableName+".xy, 1.0, 0.0));\r\n",e.compilationString+="#elif defined("+this._mainUVDefineName+")\r\n",e.compilationString+=this._mainUVName+" = "+t.associatedVariableName+".xy;\r\n",e.compilationString+="#endif\r\n",this._outputs.some(function(e){return e.isConnectedInVertexShader})){this._writeTextureRead(e,!0);for(var i=0,n=this._outputs;i<n.length;i++){var r=n[i];r.hasEndpoints&&this._writeOutput(e,r,r.name,!0)}}},t.prototype._writeTextureRead=function(e,t){void 0===t&&(t=!1);var i=this.uv;if(t){if(e.target===rc.Fragment)return;e.compilationString+="vec4 "+this._tempTextureRead+" = texture2D("+this._samplerName+", "+i.associatedVariableName+");\r\n"}else this.uv.ownerBlock.target!==rc.Fragment?(e.compilationString+="#ifdef "+this._defineName+"\r\n",e.compilationString+="vec4 "+this._tempTextureRead+" = texture2D("+this._samplerName+", "+this._transformedUVName+");\r\n",e.compilationString+="#elif defined("+this._mainUVDefineName+")\r\n",e.compilationString+="vec4 "+this._tempTextureRead+" = texture2D("+this._samplerName+", "+this._mainUVName+");\r\n",e.compilationString+="#endif\r\n"):e.compilationString+="vec4 "+this._tempTextureRead+" = texture2D("+this._samplerName+", "+i.associatedVariableName+");\r\n"},t.prototype._writeOutput=function(e,t,i,n){if(void 0===n&&(n=!1),n){if(e.target===rc.Fragment)return;e.compilationString+=this._declareOutput(t,e)+" = "+this._tempTextureRead+"."+i+";\r\n"}else if(this.uv.ownerBlock.target!==rc.Fragment){var r=" * "+this._textureInfoName;e.compilationString+=this._declareOutput(t,e)+" = "+this._tempTextureRead+"."+i+r+";\r\n",e.compilationString+="#ifdef "+this._linearDefineName+"\r\n",e.compilationString+=t.associatedVariableName+" = toGammaSpace("+t.associatedVariableName+");\r\n",e.compilationString+="#endif\r\n"}else e.compilationString+=this._declareOutput(t,e)+" = "+this._tempTextureRead+"."+i+";\r\n"},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),t.target===rc.Vertex&&(this._tempTextureRead=t._getFreeVariableName("tempTextureRead")),(!this._isMixed&&t.target===rc.Fragment||this._isMixed&&t.target===rc.Vertex)&&(this._samplerName=t._getFreeVariableName(this.name+"Sampler"),t._emit2DSampler(this._samplerName),t.sharedData.blockingBlocks.push(this),t.sharedData.textureBlocks.push(this),t.sharedData.blocksWithDefines.push(this),t.sharedData.bindableBlocks.push(this)),t.target===rc.Fragment){if(this._outputs.some(function(e){return e.isConnectedInFragmentShader})){this._isMixed&&t._emit2DSampler(this._samplerName),this._linearDefineName=t._getFreeDefineName("ISLINEAR");var i="//"+this.name;t._emitFunctionFromInclude("helperFunctions",i),this._isMixed&&t._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(t);for(var n=0,r=this._outputs;n<r.length;n++){var o=r[n];o.hasEndpoints&&this._writeOutput(t,o,o.name)}return this}}else this._injectVertexCode(t)},t.prototype._dumpPropertiesCode=function(){if(!this.texture)return"";var e=this._codeVariableName+'.texture = new BABYLON.Texture("'+this.texture.name+'");\r\n';return e+=this._codeVariableName+".texture.wrapU = "+this.texture.wrapU+";\r\n",e+=this._codeVariableName+".texture.wrapV = "+this.texture.wrapV+";\r\n",e+=this._codeVariableName+".texture.uAng = "+this.texture.uAng+";\r\n",e+=this._codeVariableName+".texture.vAng = "+this.texture.vAng+";\r\n",e+=this._codeVariableName+".texture.wAng = "+this.texture.wAng+";\r\n",e+=this._codeVariableName+".texture.uOffset = "+this.texture.uOffset+";\r\n",e+=this._codeVariableName+".texture.vOffset = "+this.texture.vOffset+";\r\n",e+=this._codeVariableName+".texture.uScale = "+this.texture.uScale+";\r\n",e+=this._codeVariableName+".texture.vScale = "+this.texture.vScale+";\r\n",e+=this._codeVariableName+".convertToGammaSpace = "+this.convertToGammaSpace+";\r\n"},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.convertToGammaSpace=this.convertToGammaSpace,this.texture&&(t.texture=this.texture.serialize()),t},t.prototype._deserialize=function(t,i,n){e.prototype._deserialize.call(this,t,i,n),this.convertToGammaSpace=t.convertToGammaSpace,t.texture&&(n=0===t.texture.url.indexOf("data:")?"":n,this.texture=et.a.Parse(t.texture,i,n))},t}(yc);c.a.RegisteredTypes["BABYLON.TextureBlock"]=kc;var zc=function(e){function t(t){var i=e.call(this,t,rc.VertexAndFragment)||this;return i.registerInput("position",oc.Vector3,!1,rc.Vertex),i.registerInput("worldPosition",oc.Vector4,!1,rc.Vertex),i.registerInput("worldNormal",oc.Vector4,!1,rc.Fragment),i.registerInput("world",oc.Matrix,!1,rc.Vertex),i.registerInput("cameraPosition",oc.Vector3,!1,rc.Fragment),i.registerInput("view",oc.Matrix,!1,rc.Fragment),i.registerOutput("rgb",oc.Color3,rc.Fragment),i.registerOutput("r",oc.Float,rc.Fragment),i.registerOutput("g",oc.Float,rc.Fragment),i.registerOutput("b",oc.Float,rc.Fragment),i._inputs[0].acceptedConnectionPointTypes.push(oc.Vector4),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"ReflectionTextureBlock"},Object.defineProperty(t.prototype,"position",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"worldNormal",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"world",{get:function(){return this._inputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraPosition",{get:function(){return this._inputs[4]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"view",{get:function(){return this._inputs[5]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rgb",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"r",{get:function(){return this._outputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"g",{get:function(){return this._outputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"b",{get:function(){return this._outputs[3]},enumerable:!0,configurable:!0}),t.prototype.autoConfigure=function(e){if(!this.position.isConnected){var t=e.getInputBlockByPredicate(function(e){return e.isAttribute&&"position"===e.name});t||(t=new Sc("position")).setAsAttribute(),t.output.connectTo(this.position)}if(!this.world.isConnected){var i=e.getInputBlockByPredicate(function(e){return e.systemValue===sc.World});i||(i=new Sc("world")).setAsSystemValue(sc.World),i.output.connectTo(this.world)}if(!this.cameraPosition.isConnected){var n=e.getInputBlockByPredicate(function(e){return e.systemValue===sc.CameraPosition});n||(n=new Sc("cameraPosition")).setAsSystemValue(sc.CameraPosition),n.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){var r=e.getInputBlockByPredicate(function(e){return e.systemValue===sc.View});r||(r=new Sc("view")).setAsSystemValue(sc.View),r.output.connectTo(this.view)}},t.prototype.prepareDefines=function(e,t,i){i._areTexturesDirty&&this.texture&&this.texture.getTextureMatrix&&(i.setValue(this._define3DName,this.texture.isCube),i.setValue(this._defineLocalCubicName,!!this.texture.boundingBoxSize),i.setValue(this._defineExplicitName,this.texture.coordinatesMode===g.a.TEXTURE_EXPLICIT_MODE),i.setValue(this._defineSkyboxName,this.texture.coordinatesMode===g.a.TEXTURE_SKYBOX_MODE),i.setValue(this._defineCubicName,this.texture.coordinatesMode===g.a.TEXTURE_CUBIC_MODE),i.setValue(this._defineSphericalName,this.texture.coordinatesMode===g.a.TEXTURE_SPHERICAL_MODE),i.setValue(this._definePlanarName,this.texture.coordinatesMode===g.a.TEXTURE_PLANAR_MODE),i.setValue(this._defineProjectionName,this.texture.coordinatesMode===g.a.TEXTURE_PROJECTION_MODE),i.setValue(this._defineEquirectangularName,this.texture.coordinatesMode===g.a.TEXTURE_EQUIRECTANGULAR_MODE),i.setValue(this._defineEquirectangularFixedName,this.texture.coordinatesMode===g.a.TEXTURE_FIXED_EQUIRECTANGULAR_MODE),i.setValue(this._defineMirroredEquirectangularFixedName,this.texture.coordinatesMode===g.a.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE))},t.prototype.isReady=function(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())},t.prototype.bind=function(e,t,i){i&&this.texture&&(e.setMatrix(this._reflectionMatrixName,this.texture.getReflectionTextureMatrix()),this.texture.isCube?e.setTexture(this._cubeSamplerName,this.texture):e.setTexture(this._2DSamplerName,this.texture))},t.prototype._injectVertexCode=function(e){var t="v_"+this.worldPosition.associatedVariableName;e._emitVaryingFromString(t,"vec4")&&(e.compilationString+=t+" = "+this.worldPosition.associatedVariableName+";\r\n"),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName)&&(e.compilationString+="#ifdef "+this._defineSkyboxName+"\r\n",e.compilationString+=this._positionUVWName+" = "+this.position.associatedVariableName+".xyz;\r\n",e.compilationString+="#endif\r\n"),e._emitVaryingFromString(this._directionWName,"vec3","defined("+this._defineEquirectangularFixedName+") || defined("+this._defineMirroredEquirectangularFixedName+")")&&(e.compilationString+="#if defined("+this._defineEquirectangularFixedName+") || defined("+this._defineMirroredEquirectangularFixedName+")\r\n",e.compilationString+=this._directionWName+" = normalize(vec3("+this.world.associatedVariableName+" * vec4("+this.position.associatedVariableName+".xyz, 0.0)));\r\n",e.compilationString+="#endif\r\n")},t.prototype._writeOutput=function(e,t,i){e.compilationString+=this._declareOutput(t,e)+" = "+this._reflectionColorName+"."+i+";\r\n"},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),this.texture){if(t.target!==rc.Fragment)return this._define3DName=t._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=t._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=t._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=t._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=t._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=t._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=t._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=t._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=t._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=t._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=t._getFreeDefineName("REFLECTIONMAP_SKYBOX"),void this._injectVertexCode(t);t.sharedData.blockingBlocks.push(this),t.sharedData.textureBlocks.push(this),this._cubeSamplerName=t._getFreeVariableName(this.name+"CubeSampler"),t.samplers.push(this._cubeSamplerName),this._2DSamplerName=t._getFreeVariableName(this.name+"2DSampler"),t.samplers.push(this._2DSamplerName),t._samplerDeclaration+="#ifdef "+this._define3DName+"\r\n",t._samplerDeclaration+="uniform samplerCube "+this._cubeSamplerName+";\r\n",t._samplerDeclaration+="#else\r\n",t._samplerDeclaration+="uniform sampler2D "+this._2DSamplerName+";\r\n",t._samplerDeclaration+="#endif\r\n",t.sharedData.blocksWithDefines.push(this),t.sharedData.bindableBlocks.push(this);var i="//"+this.name;t._emitFunction("ReciprocalPI","#define RECIPROCAL_PI2 0.15915494",""),t._emitFunctionFromInclude("reflectionFunction",i),this._reflectionColorName=t._getFreeVariableName("reflectionColor"),this._reflectionCoordsName=t._getFreeVariableName("reflectionUVW"),this._reflection2DCoordsName=t._getFreeVariableName("reflectionUV"),this._reflectionMatrixName=t._getFreeVariableName("reflectionMatrix"),t._emitUniformFromString(this._reflectionMatrixName,"mat4");var n="v_"+this.worldPosition.associatedVariableName,r=this.worldNormal.associatedVariableName+".xyz",o=this._reflectionMatrixName,a="normalize("+this._directionWName+")",s=""+this._positionUVWName,c=""+this.cameraPosition.associatedVariableName,l=""+this.view.associatedVariableName;t.compilationString+="vec3 "+this._reflectionColorName+";\r\n",t.compilationString+="#ifdef "+this._defineMirroredEquirectangularFixedName+"\r\n",t.compilationString+="    vec3 "+this._reflectionCoordsName+" = computeMirroredFixedEquirectangularCoords("+n+", "+r+", "+a+");\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#ifdef "+this._defineEquirectangularFixedName+"\r\n",t.compilationString+="    vec3 "+this._reflectionCoordsName+" = computeFixedEquirectangularCoords("+n+", "+r+", "+a+");\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#ifdef "+this._defineEquirectangularName+"\r\n",t.compilationString+="    vec3 "+this._reflectionCoordsName+" = computeEquirectangularCoords("+n+", "+r+", "+c+".xyz, "+o+");\r\n",t.compilationString+=" #endif\r\n",t.compilationString+="#ifdef "+this._defineSphericalName+"\r\n",t.compilationString+="    vec3 "+this._reflectionCoordsName+" = computeSphericalCoords("+n+", "+r+", "+l+", "+o+");\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#ifdef "+this._definePlanarName+"\r\n",t.compilationString+="    vec3 "+this._reflectionCoordsName+" = computePlanarCoords("+n+", "+r+", "+c+".xyz, "+o+");\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#ifdef "+this._defineCubicName+"\r\n",t.compilationString+="    #ifdef "+this._defineLocalCubicName+"\r\n",t.compilationString+="        vec3 "+this._reflectionCoordsName+" = computeCubicLocalCoords("+n+", "+r+", "+c+".xyz, "+o+", vReflectionSize, vReflectionPosition);\r\n",t.compilationString+="    #else\r\n",t.compilationString+="       vec3 "+this._reflectionCoordsName+" = computeCubicCoords("+n+", "+r+", "+c+".xyz, "+o+");\r\n",t.compilationString+="    #endif\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#ifdef "+this._defineProjectionName+"\r\n",t.compilationString+="    vec3 "+this._reflectionCoordsName+" = computeProjectionCoords("+n+", "+l+", "+o+");\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#ifdef "+this._defineSkyboxName+"\r\n",t.compilationString+="    vec3 "+this._reflectionCoordsName+" = computeSkyBoxCoords("+s+", "+o+");\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#ifdef "+this._defineExplicitName+"\r\n",t.compilationString+="    vec3 "+this._reflectionCoordsName+" = vec3(0, 0, 0);\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#ifdef "+this._define3DName+"\r\n",t.compilationString+=this._reflectionColorName+" = textureCube("+this._cubeSamplerName+", "+this._reflectionCoordsName+").rgb;\r\n",t.compilationString+="#else\r\n",t.compilationString+="vec2 "+this._reflection2DCoordsName+" = "+this._reflectionCoordsName+".xy;\r\n",t.compilationString+="#ifdef "+this._defineProjectionName+"\r\n",t.compilationString+=this._reflection2DCoordsName+" /= "+this._reflectionCoordsName+".z;\r\n",t.compilationString+="#endif\r\n",t.compilationString+=this._reflection2DCoordsName+".y = 1.0 - "+this._reflection2DCoordsName+".y;\r\n",t.compilationString+=this._reflectionColorName+" = texture2D("+this._2DSamplerName+", "+this._reflection2DCoordsName+").rgb;\r\n",t.compilationString+="#endif\r\n";for(var u=0,h=this._outputs;u<h.length;u++){(p=h[u]).hasEndpoints&&this._writeOutput(t,p,p.name)}return this}if(t.target===rc.Fragment)for(var d=0,f=this._outputs;d<f.length;d++){var p;(p=f[d]).hasEndpoints&&(t.compilationString+=this._declareOutput(p,t)+" = vec3(0.)."+p.name+";\r\n")}},t.prototype._dumpPropertiesCode=function(){return this.texture?(e=this.texture.isCube?this._codeVariableName+'.texture = new BABYLON.CubeTexture("'+this.texture.name+'");\r\n':this._codeVariableName+'.texture = new BABYLON.Texture("'+this.texture.name+'");\r\n',e+=this._codeVariableName+".texture.coordinatesMode = "+this.texture.coordinatesMode+";\r\n"):"";var e},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return this.texture&&(t.texture=this.texture.serialize()),t},t.prototype._deserialize=function(t,i,n){e.prototype._deserialize.call(this,t,i,n),t.texture&&(n=0===t.texture.url.indexOf("data:")?"":n,t.texture.isCube?this.texture=to.Parse(t.texture,i,n):this.texture=et.a.Parse(t.texture,i,n))},t}(yc);c.a.RegisteredTypes["BABYLON.ReflectionTextureBlock"]=zc;var Gc=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("left",oc.AutoDetect),i.registerInput("right",oc.AutoDetect),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"MultiplyBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = "+this.left.associatedVariableName+" * "+this.right.associatedVariableName+";\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.MultiplyBlock"]=Gc;var jc=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("left",oc.AutoDetect),i.registerInput("right",oc.AutoDetect),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"AddBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = "+this.left.associatedVariableName+" + "+this.right.associatedVariableName+";\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.AddBlock"]=jc;var Wc=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("input",oc.AutoDetect),i.registerInput("factor",oc.Float),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"ScaleBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"factor",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = "+this.input.associatedVariableName+" * "+this.factor.associatedVariableName+";\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.ScaleBlock"]=Wc;var Xc=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.minimum=0,i.maximum=1,i.registerInput("value",oc.AutoDetect),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"ClampBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = clamp("+this.value.associatedVariableName+", "+this._writeFloat(this.minimum)+", "+this._writeFloat(this.maximum)+");\r\n",this},t.prototype._dumpPropertiesCode=function(){var e=this._codeVariableName+".minimum = "+this.minimum+";\r\n";return e+=this._codeVariableName+".maximum = "+this.maximum+";\r\n"},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.minimum=this.minimum,t.maximum=this.maximum,t},t.prototype._deserialize=function(t,i,n){e.prototype._deserialize.call(this,t,i,n),this.minimum=t.minimum,this.maximum=t.maximum},t}(yc);c.a.RegisteredTypes["BABYLON.ClampBlock"]=Xc;var Hc=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("left",oc.AutoDetect),i.registerInput("right",oc.AutoDetect),i.registerOutput("output",oc.Vector3),i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(oc.Float),i._inputs[0].excludedConnectionPointTypes.push(oc.Matrix),i._inputs[0].excludedConnectionPointTypes.push(oc.Vector2),i._inputs[1].excludedConnectionPointTypes.push(oc.Float),i._inputs[1].excludedConnectionPointTypes.push(oc.Matrix),i._inputs[1].excludedConnectionPointTypes.push(oc.Vector2),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"CrossBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = cross("+this.left.associatedVariableName+".xyz, "+this.right.associatedVariableName+".xyz);\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.CrossBlock"]=Hc;var Yc=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("left",oc.AutoDetect),i.registerInput("right",oc.AutoDetect),i.registerOutput("output",oc.Float),i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(oc.Float),i._inputs[0].excludedConnectionPointTypes.push(oc.Matrix),i._inputs[1].excludedConnectionPointTypes.push(oc.Float),i._inputs[1].excludedConnectionPointTypes.push(oc.Matrix),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"DotBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = dot("+this.left.associatedVariableName+", "+this.right.associatedVariableName+");\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.DotBlock"]=Yc;var Kc=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.sourceRange=new a.d(-1,1),i.targetRange=new a.d(0,1),i.registerInput("input",oc.AutoDetect),i.registerInput("sourceMin",oc.Float,!0),i.registerInput("sourceMax",oc.Float,!0),i.registerInput("targetMin",oc.Float,!0),i.registerInput("targetMax",oc.Float,!0),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"RemapBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"sourceMin",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"sourceMax",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"targetMin",{get:function(){return this._inputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"targetMax",{get:function(){return this._inputs[4]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],n=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),r=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),o=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),a=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return t.compilationString+=this._declareOutput(i,t)+" = "+o+" + ("+this._inputs[0].associatedVariableName+" - "+n+") * ("+a+" - "+o+") / ("+r+" - "+n+");\r\n",this},t.prototype._dumpPropertiesCode=function(){var e=this._codeVariableName+".sourceRange = new BABYLON.Vector2("+this.sourceRange.x+", "+this.sourceRange.y+");\r\n";return e+=this._codeVariableName+".targetRange = new BABYLON.Vector2("+this.targetRange.x+", "+this.targetRange.y+");\r\n"},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.sourceRange=this.sourceRange.asArray(),t.targetRange=this.targetRange.asArray(),t},t.prototype._deserialize=function(t,i,n){e.prototype._deserialize.call(this,t,i,n),this.sourceRange=a.d.FromArray(t.sourceRange),this.targetRange=a.d.FromArray(t.targetRange)},t}(yc);c.a.RegisteredTypes["BABYLON.RemapBlock"]=Kc;var Qc,qc=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("input",oc.AutoDetect),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._inputs[0].excludedConnectionPointTypes.push(oc.Float),i._inputs[0].excludedConnectionPointTypes.push(oc.Matrix),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"NormalizeBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],n=this._inputs[0];return t.compilationString+=this._declareOutput(i,t)+" = normalize("+n.associatedVariableName+");\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.NormalizeBlock"]=qc,function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees"}(Qc||(Qc={}));var Zc=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.operation=Qc.Cos,i.registerInput("input",oc.AutoDetect),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"TrigonometryBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],n="";switch(this.operation){case Qc.Cos:n="cos";break;case Qc.Sin:n="sin";break;case Qc.Abs:n="abs";break;case Qc.Exp:n="exp";break;case Qc.Exp2:n="exp2";break;case Qc.Round:n="round";break;case Qc.Floor:n="floor";break;case Qc.Ceiling:n="ceil";break;case Qc.Sqrt:n="sqrt";break;case Qc.Log:n="log";break;case Qc.Tan:n="tan";break;case Qc.ArcTan:n="atan";break;case Qc.ArcCos:n="acos";break;case Qc.ArcSin:n="asin";break;case Qc.Fract:n="fract";break;case Qc.Sign:n="sign";break;case Qc.Radians:n="radians";break;case Qc.Degrees:n="degrees"}return t.compilationString+=this._declareOutput(i,t)+" = "+n+"("+this.input.associatedVariableName+");\r\n",this},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.operation=this.operation,t},t.prototype._deserialize=function(t,i,n){e.prototype._deserialize.call(this,t,i,n),this.operation=t.operation},t.prototype._dumpPropertiesCode=function(){return this._codeVariableName+".operation = BABYLON.TrigonometryBlockOperations."+Qc[this.operation]+";\r\n"},t}(yc);c.a.RegisteredTypes["BABYLON.TrigonometryBlock"]=Zc;var Jc=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("rgb ",oc.Color3,!0),i.registerInput("r",oc.Float,!0),i.registerInput("g",oc.Float,!0),i.registerInput("b",oc.Float,!0),i.registerInput("a",oc.Float,!0),i.registerOutput("rgba",oc.Color4),i.registerOutput("rgb",oc.Color3),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"ColorMergerBlock"},Object.defineProperty(t.prototype,"rgbIn",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"r",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"g",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"b",{get:function(){return this._inputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"a",{get:function(){return this._inputs[4]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rgba",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rgbOut",{get:function(){return this._outputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rgb",{get:function(){return this.rgbOut},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.r,n=this.g,r=this.b,o=this.a,a=this.rgbIn,s=this._outputs[0],c=this._outputs[1];return a.isConnected?s.hasEndpoints?t.compilationString+=this._declareOutput(s,t)+" = vec4("+a.associatedVariableName+", "+(o.isConnected?this._writeVariable(o):"0.0")+");\r\n":c.hasEndpoints&&(t.compilationString+=this._declareOutput(c,t)+" = "+a.associatedVariableName+";\r\n"):s.hasEndpoints?t.compilationString+=this._declareOutput(s,t)+" = vec4("+(i.isConnected?this._writeVariable(i):"0.0")+", "+(n.isConnected?this._writeVariable(n):"0.0")+", "+(r.isConnected?this._writeVariable(r):"0.0")+", "+(o.isConnected?this._writeVariable(o):"0.0")+");\r\n":c.hasEndpoints&&(t.compilationString+=this._declareOutput(c,t)+" = vec3("+(i.isConnected?this._writeVariable(i):"0.0")+", "+(n.isConnected?this._writeVariable(n):"0.0")+", "+(r.isConnected?this._writeVariable(r):"0.0")+");\r\n"),this},t}(yc);c.a.RegisteredTypes["BABYLON.ColorMergerBlock"]=Jc;var $c=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("xyz ",oc.Vector3,!0),i.registerInput("xy ",oc.Vector2,!0),i.registerInput("x",oc.Float,!0),i.registerInput("y",oc.Float,!0),i.registerInput("z",oc.Float,!0),i.registerInput("w",oc.Float,!0),i.registerOutput("xyzw",oc.Vector4),i.registerOutput("xyz",oc.Vector3),i.registerOutput("xy",oc.Vector2),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"VectorMergerBlock"},Object.defineProperty(t.prototype,"xyzIn",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"xyIn",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"x",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._inputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"z",{get:function(){return this._inputs[4]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"w",{get:function(){return this._inputs[5]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"xyzw",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"xyzOut",{get:function(){return this._outputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"xyOut",{get:function(){return this._outputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"xy",{get:function(){return this.xyOut},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"xyz",{get:function(){return this.xyzOut},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.x,n=this.y,r=this.z,o=this.w,a=this.xyIn,s=this.xyzIn,c=this._outputs[0],l=this._outputs[1],u=this._outputs[2];return a.isConnected?c.hasEndpoints?t.compilationString+=this._declareOutput(c,t)+" = vec4("+a.associatedVariableName+", "+(r.isConnected?this._writeVariable(r):"0.0")+", "+(o.isConnected?this._writeVariable(o):"0.0")+");\r\n":l.hasEndpoints?t.compilationString+=this._declareOutput(l,t)+" = vec3("+a.associatedVariableName+", "+(r.isConnected?this._writeVariable(r):"0.0")+");\r\n":u.hasEndpoints&&(t.compilationString+=this._declareOutput(u,t)+" = "+a.associatedVariableName+";\r\n"):s.isConnected?c.hasEndpoints?t.compilationString+=this._declareOutput(c,t)+" = vec4("+s.associatedVariableName+", "+(o.isConnected?this._writeVariable(o):"0.0")+");\r\n":l.hasEndpoints?t.compilationString+=this._declareOutput(l,t)+" = "+s.associatedVariableName+";\r\n":u.hasEndpoints&&(t.compilationString+=this._declareOutput(u,t)+" = "+s.associatedVariableName+".xy;\r\n"):c.hasEndpoints?t.compilationString+=this._declareOutput(c,t)+" = vec4("+(i.isConnected?this._writeVariable(i):"0.0")+", "+(n.isConnected?this._writeVariable(n):"0.0")+", "+(r.isConnected?this._writeVariable(r):"0.0")+", "+(o.isConnected?this._writeVariable(o):"0.0")+");\r\n":l.hasEndpoints?t.compilationString+=this._declareOutput(l,t)+" = vec3("+(i.isConnected?this._writeVariable(i):"0.0")+", "+(n.isConnected?this._writeVariable(n):"0.0")+", "+(r.isConnected?this._writeVariable(r):"0.0")+");\r\n":u.hasEndpoints&&(t.compilationString+=this._declareOutput(u,t)+" = vec2("+(i.isConnected?this._writeVariable(i):"0.0")+", "+(n.isConnected?this._writeVariable(n):"0.0")+");\r\n"),this},t}(yc);c.a.RegisteredTypes["BABYLON.VectorMergerBlock"]=$c;var el=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("rgba",oc.Color4,!0),i.registerInput("rgb ",oc.Color3,!0),i.registerOutput("rgb",oc.Color3),i.registerOutput("r",oc.Float),i.registerOutput("g",oc.Float),i.registerOutput("b",oc.Float),i.registerOutput("a",oc.Float),i.inputsAreExclusive=!0,i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"ColorSplitterBlock"},Object.defineProperty(t.prototype,"rgba",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rgbIn",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rgbOut",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"r",{get:function(){return this._outputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"g",{get:function(){return this._outputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"b",{get:function(){return this._outputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"a",{get:function(){return this._outputs[4]},enumerable:!0,configurable:!0}),t.prototype._inputRename=function(e){return"rgb "===e?"rgbIn":e},t.prototype._outputRename=function(e){return"rgb"===e?"rgbOut":e},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.rgba.isConnected?this.rgba:this.rgbIn;if(i.isConnected){var n=this._outputs[0],r=this._outputs[1],o=this._outputs[2],a=this._outputs[3],s=this._outputs[4];return n.hasEndpoints&&(t.compilationString+=this._declareOutput(n,t)+" = "+i.associatedVariableName+".rgb;\r\n"),r.hasEndpoints&&(t.compilationString+=this._declareOutput(r,t)+" = "+i.associatedVariableName+".r;\r\n"),o.hasEndpoints&&(t.compilationString+=this._declareOutput(o,t)+" = "+i.associatedVariableName+".g;\r\n"),a.hasEndpoints&&(t.compilationString+=this._declareOutput(a,t)+" = "+i.associatedVariableName+".b;\r\n"),s.hasEndpoints&&(t.compilationString+=this._declareOutput(s,t)+" = "+i.associatedVariableName+".a;\r\n"),this}},t}(yc);c.a.RegisteredTypes["BABYLON.ColorSplitterBlock"]=el;var tl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("xyzw",oc.Vector4,!0),i.registerInput("xyz ",oc.Vector3,!0),i.registerInput("xy ",oc.Vector2,!0),i.registerOutput("xyz",oc.Vector3),i.registerOutput("xy",oc.Vector2),i.registerOutput("x",oc.Float),i.registerOutput("y",oc.Float),i.registerOutput("z",oc.Float),i.registerOutput("w",oc.Float),i.inputsAreExclusive=!0,i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"VectorSplitterBlock"},Object.defineProperty(t.prototype,"xyzw",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"xyzIn",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"xyIn",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"xyzOut",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"xyOut",{get:function(){return this._outputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"x",{get:function(){return this._outputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._outputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"z",{get:function(){return this._outputs[4]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"w",{get:function(){return this._outputs[5]},enumerable:!0,configurable:!0}),t.prototype._inputRename=function(e){switch(e){case"xy ":return"xyIn";case"xyz ":return"xyzIn";default:return e}},t.prototype._outputRename=function(e){switch(e){case"xy":return"xyOut";case"xyz":return"xyzOut";default:return e}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.xyzw.isConnected?this.xyzw:this.xyzIn.isConnected?this.xyzIn:this.xyIn,n=this._outputs[0],r=this._outputs[1],o=this._outputs[2],a=this._outputs[3],s=this._outputs[4],c=this._outputs[5];return n.hasEndpoints&&(i===this.xyIn?t.compilationString+=this._declareOutput(n,t)+" = vec3("+i.associatedVariableName+", 0.0);\r\n":t.compilationString+=this._declareOutput(n,t)+" = "+i.associatedVariableName+".xyz;\r\n"),r.hasEndpoints&&(t.compilationString+=this._declareOutput(r,t)+" = "+i.associatedVariableName+".xy;\r\n"),o.hasEndpoints&&(t.compilationString+=this._declareOutput(o,t)+" = "+i.associatedVariableName+".x;\r\n"),a.hasEndpoints&&(t.compilationString+=this._declareOutput(a,t)+" = "+i.associatedVariableName+".y;\r\n"),s.hasEndpoints&&(t.compilationString+=this._declareOutput(s,t)+" = "+i.associatedVariableName+".z;\r\n"),c.hasEndpoints&&(t.compilationString+=this._declareOutput(c,t)+" = "+i.associatedVariableName+".w;\r\n"),this},t}(yc);c.a.RegisteredTypes["BABYLON.VectorSplitterBlock"]=tl;var il=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("left",oc.AutoDetect),i.registerInput("right",oc.AutoDetect),i.registerInput("gradient",oc.Float),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"LerpBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gradient",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = mix("+this.left.associatedVariableName+" , "+this.right.associatedVariableName+", "+this.gradient.associatedVariableName+");\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.LerpBlock"]=il;var nl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("left",oc.AutoDetect),i.registerInput("right",oc.AutoDetect),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"DivideBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = "+this.left.associatedVariableName+" / "+this.right.associatedVariableName+";\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.DivideBlock"]=nl;var rl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("left",oc.AutoDetect),i.registerInput("right",oc.AutoDetect),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"SubtractBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = "+this.left.associatedVariableName+" - "+this.right.associatedVariableName+";\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.SubtractBlock"]=rl;var ol=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("value",oc.Float),i.registerInput("edge",oc.Float),i.registerOutput("output",oc.Float),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"StepBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"edge",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = step("+this.edge.associatedVariableName+", "+this.value.associatedVariableName+");\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.StepBlock"]=ol;var al=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("input",oc.AutoDetect),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._outputs[0].excludedConnectionPointTypes.push(oc.Matrix),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"OneMinusBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = 1. - "+this.input.associatedVariableName+";\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.OneMinusBlock"]=al,c.a.RegisteredTypes["BABYLON.OppositeBlock"]=al;var sl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("worldPosition",oc.Vector4),i.registerInput("cameraPosition",oc.Vector3),i.registerOutput("output",oc.Vector3),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"ViewDirectionBlock"},Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraPosition",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype.autoConfigure=function(e){if(!this.cameraPosition.isConnected){var t=e.getInputBlockByPredicate(function(e){return e.systemValue===sc.CameraPosition});t||(t=new Sc("cameraPosition")).setAsSystemValue(sc.CameraPosition),t.output.connectTo(this.cameraPosition)}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = normalize("+this.cameraPosition.associatedVariableName+" - "+this.worldPosition.associatedVariableName+".xyz);\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.ViewDirectionBlock"]=sl;i(145);var cl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("worldNormal",oc.Vector4),i.registerInput("viewDirection",oc.Vector3),i.registerInput("bias",oc.Float),i.registerInput("power",oc.Float),i.registerOutput("fresnel",oc.Float),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"FresnelBlock"},Object.defineProperty(t.prototype,"worldNormal",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"viewDirection",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bias",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"power",{get:function(){return this._inputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fresnel",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype.autoConfigure=function(e){if(!this.viewDirection.isConnected){var t=new sl("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){var i=new Sc("bias");i.value=0,i.output.connectTo(this.bias)}if(!this.power.isConnected){var n=new Sc("power");n.value=1,n.output.connectTo(this.power)}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i="//"+this.name;return t._emitFunctionFromInclude("fresnelFunction",i,{removeIfDef:!0}),t.compilationString+=this._declareOutput(this.fresnel,t)+" = computeFresnelTerm("+this.viewDirection.associatedVariableName+".xyz, "+this.worldNormal.associatedVariableName+".xyz, "+this.bias.associatedVariableName+", "+this.power.associatedVariableName+");\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.FresnelBlock"]=cl;var ll=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("left",oc.AutoDetect),i.registerInput("right",oc.AutoDetect),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"MaxBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = max("+this.left.associatedVariableName+", "+this.right.associatedVariableName+");\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.MaxBlock"]=ll;var ul=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("left",oc.AutoDetect),i.registerInput("right",oc.AutoDetect),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"MinBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = min("+this.left.associatedVariableName+", "+this.right.associatedVariableName+");\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.MinBlock"]=ul;var hl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("left",oc.AutoDetect),i.registerInput("right",oc.AutoDetect),i.registerOutput("output",oc.Float),i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(oc.Float),i._inputs[0].excludedConnectionPointTypes.push(oc.Matrix),i._inputs[1].excludedConnectionPointTypes.push(oc.Float),i._inputs[1].excludedConnectionPointTypes.push(oc.Matrix),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"DistanceBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = length("+this.left.associatedVariableName+" - "+this.right.associatedVariableName+");\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.DistanceBlock"]=hl;var dl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("value",oc.AutoDetect),i.registerOutput("output",oc.Float),i._inputs[0].excludedConnectionPointTypes.push(oc.Float),i._inputs[0].excludedConnectionPointTypes.push(oc.Matrix),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"LengthBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = length("+this.value.associatedVariableName+");\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.LengthBlock"]=dl;var fl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("value",oc.AutoDetect),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"NegateBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = -1.0 * "+this.value.associatedVariableName+";\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.NegateBlock"]=fl;var pl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("value",oc.Float),i.registerInput("power",oc.Float),i.registerOutput("output",oc.Float),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"PowBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"power",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = pow("+this.value.associatedVariableName+", "+this.power.associatedVariableName+");\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.PowBlock"]=pl;var _l=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("seed",oc.Vector2),i.registerOutput("output",oc.Float),i._inputs[0].acceptedConnectionPointTypes.push(oc.Vector3),i._inputs[0].acceptedConnectionPointTypes.push(oc.Vector4),i._inputs[0].acceptedConnectionPointTypes.push(oc.Color3),i._inputs[0].acceptedConnectionPointTypes.push(oc.Color4),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"RandomNumberBlock"},Object.defineProperty(t.prototype,"seed",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],n="//"+this.name;return t._emitFunctionFromInclude("helperFunctions",n),t.compilationString+=this._declareOutput(i,t)+" = getRand("+this.seed.associatedVariableName+".xy);\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.RandomNumberBlock"]=_l;var ml=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("x",oc.Float),i.registerInput("y",oc.Float),i.registerOutput("output",oc.Float),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"ArcTan2Block"},Object.defineProperty(t.prototype,"x",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = atan("+this.x.associatedVariableName+", "+this.y.associatedVariableName+");\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.ArcTan2Block"]=ml;var gl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("value",oc.Float),i.registerInput("edge0",oc.Float),i.registerInput("edge1",oc.Float),i.registerOutput("output",oc.Float),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"SmoothStepBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"edge0",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"edge1",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = smoothstep("+this.edge0.associatedVariableName+", "+this.edge1.associatedVariableName+", "+this.value.associatedVariableName+");\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.SmoothStepBlock"]=gl;var vl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("input",oc.AutoDetect),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._outputs[0].excludedConnectionPointTypes.push(oc.Matrix),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"ReciprocalBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = 1. / "+this.input.associatedVariableName+";\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.ReciprocalBlock"]=vl;var yl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("value",oc.AutoDetect),i.registerInput("reference",oc.AutoDetect),i.registerInput("distance",oc.Float),i.registerInput("replacement",oc.AutoDetect),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i._linkConnectionTypes(0,3),i._inputs[0].excludedConnectionPointTypes.push(oc.Float),i._inputs[0].excludedConnectionPointTypes.push(oc.Matrix),i._inputs[1].excludedConnectionPointTypes.push(oc.Float),i._inputs[1].excludedConnectionPointTypes.push(oc.Matrix),i._inputs[3].excludedConnectionPointTypes.push(oc.Float),i._inputs[3].excludedConnectionPointTypes.push(oc.Matrix),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"ReplaceColorBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"reference",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"distance",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"replacement",{get:function(){return this._inputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+";\r\n",t.compilationString+="if (length("+this.value.associatedVariableName+" - "+this.reference.associatedVariableName+") < "+this.distance.associatedVariableName+") {\r\n",t.compilationString+=i.associatedVariableName+" = "+this.replacement.associatedVariableName+";\r\n",t.compilationString+="} else {\r\n",t.compilationString+=i.associatedVariableName+" = "+this.value.associatedVariableName+";\r\n",t.compilationString+="}\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.ReplaceColorBlock"]=yl;var bl,Tl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("value",oc.AutoDetect),i.registerInput("steps",oc.AutoDetect),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(oc.Matrix),i._inputs[1].excludedConnectionPointTypes.push(oc.Matrix),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"PosterizeBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"steps",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = floor("+this.value.associatedVariableName+" / (1.0 / "+this.steps.associatedVariableName+")) * (1.0 / "+this.steps.associatedVariableName+");\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.PosterizeBlock"]=Tl,function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(bl||(bl={}));var El=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.kind=bl.SawTooth,i.registerInput("input",oc.AutoDetect),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._inputs[0].excludedConnectionPointTypes.push(oc.Matrix),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"WaveBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];switch(this.kind){case bl.SawTooth:t.compilationString+=this._declareOutput(i,t)+" = "+this.input.associatedVariableName+" - floor(0.5 + "+this.input.associatedVariableName+");\r\n";break;case bl.Square:t.compilationString+=this._declareOutput(i,t)+" = 1.0 - 2.0 * round(fract("+this.input.associatedVariableName+"));\r\n";break;case bl.Triangle:t.compilationString+=this._declareOutput(i,t)+" = 2.0 * abs(2.0 * ("+this.input.associatedVariableName+" - floor(0.5 + "+this.input.associatedVariableName+"))) - 1.0;\r\n"}return this},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.kind=this.kind,t},t.prototype._deserialize=function(t,i,n){e.prototype._deserialize.call(this,t,i,n),this.kind=t.kind},t}(yc);c.a.RegisteredTypes["BABYLON.WaveBlock"]=El;var xl=function(e,t){this.step=e,this.color=t},Pl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.colorSteps=[new xl(0,s.a.Black()),new xl(1,s.a.White())],i.registerInput("gradient",oc.Float),i.registerOutput("output",oc.Color3),i._inputs[0].acceptedConnectionPointTypes.push(oc.Vector2),i._inputs[0].acceptedConnectionPointTypes.push(oc.Vector3),i._inputs[0].acceptedConnectionPointTypes.push(oc.Vector4),i._inputs[0].acceptedConnectionPointTypes.push(oc.Color3),i._inputs[0].acceptedConnectionPointTypes.push(oc.Color4),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"GradientBlock"},Object.defineProperty(t.prototype,"gradient",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._writeColorConstant=function(e){var t=this.colorSteps[e];return"vec3("+t.color.r+", "+t.color.g+", "+t.color.b+")"},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];if(this.colorSteps.length&&this.gradient.connectedPoint){var n=t._getFreeVariableName("gradientTempColor"),r=t._getFreeVariableName("gradientTempPosition");t.compilationString+="vec3 "+n+" = "+this._writeColorConstant(0)+";\r\n",t.compilationString+="float "+r+";\r\n";var o=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==oc.Float&&(o+=".x");for(var a=1;a<this.colorSteps.length;a++){var s=this.colorSteps[a],c=this.colorSteps[a-1];t.compilationString+=r+" = clamp(("+o+" - "+t._emitFloat(c.step)+") / ("+t._emitFloat(s.step)+" -  "+t._emitFloat(c.step)+"), 0.0, 1.0) * step("+t._emitFloat(a)+", "+t._emitFloat(this.colorSteps.length-1)+");\r\n",t.compilationString+=n+" = mix("+n+", "+this._writeColorConstant(a)+", "+r+");\r\n"}return t.compilationString+=this._declareOutput(i,t)+" = "+n+";\r\n",this}t.compilationString+=this._declareOutput(i,t)+" = vec3(0., 0., 0.);\r\n"},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.colorSteps=this.colorSteps,t},t.prototype._deserialize=function(t,i,n){e.prototype._deserialize.call(this,t,i,n),this.colorSteps=[];for(var r=0,o=t.colorSteps;r<o.length;r++){var a=o[r];this.colorSteps.push(new xl(a.step,new s.a(a.color.r,a.color.g,a.color.b)))}},t.prototype._dumpPropertiesCode=function(){for(var e="",t=0,i=this.colorSteps;t<i.length;t++){var n=i[t];e+=this._codeVariableName+".colorSteps.push(new BABYLON.GradientBlockColorStep("+n.step+", new BABYLON.Color3("+n.color.r+", "+n.color.g+", "+n.color.b+")));\r\n"}return e},t}(yc);c.a.RegisteredTypes["BABYLON.GradientBlock"]=Pl;var Al=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("left",oc.AutoDetect),i.registerInput("right",oc.AutoDetect),i.registerInput("gradient",oc.Float),i.registerOutput("output",oc.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"NLerpBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gradient",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = normalize(mix("+this.left.associatedVariableName+" , "+this.right.associatedVariableName+", "+this.gradient.associatedVariableName+"));\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.NLerpBlock"]=Al;var Sl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.manhattanDistance=!1,i.registerInput("seed",oc.Vector3),i.registerInput("jitter",oc.Float),i.registerOutput("output",oc.Vector2),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"WorleyNoise3DBlock"},Object.defineProperty(t.prototype,"seed",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"jitter",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),this.seed.isConnected&&this._outputs[0].hasEndpoints){return"    return mod((34.0 * x + 1.0) * x, 289.0);\r\n","}\r\n\r\n","vec3 dist(vec3 x, vec3 y, vec3 z,  bool manhattanDistance){\r\n","    return manhattanDistance ?  abs(x) + abs(y) + abs(z) :  (x * x + y * y + z * z);\r\n","}\r\n\r\n","vec2 worley(vec3 P, float jitter, bool manhattanDistance){\r\n","    float K = 0.142857142857; // 1/7\r\n","    float Ko = 0.428571428571; // 1/2-K/2\r\n","    float  K2 = 0.020408163265306; // 1/(7*7)\r\n","    float Kz = 0.166666666667; // 1/6\r\n","    float Kzo = 0.416666666667; // 1/2-1/6*2\r\n","\r\n","    vec3 Pi = mod(floor(P), 289.0);\r\n","    vec3 Pf = fract(P) - 0.5;\r\n","\r\n","    vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);\r\n","    vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);\r\n","    vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);\r\n","\r\n","    vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));\r\n","    vec3 p1 = permute(p + Pi.y - 1.0);\r\n","    vec3 p2 = permute(p + Pi.y);\r\n","    vec3 p3 = permute(p + Pi.y + 1.0);\r\n","\r\n","    vec3 p11 = permute(p1 + Pi.z - 1.0);\r\n","    vec3 p12 = permute(p1 + Pi.z);\r\n","    vec3 p13 = permute(p1 + Pi.z + 1.0);\r\n","\r\n","    vec3 p21 = permute(p2 + Pi.z - 1.0);\r\n","    vec3 p22 = permute(p2 + Pi.z);\r\n","    vec3 p23 = permute(p2 + Pi.z + 1.0);\r\n","\r\n","    vec3 p31 = permute(p3 + Pi.z - 1.0);\r\n","    vec3 p32 = permute(p3 + Pi.z);\r\n","    vec3 p33 = permute(p3 + Pi.z + 1.0);\r\n","\r\n","    vec3 ox11 = fract(p11*K) - Ko;\r\n","    vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;\r\n","    vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed\r\n","\r\n","    vec3 ox12 = fract(p12*K) - Ko;\r\n","    vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;\r\n","    vec3 oz12 = floor(p12*K2)*Kz - Kzo;\r\n","\r\n","    vec3 ox13 = fract(p13*K) - Ko;\r\n","    vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;\r\n","    vec3 oz13 = floor(p13*K2)*Kz - Kzo;\r\n","\r\n","    vec3 ox21 = fract(p21*K) - Ko;\r\n","    vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;\r\n","    vec3 oz21 = floor(p21*K2)*Kz - Kzo;\r\n","\r\n","    vec3 ox22 = fract(p22*K) - Ko;\r\n","    vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;\r\n","    vec3 oz22 = floor(p22*K2)*Kz - Kzo;\r\n","\r\n","    vec3 ox23 = fract(p23*K) - Ko;\r\n","    vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;\r\n","    vec3 oz23 = floor(p23*K2)*Kz - Kzo;\r\n","\r\n","    vec3 ox31 = fract(p31*K) - Ko;\r\n","    vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;\r\n","    vec3 oz31 = floor(p31*K2)*Kz - Kzo;\r\n","\r\n","    vec3 ox32 = fract(p32*K) - Ko;\r\n","    vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;\r\n","    vec3 oz32 = floor(p32*K2)*Kz - Kzo;\r\n","\r\n","    vec3 ox33 = fract(p33*K) - Ko;\r\n","    vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;\r\n","    vec3 oz33 = floor(p33*K2)*Kz - Kzo;\r\n","\r\n","    vec3 dx11 = Pfx + jitter*ox11;\r\n","    vec3 dy11 = Pfy.x + jitter*oy11;\r\n","    vec3 dz11 = Pfz.x + jitter*oz11;\r\n","\r\n","    vec3 dx12 = Pfx + jitter*ox12;\r\n","    vec3 dy12 = Pfy.x + jitter*oy12;\r\n","    vec3 dz12 = Pfz.y + jitter*oz12;\r\n","\r\n","    vec3 dx13 = Pfx + jitter*ox13;\r\n","    vec3 dy13 = Pfy.x + jitter*oy13;\r\n","    vec3 dz13 = Pfz.z + jitter*oz13;\r\n","\r\n","    vec3 dx21 = Pfx + jitter*ox21;\r\n","    vec3 dy21 = Pfy.y + jitter*oy21;\r\n","    vec3 dz21 = Pfz.x + jitter*oz21;\r\n","\r\n","    vec3 dx22 = Pfx + jitter*ox22;\r\n","    vec3 dy22 = Pfy.y + jitter*oy22;\r\n","    vec3 dz22 = Pfz.y + jitter*oz22;\r\n","\r\n","    vec3 dx23 = Pfx + jitter*ox23;\r\n","    vec3 dy23 = Pfy.y + jitter*oy23;\r\n","    vec3 dz23 = Pfz.z + jitter*oz23;\r\n","\r\n","    vec3 dx31 = Pfx + jitter*ox31;\r\n","    vec3 dy31 = Pfy.z + jitter*oy31;\r\n","    vec3 dz31 = Pfz.x + jitter*oz31;\r\n","\r\n","    vec3 dx32 = Pfx + jitter*ox32;\r\n","    vec3 dy32 = Pfy.z + jitter*oy32;\r\n","    vec3 dz32 = Pfz.y + jitter*oz32;\r\n","\r\n","    vec3 dx33 = Pfx + jitter*ox33;\r\n","    vec3 dy33 = Pfy.z + jitter*oy33;\r\n","    vec3 dz33 = Pfz.z + jitter*oz33;\r\n","\r\n","    vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);\r\n","    vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance);\r\n","    vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);\r\n","    vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);\r\n","    vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);\r\n","    vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);\r\n","    vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);\r\n","    vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);\r\n","    vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);\r\n","\r\n","    vec3 d1a = min(d11, d12);\r\n","    d12 = max(d11, d12);\r\n","    d11 = min(d1a, d13); // Smallest now not in d12 or d13\r\n","    d13 = max(d1a, d13);\r\n","    d12 = min(d12, d13); // 2nd smallest now not in d13\r\n","    vec3 d2a = min(d21, d22);\r\n","    d22 = max(d21, d22);\r\n","    d21 = min(d2a, d23); // Smallest now not in d22 or d23\r\n","    d23 = max(d2a, d23);\r\n","    d22 = min(d22, d23); // 2nd smallest now not in d23\r\n","    vec3 d3a = min(d31, d32);\r\n","    d32 = max(d31, d32);\r\n","    d31 = min(d3a, d33); // Smallest now not in d32 or d33\r\n","    d33 = max(d3a, d33);\r\n","    d32 = min(d32, d33); // 2nd smallest now not in d33\r\n","    vec3 da = min(d11, d21);\r\n","    d21 = max(d11, d21);\r\n","    d11 = min(da, d31); // Smallest now in d11\r\n","    d31 = max(da, d31); // 2nd smallest now not in d31\r\n","    d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;\r\n","    d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest\r\n","    d12 = min(d12, d21); // 2nd smallest now not in d21\r\n","    d12 = min(d12, d22); // nor in d22\r\n","    d12 = min(d12, d31); // nor in d31\r\n","    d12 = min(d12, d32); // nor in d32\r\n","    d11.yz = min(d11.yz,d12.xy); // nor in d12.yz\r\n","    d11.y = min(d11.y,d12.z); // Only two more to go\r\n","    d11.y = min(d11.y,d11.z); // Done! (Phew!)\r\n","    return sqrt(d11.xy); // F1, F2\r\n","}\r\n\r\n",t._emitFunction("worley3D","vec3 permute(vec3 x){\r\n    return mod((34.0 * x + 1.0) * x, 289.0);\r\n}\r\n\r\nvec3 dist(vec3 x, vec3 y, vec3 z,  bool manhattanDistance){\r\n    return manhattanDistance ?  abs(x) + abs(y) + abs(z) :  (x * x + y * y + z * z);\r\n}\r\n\r\nvec2 worley(vec3 P, float jitter, bool manhattanDistance){\r\n    float K = 0.142857142857; // 1/7\r\n    float Ko = 0.428571428571; // 1/2-K/2\r\n    float  K2 = 0.020408163265306; // 1/(7*7)\r\n    float Kz = 0.166666666667; // 1/6\r\n    float Kzo = 0.416666666667; // 1/2-1/6*2\r\n\r\n    vec3 Pi = mod(floor(P), 289.0);\r\n    vec3 Pf = fract(P) - 0.5;\r\n\r\n    vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);\r\n    vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);\r\n    vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);\r\n\r\n    vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));\r\n    vec3 p1 = permute(p + Pi.y - 1.0);\r\n    vec3 p2 = permute(p + Pi.y);\r\n    vec3 p3 = permute(p + Pi.y + 1.0);\r\n\r\n    vec3 p11 = permute(p1 + Pi.z - 1.0);\r\n    vec3 p12 = permute(p1 + Pi.z);\r\n    vec3 p13 = permute(p1 + Pi.z + 1.0);\r\n\r\n    vec3 p21 = permute(p2 + Pi.z - 1.0);\r\n    vec3 p22 = permute(p2 + Pi.z);\r\n    vec3 p23 = permute(p2 + Pi.z + 1.0);\r\n\r\n    vec3 p31 = permute(p3 + Pi.z - 1.0);\r\n    vec3 p32 = permute(p3 + Pi.z);\r\n    vec3 p33 = permute(p3 + Pi.z + 1.0);\r\n\r\n    vec3 ox11 = fract(p11*K) - Ko;\r\n    vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;\r\n    vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed\r\n\r\n    vec3 ox12 = fract(p12*K) - Ko;\r\n    vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;\r\n    vec3 oz12 = floor(p12*K2)*Kz - Kzo;\r\n\r\n    vec3 ox13 = fract(p13*K) - Ko;\r\n    vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;\r\n    vec3 oz13 = floor(p13*K2)*Kz - Kzo;\r\n\r\n    vec3 ox21 = fract(p21*K) - Ko;\r\n    vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;\r\n    vec3 oz21 = floor(p21*K2)*Kz - Kzo;\r\n\r\n    vec3 ox22 = fract(p22*K) - Ko;\r\n    vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;\r\n    vec3 oz22 = floor(p22*K2)*Kz - Kzo;\r\n\r\n    vec3 ox23 = fract(p23*K) - Ko;\r\n    vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;\r\n    vec3 oz23 = floor(p23*K2)*Kz - Kzo;\r\n\r\n    vec3 ox31 = fract(p31*K) - Ko;\r\n    vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;\r\n    vec3 oz31 = floor(p31*K2)*Kz - Kzo;\r\n\r\n    vec3 ox32 = fract(p32*K) - Ko;\r\n    vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;\r\n    vec3 oz32 = floor(p32*K2)*Kz - Kzo;\r\n\r\n    vec3 ox33 = fract(p33*K) - Ko;\r\n    vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;\r\n    vec3 oz33 = floor(p33*K2)*Kz - Kzo;\r\n\r\n    vec3 dx11 = Pfx + jitter*ox11;\r\n    vec3 dy11 = Pfy.x + jitter*oy11;\r\n    vec3 dz11 = Pfz.x + jitter*oz11;\r\n\r\n    vec3 dx12 = Pfx + jitter*ox12;\r\n    vec3 dy12 = Pfy.x + jitter*oy12;\r\n    vec3 dz12 = Pfz.y + jitter*oz12;\r\n\r\n    vec3 dx13 = Pfx + jitter*ox13;\r\n    vec3 dy13 = Pfy.x + jitter*oy13;\r\n    vec3 dz13 = Pfz.z + jitter*oz13;\r\n\r\n    vec3 dx21 = Pfx + jitter*ox21;\r\n    vec3 dy21 = Pfy.y + jitter*oy21;\r\n    vec3 dz21 = Pfz.x + jitter*oz21;\r\n\r\n    vec3 dx22 = Pfx + jitter*ox22;\r\n    vec3 dy22 = Pfy.y + jitter*oy22;\r\n    vec3 dz22 = Pfz.y + jitter*oz22;\r\n\r\n    vec3 dx23 = Pfx + jitter*ox23;\r\n    vec3 dy23 = Pfy.y + jitter*oy23;\r\n    vec3 dz23 = Pfz.z + jitter*oz23;\r\n\r\n    vec3 dx31 = Pfx + jitter*ox31;\r\n    vec3 dy31 = Pfy.z + jitter*oy31;\r\n    vec3 dz31 = Pfz.x + jitter*oz31;\r\n\r\n    vec3 dx32 = Pfx + jitter*ox32;\r\n    vec3 dy32 = Pfy.z + jitter*oy32;\r\n    vec3 dz32 = Pfz.y + jitter*oz32;\r\n\r\n    vec3 dx33 = Pfx + jitter*ox33;\r\n    vec3 dy33 = Pfy.z + jitter*oy33;\r\n    vec3 dz33 = Pfz.z + jitter*oz33;\r\n\r\n    vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);\r\n    vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance);\r\n    vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);\r\n    vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);\r\n    vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);\r\n    vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);\r\n    vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);\r\n    vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);\r\n    vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);\r\n\r\n    vec3 d1a = min(d11, d12);\r\n    d12 = max(d11, d12);\r\n    d11 = min(d1a, d13); // Smallest now not in d12 or d13\r\n    d13 = max(d1a, d13);\r\n    d12 = min(d12, d13); // 2nd smallest now not in d13\r\n    vec3 d2a = min(d21, d22);\r\n    d22 = max(d21, d22);\r\n    d21 = min(d2a, d23); // Smallest now not in d22 or d23\r\n    d23 = max(d2a, d23);\r\n    d22 = min(d22, d23); // 2nd smallest now not in d23\r\n    vec3 d3a = min(d31, d32);\r\n    d32 = max(d31, d32);\r\n    d31 = min(d3a, d33); // Smallest now not in d32 or d33\r\n    d33 = max(d3a, d33);\r\n    d32 = min(d32, d33); // 2nd smallest now not in d33\r\n    vec3 da = min(d11, d21);\r\n    d21 = max(d11, d21);\r\n    d11 = min(da, d31); // Smallest now in d11\r\n    d31 = max(da, d31); // 2nd smallest now not in d31\r\n    d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;\r\n    d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest\r\n    d12 = min(d12, d21); // 2nd smallest now not in d21\r\n    d12 = min(d12, d22); // nor in d22\r\n    d12 = min(d12, d31); // nor in d31\r\n    d12 = min(d12, d32); // nor in d32\r\n    d11.yz = min(d11.yz,d12.xy); // nor in d12.yz\r\n    d11.y = min(d11.y,d12.z); // Only two more to go\r\n    d11.y = min(d11.y,d11.z); // Done! (Phew!)\r\n    return sqrt(d11.xy); // F1, F2\r\n}\r\n\r\n","// Worley3D"),t.compilationString+=this._declareOutput(this._outputs[0],t)+" = worley("+this.seed.associatedVariableName+", "+this.jitter.associatedVariableName+", "+this.manhattanDistance+");\r\n",this}},t.prototype._dumpPropertiesCode=function(){return this._codeVariableName+".manhattanDistance = "+this.manhattanDistance+";\r\n"},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.manhattanDistance=this.manhattanDistance,t},t.prototype._deserialize=function(t,i,n){e.prototype._deserialize.call(this,t,i,n),this.manhattanDistance=t.manhattanDistance},t}(yc);c.a.RegisteredTypes["BABYLON.WorleyNoise3DBlock"]=Sl;var Cl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("seed",oc.Vector3),i.registerOutput("output",oc.Float),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"SimplexPerlin3DBlock"},Object.defineProperty(t.prototype,"seed",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),this.seed.isConnected&&this._outputs[0].hasEndpoints){return"const float UNSKEWFACTOR = 1.0/6.0;\r\n","const float SIMPLEX_CORNER_POS = 0.5;\r\n","const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485;\r\n","float SimplexPerlin3D( vec3 P ){\r\n","    P *= SIMPLEX_TETRAHADRON_HEIGHT;\r\n","    vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) );","    vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) );\r\n","    vec3 g = step(x0.yzx, x0.xyz);\r\n","    vec3 l = 1.0 - g;\r\n","    vec3 Pi_1 = min( g.xyz, l.zxy );\r\n","    vec3 Pi_2 = max( g.xyz, l.zxy );\r\n","    vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR;\r\n","    vec3 x2 = x0 - Pi_2 + SKEWFACTOR;\r\n","    vec3 x3 = x0 - SIMPLEX_CORNER_POS;\r\n","    vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x );\r\n","    vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y );\r\n","    vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z );\r\n","    Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;\r\n","    vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 );\r\n","    vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy;\r\n","    Pt *= Pt;\r\n","    vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) );\r\n","    Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w );\r\n","    const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );\r\n","    const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );\r\n","    vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) );\r\n","    vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) );\r\n","    Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods;\r\n","    Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods;\r\n","    vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999;\r\n","    vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999;\r\n","    vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999;\r\n","    vec4 grad_results = inversesqrt( hash_0 * hash_0 + hash_1 * hash_1 + hash_2 * hash_2 ) * ( hash_0 * v1234_x + hash_1 * v1234_y + hash_2 * v1234_z );\r\n","    const float FINAL_NORMALIZATION = 37.837227241611314102871574478976;\r\n","    vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z;\r\n","    kernel_weights = max(0.5 - kernel_weights, 0.0);\r\n","    kernel_weights = kernel_weights*kernel_weights*kernel_weights;\r\n","    return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION;\r\n","}\r\n",t._emitFunction("SimplexPerlin3D","const float SKEWFACTOR = 1.0/3.0;\r\nconst float UNSKEWFACTOR = 1.0/6.0;\r\nconst float SIMPLEX_CORNER_POS = 0.5;\r\nconst float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485;\r\nfloat SimplexPerlin3D( vec3 P ){\r\n    P *= SIMPLEX_TETRAHADRON_HEIGHT;\r\n    vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) );    vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) );\r\n    vec3 g = step(x0.yzx, x0.xyz);\r\n    vec3 l = 1.0 - g;\r\n    vec3 Pi_1 = min( g.xyz, l.zxy );\r\n    vec3 Pi_2 = max( g.xyz, l.zxy );\r\n    vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR;\r\n    vec3 x2 = x0 - Pi_2 + SKEWFACTOR;\r\n    vec3 x3 = x0 - SIMPLEX_CORNER_POS;\r\n    vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x );\r\n    vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y );\r\n    vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z );\r\n    Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;\r\n    vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 );\r\n    vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy;\r\n    Pt *= Pt;\r\n    vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) );\r\n    Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w );\r\n    const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );\r\n    const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );\r\n    vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) );\r\n    vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) );\r\n    Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods;\r\n    Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods;\r\n    vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999;\r\n    vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999;\r\n    vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999;\r\n    vec4 grad_results = inversesqrt( hash_0 * hash_0 + hash_1 * hash_1 + hash_2 * hash_2 ) * ( hash_0 * v1234_x + hash_1 * v1234_y + hash_2 * v1234_z );\r\n    const float FINAL_NORMALIZATION = 37.837227241611314102871574478976;\r\n    vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z;\r\n    kernel_weights = max(0.5 - kernel_weights, 0.0);\r\n    kernel_weights = kernel_weights*kernel_weights*kernel_weights;\r\n    return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION;\r\n}\r\n","// SimplexPerlin3D"),t.compilationString+=this._declareOutput(this._outputs[0],t)+" = SimplexPerlin3D("+this.seed.associatedVariableName+");\r\n",this}},t}(yc);c.a.RegisteredTypes["BABYLON.SimplexPerlin3DBlock"]=Cl;var Rl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("normalMap0",oc.Vector3),i.registerInput("normalMap1",oc.Vector3),i.registerOutput("output",oc.Vector3),i._inputs[0].acceptedConnectionPointTypes.push(oc.Color3),i._inputs[0].acceptedConnectionPointTypes.push(oc.Color4),i._inputs[0].acceptedConnectionPointTypes.push(oc.Vector4),i._inputs[1].acceptedConnectionPointTypes.push(oc.Color3),i._inputs[1].acceptedConnectionPointTypes.push(oc.Color4),i._inputs[1].acceptedConnectionPointTypes.push(oc.Vector4),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"NormalBlendBlock"},Object.defineProperty(t.prototype,"normalMap0",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"normalMap1",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],n=this._inputs[0],r=this._inputs[1],o=t._getFreeVariableName("stepR"),a=t._getFreeVariableName("stepG");return t.compilationString+="float "+o+" = step(0.5, "+n.associatedVariableName+".r);\r\n",t.compilationString+="float "+a+" = step(0.5, "+n.associatedVariableName+".g);\r\n",t.compilationString+=this._declareOutput(i,t)+";\r\n",t.compilationString+=i.associatedVariableName+".r = (1.0 - "+o+") * "+n.associatedVariableName+".r * "+r.associatedVariableName+".r * 2.0 + "+o+" * (1.0 - "+n.associatedVariableName+".r) * (1.0 - "+r.associatedVariableName+".r) * 2.0;\r\n",t.compilationString+=i.associatedVariableName+".g = (1.0 - "+a+") * "+n.associatedVariableName+".g * "+r.associatedVariableName+".g * 2.0 + "+a+" * (1.0 - "+n.associatedVariableName+".g) * (1.0 - "+r.associatedVariableName+".g) * 2.0;\r\n",t.compilationString+=i.associatedVariableName+".b = "+n.associatedVariableName+".b * "+r.associatedVariableName+".b;\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.NormalBlendBlock"]=Rl;var Ol=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("input",oc.Vector2),i.registerInput("angle",oc.Float),i.registerOutput("output",oc.Vector2),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"Rotate2dBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"angle",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype.autoConfigure=function(e){if(!this.angle.isConnected){var t=new Sc("angle");t.value=0,t.output.connectTo(this.angle)}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],n=this.angle,r=this.input;return t.compilationString+=this._declareOutput(i,t)+" = vec2(cos("+n.associatedVariableName+") * "+r.associatedVariableName+".x - sin("+n.associatedVariableName+") * "+r.associatedVariableName+".y, sin("+n.associatedVariableName+") * "+r.associatedVariableName+".x + cos("+n.associatedVariableName+") * "+r.associatedVariableName+".y);\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.Rotate2dBlock"]=Ol;var Ml=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("incident",oc.Vector3),i.registerInput("normal",oc.Vector3),i.registerOutput("output",oc.Vector3),i._inputs[0].acceptedConnectionPointTypes.push(oc.Vector4),i._inputs[0].acceptedConnectionPointTypes.push(oc.Color3),i._inputs[0].acceptedConnectionPointTypes.push(oc.Color4),i._inputs[1].acceptedConnectionPointTypes.push(oc.Vector4),i._inputs[1].acceptedConnectionPointTypes.push(oc.Color3),i._inputs[1].acceptedConnectionPointTypes.push(oc.Color4),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"ReflectBlock"},Object.defineProperty(t.prototype,"incident",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"normal",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = reflect("+this.incident.associatedVariableName+".xyz, "+this.normal.associatedVariableName+".xyz);\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.ReflectBlock"]=Ml;var Il=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("incident",oc.Vector3),i.registerInput("normal",oc.Vector3),i.registerInput("ior",oc.Float),i.registerOutput("output",oc.Vector3),i._inputs[0].acceptedConnectionPointTypes.push(oc.Vector4),i._inputs[0].acceptedConnectionPointTypes.push(oc.Color3),i._inputs[0].acceptedConnectionPointTypes.push(oc.Color4),i._inputs[1].acceptedConnectionPointTypes.push(oc.Vector4),i._inputs[1].acceptedConnectionPointTypes.push(oc.Color3),i._inputs[1].acceptedConnectionPointTypes.push(oc.Color4),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"RefractBlock"},Object.defineProperty(t.prototype,"incident",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"normal",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ior",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = refract("+this.incident.associatedVariableName+".xyz, "+this.normal.associatedVariableName+".xyz, "+this.ior.associatedVariableName+");\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.RefractBlock"]=Il;var Dl=function(e){function t(t){var i=e.call(this,t,rc.Neutral)||this;return i.registerInput("color",oc.Color3),i.registerInput("level",oc.Float),i.registerOutput("output",oc.Color3),i}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"DesaturateBlock"},Object.defineProperty(t.prototype,"color",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"level",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],n=this.color.associatedVariableName,r=t._getFreeVariableName("colorMin"),o=t._getFreeVariableName("colorMax"),a=t._getFreeVariableName("colorMerge");return t.compilationString+="float "+r+" = min(min("+n+".x, "+n+".y), "+n+".z);\r\n",t.compilationString+="float "+o+" = max(max("+n+".x, "+n+".y), "+n+".z);\r\n",t.compilationString+="float "+a+" = 0.5 * ("+r+" + "+o+");\r\n",t.compilationString+=this._declareOutput(i,t)+" = mix("+n+", vec3("+a+", "+a+", "+a+"), "+this.level.associatedVariableName+");\r\n",this},t}(yc);c.a.RegisteredTypes["BABYLON.DesaturateBlock"]=Dl;var wl=function(){function e(){}return e.prototype.optimize=function(e,t){},e}(),Ll=function(){function e(t,i){var n;void 0===i&&(i=e._DefaultOptions),this.engine=t,this._ringBufferIndex=0,this._ringScreenBuffer=null,this._fullscreenViewport=new ki.a(0,0,1,1),i=Object(h.a)(Object(h.a)({},e._DefaultOptions),i),this._vertexBuffers=((n={})[en.b.PositionKind]=new en.b(t,i.positions,en.b.PositionKind,!1,!1,2),n),this._indexBuffer=t.createIndexBuffer(i.indices),t.depthCullingState.depthTest=!1,t.stencilState.stencilTest=!1}return e.prototype._getNextFrameBuffer=function(e){if(void 0===e&&(e=!0),!this._ringScreenBuffer){this._ringScreenBuffer=[];for(var t=0;t<2;t++){var i=this.engine.createRenderTargetTexture({width:this.engine.getRenderWidth(!0),height:this.engine.getRenderHeight(!0)},{generateDepthBuffer:!1,generateStencilBuffer:!1,generateMipMaps:!1,samplingMode:g.a.TEXTURE_NEAREST_NEAREST}),n=new et.a("",null);n._texture=i,this._ringScreenBuffer.push(n)}}var r=this._ringScreenBuffer[this._ringBufferIndex];return e&&(this._ringBufferIndex=(this._ringBufferIndex+1)%2),r},e.prototype.setViewport=function(e){void 0===e&&(e=this._fullscreenViewport),this.engine.setViewport(e)},e.prototype.bindBuffers=function(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)},e.prototype.applyEffectWrapper=function(e){this.engine.enableEffect(e.effect),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})},e.prototype.draw=function(){this.engine.drawElementsType(g.a.MATERIAL_TriangleFillMode,0,6)},e.prototype.render=function(e,t){var i=this;void 0===t&&(t=null),Array.isArray(e)||(e=[e]);for(var n=0,r=e;n<r.length;n++){if(!r[n].effect.isReady())return}e.forEach(function(n,r){var o=t;0!==r&&n.effect.onBindObservable.addOnce(function(){n.effect.setTexture("textureSampler",i._getNextFrameBuffer(!1))}),o=e.length>1&&r!=e.length-1?i._getNextFrameBuffer():t,i.setViewport(),i.applyEffectWrapper(n),o&&i.engine.bindFramebuffer(o.getInternalTexture()),i.draw(),o&&i.engine.unBindFramebuffer(o.getInternalTexture())})},e.prototype.dispose=function(){this._ringScreenBuffer&&(this._ringScreenBuffer.forEach(function(e){e.dispose()}),this._ringScreenBuffer=null);var e=this._vertexBuffers[en.b.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[en.b.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer)},e._DefaultOptions={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]},e}(),Nl=function(){function e(e){var t,i=this;this.onApplyObservable=new o.c;var n=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(n.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add(function(){i.effect.setFloat2("scale",1,1)})),this.effect=new ai.a(t,e.attributeNames||["position"],n,e.samplerNames,e.engine)}return e.prototype.dispose=function(){this.effect.dispose()},e}(),Fl=function(){function e(e){this._pendingActions=new Array,this._workerInfos=e.map(function(e){return{worker:e,active:!1}})}return e.prototype.dispose=function(){for(var e=0,t=this._workerInfos;e<t.length;e++){t[e].worker.terminate()}delete this._workerInfos,delete this._pendingActions},e.prototype.push=function(e){for(var t=0,i=this._workerInfos;t<i.length;t++){var n=i[t];if(!n.active)return void this._execute(n,e)}this._pendingActions.push(e)},e.prototype._execute=function(e,t){var i=this;e.active=!0,t(e.worker,function(){e.active=!1;var t=i._pendingActions.shift();t&&i._execute(e,t)})},e}();function Bl(e){return new Promise(function(t){DracoDecoderModule({wasmBinary:e}).then(function(e){t({module:e})})})}function Ul(e,t,i,n,r){var o=new e.DecoderBuffer;o.Init(t,t.byteLength);var a,s,c=new e.Decoder;try{var l=c.GetEncodedGeometryType(o);switch(l){case e.TRIANGULAR_MESH:a=new e.Mesh,s=c.DecodeBufferToMesh(o,a);break;case e.POINT_CLOUD:a=new e.PointCloud,s=c.DecodeBufferToPointCloud(o,a);break;default:throw new Error("Invalid geometry type "+l)}if(!s.ok()||!a.ptr)throw new Error(s.error_msg());var u=a.num_points();if(l===e.TRIANGULAR_MESH){var h=a.num_faces(),d=new e.DracoInt32Array;try{for(var f=new Uint32Array(3*h),p=0;p<h;p++){c.GetFaceFromMesh(a,p,d);var _=3*p;f[_+0]=d.GetValue(0),f[_+1]=d.GetValue(1),f[_+2]=d.GetValue(2)}n(f)}finally{e.destroy(d)}}var m=function(t,i){var n=new e.DracoFloat32Array;try{c.GetAttributeFloatForAllPoints(a,i,n);var o=i.num_components();if("color"===t&&3===o){for(var s=new Float32Array(4*u),l=0,h=0;l<s.length;l+=4,h+=o)s[l+0]=n.GetValue(h+0),s[l+1]=n.GetValue(h+1),s[l+2]=n.GetValue(h+2),s[l+3]=1;r(t,s)}else{for(s=new Float32Array(u*o),l=0;l<s.length;l++)s[l]=n.GetValue(l);r(t,s)}}finally{e.destroy(n)}};if(i)for(var g in i){var v=i[g];m(g,c.GetAttributeByUniqueId(a,v))}else{var y={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"};for(var g in y){if(-1!==(v=c.GetAttributeId(a,e[y[g]])))m(g,c.GetAttribute(a,v))}}}finally{a&&e.destroy(a),e.destroy(c),e.destroy(o)}}function Vl(e){return"object"!=typeof document||"string"!=typeof e?e:De.b.GetAbsoluteUrl(e)}var kl=function(){function e(t){void 0===t&&(t=e.DefaultNumWorkers);var i=e.Configuration.decoder,n=i.wasmUrl&&i.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:i.wasmUrl,wasmBinaryPromise:De.b.LoadFileAsync(Vl(i.wasmBinaryUrl))}:{url:i.fallbackUrl,wasmBinaryPromise:Promise.resolve(void 0)};t&&"function"==typeof Worker?this._workerPoolPromise=n.wasmBinaryPromise.then(function(e){for(var i=""+Bl+Ul+"("+function(){var e;onmessage=function(t){var i=t.data;switch(i.id){case"init":var n=i.decoder;n.url&&(importScripts(n.url),e=Bl(n.wasmBinary)),postMessage("done");break;case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then(function(e){Ul(e.module,i.dataView,i.attributes,function(e){postMessage({id:"indices",value:e},[e.buffer])},function(e,t){postMessage({id:e,value:t},[t.buffer])}),postMessage("done")})}}}+")()",r=URL.createObjectURL(new Blob([i],{type:"application/javascript"})),o=new Array(t),a=0;a<o.length;a++)o[a]=new Promise(function(t,i){var o=new Worker(r),a=function(e){o.removeEventListener("error",a),o.removeEventListener("message",s),i(e)},s=function(e){"done"===e.data&&(o.removeEventListener("error",a),o.removeEventListener("message",s),t(o))};o.addEventListener("error",a),o.addEventListener("message",s),o.postMessage({id:"init",decoder:{url:Vl(n.url),wasmBinary:e}})});return Promise.all(o).then(function(e){return new Fl(e)})}):this._decoderModulePromise=n.wasmBinaryPromise.then(function(e){if(!n.url)throw new Error("Draco decoder module is not available");return De.b.LoadScriptAsync(n.url).then(function(){return Bl(e)})})}return Object.defineProperty(e,"DecoderAvailable",{get:function(){var t=e.Configuration.decoder;return!!(t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly||t.fallbackUrl)},enumerable:!0,configurable:!0}),e.GetDefaultNumWorkers=function(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1},Object.defineProperty(e,"Default",{get:function(){return e._Default||(e._Default=new e),e._Default},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this._workerPoolPromise&&this._workerPoolPromise.then(function(e){e.dispose()}),delete this._workerPoolPromise,delete this._decoderModulePromise},e.prototype.whenReadyAsync=function(){return this._workerPoolPromise?this._workerPoolPromise.then(function(){}):this._decoderModulePromise?this._decoderModulePromise.then(function(){}):Promise.resolve()},e.prototype.decodeMeshAsync=function(e,t){var i=e instanceof ArrayBuffer?new Uint8Array(e):e;if(this._workerPoolPromise)return this._workerPoolPromise.then(function(e){return new Promise(function(n,r){e.push(function(e,o){var a=new $i.a,s=function(t){e.removeEventListener("error",s),e.removeEventListener("message",c),r(t),o()},c=function(t){"done"===t.data?(e.removeEventListener("error",s),e.removeEventListener("message",c),n(a),o()):"indices"===t.data.id?a.indices=t.data.value:a.set(t.data.value,t.data.id)};e.addEventListener("error",s),e.addEventListener("message",c);var l=new Uint8Array(i.byteLength);l.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),e.postMessage({id:"decodeMesh",dataView:l,attributes:t},[l.buffer])})})});if(this._decoderModulePromise)return this._decoderModulePromise.then(function(e){var n=new $i.a;return Ul(e.module,i,t,function(e){n.indices=e},function(e,t){n.set(t,e)}),n});throw new Error("Draco decoder module is not available")},e.Configuration={decoder:{wasmUrl:"https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://preview.babylonjs.com/draco_decoder_gltf.wasm",fallbackUrl:"https://preview.babylonjs.com/draco_decoder_gltf.js"}},e.DefaultNumWorkers=e.GetDefaultNumWorkers(),e._Default=null,e}(),zl=i(57),Gl=0,jl=function(){function e(e,t,i){this.pos=e,this.normal=t,this.uv=i}return e.prototype.clone=function(){return new e(this.pos.clone(),this.normal.clone(),this.uv.clone())},e.prototype.flip=function(){this.normal=this.normal.scale(-1)},e.prototype.interpolate=function(t,i){return new e(a.e.Lerp(this.pos,t.pos,i),a.e.Lerp(this.normal,t.normal,i),a.d.Lerp(this.uv,t.uv,i))},e}(),Wl=function(){function e(e,t){this.normal=e,this.w=t}return e.FromPoints=function(t,i,n){var r=n.subtract(t),o=i.subtract(t);if(0===r.lengthSquared()||0===o.lengthSquared())return null;var s=a.e.Normalize(a.e.Cross(r,o));return new e(s,a.e.Dot(s,t))},e.prototype.clone=function(){return new e(this.normal.clone(),this.w)},e.prototype.flip=function(){this.normal.scaleInPlace(-1),this.w=-this.w},e.prototype.splitPolygon=function(t,i,n,r,o){var s,c,l=0,u=[];for(s=0;s<t.vertices.length;s++){var h=(c=a.e.Dot(this.normal,t.vertices[s].pos)-this.w)<-e.EPSILON?2:c>e.EPSILON?1:0;l|=h,u.push(h)}switch(l){case 0:(a.e.Dot(this.normal,t.plane.normal)>0?i:n).push(t);break;case 1:r.push(t);break;case 2:o.push(t);break;case 3:var d,f=[],p=[];for(s=0;s<t.vertices.length;s++){var _=(s+1)%t.vertices.length,m=u[s],g=u[_],v=t.vertices[s],y=t.vertices[_];if(2!==m&&f.push(v),1!==m&&p.push(2!==m?v.clone():v),3==(m|g)){c=(this.w-a.e.Dot(this.normal,v.pos))/a.e.Dot(this.normal,y.pos.subtract(v.pos));var b=v.interpolate(y,c);f.push(b),p.push(b.clone())}}f.length>=3&&(d=new Xl(f,t.shared)).plane&&r.push(d),p.length>=3&&(d=new Xl(p,t.shared)).plane&&o.push(d)}},e.EPSILON=1e-5,e}(),Xl=function(){function e(e,t){this.vertices=e,this.shared=t,this.plane=Wl.FromPoints(e[0].pos,e[1].pos,e[2].pos)}return e.prototype.clone=function(){return new e(this.vertices.map(function(e){return e.clone()}),this.shared)},e.prototype.flip=function(){this.vertices.reverse().map(function(e){e.flip()}),this.plane.flip()},e}(),Hl=function(){function e(e){this.plane=null,this.front=null,this.back=null,this.polygons=new Array,e&&this.build(e)}return e.prototype.clone=function(){var t=new e;return t.plane=this.plane&&this.plane.clone(),t.front=this.front&&this.front.clone(),t.back=this.back&&this.back.clone(),t.polygons=this.polygons.map(function(e){return e.clone()}),t},e.prototype.invert=function(){for(var e=0;e<this.polygons.length;e++)this.polygons[e].flip();this.plane&&this.plane.flip(),this.front&&this.front.invert(),this.back&&this.back.invert();var t=this.front;this.front=this.back,this.back=t},e.prototype.clipPolygons=function(e){if(!this.plane)return e.slice();for(var t=new Array,i=new Array,n=0;n<e.length;n++)this.plane.splitPolygon(e[n],t,i,t,i);return this.front&&(t=this.front.clipPolygons(t)),i=this.back?this.back.clipPolygons(i):[],t.concat(i)},e.prototype.clipTo=function(e){this.polygons=e.clipPolygons(this.polygons),this.front&&this.front.clipTo(e),this.back&&this.back.clipTo(e)},e.prototype.allPolygons=function(){var e=this.polygons.slice();return this.front&&(e=e.concat(this.front.allPolygons())),this.back&&(e=e.concat(this.back.allPolygons())),e},e.prototype.build=function(t){if(t.length){this.plane||(this.plane=t[0].plane.clone());for(var i=new Array,n=new Array,r=0;r<t.length;r++)this.plane.splitPolygon(t[r],this.polygons,this.polygons,i,n);i.length&&(this.front||(this.front=new e),this.front.build(i)),n.length&&(this.back||(this.back=new e),this.back.build(n))}},e}(),Yl=function(){function e(){this.polygons=new Array}return e.FromMesh=function(t){var i,n,r,o,s,c,l,u,h,d,f=new Array,p=null;if(!(t instanceof Ae.a))throw"BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh";t.computeWorldMatrix(!0),l=t.getWorldMatrix(),u=t.position.clone(),h=t.rotation.clone(),t.rotationQuaternion&&(p=t.rotationQuaternion.clone()),d=t.scaling.clone();for(var _=t.getIndices(),m=t.getVerticesData(en.b.PositionKind),g=t.getVerticesData(en.b.NormalKind),v=t.getVerticesData(en.b.UVKind),y=t.subMeshes,b=0,T=y.length;b<T;b++)for(var E=y[b].indexStart,x=y[b].indexCount+y[b].indexStart;E<x;E+=3){c=[];for(var P=0;P<3;P++){var A=new a.e(g[3*_[E+P]],g[3*_[E+P]+1],g[3*_[E+P]+2]);r=new a.d(v[2*_[E+P]],v[2*_[E+P]+1]);var S=new a.e(m[3*_[E+P]],m[3*_[E+P]+1],m[3*_[E+P]+2]);o=a.e.TransformCoordinates(S,l),n=a.e.TransformNormal(A,l),i=new jl(o,n,r),c.push(i)}(s=new Xl(c,{subMeshId:b,meshId:Gl,materialIndex:y[b].materialIndex})).plane&&f.push(s)}var C=e.FromPolygons(f);return C.matrix=l,C.position=u,C.rotation=h,C.scaling=d,C.rotationQuaternion=p,Gl++,C},e.FromPolygons=function(t){var i=new e;return i.polygons=t,i},e.prototype.clone=function(){var t=new e;return t.polygons=this.polygons.map(function(e){return e.clone()}),t.copyTransformAttributes(this),t},e.prototype.union=function(t){var i=new Hl(this.clone().polygons),n=new Hl(t.clone().polygons);return i.clipTo(n),n.clipTo(i),n.invert(),n.clipTo(i),n.invert(),i.build(n.allPolygons()),e.FromPolygons(i.allPolygons()).copyTransformAttributes(this)},e.prototype.unionInPlace=function(e){var t=new Hl(this.polygons),i=new Hl(e.polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this.polygons=t.allPolygons()},e.prototype.subtract=function(t){var i=new Hl(this.clone().polygons),n=new Hl(t.clone().polygons);return i.invert(),i.clipTo(n),n.clipTo(i),n.invert(),n.clipTo(i),n.invert(),i.build(n.allPolygons()),i.invert(),e.FromPolygons(i.allPolygons()).copyTransformAttributes(this)},e.prototype.subtractInPlace=function(e){var t=new Hl(this.polygons),i=new Hl(e.polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this.polygons=t.allPolygons()},e.prototype.intersect=function(t){var i=new Hl(this.clone().polygons),n=new Hl(t.clone().polygons);return i.invert(),n.clipTo(i),n.invert(),i.clipTo(n),n.clipTo(i),i.build(n.allPolygons()),i.invert(),e.FromPolygons(i.allPolygons()).copyTransformAttributes(this)},e.prototype.intersectInPlace=function(e){var t=new Hl(this.polygons),i=new Hl(e.polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this.polygons=t.allPolygons()},e.prototype.inverse=function(){var e=this.clone();return e.inverseInPlace(),e},e.prototype.inverseInPlace=function(){this.polygons.map(function(e){e.flip()})},e.prototype.copyTransformAttributes=function(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this},e.prototype.buildMeshGeometry=function(e,t,i){var n=this.matrix.clone();n.invert();var r,o,s,c=new Ae.a(e,t),l=[],u=[],h=[],d=[],f=a.e.Zero(),p=a.e.Zero(),_=a.d.Zero(),m=this.polygons,g=[0,0,0],v={},y=0,b={};i&&m.sort(function(e,t){return e.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId});for(var T=0,E=m.length;T<E;T++){b[(r=m[T]).shared.meshId]||(b[r.shared.meshId]={}),b[r.shared.meshId][r.shared.subMeshId]||(b[r.shared.meshId][r.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:r.shared.materialIndex}),s=b[r.shared.meshId][r.shared.subMeshId];for(var x=2,P=r.vertices.length;x<P;x++){g[0]=0,g[1]=x-1,g[2]=x;for(var A=0;A<3;A++){f.copyFrom(r.vertices[g[A]].pos),p.copyFrom(r.vertices[g[A]].normal),_.copyFrom(r.vertices[g[A]].uv);var S=a.e.TransformCoordinates(f,n),C=a.e.TransformNormal(p,n);void 0!==(o=v[S.x+","+S.y+","+S.z])&&h[3*o]===C.x&&h[3*o+1]===C.y&&h[3*o+2]===C.z&&d[2*o]===_.x&&d[2*o+1]===_.y||(l.push(S.x,S.y,S.z),d.push(_.x,_.y),h.push(p.x,p.y,p.z),o=v[S.x+","+S.y+","+S.z]=l.length/3-1),u.push(o),s.indexStart=Math.min(y,s.indexStart),s.indexEnd=Math.max(y,s.indexEnd),y++}}}if(c.setVerticesData(en.b.PositionKind,l),c.setVerticesData(en.b.NormalKind,h),c.setVerticesData(en.b.UVKind,d),c.setIndices(u,null),i){var R,O=0;for(var M in c.subMeshes=new Array,b){for(var I in R=-1,b[M])s=b[M][I],zl.b.CreateFromIndices(s.materialIndex+O,s.indexStart,s.indexEnd-s.indexStart+1,c),R=Math.max(s.materialIndex,R);O+=++R}}return c},e.prototype.toMesh=function(e,t,i,n){void 0===t&&(t=null);var r=this.buildMeshGeometry(e,i,n);return r.material=t,r.position.copyFrom(this.position),r.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(r.rotationQuaternion=this.rotationQuaternion.clone()),r.scaling.copyFrom(this.scaling),r.computeWorldMatrix(!0),r},e}(),Kl=function(e){function t(t,i,n,r,o,s){void 0===r&&(r=1),void 0===o&&(o=60),void 0===s&&(s=!0);var c=e.call(this,t,n)||this;c._sectionPolygonPointsCount=4,c._running=!1,c._autoStart=s,c._generator=i,c._diameter=r,c._length=o,c._sectionVectors=[],c._sectionNormalVectors=[];for(var l=0;l<c._sectionPolygonPointsCount;l++)c._sectionVectors[l]=a.e.Zero(),c._sectionNormalVectors[l]=a.e.Zero();return c._createMesh(),c}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"TrailMesh"},t.prototype._createMesh=function(){var e=new $i.a,t=[],i=[],n=[],r=a.e.Zero();r=this._generator instanceof Ke.a&&this._generator._boundingInfo?this._generator._boundingInfo.boundingBox.centerWorld:this._generator.position;for(var o=2*Math.PI/this._sectionPolygonPointsCount,s=0;s<this._sectionPolygonPointsCount;s++)t.push(r.x+Math.cos(s*o)*this._diameter,r.y+Math.sin(s*o)*this._diameter,r.z);for(s=1;s<=this._length;s++){for(var c=0;c<this._sectionPolygonPointsCount;c++)t.push(r.x+Math.cos(c*o)*this._diameter,r.y+Math.sin(c*o)*this._diameter,r.z);var l=t.length/3-2*this._sectionPolygonPointsCount;for(c=0;c<this._sectionPolygonPointsCount-1;c++)n.push(l+c,l+c+this._sectionPolygonPointsCount,l+c+this._sectionPolygonPointsCount+1),n.push(l+c,l+c+this._sectionPolygonPointsCount+1,l+c+1);n.push(l+this._sectionPolygonPointsCount-1,l+this._sectionPolygonPointsCount-1+this._sectionPolygonPointsCount,l+this._sectionPolygonPointsCount),n.push(l+this._sectionPolygonPointsCount-1,l+this._sectionPolygonPointsCount,l)}$i.a.ComputeNormals(t,n,i),e.positions=t,e.normals=i,e.indices=n,e.applyToMesh(this,!0),this._autoStart&&this.start()},t.prototype.start=function(){var e=this;this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add(function(){e.update()}))},t.prototype.stop=function(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))},t.prototype.update=function(){var e=this.getVerticesData(en.b.PositionKind),t=this.getVerticesData(en.b.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(var n=3*this._sectionPolygonPointsCount;n<e.length;n++)e[n-3*this._sectionPolygonPointsCount]=e[n]-t[n]/this._length*this._diameter;for(n=3*this._sectionPolygonPointsCount;n<t.length;n++)t[n-3*this._sectionPolygonPointsCount]=t[n];var r=e.length-3*this._sectionPolygonPointsCount,o=2*Math.PI/this._sectionPolygonPointsCount;for(n=0;n<this._sectionPolygonPointsCount;n++)this._sectionVectors[n].copyFromFloats(Math.cos(n*o)*this._diameter,Math.sin(n*o)*this._diameter,0),this._sectionNormalVectors[n].copyFromFloats(Math.cos(n*o),Math.sin(n*o),0),a.e.TransformCoordinatesToRef(this._sectionVectors[n],i,this._sectionVectors[n]),a.e.TransformNormalToRef(this._sectionNormalVectors[n],i,this._sectionNormalVectors[n]);for(n=0;n<this._sectionPolygonPointsCount;n++)e[r+3*n]=this._sectionVectors[n].x,e[r+3*n+1]=this._sectionVectors[n].y,e[r+3*n+2]=this._sectionVectors[n].z,t[r+3*n]=this._sectionNormalVectors[n].x,t[r+3*n+1]=this._sectionNormalVectors[n].y,t[r+3*n+2]=this._sectionNormalVectors[n].z;this.updateVerticesData(en.b.PositionKind,e,!0,!1),this.updateVerticesData(en.b.NormalKind,t,!0,!1)}},t.prototype.clone=function(e,i){return void 0===e&&(e=""),new t(e,void 0===i?this._generator:i,this.getScene(),this._diameter,this._length,this._autoStart)},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t)},t.Parse=function(e,i){return new t(e.name,e._generator,i,e._diameter,e._length,e._autoStart)},t}(Ae.a),Ql=i(136),ql=i(92);$i.a.CreateDisc=function(e){var t=new Array,i=new Array,n=new Array,r=new Array,o=e.radius||.5,a=e.tessellation||64,s=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,c=0===e.sideOrientation?0:e.sideOrientation||$i.a.DEFAULTSIDE;t.push(0,0,0),r.push(.5,.5);for(var l=2*Math.PI*s,u=l/a,h=0;h<l;h+=u){var d=Math.cos(h),f=Math.sin(h),p=(d+1)/2,_=(1-f)/2;t.push(o*d,o*f,0),r.push(p,_)}1===s&&(t.push(t[3],t[4],t[5]),r.push(r[2],r[3]));for(var m=t.length/3,g=1;g<m-1;g++)i.push(g+1,0,g);$i.a.ComputeNormals(t,i,n),$i.a._ComputeSides(c,t,i,n,r,e.frontUVs,e.backUVs);var v=new $i.a;return v.indices=i,v.positions=t,v.normals=n,v.uvs=r,v},Ae.a.CreateDisc=function(e,t,i,n,r,o){void 0===n&&(n=null);var a={radius:t,tessellation:i,sideOrientation:o,updatable:r};return Zl.CreateDisc(e,a,n)};var Zl=function(){function e(){}return e.CreateDisc=function(e,t,i){void 0===i&&(i=null);var n=new Ae.a(e,i);return t.sideOrientation=Ae.a._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,$i.a.CreateDisc(t).applyToMesh(n,t.updatable),n},e}();$i.a.CreateTiledBox=function(e){for(var t=e.faceUV||new Array(6),i=e.faceColors,n=e.pattern||Ae.a.NO_FLIP,r=e.width||e.size||1,o=e.height||e.size||1,c=e.depth||e.size||1,l=e.tileWidth||e.tileSize||1,u=e.tileHeight||e.tileSize||1,h=e.alignHorizontal||0,d=e.alignVertical||0,f=0===e.sideOrientation?0:e.sideOrientation||$i.a.DEFAULTSIDE,p=0;p<6;p++)void 0===t[p]&&(t[p]=new a.f(0,0,1,1)),i&&void 0===i[p]&&(i[p]=new s.b(1,1,1,1));var _=r/2,m=o/2,g=c/2,v=[];for(p=0;p<2;p++)v[p]=$i.a.CreateTiledPlane({pattern:n,tileWidth:l,tileHeight:u,width:r,height:o,alignVertical:d,alignHorizontal:h,sideOrientation:f});for(p=2;p<4;p++)v[p]=$i.a.CreateTiledPlane({pattern:n,tileWidth:l,tileHeight:u,width:c,height:o,alignVertical:d,alignHorizontal:h,sideOrientation:f});var y=d;d===Ae.a.BOTTOM?y=Ae.a.TOP:d===Ae.a.TOP&&(y=Ae.a.BOTTOM);for(p=4;p<6;p++)v[p]=$i.a.CreateTiledPlane({pattern:n,tileWidth:l,tileHeight:u,width:r,height:c,alignVertical:y,alignHorizontal:h,sideOrientation:f});var b=[],T=[],E=[],x=[],P=[],A=[],S=[],C=[],R=0,O=0,M=0;for(p=0;p<6;p++){R=v[p].positions.length;A[p]=[],S[p]=[];for(var I=0;I<R/3;I++)A[p].push(new a.e(v[p].positions[3*I],v[p].positions[3*I+1],v[p].positions[3*I+2])),S[p].push(new a.e(v[p].normals[3*I],v[p].normals[3*I+1],v[p].normals[3*I+2]));O=v[p].uvs.length,C[p]=[];for(var D=0;D<O;D+=2)C[p][D]=t[p].x+(t[p].z-t[p].x)*v[p].uvs[D],C[p][D+1]=t[p].y+(t[p].w-t[p].y)*v[p].uvs[D+1];if(E=E.concat(C[p]),x=x.concat(v[p].indices.map(function(e){return e+M})),M+=A[p].length,i)for(var w=0;w<4;w++)P.push(i[p].r,i[p].g,i[p].b,i[p].a)}var L=new a.e(0,0,g),N=a.a.RotationY(Math.PI);b=A[0].map(function(e){return a.e.TransformNormal(e,N).add(L)}).map(function(e){return[e.x,e.y,e.z]}).reduce(function(e,t){return e.concat(t)},[]),T=S[0].map(function(e){return a.e.TransformNormal(e,N)}).map(function(e){return[e.x,e.y,e.z]}).reduce(function(e,t){return e.concat(t)},[]),b=b.concat(A[1].map(function(e){return e.subtract(L)}).map(function(e){return[e.x,e.y,e.z]}).reduce(function(e,t){return e.concat(t)},[])),T=T.concat(S[1].map(function(e){return[e.x,e.y,e.z]}).reduce(function(e,t){return e.concat(t)},[]));var F=new a.e(_,0,0),B=a.a.RotationY(-Math.PI/2);b=b.concat(A[2].map(function(e){return a.e.TransformNormal(e,B).add(F)}).map(function(e){return[e.x,e.y,e.z]}).reduce(function(e,t){return e.concat(t)},[])),T=T.concat(S[2].map(function(e){return a.e.TransformNormal(e,B)}).map(function(e){return[e.x,e.y,e.z]}).reduce(function(e,t){return e.concat(t)},[]));var U=a.a.RotationY(Math.PI/2);b=b.concat(A[3].map(function(e){return a.e.TransformNormal(e,U).subtract(F)}).map(function(e){return[e.x,e.y,e.z]}).reduce(function(e,t){return e.concat(t)},[])),T=T.concat(S[3].map(function(e){return a.e.TransformNormal(e,U)}).map(function(e){return[e.x,e.y,e.z]}).reduce(function(e,t){return e.concat(t)},[]));var V=new a.e(0,m,0),k=a.a.RotationX(Math.PI/2);b=b.concat(A[4].map(function(e){return a.e.TransformNormal(e,k).add(V)}).map(function(e){return[e.x,e.y,e.z]}).reduce(function(e,t){return e.concat(t)},[])),T=T.concat(S[4].map(function(e){return a.e.TransformNormal(e,k)}).map(function(e){return[e.x,e.y,e.z]}).reduce(function(e,t){return e.concat(t)},[]));var z=a.a.RotationX(-Math.PI/2);b=b.concat(A[5].map(function(e){return a.e.TransformNormal(e,z).subtract(V)}).map(function(e){return[e.x,e.y,e.z]}).reduce(function(e,t){return e.concat(t)},[])),T=T.concat(S[5].map(function(e){return a.e.TransformNormal(e,z)}).map(function(e){return[e.x,e.y,e.z]}).reduce(function(e,t){return e.concat(t)},[])),$i.a._ComputeSides(f,b,x,T,E);var G=new $i.a;if(G.indices=x,G.positions=b,G.normals=T,G.uvs=E,i){var j=f===$i.a.DOUBLESIDE?P.concat(P):P;G.colors=j}return G};var Jl=function(){function e(){}return e.CreateTiledBox=function(e,t,i){void 0===i&&(i=null);var n=new Ae.a(e,i);return t.sideOrientation=Ae.a._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,$i.a.CreateTiledBox(t).applyToMesh(n,t.updatable),n},e}();$i.a.CreateTorusKnot=function(e){var t,i,n=new Array,r=new Array,o=new Array,s=new Array,c=e.radius||2,l=e.tube||.5,u=e.radialSegments||32,h=e.tubularSegments||32,d=e.p||2,f=e.q||3,p=0===e.sideOrientation?0:e.sideOrientation||$i.a.DEFAULTSIDE,_=function(e){var t=Math.cos(e),i=Math.sin(e),n=f/d*e,r=Math.cos(n),o=c*(2+r)*.5*t,s=c*(2+r)*i*.5,l=c*Math.sin(n)*.5;return new a.e(o,s,l)};for(t=0;t<=u;t++){var m=t%u/u*2*d*Math.PI,g=_(m),v=_(m+.01),y=v.subtract(g),b=v.add(g),T=a.e.Cross(y,b);for(b=a.e.Cross(T,y),T.normalize(),b.normalize(),i=0;i<h;i++){var E=i%h/h*2*Math.PI,x=-l*Math.cos(E),P=l*Math.sin(E);r.push(g.x+x*b.x+P*T.x),r.push(g.y+x*b.y+P*T.y),r.push(g.z+x*b.z+P*T.z),s.push(t/u),s.push(i/h)}}for(t=0;t<u;t++)for(i=0;i<h;i++){var A=(i+1)%h,S=t*h+i,C=(t+1)*h+i,R=(t+1)*h+A,O=t*h+A;n.push(O),n.push(C),n.push(S),n.push(O),n.push(R),n.push(C)}$i.a.ComputeNormals(r,n,o),$i.a._ComputeSides(p,r,n,o,s,e.frontUVs,e.backUVs);var M=new $i.a;return M.indices=n,M.positions=r,M.normals=o,M.uvs=s,M},Ae.a.CreateTorusKnot=function(e,t,i,n,r,o,a,s,c,l){var u={radius:t,tube:i,radialSegments:n,tubularSegments:r,p:o,q:a,sideOrientation:l,updatable:c};return $l.CreateTorusKnot(e,u,s)};var $l=function(){function e(){}return e.CreateTorusKnot=function(e,t,i){var n=new Ae.a(e,i);return t.sideOrientation=Ae.a._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,$i.a.CreateTorusKnot(t).applyToMesh(n,t.updatable),n},e}(),eu=function(e){function t(t,i){var n=e.call(this,t.x,t.y)||this;return n.index=i,n}return Object(h.d)(t,e),t}(a.d),tu=function(){function e(){this.elements=new Array}return e.prototype.add=function(e){var t=this,i=new Array;return e.forEach(function(e){if(0===i.length||!e.equalsWithEpsilon(i[0])){var n=new eu(e,t.elements.length);i.push(n),t.elements.push(n)}}),i},e.prototype.computeBounds=function(){var e=new a.d(this.elements[0].x,this.elements[0].y),t=new a.d(this.elements[0].x,this.elements[0].y);return this.elements.forEach(function(i){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)}),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}},e}(),iu=function(){function e(){}return e.Rectangle=function(e,t,i,n){return[new a.d(e,t),new a.d(i,t),new a.d(i,n),new a.d(e,n)]},e.Circle=function(e,t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=32);for(var r=new Array,o=0,s=2*Math.PI/n,c=0;c<n;c++)r.push(new a.d(t+Math.cos(o)*e,i+Math.sin(o)*e)),o-=s;return r},e.Parse=function(e){var t,i=e.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function(e){return!isNaN(e)}),n=[];for(t=0;t<(2147483646&i.length);t+=2)n.push(new a.d(i[t],i[t+1]));return n},e.StartingAt=function(e,t){return ce.StartingAt(e,t)},e}(),nu=function(){function e(e,t,i,n){var r;void 0===n&&(n=earcut),this._points=new tu,this._outlinepoints=new tu,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=n,this._name=e,this._scene=i||Oe.a.LastCreatedScene,r=t instanceof ce?t.getPoints():t,this._addToepoint(r),this._points.add(r),this._outlinepoints.add(r),void 0===this.bjsEarcut&&m.a.Warn("Earcut was not found, the polygon will not be built.")}return e.prototype._addToepoint=function(e){for(var t=0,i=e;t<i.length;t++){var n=i[t];this._epoints.push(n.x,n.y)}},e.prototype.addHole=function(e){this._points.add(e);var t=new tu;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this},e.prototype.build=function(e,t){void 0===e&&(e=!1),void 0===t&&(t=0);var i=new Ae.a(this._name,this._scene),n=this.buildVertexData(t);return i.setVerticesData(en.b.PositionKind,n.positions,e),i.setVerticesData(en.b.NormalKind,n.normals,e),i.setVerticesData(en.b.UVKind,n.uvs,e),i.setIndices(n.indices),i},e.prototype.buildVertexData=function(e){var t=this;void 0===e&&(e=0);var i=new $i.a,n=new Array,r=new Array,o=new Array,a=this._points.computeBounds();this._points.elements.forEach(function(e){n.push(0,1,0),r.push(e.x,0,e.y),o.push((e.x-a.min.x)/a.width,(e.y-a.min.y)/a.height)});for(var s=new Array,c=this.bjsEarcut(this._epoints,this._eholes,2),l=0;l<c.length;l++)s.push(c[l]);if(e>0){var u=r.length/3;this._points.elements.forEach(function(t){n.push(0,-1,0),r.push(t.x,-e,t.y),o.push(1-(t.x-a.min.x)/a.width,1-(t.y-a.min.y)/a.height)});var h=s.length;for(l=0;l<h;l+=3){var d=s[l+0],f=s[l+1],p=s[l+2];s.push(p+u),s.push(f+u),s.push(d+u)}this.addSide(r,n,o,s,a,this._outlinepoints,e,!1),this._holes.forEach(function(i){t.addSide(r,n,o,s,a,i,e,!0)})}return i.indices=s,i.positions=r,i.normals=n,i.uvs=o,i},e.prototype.addSide=function(e,t,i,n,r,o,s,c){for(var l=e.length/3,u=0,h=0;h<o.elements.length;h++){var d,f=o.elements[h];d=h+1>o.elements.length-1?o.elements[0]:o.elements[h+1],e.push(f.x,0,f.y),e.push(f.x,-s,f.y),e.push(d.x,0,d.y),e.push(d.x,-s,d.y);var p=new a.e(f.x,0,f.y),_=new a.e(d.x,0,d.y).subtract(p),m=new a.e(0,1,0),g=a.e.Cross(_,m);g=g.normalize(),i.push(u/r.width,0),i.push(u/r.width,1),u+=_.length(),i.push(u/r.width,0),i.push(u/r.width,1),c?(t.push(g.x,g.y,g.z),t.push(g.x,g.y,g.z),t.push(g.x,g.y,g.z),t.push(g.x,g.y,g.z),n.push(l),n.push(l+2),n.push(l+1),n.push(l+1),n.push(l+2),n.push(l+3)):(t.push(-g.x,-g.y,-g.z),t.push(-g.x,-g.y,-g.z),t.push(-g.x,-g.y,-g.z),t.push(-g.x,-g.y,-g.z),n.push(l),n.push(l+1),n.push(l+2),n.push(l+1),n.push(l+3),n.push(l+2)),l+=4}},e}();$i.a.CreatePolygon=function(e,t,i,n,r,o){for(var c=i||new Array(3),l=n,u=[],h=0;h<3;h++)void 0===c[h]&&(c[h]=new a.f(0,0,1,1)),l&&void 0===l[h]&&(l[h]=new s.b(1,1,1,1));for(var d=e.getVerticesData(en.b.PositionKind),f=e.getVerticesData(en.b.NormalKind),p=e.getVerticesData(en.b.UVKind),_=e.getIndices(),m=0,g=0,v=0;v<f.length;v+=3)Math.abs(f[v+1])<.001&&(g=1),Math.abs(f[v+1]-1)<.001&&(g=0),Math.abs(f[v+1]+1)<.001&&(g=2),p[2*(m=v/3)]=(1-p[2*m])*c[g].x+p[2*m]*c[g].z,p[2*m+1]=(1-p[2*m+1])*c[g].y+p[2*m+1]*c[g].w,l&&u.push(l[g].r,l[g].g,l[g].b,l[g].a);$i.a._ComputeSides(t,d,_,f,p,r,o);var y=new $i.a;if(y.indices=_,y.positions=d,y.normals=f,y.uvs=p,l){var b=t===$i.a.DOUBLESIDE?u.concat(u):u;y.colors=b}return y},Ae.a.CreatePolygon=function(e,t,i,n,r,o,a){void 0===a&&(a=earcut);var s={shape:t,holes:n,updatable:r,sideOrientation:o};return ru.CreatePolygon(e,s,i,a)},Ae.a.ExtrudePolygon=function(e,t,i,n,r,o,a,s){void 0===s&&(s=earcut);var c={shape:t,holes:r,depth:i,updatable:o,sideOrientation:a};return ru.ExtrudePolygon(e,c,n,s)};var ru=function(){function e(){}return e.CreatePolygon=function(e,t,i,n){void 0===i&&(i=null),void 0===n&&(n=earcut),t.sideOrientation=Ae.a._GetDefaultSideOrientation(t.sideOrientation);for(var r=t.shape,o=t.holes||[],s=t.depth||0,c=[],l=[],u=0;u<r.length;u++)c[u]=new a.d(r[u].x,r[u].z);c[0].equalsWithEpsilon(c[c.length-1],1e-8)&&c.pop();for(var h=new nu(e,c,i||R.a.LastCreatedScene,n),d=0;d<o.length;d++){l=[];for(var f=0;f<o[d].length;f++)l.push(new a.d(o[d][f].x,o[d][f].z));h.addHole(l)}var p=h.build(t.updatable,s);return p._originalBuilderSideOrientation=t.sideOrientation,$i.a.CreatePolygon(p,t.sideOrientation,t.faceUV,t.faceColors,t.frontUVs,t.backUVs).applyToMesh(p,t.updatable),p},e.ExtrudePolygon=function(t,i,n,r){return void 0===n&&(n=null),void 0===r&&(r=earcut),e.CreatePolygon(t,i,n,r)},e}();Ae.a.CreateLathe=function(e,t,i,n,r,o,a){var s={shape:t,radius:i,tessellation:n,sideOrientation:a,updatable:o};return ou.CreateLathe(e,s,r)};var ou=function(){function e(){}return e.CreateLathe=function(e,t,i){void 0===i&&(i=null);var n,r=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,o=void 0===t.closed||t.closed,s=t.shape,c=t.radius||1,l=t.tessellation||64,u=t.clip||0,h=t.updatable,d=Ae.a._GetDefaultSideOrientation(t.sideOrientation),f=t.cap||Ae.a.NO_CAP,p=2*Math.PI,_=new Array,m=t.invertUV||!1,g=0,v=0,y=p/l*r,b=new Array;for(g=0;g<=l-u;g++){b=[];for(f!=Ae.a.CAP_START&&f!=Ae.a.CAP_ALL||(b.push(new a.e(0,s[0].y,0)),b.push(new a.e(Math.cos(g*y)*s[0].x*c,s[0].y,Math.sin(g*y)*s[0].x*c))),v=0;v<s.length;v++)n=new a.e(Math.cos(g*y)*s[v].x*c,s[v].y,Math.sin(g*y)*s[v].x*c),b.push(n);f!=Ae.a.CAP_END&&f!=Ae.a.CAP_ALL||(b.push(new a.e(Math.cos(g*y)*s[s.length-1].x*c,s[s.length-1].y,Math.sin(g*y)*s[s.length-1].x*c)),b.push(new a.e(0,s[s.length-1].y,0))),_.push(b)}return As.CreateRibbon(e,{pathArray:_,closeArray:o,sideOrientation:d,updatable:h,invertUV:m,frontUVs:t.frontUVs,backUVs:t.backUVs},i)},e}();$i.a.CreateTiledPlane=function(e){var t=e.pattern||Ae.a.NO_FLIP,i=e.tileWidth||e.tileSize||1,n=e.tileHeight||e.tileSize||1,r=e.alignHorizontal||0,o=e.alignVertical||0,a=e.width||e.size||1,s=Math.floor(a/i),c=a-s*i,l=e.height||e.size||1,u=Math.floor(l/n),h=l-u*n,d=i*s/2,f=n*u/2,p=0,_=0,m=0,g=0,v=0,y=0;if(c>0||h>0){m=-d,g=-f;v=d,y=f;switch(r){case Ae.a.CENTER:m-=c/=2,v+=c;break;case Ae.a.LEFT:v+=c,p=-c/2;break;case Ae.a.RIGHT:m-=c,p=c/2}switch(o){case Ae.a.CENTER:g-=h/=2,y+=h;break;case Ae.a.BOTTOM:y+=h,_=-h/2;break;case Ae.a.TOP:g-=h,_=h/2}}var b=[],T=[],E=[];E[0]=[0,0,1,0,1,1,0,1],E[1]=[0,0,1,0,1,1,0,1],t!==Ae.a.ROTATE_TILE&&t!==Ae.a.ROTATE_ROW||(E[1]=[1,1,0,1,0,0,1,0]),t!==Ae.a.FLIP_TILE&&t!==Ae.a.FLIP_ROW||(E[1]=[1,0,0,0,0,1,1,1]),t!==Ae.a.FLIP_N_ROTATE_TILE&&t!==Ae.a.FLIP_N_ROTATE_ROW||(E[1]=[0,1,1,1,1,0,0,0]);for(var x=[],P=[],A=[],S=0,C=0;C<u;C++)for(var R=0;R<s;R++)b.push(R*i-d+p,C*n-f+_,0),b.push((R+1)*i-d+p,C*n-f+_,0),b.push((R+1)*i-d+p,(C+1)*n-f+_,0),b.push(R*i-d+p,(C+1)*n-f+_,0),A.push(S,S+1,S+3,S+1,S+2,S+3),x=t===Ae.a.FLIP_TILE||t===Ae.a.ROTATE_TILE||t===Ae.a.FLIP_N_ROTATE_TILE?x.concat(E[(R%2+C%2)%2]):t===Ae.a.FLIP_ROW||t===Ae.a.ROTATE_ROW||t===Ae.a.FLIP_N_ROTATE_ROW?x.concat(E[C%2]):x.concat(E[0]),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1),S+=4;if(c>0||h>0){var O,M,I,D,w=h>0&&(o===Ae.a.CENTER||o===Ae.a.TOP),L=h>0&&(o===Ae.a.CENTER||o===Ae.a.BOTTOM),N=c>0&&(r===Ae.a.CENTER||r===Ae.a.RIGHT),F=c>0&&(r===Ae.a.CENTER||r===Ae.a.LEFT),B=[];if(w&&N&&(b.push(m+p,g+_,0),b.push(-d+p,g+_,0),b.push(-d+p,g+h+_,0),b.push(m+p,g+h+_,0),A.push(S,S+1,S+3,S+1,S+2,S+3),S+=4,B=[O=1-c/i,M=1-h/n,I=1,M,I,D=1,O,D],t===Ae.a.ROTATE_ROW&&(B=[1-O,1-M,1-I,1-M,1-I,1-D,1-O,1-D]),t===Ae.a.FLIP_ROW&&(B=[1-O,M,1-I,M,1-I,D,1-O,D]),t===Ae.a.FLIP_N_ROTATE_ROW&&(B=[O,1-M,I,1-M,I,1-D,O,1-D]),x=x.concat(B),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),w&&F&&(b.push(d+p,g+_,0),b.push(v+p,g+_,0),b.push(v+p,g+h+_,0),b.push(d+p,g+h+_,0),A.push(S,S+1,S+3,S+1,S+2,S+3),S+=4,B=[O=0,M=1-h/n,I=c/i,M,I,D=1,O,D],(t===Ae.a.ROTATE_ROW||t===Ae.a.ROTATE_TILE&&s%2==0)&&(B=[1-O,1-M,1-I,1-M,1-I,1-D,1-O,1-D]),(t===Ae.a.FLIP_ROW||t===Ae.a.FLIP_TILE&&s%2==0)&&(B=[1-O,M,1-I,M,1-I,D,1-O,D]),(t===Ae.a.FLIP_N_ROTATE_ROW||t===Ae.a.FLIP_N_ROTATE_TILE&&s%2==0)&&(B=[O,1-M,I,1-M,I,1-D,O,1-D]),x=x.concat(B),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),L&&N&&(b.push(m+p,f+_,0),b.push(-d+p,f+_,0),b.push(-d+p,y+_,0),b.push(m+p,y+_,0),A.push(S,S+1,S+3,S+1,S+2,S+3),S+=4,B=[O=1-c/i,M=0,I=1,M,I,D=h/n,O,D],(t===Ae.a.ROTATE_ROW&&u%2==1||t===Ae.a.ROTATE_TILE&&u%1==0)&&(B=[1-O,1-M,1-I,1-M,1-I,1-D,1-O,1-D]),(t===Ae.a.FLIP_ROW&&u%2==1||t===Ae.a.FLIP_TILE&&u%2==0)&&(B=[1-O,M,1-I,M,1-I,D,1-O,D]),(t===Ae.a.FLIP_N_ROTATE_ROW&&u%2==1||t===Ae.a.FLIP_N_ROTATE_TILE&&u%2==0)&&(B=[O,1-M,I,1-M,I,1-D,O,1-D]),x=x.concat(B),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),L&&F&&(b.push(d+p,f+_,0),b.push(v+p,f+_,0),b.push(v+p,y+_,0),b.push(d+p,y+_,0),A.push(S,S+1,S+3,S+1,S+2,S+3),S+=4,B=[O=0,M=0,I=c/i,M,I,D=h/n,O,D],(t===Ae.a.ROTATE_ROW&&u%2==1||t===Ae.a.ROTATE_TILE&&(u+s)%2==1)&&(B=[1-O,1-M,1-I,1-M,1-I,1-D,1-O,1-D]),(t===Ae.a.FLIP_ROW&&u%2==1||t===Ae.a.FLIP_TILE&&(u+s)%2==1)&&(B=[1-O,M,1-I,M,1-I,D,1-O,D]),(t===Ae.a.FLIP_N_ROTATE_ROW&&u%2==1||t===Ae.a.FLIP_N_ROTATE_TILE&&(u+s)%2==1)&&(B=[O,1-M,I,1-M,I,1-D,O,1-D]),x=x.concat(B),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),w){var U=[];O=0,M=1-h/n,I=1,D=1,U[0]=[O,M,I,M,I,D,O,D],U[1]=[O,M,I,M,I,D,O,D],t!==Ae.a.ROTATE_TILE&&t!==Ae.a.ROTATE_ROW||(U[1]=[1-O,1-M,1-I,1-M,1-I,1-D,1-O,1-D]),t!==Ae.a.FLIP_TILE&&t!==Ae.a.FLIP_ROW||(U[1]=[1-O,M,1-I,M,1-I,D,1-O,D]),t!==Ae.a.FLIP_N_ROTATE_TILE&&t!==Ae.a.FLIP_N_ROTATE_ROW||(U[1]=[O,1-M,I,1-M,I,1-D,O,1-D]);for(R=0;R<s;R++)b.push(R*i-d+p,g+_,0),b.push((R+1)*i-d+p,g+_,0),b.push((R+1)*i-d+p,g+h+_,0),b.push(R*i-d+p,g+h+_,0),A.push(S,S+1,S+3,S+1,S+2,S+3),S+=4,x=t===Ae.a.FLIP_TILE||t===Ae.a.ROTATE_TILE||t===Ae.a.FLIP_N_ROTATE_TILE?x.concat(U[(R+1)%2]):t===Ae.a.FLIP_ROW||t===Ae.a.ROTATE_ROW||t===Ae.a.FLIP_N_ROTATE_ROW?x.concat(U[1]):x.concat(U[0]),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(L){var V=[];O=0,M=0,I=1,D=h/n,V[0]=[O,M,I,M,I,D,O,D],V[1]=[O,M,I,M,I,D,O,D],t!==Ae.a.ROTATE_TILE&&t!==Ae.a.ROTATE_ROW||(V[1]=[1-O,1-M,1-I,1-M,1-I,1-D,1-O,1-D]),t!==Ae.a.FLIP_TILE&&t!==Ae.a.FLIP_ROW||(V[1]=[1-O,M,1-I,M,1-I,D,1-O,D]),t!==Ae.a.FLIP_N_ROTATE_TILE&&t!==Ae.a.FLIP_N_ROTATE_ROW||(V[1]=[O,1-M,I,1-M,I,1-D,O,1-D]);for(R=0;R<s;R++)b.push(R*i-d+p,y-h+_,0),b.push((R+1)*i-d+p,y-h+_,0),b.push((R+1)*i-d+p,y+_,0),b.push(R*i-d+p,y+_,0),A.push(S,S+1,S+3,S+1,S+2,S+3),S+=4,x=t===Ae.a.FLIP_TILE||t===Ae.a.ROTATE_TILE||t===Ae.a.FLIP_N_ROTATE_TILE?x.concat(V[(R+u)%2]):t===Ae.a.FLIP_ROW||t===Ae.a.ROTATE_ROW||t===Ae.a.FLIP_N_ROTATE_ROW?x.concat(V[u%2]):x.concat(V[0]),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(N){var k=[];O=1-c/i,M=0,I=1,D=1,k[0]=[O,M,I,M,I,D,O,D],k[1]=[O,M,I,M,I,D,O,D],t!==Ae.a.ROTATE_TILE&&t!==Ae.a.ROTATE_ROW||(k[1]=[1-O,1-M,1-I,1-M,1-I,1-D,1-O,1-D]),t!==Ae.a.FLIP_TILE&&t!==Ae.a.FLIP_ROW||(k[1]=[1-O,M,1-I,M,1-I,D,1-O,D]),t!==Ae.a.FLIP_N_ROTATE_TILE&&t!==Ae.a.FLIP_N_ROTATE_ROW||(k[1]=[O,1-M,I,1-M,I,1-D,O,1-D]);for(C=0;C<u;C++)b.push(m+p,C*n-f+_,0),b.push(m+c+p,C*n-f+_,0),b.push(m+c+p,(C+1)*n-f+_,0),b.push(m+p,(C+1)*n-f+_,0),A.push(S,S+1,S+3,S+1,S+2,S+3),S+=4,x=t===Ae.a.FLIP_TILE||t===Ae.a.ROTATE_TILE||t===Ae.a.FLIP_N_ROTATE_TILE?x.concat(k[(C+1)%2]):t===Ae.a.FLIP_ROW||t===Ae.a.ROTATE_ROW||t===Ae.a.FLIP_N_ROTATE_ROW?x.concat(k[C%2]):x.concat(k[0]),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(F){var z=[];O=0,M=0,I=c/n,D=1,z[0]=[O,M,I,M,I,D,O,D],z[1]=[O,M,I,M,I,D,O,D],t!==Ae.a.ROTATE_TILE&&t!==Ae.a.ROTATE_ROW||(z[1]=[1-O,1-M,1-I,1-M,1-I,1-D,1-O,1-D]),t!==Ae.a.FLIP_TILE&&t!==Ae.a.FLIP_ROW||(z[1]=[1-O,M,1-I,M,1-I,D,1-O,D]),t!==Ae.a.FLIP_N_ROTATE_TILE&&t!==Ae.a.FLIP_N_ROTATE_ROW||(z[1]=[O,1-M,I,1-M,I,1-D,O,1-D]);for(C=0;C<u;C++)b.push(v-c+p,C*n-f+_,0),b.push(v+p,C*n-f+_,0),b.push(v+p,(C+1)*n-f+_,0),b.push(v-c+p,(C+1)*n-f+_,0),A.push(S,S+1,S+3,S+1,S+2,S+3),S+=4,x=t===Ae.a.FLIP_TILE||t===Ae.a.ROTATE_TILE||t===Ae.a.FLIP_N_ROTATE_TILE?x.concat(z[(C+s)%2]):t===Ae.a.FLIP_ROW||t===Ae.a.ROTATE_ROW||t===Ae.a.FLIP_N_ROTATE_ROW?x.concat(z[C%2]):x.concat(z[0]),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}}var G=0===e.sideOrientation?0:e.sideOrientation||$i.a.DEFAULTSIDE;$i.a._ComputeSides(G,b,A,T,x,e.frontUVs,e.backUVs);var j=new $i.a;j.indices=A,j.positions=b,j.normals=T,j.uvs=x;var W=G===$i.a.DOUBLESIDE?P.concat(P):P;return j.colors=W,j};var au=function(){function e(){}return e.CreateTiledPlane=function(e,t,i){void 0===i&&(i=null);var n=new Ae.a(e,i);return t.sideOrientation=Ae.a._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,$i.a.CreateTiledPlane(t).applyToMesh(n,t.updatable),n},e}();Ae.a.CreateTube=function(e,t,i,n,r,o,a,s,c,l){var u={path:t,radius:i,tessellation:n,radiusFunction:r,arc:1,cap:o,updatable:s,sideOrientation:c,instance:l};return su.CreateTube(e,u,a)};var su=function(){function e(){}return e.CreateTube=function(e,t,i){void 0===i&&(i=null);var n=t.path,r=t.instance,o=1;void 0!==t.radius?o=t.radius:r&&(o=r._creationDataStorage.radius);var s=t.tessellation||64,c=t.radiusFunction||null,l=t.cap||Ae.a.NO_CAP,u=t.invertUV||!1,h=t.updatable,d=Ae.a._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;var f,p,_=function(e,t,i,n,r,o,s,c){for(var l,u,h,d,f=t.getTangents(),p=t.getNormals(),_=t.getDistances(),m=2*Math.PI/r*c,g=o||function(){return n},v=a.c.Matrix[0],y=s===Ae.a.NO_CAP||s===Ae.a.CAP_END?0:2,b=0;b<e.length;b++){u=g(b,_[b]),l=Array(),h=p[b];for(var T=0;T<r;T++)a.a.RotationAxisToRef(f[b],m*T,v),d=l[T]?l[T]:a.e.Zero(),a.e.TransformCoordinatesToRef(h,v,d),d.scaleInPlace(u).addInPlace(e[b]),l[T]=d;i[y]=l,y++}var E=function(t,i){for(var n=Array(),r=0;r<t;r++)n.push(e[i]);return n};switch(s){case Ae.a.NO_CAP:break;case Ae.a.CAP_START:i[0]=E(r,0),i[1]=i[2].slice(0);break;case Ae.a.CAP_END:i[y]=i[y-1].slice(0),i[y+1]=E(r,e.length-1);break;case Ae.a.CAP_ALL:i[0]=E(r,0),i[1]=i[2].slice(0),i[y]=i[y-1].slice(0),i[y+1]=E(r,e.length-1)}return i};if(r){var m=r._creationDataStorage,g=t.arc||m.arc;return p=_(n,f=m.path3D.update(n),m.pathArray,o,m.tessellation,c,m.cap,g),r=As.CreateRibbon("",{pathArray:p,instance:r}),m.path3D=f,m.pathArray=p,m.arc=g,m.radius=o,r}p=_(n,f=new le(n),new Array,o,s,c,l=l<0||l>3?0:l,t.arc);var v=As.CreateRibbon(e,{pathArray:p,closePath:!0,closeArray:!1,updatable:h,sideOrientation:d,invertUV:u,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return v._creationDataStorage.pathArray=p,v._creationDataStorage.path3D=f,v._creationDataStorage.tessellation=s,v._creationDataStorage.cap=l,v._creationDataStorage.arc=t.arc,v._creationDataStorage.radius=o,v},e}();$i.a.CreateIcoSphere=function(e){var t,i=e.sideOrientation||$i.a.DEFAULTSIDE,n=e.radius||1,r=void 0===e.flat||e.flat,o=e.subdivisions||4,s=e.radiusX||n,c=e.radiusY||n,l=e.radiusZ||n,u=(1+Math.sqrt(5))/2,h=[-1,u,-0,1,u,0,-1,-u,0,1,-u,0,0,-1,-u,0,1,-u,0,-1,u,0,1,u,u,0,1,u,0,-1,-u,0,1,-u,0,-1],d=[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],f=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],p=[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],_=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],m=new Array,g=new Array,v=new Array,y=new Array,b=0,T=new Array(3),E=new Array(3);for(t=0;t<3;t++)T[t]=a.e.Zero(),E[t]=a.d.Zero();for(var x=0;x<20;x++){for(t=0;t<3;t++){var P=d[3*x+t];T[t].copyFromFloats(h[3*f[P]],h[3*f[P]+1],h[3*f[P]+2]),T[t].normalize().scaleInPlace(n),E[t].copyFromFloats(p[2*P]*(138/1024)+60/1024+_[x]*(-40/1024),p[2*P+1]*(239/1024)+26/1024+_[x]*(20/1024))}for(var A=function(e,t,i,n){var u,h=a.e.Lerp(T[0],T[2],t/o),d=a.e.Lerp(T[1],T[2],t/o),f=o===t?T[2]:a.e.Lerp(h,d,e/(o-t));if(f.normalize(),r){var p=a.e.Lerp(T[0],T[2],n/o),_=a.e.Lerp(T[1],T[2],n/o);u=a.e.Lerp(p,_,i/(o-n))}else u=new a.e(f.x,f.y,f.z);u.x/=s,u.y/=c,u.z/=l,u.normalize();var x=a.d.Lerp(E[0],E[2],t/o),P=a.d.Lerp(E[1],E[2],t/o),A=o===t?E[2]:a.d.Lerp(x,P,e/(o-t));g.push(f.x*s,f.y*c,f.z*l),v.push(u.x,u.y,u.z),y.push(A.x,A.y),m.push(b),b++},S=0;S<o;S++)for(var C=0;C+S<o;C++)A(C,S,C+1/3,S+1/3),A(C+1,S,C+1/3,S+1/3),A(C,S+1,C+1/3,S+1/3),C+S+1<o&&(A(C+1,S,C+2/3,S+2/3),A(C+1,S+1,C+2/3,S+2/3),A(C,S+1,C+2/3,S+2/3))}$i.a._ComputeSides(i,g,m,v,y,e.frontUVs,e.backUVs);var R=new $i.a;return R.indices=m,R.positions=g,R.normals=v,R.uvs=y,R},Ae.a.CreateIcoSphere=function(e,t,i){return cu.CreateIcoSphere(e,t,i)};var cu=function(){function e(){}return e.CreateIcoSphere=function(e,t,i){void 0===i&&(i=null);var n=new Ae.a(e,i);return t.sideOrientation=Ae.a._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,$i.a.CreateIcoSphere(t).applyToMesh(n,t.updatable),n},e}();Ae.a.CreateDecal=function(e,t,i,n,r,o){var a={position:i,normal:n,size:r,angle:o};return uu.CreateDecal(e,t,a)};var lu,uu=function(){function e(){}return e.CreateDecal=function(e,t,i){var n=t.getIndices(),r=t.getVerticesData(en.b.PositionKind),o=t.getVerticesData(en.b.NormalKind),s=i.position||a.e.Zero(),c=i.normal||a.e.Up(),l=i.size||a.e.One(),u=i.angle||0;if(!c){var h=new a.e(0,0,1),d=t.getScene().activeCamera,f=a.e.TransformCoordinates(h,d.getWorldMatrix());c=d.globalPosition.subtract(f)}var p=-Math.atan2(c.z,c.x)-Math.PI/2,_=Math.sqrt(c.x*c.x+c.z*c.z),m=Math.atan2(c.y,_),g=a.a.RotationYawPitchRoll(p,m,u).multiply(a.a.Translation(s.x,s.y,s.z)),v=a.a.Invert(g),y=t.getWorldMatrix().multiply(v),b=new $i.a;b.indices=[],b.positions=[],b.normals=[],b.uvs=[];for(var T=0,E=function(e){var t=new Ta;if(!n||!r||!o)return t;var i=n[e];return t.position=new a.e(r[3*i],r[3*i+1],r[3*i+2]),t.position=a.e.TransformCoordinates(t.position,y),t.normal=new a.e(o[3*i],o[3*i+1],o[3*i+2]),t.normal=a.e.TransformNormal(t.normal,y),t},x=function(e,t){if(0===e.length)return e;for(var i=.5*Math.abs(a.e.Dot(l,t)),n=function(e,n){var r=a.e.GetClipFactor(e.position,n.position,t,i);return new Ta(a.e.Lerp(e.position,n.position,r),a.e.Lerp(e.normal,n.normal,r))},r=new Array,o=0;o<e.length;o+=3){var s,c,u,h=null,d=null,f=null,p=null;switch(((s=a.e.Dot(e[o].position,t)-i>0)?1:0)+((c=a.e.Dot(e[o+1].position,t)-i>0)?1:0)+((u=a.e.Dot(e[o+2].position,t)-i>0)?1:0)){case 0:r.push(e[o]),r.push(e[o+1]),r.push(e[o+2]);break;case 1:if(s&&(h=e[o+1],d=e[o+2],f=n(e[o],h),p=n(e[o],d)),c){h=e[o],d=e[o+2],f=n(e[o+1],h),p=n(e[o+1],d),r.push(f),r.push(d.clone()),r.push(h.clone()),r.push(d.clone()),r.push(f.clone()),r.push(p);break}u&&(h=e[o],d=e[o+1],f=n(e[o+2],h),p=n(e[o+2],d)),h&&d&&f&&p&&(r.push(h.clone()),r.push(d.clone()),r.push(f),r.push(p),r.push(f.clone()),r.push(d.clone()));break;case 2:s||(d=n(h=e[o].clone(),e[o+1]),f=n(h,e[o+2]),r.push(h),r.push(d),r.push(f)),c||(d=n(h=e[o+1].clone(),e[o+2]),f=n(h,e[o]),r.push(h),r.push(d),r.push(f)),u||(d=n(h=e[o+2].clone(),e[o]),f=n(h,e[o+1]),r.push(h),r.push(d),r.push(f))}}return r},P=0;P<n.length;P+=3){var A=new Array;if(A.push(E(P)),A.push(E(P+1)),A.push(E(P+2)),A=x(A,new a.e(1,0,0)),A=x(A,new a.e(-1,0,0)),A=x(A,new a.e(0,1,0)),A=x(A,new a.e(0,-1,0)),A=x(A,new a.e(0,0,1)),0!==(A=x(A,new a.e(0,0,-1))).length)for(var S=0;S<A.length;S++){var C=A[S];b.indices.push(T),C.position.toArray(b.positions,3*T),C.normal.toArray(b.normals,3*T),b.uvs.push(.5+C.position.x/l.x),b.uvs.push(.5+C.position.y/l.y),T++}}var R=new Ae.a(e,t.getScene());return b.applyToMesh(R),R.position=s.clone(),R.rotation=new a.e(m,p,u),R},e}(),hu=function(){function e(){}return e.CreateBox=function(e,t,i){return void 0===i&&(i=null),Pr.a.CreateBox(e,t,i)},e.CreateTiledBox=function(e,t,i){return void 0===i&&(i=null),Jl.CreateTiledBox(e,t,i)},e.CreateSphere=function(e,t,i){return void 0===i&&(i=null),Rr.a.CreateSphere(e,t,i)},e.CreateDisc=function(e,t,i){return void 0===i&&(i=null),Zl.CreateDisc(e,t,i)},e.CreateIcoSphere=function(e,t,i){return void 0===i&&(i=null),cu.CreateIcoSphere(e,t,i)},e.CreateRibbon=function(e,t,i){return void 0===i&&(i=null),As.CreateRibbon(e,t,i)},e.CreateCylinder=function(e,t,i){return void 0===i&&(i=null),an.a.CreateCylinder(e,t,i)},e.CreateTorus=function(e,t,i){return void 0===i&&(i=null),on.CreateTorus(e,t,i)},e.CreateTorusKnot=function(e,t,i){return void 0===i&&(i=null),$l.CreateTorusKnot(e,t,i)},e.CreateLineSystem=function(e,t,i){return Or.a.CreateLineSystem(e,t,i)},e.CreateLines=function(e,t,i){return void 0===i&&(i=null),Or.a.CreateLines(e,t,i)},e.CreateDashedLines=function(e,t,i){return void 0===i&&(i=null),Or.a.CreateDashedLines(e,t,i)},e.ExtrudeShape=function(e,t,i){return void 0===i&&(i=null),Ss.ExtrudeShape(e,t,i)},e.ExtrudeShapeCustom=function(e,t,i){return void 0===i&&(i=null),Ss.ExtrudeShapeCustom(e,t,i)},e.CreateLathe=function(e,t,i){return void 0===i&&(i=null),ou.CreateLathe(e,t,i)},e.CreateTiledPlane=function(e,t,i){return void 0===i&&(i=null),au.CreateTiledPlane(e,t,i)},e.CreatePlane=function(e,t,i){return void 0===i&&(i=null),Lr.a.CreatePlane(e,t,i)},e.CreateGround=function(e,t,i){return void 0===i&&(i=null),nn.CreateGround(e,t,i)},e.CreateTiledGround=function(e,t,i){return void 0===i&&(i=null),nn.CreateTiledGround(e,t,i)},e.CreateGroundFromHeightMap=function(e,t,i,n){return void 0===n&&(n=null),nn.CreateGroundFromHeightMap(e,t,i,n)},e.CreatePolygon=function(e,t,i,n){return void 0===i&&(i=null),void 0===n&&(n=earcut),ru.CreatePolygon(e,t,i,n)},e.ExtrudePolygon=function(e,t,i,n){return void 0===i&&(i=null),void 0===n&&(n=earcut),ru.ExtrudePolygon(e,t,i,n)},e.CreateTube=function(e,t,i){return void 0===i&&(i=null),su.CreateTube(e,t,i)},e.CreatePolyhedron=function(e,t,i){return void 0===i&&(i=null),Br.CreatePolyhedron(e,t,i)},e.CreateDecal=function(e,t,i){return uu.CreateDecal(e,t,i)},e}(),du=function(e,t,i){this.quality=e,this.distance=t,this.optimizeMesh=i},fu=function(){function e(){this.running=!1,this._simplificationArray=[]}return e.prototype.addTask=function(e){this._simplificationArray.push(e)},e.prototype.executeNext=function(){var e=this._simplificationArray.pop();e?(this.running=!0,this.runSimplification(e)):this.running=!1},e.prototype.runSimplification=function(e){var t=this;if(e.parallelProcessing)e.settings.forEach(function(i){t.getSimplifier(e).simplify(i,function(n){e.mesh.addLODLevel(i.distance,n),n.isVisible=!0,i.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),t.executeNext()})});else{var i=this.getSimplifier(e);De.a.Run(e.settings.length,function(t){var n,r;n=e.settings[t.index],r=function(){t.executeNext()},i.simplify(n,function(t){e.mesh.addLODLevel(n.distance,t),t.isVisible=!0,r()})},function(){e.successCallback&&e.successCallback(),t.executeNext()})}},e.prototype.getSimplifier=function(e){switch(e.simplificationType){case lu.QUADRATIC:default:return new vu(e.mesh)}},e}();!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(lu||(lu={}));var pu=function(e){this.vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0},_u=function(){function e(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new mu,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}return e.prototype.updatePosition=function(e){this.position.copyFrom(e)},e}(),mu=function(){function e(e){this.data=new Array(10);for(var t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}return e.prototype.det=function(e,t,i,n,r,o,a,s,c){return this.data[e]*this.data[r]*this.data[c]+this.data[i]*this.data[n]*this.data[s]+this.data[t]*this.data[o]*this.data[a]-this.data[i]*this.data[r]*this.data[a]-this.data[e]*this.data[o]*this.data[s]-this.data[t]*this.data[n]*this.data[c]},e.prototype.addInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e.data[t]},e.prototype.addArrayInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e[t]},e.prototype.add=function(t){for(var i=new e,n=0;n<10;++n)i.data[n]=this.data[n]+t.data[n];return i},e.FromData=function(t,i,n,r){return new e(e.DataFromNumbers(t,i,n,r))},e.DataFromNumbers=function(e,t,i,n){return[e*e,e*t,e*i,e*n,t*t,t*i,t*n,i*i,i*n,n*n]},e}(),gu=function(e,t){this.vertexId=e,this.triangleId=t},vu=function(){function e(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=re.a}return e.prototype.simplify=function(e,t){var i=this;this.initDecimatedMesh(),De.a.Run(this._mesh.subMeshes.length,function(t){i.initWithMesh(t.index,function(){i.runDecimation(e,t.index,function(){t.executeNext()})},e.optimizeMesh)},function(){setTimeout(function(){t(i._reconstructedMesh)},0)})},e.prototype.runDecimation=function(e,t,i){var n=this,r=~~(this.triangles.length*e.quality),o=0,s=this.triangles.length;De.a.Run(this.decimationIterations,function(e){var t,i;s-o<=r?e.breakLoop():(t=e.index,i=function(){e.executeNext()},setTimeout(function(){t%5==0&&n.updateMesh(0===t);for(var e=0;e<n.triangles.length;++e)n.triangles[e].isDirty=!1;var c=1e-9*Math.pow(t+3,n.aggressiveness);De.a.SyncAsyncForLoop(n.triangles.length,n.syncIterations,function(e){var t=~~((n.triangles.length/2+e)%n.triangles.length),i=n.triangles[t];if(i&&!(i.error[3]>c||i.deleted||i.isDirty))for(var r=0;r<3;++r)if(i.error[r]<c){var s=[],l=[],u=i.vertices[r],h=i.vertices[(r+1)%3];if(u.isBorder||h.isBorder)continue;var d=a.e.Zero();n.calculateError(u,h,d);var f=new Array;if(n.isFlipped(u,h,d,s,f))continue;if(n.isFlipped(h,u,d,l,f))continue;if(s.indexOf(!0)<0||l.indexOf(!0)<0)continue;var p=new Array;if(f.forEach(function(e){-1===p.indexOf(e)&&(e.deletePending=!0,p.push(e))}),p.length%2!=0)continue;u.q=h.q.add(u.q),u.updatePosition(d);var _=n.references.length;o=n.updateTriangles(u,u,s,o),o=n.updateTriangles(u,h,l,o);var m=n.references.length-_;if(m<=u.triangleCount){if(m)for(var g=0;g<m;g++)n.references[u.triangleStart+g]=n.references[_+g]}else u.triangleStart=_;u.triangleCount=m;break}},i,function(){return s-o<=r})},0))},function(){setTimeout(function(){n.reconstructMesh(t),i()},0)})},e.prototype.initWithMesh=function(e,t,i){var n=this;this.vertices=[],this.triangles=[];var r=this._mesh.getVerticesData(en.b.PositionKind),o=this._mesh.getIndices(),s=this._mesh.subMeshes[e],c=[],l=s.verticesCount;De.a.SyncAsyncForLoop(l,this.syncIterations/4>>0,function(e){if(r){var t=e+s.verticesStart,o=a.e.FromArray(r,3*t),l=function(e){if(i)for(var t=0;t<n.vertices.length;++t)if(n.vertices[t].position.equals(e))return n.vertices[t];return null}(o)||new _u(o,n.vertices.length);l.originalOffsets.push(t),l.id===n.vertices.length&&n.vertices.push(l),c.push(l.id)}},function(){De.a.SyncAsyncForLoop(s.indexCount/3,n.syncIterations,function(e){if(o){var t=3*(s.indexStart/3+e),i=o[t+0],r=o[t+1],a=o[t+2],l=n.vertices[c[i-s.verticesStart]],u=n.vertices[c[r-s.verticesStart]],h=n.vertices[c[a-s.verticesStart]],d=new pu([l,u,h]);d.originalOffset=t,n.triangles.push(d)}},function(){n.init(t)})})},e.prototype.init=function(e){var t=this;De.a.SyncAsyncForLoop(this.triangles.length,this.syncIterations,function(e){var i=t.triangles[e];i.normal=a.e.Cross(i.vertices[1].position.subtract(i.vertices[0].position),i.vertices[2].position.subtract(i.vertices[0].position)).normalize();for(var n=0;n<3;n++)i.vertices[n].q.addArrayInPlace(mu.DataFromNumbers(i.normal.x,i.normal.y,i.normal.z,-a.e.Dot(i.normal,i.vertices[0].position)))},function(){De.a.SyncAsyncForLoop(t.triangles.length,t.syncIterations,function(e){for(var i=t.triangles[e],n=0;n<3;++n)i.error[n]=t.calculateError(i.vertices[n],i.vertices[(n+1)%3]);i.error[3]=Math.min(i.error[0],i.error[1],i.error[2])},function(){e()})})},e.prototype.reconstructMesh=function(e){var t,i,n,r=[];for(t=0;t<this.vertices.length;++t)this.vertices[t].triangleCount=0;for(t=0;t<this.triangles.length;++t)if(!this.triangles[t].deleted){for(i=this.triangles[t],n=0;n<3;++n)i.vertices[n].triangleCount=1;r.push(i)}var o=this._reconstructedMesh.getVerticesData(en.b.PositionKind)||[],a=this._reconstructedMesh.getVerticesData(en.b.NormalKind)||[],s=this._reconstructedMesh.getVerticesData(en.b.UVKind)||[],c=this._reconstructedMesh.getVerticesData(en.b.ColorKind)||[],l=this._mesh.getVerticesData(en.b.NormalKind),u=this._mesh.getVerticesData(en.b.UVKind),h=this._mesh.getVerticesData(en.b.ColorKind),d=0;for(t=0;t<this.vertices.length;++t){var f=this.vertices[t];f.id=d,f.triangleCount&&f.originalOffsets.forEach(function(e){l&&(o.push(f.position.x),o.push(f.position.y),o.push(f.position.z),a.push(l[3*e]),a.push(l[3*e+1]),a.push(l[3*e+2]),u&&u.length&&(s.push(u[2*e]),s.push(u[2*e+1])),h&&h.length&&(c.push(h[4*e]),c.push(h[4*e+1]),c.push(h[4*e+2]),c.push(h[4*e+3])),++d)})}var p=this._reconstructedMesh.getTotalIndices(),_=this._reconstructedMesh.getTotalVertices(),m=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];var g=this._reconstructedMesh.getIndices(),v=this._mesh.getIndices();for(t=0;t<r.length;++t)i=r[t],[0,1,2].forEach(function(e){var t=v[i.originalOffset+e],n=i.vertices[e].originalOffsets.indexOf(t);n<0&&(n=0),g.push(i.vertices[e].id+n+_)});this._reconstructedMesh.setIndices(g),this._reconstructedMesh.setVerticesData(en.b.PositionKind,o),this._reconstructedMesh.setVerticesData(en.b.NormalKind,a),s.length>0&&this._reconstructedMesh.setVerticesData(en.b.UVKind,s),c.length>0&&this._reconstructedMesh.setVerticesData(en.b.ColorKind,c);var y=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],m.forEach(function(e){zl.b.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())}),zl.b.AddToMesh(y.materialIndex,_,d,p,3*r.length,this._reconstructedMesh))},e.prototype.initDecimatedMesh=function(){this._reconstructedMesh=new Ae.a(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId},e.prototype.isFlipped=function(e,t,i,n,r){for(var o=0;o<e.triangleCount;++o){var s=this.triangles[this.references[e.triangleStart+o].triangleId];if(!s.deleted){var c=this.references[e.triangleStart+o].vertexId,l=s.vertices[(c+1)%3],u=s.vertices[(c+2)%3];if(l!==t&&u!==t){var h=l.position.subtract(i);h=h.normalize();var d=u.position.subtract(i);if(d=d.normalize(),Math.abs(a.e.Dot(h,d))>.999)return!0;var f=a.e.Cross(h,d).normalize();if(n[o]=!1,a.e.Dot(f,s.normal)<.2)return!0}else n[o]=!0,r.push(s)}}return!1},e.prototype.updateTriangles=function(e,t,i,n){for(var r=n,o=0;o<t.triangleCount;++o){var a=this.references[t.triangleStart+o],s=this.triangles[a.triangleId];s.deleted||(i[o]&&s.deletePending?(s.deleted=!0,r++):(s.vertices[a.vertexId]=e,s.isDirty=!0,s.error[0]=this.calculateError(s.vertices[0],s.vertices[1])+s.borderFactor/2,s.error[1]=this.calculateError(s.vertices[1],s.vertices[2])+s.borderFactor/2,s.error[2]=this.calculateError(s.vertices[2],s.vertices[0])+s.borderFactor/2,s.error[3]=Math.min(s.error[0],s.error[1],s.error[2]),this.references.push(a)))}return r},e.prototype.identifyBorder=function(){for(var e=0;e<this.vertices.length;++e){var t,i=[],n=[],r=this.vertices[e];for(t=0;t<r.triangleCount;++t)for(var o=this.triangles[this.references[r.triangleStart+t].triangleId],a=0;a<3;a++){for(var s=0,c=o.vertices[a];s<i.length&&n[s]!==c.id;)++s;s===i.length?(i.push(1),n.push(c.id)):i[s]++}for(t=0;t<i.length;++t)1===i[t]?this.vertices[n[t]].isBorder=!0:this.vertices[n[t]].isBorder=!1}},e.prototype.updateMesh=function(e){var t,i,n,r;if(void 0===e&&(e=!1),!e){var o=[];for(t=0;t<this.triangles.length;++t)this.triangles[t].deleted||o.push(this.triangles[t]);this.triangles=o}for(t=0;t<this.vertices.length;++t)this.vertices[t].triangleCount=0,this.vertices[t].triangleStart=0;for(t=0;t<this.triangles.length;++t)for(i=this.triangles[t],n=0;n<3;++n)(r=i.vertices[n]).triangleCount++;var a=0;for(t=0;t<this.vertices.length;++t)this.vertices[t].triangleStart=a,a+=this.vertices[t].triangleCount,this.vertices[t].triangleCount=0;var s=new Array(3*this.triangles.length);for(t=0;t<this.triangles.length;++t)for(i=this.triangles[t],n=0;n<3;++n)s[(r=i.vertices[n]).triangleStart+r.triangleCount]=new gu(n,t),r.triangleCount++;this.references=s,e&&this.identifyBorder()},e.prototype.vertexError=function(e,t){var i=t.x,n=t.y,r=t.z;return e.data[0]*i*i+2*e.data[1]*i*n+2*e.data[2]*i*r+2*e.data[3]*i+e.data[4]*n*n+2*e.data[5]*n*r+2*e.data[6]*n+e.data[7]*r*r+2*e.data[8]*r+e.data[9]},e.prototype.calculateError=function(e,t,i){var n=e.q.add(t.q),r=e.isBorder&&t.isBorder,o=0,s=n.det(0,1,2,1,4,5,2,5,7);if(0===s||r){var c=e.position.add(t.position).divide(new a.e(2,2,2)),l=this.vertexError(n,e.position),u=this.vertexError(n,t.position),h=this.vertexError(n,c);(o=Math.min(l,u,h))===l?i&&i.copyFrom(e.position):o===u?i&&i.copyFrom(t.position):i&&i.copyFrom(c)}else i||(i=a.e.Zero()),i.x=-1/s*n.det(1,2,3,4,5,6,5,7,8),i.y=1/s*n.det(0,2,3,1,5,6,2,7,8),i.z=-1/s*n.det(0,1,3,1,4,6,2,5,8),o=this.vertexError(n,i);return o},e}();Object.defineProperty(K.a.prototype,"simplificationQueue",{get:function(){if(!this._simplificationQueue){this._simplificationQueue=new fu;var e=this._getComponent(Fe.a.NAME_SIMPLIFICATIONQUEUE);e||(e=new yu(this),this._addComponent(e))}return this._simplificationQueue},set:function(e){this._simplificationQueue=e},enumerable:!0,configurable:!0}),Ae.a.prototype.simplify=function(e,t,i,n){return void 0===t&&(t=!0),void 0===i&&(i=lu.QUADRATIC),this.getScene().simplificationQueue.addTask({settings:e,parallelProcessing:t,mesh:this,simplificationType:i,successCallback:n}),this};var yu=function(){function e(e){this.name=Fe.a.NAME_SIMPLIFICATIONQUEUE,this.scene=e}return e.prototype.register=function(){this.scene._beforeCameraUpdateStage.registerStep(Fe.a.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE,this,this._beforeCameraUpdate)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){},e.prototype._beforeCameraUpdate=function(){this.scene._simplificationQueue&&!this.scene._simplificationQueue.running&&this.scene._simplificationQueue.executeNext()},e}(),bu=i(135),Tu=i(84),Eu=function(){function e(e){void 0===e&&(e=Recast),this.bjsRECAST={},this.name="RecastJSPlugin","function"==typeof e?e(this.bjsRECAST):this.bjsRECAST=e,this.isSupported()||m.a.Error("RecastJS is not available. Please make sure you included the js file.")}return e.prototype.createNavMesh=function(e,t){var i,n,r,o=new this.bjsRECAST.rcConfig;o.cs=t.cs,o.ch=t.ch,o.borderSize=0,o.tileSize=0,o.walkableSlopeAngle=t.walkableSlopeAngle,o.walkableHeight=t.walkableHeight,o.walkableClimb=t.walkableClimb,o.walkableRadius=t.walkableRadius,o.maxEdgeLen=t.maxEdgeLen,o.maxSimplificationError=t.maxSimplificationError,o.minRegionArea=t.minRegionArea,o.mergeRegionArea=t.mergeRegionArea,o.maxVertsPerPoly=t.maxVertsPerPoly,o.detailSampleDist=t.detailSampleDist,o.detailSampleMaxError=t.detailSampleMaxError,this.navMesh=new this.bjsRECAST.NavMesh;var s=[],c=[],l=0;for(i=0;i<e.length;i++)if(e[i]){var u=e[i],h=u.getIndices();if(!h)continue;var d=u.getVerticesData(en.b.PositionKind,!1,!1);if(!d)continue;var f=u.computeWorldMatrix(!1);for(n=0;n<h.length;n++)s.push(h[n]+l);var p=a.e.Zero(),_=a.e.Zero();for(r=0;r<d.length;r+=3)a.e.FromArrayToRef(d,r,_),a.e.TransformCoordinatesToRef(_,f,p),c.push(p.x,p.y,p.z);l+=d.length/3}this.navMesh.build(c,l,s,s.length,o)},e.prototype.createDebugNavMesh=function(e){var t,i,n=this.navMesh.getDebugNavMesh(),r=n.getTriangleCount(),o=[],a=[];for(t=0;t<3*r;t++)o.push(t);for(t=0;t<r;t++)for(i=0;i<3;i++){var s=n.getTriangle(t).getPoint(i);a.push(s.x,s.y,s.z)}var c=new Ae.a("NavMeshDebug",e),l=new $i.a;return l.indices=o,l.positions=a,l.applyToMesh(c,!1),c},e.prototype.getClosestPoint=function(e){var t=new this.bjsRECAST.Vec3(e.x,e.y,e.z),i=this.navMesh.getClosestPoint(t);return new a.e(i.x,i.y,i.z)},e.prototype.getRandomPointAround=function(e,t){var i=new this.bjsRECAST.Vec3(e.x,e.y,e.z),n=this.navMesh.getRandomPointAround(i,t);return new a.e(n.x,n.y,n.z)},e.prototype.moveAlong=function(e,t){var i=new this.bjsRECAST.Vec3(e.x,e.y,e.z),n=new this.bjsRECAST.Vec3(t.x,t.y,t.z),r=this.navMesh.moveAlong(i,n);return new a.e(r.x,r.y,r.z)},e.prototype.computePath=function(e,t){var i,n=new this.bjsRECAST.Vec3(e.x,e.y,e.z),r=new this.bjsRECAST.Vec3(t.x,t.y,t.z),o=this.navMesh.computePath(n,r),s=o.getPointCount(),c=[];for(i=0;i<s;i++){var l=o.getPoint(i);c.push(new a.e(l.x,l.y,l.z))}return c},e.prototype.createCrowd=function(e,t,i){return new xu(this,e,t,i)},e.prototype.setDefaultQueryExtent=function(e){var t=new this.bjsRECAST.Vec3(e.x,e.y,e.z);this.navMesh.setDefaultQueryExtent(t)},e.prototype.getDefaultQueryExtent=function(){var e=this.navMesh.getDefaultQueryExtent();return new a.e(e.x,e.y,e.z)},e.prototype.dispose=function(){},e.prototype.isSupported=function(){return void 0!==this.bjsRECAST},e}(),xu=function(){function e(e,t,i,n){var r=this;this.recastCrowd={},this.transforms=new Array,this.agents=new Array,this._onBeforeAnimationsObserver=null,this.bjsRECASTPlugin=e,this.recastCrowd=new this.bjsRECASTPlugin.bjsRECAST.Crowd(t,i,this.bjsRECASTPlugin.navMesh.getNavMesh()),this._scene=n,this._onBeforeAnimationsObserver=n.onBeforeAnimationsObservable.add(function(){r.update(.001*n.getEngine().getDeltaTime())})}return e.prototype.addAgent=function(e,t,i){var n=new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams;n.radius=t.radius,n.height=t.height,n.maxAcceleration=t.maxAcceleration,n.maxSpeed=t.maxSpeed,n.collisionQueryRange=t.collisionQueryRange,n.pathOptimizationRange=t.pathOptimizationRange,n.separationWeight=t.separationWeight,n.updateFlags=7,n.obstacleAvoidanceType=0,n.queryFilterType=0,n.userData=0;var r=this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z),n);return this.transforms.push(i),this.agents.push(r),r},e.prototype.getAgentPosition=function(e){var t=this.recastCrowd.getAgentPosition(e);return new a.e(t.x,t.y,t.z)},e.prototype.getAgentVelocity=function(e){var t=this.recastCrowd.getAgentVelocity(e);return new a.e(t.x,t.y,t.z)},e.prototype.agentGoto=function(e,t){this.recastCrowd.agentGoto(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z))},e.prototype.agentTeleport=function(e,t){this.recastCrowd.agentTeleport(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z))},e.prototype.updateAgentParameters=function(e,t){var i=this.recastCrowd.getAgentParameters(e);void 0!==t.radius&&(i.radius=t.radius),void 0!==t.height&&(i.height=t.height),void 0!==t.maxAcceleration&&(i.maxAcceleration=t.maxAcceleration),void 0!==t.maxSpeed&&(i.maxSpeed=t.maxSpeed),void 0!==t.collisionQueryRange&&(i.collisionQueryRange=t.collisionQueryRange),void 0!==t.pathOptimizationRange&&(i.pathOptimizationRange=t.pathOptimizationRange),void 0!==t.separationWeight&&(i.separationWeight=t.separationWeight),this.recastCrowd.setAgentParameters(e,i)},e.prototype.removeAgent=function(e){this.recastCrowd.removeAgent(e);var t=this.agents.indexOf(e);t>-1&&(this.agents.splice(t,1),this.transforms.splice(t,1))},e.prototype.getAgents=function(){return this.agents},e.prototype.update=function(e){this.recastCrowd.update(e);for(var t=0;t<this.agents.length;t++)this.transforms[t].position=this.getAgentPosition(this.agents[t])},e.prototype.setDefaultQueryExtent=function(e){var t=new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z);this.recastCrowd.setDefaultQueryExtent(t)},e.prototype.getDefaultQueryExtent=function(){var e=this.recastCrowd.getDefaultQueryExtent();return new a.e(e.x,e.y,e.z)},e.prototype.dispose=function(){this.recastCrowd.destroy(),this._scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null},e}();Oe.a.OfflineProviderFactory=function(e,t,i){return void 0===i&&(i=!1),new Au(e,t,i)};var Pu,Au=function(){function e(t,i,n){var r=this;void 0===n&&(n=!1),this._idbFactory="undefined"!=typeof window?window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB:indexedDB,this._callbackManifestChecked=i,this._currentSceneUrl=e._ReturnFullUrlLocation(t),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,e.IDBStorageEnabled?n?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,De.b.SetImmediate(function(){r._callbackManifestChecked(!0)})):this._checkManifestFile():this._callbackManifestChecked(!0)}return Object.defineProperty(e.prototype,"enableSceneOffline",{get:function(){return this._enableSceneOffline},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"enableTexturesOffline",{get:function(){return this._enableTexturesOffline},enumerable:!0,configurable:!0}),e.prototype._checkManifestFile=function(){var t=this,i=function(){t._enableSceneOffline=!1,t._enableTexturesOffline=!1,t._callbackManifestChecked(!1)},n=!1,r=this._currentSceneUrl+".manifest",o=new ec.a;navigator.onLine&&(n=!0,r=r+(null==r.match(/\?/)?"?":"&")+Date.now()),o.open("GET",r),o.addEventListener("load",function(){if(200===o.status||e._ValidateXHRData(o,1))try{var n=JSON.parse(o.response);t._enableSceneOffline=n.enableSceneOffline,t._enableTexturesOffline=n.enableTexturesOffline&&e.IsUASupportingBlobStorage,n.version&&!isNaN(parseInt(n.version))&&(t._manifestVersionFound=n.version),t._callbackManifestChecked&&t._callbackManifestChecked(!0)}catch(e){i()}else i()},!1),o.addEventListener("error",function(){if(n){n=!1;var e=t._currentSceneUrl+".manifest";o.open("GET",e),o.send()}else i()},!1);try{o.send()}catch(e){m.a.Error("Error on XHR send request."),this._callbackManifestChecked(!1)}},e.prototype.open=function(e,t){var i=this,n=function(){i._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline))if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;var r=this._idbFactory.open("babylonjs",1);r.onerror=function(){n()},r.onblocked=function(){m.a.Error("IDB request blocked. Please reload the page."),n()},r.onsuccess=function(){i._db=r.result,e()},r.onupgradeneeded=function(e){if(i._db=e.target.result,i._db)try{i._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),i._db.createObjectStore("versions",{keyPath:"sceneUrl"}),i._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){m.a.Error("Error while creating object stores. Exception: "+e.message),n()}}}else this._isSupported=!1,t&&t()},e.prototype.loadImage=function(t,i){var n=this,r=e._ReturnFullUrlLocation(t),o=function(){n._hasReachedQuota||null===n._db?i.src=t:n._saveImageIntoDBAsync(r,i)};this._mustUpdateRessources?o():this._loadImageFromDBAsync(r,i,o)},e.prototype._loadImageFromDBAsync=function(e,t,i){if(this._isSupported&&null!==this._db){var n,r=this._db.transaction(["textures"]);r.onabort=function(){t.src=e},r.oncomplete=function(){var r;if(n){var o=window.URL||window.webkitURL;r=o.createObjectURL(n.data),t.onerror=function(){m.a.Error("Error loading image from blob URL: "+r+" switching back to web url: "+e),t.src=e},t.src=r}else i()};var o=r.objectStore("textures").get(e);o.onsuccess=function(e){n=e.target.result},o.onerror=function(){m.a.Error("Error loading texture "+e+" from DB."),t.src=e}}else m.a.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e},e.prototype._saveImageIntoDBAsync=function(t,i){var n=this;if(this._isSupported){var r=function(){var e;if(o){var t=window.URL||window.webkitURL;try{e=t.createObjectURL(o)}catch(i){e=t.createObjectURL(o)}}e&&(i.src=e)};if(e.IsUASupportingBlobStorage){var o,a=new ec.a;a.open("GET",t),a.responseType="blob",a.addEventListener("load",function(){if(200===a.status&&n._db){o=a.response;var s=n._db.transaction(["textures"],"readwrite");s.onabort=function(e){try{var t=(e.srcElement||e.target).error;t&&"QuotaExceededError"===t.name&&(n._hasReachedQuota=!0)}catch(e){}r()},s.oncomplete=function(){r()};var c={textureUrl:t,data:o};try{var l=s.objectStore("textures").put(c);l.onsuccess=function(){},l.onerror=function(){r()}}catch(r){25===r.code&&(e.IsUASupportingBlobStorage=!1,n._enableTexturesOffline=!1),i.src=t}}else i.src=t},!1),a.addEventListener("error",function(){m.a.Error("Error in XHR request in BABYLON.Database."),i.src=t},!1),a.send()}else i.src=t}else m.a.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),i.src=t},e.prototype._checkVersionFromDB=function(e,t){var i=this;this._loadVersionFromDBAsync(e,t,function(){i._saveVersionIntoDBAsync(e,t)})},e.prototype._loadVersionFromDBAsync=function(e,t,i){var n,r=this;if(this._isSupported&&this._db)try{var o=this._db.transaction(["versions"]);o.oncomplete=function(){n?r._manifestVersionFound!==n.data?(r._mustUpdateRessources=!0,i()):t(n.data):(r._mustUpdateRessources=!0,i())},o.onabort=function(){t(-1)};var a=o.objectStore("versions").get(e);a.onsuccess=function(e){n=e.target.result},a.onerror=function(){m.a.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){m.a.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}else m.a.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)},e.prototype._saveVersionIntoDBAsync=function(e,t){var i=this;if(this._isSupported&&!this._hasReachedQuota&&this._db)try{var n=this._db.transaction(["versions"],"readwrite");n.onabort=function(e){try{var n=e.srcElement.error;n&&"QuotaExceededError"===n.name&&(i._hasReachedQuota=!0)}catch(e){}t(-1)},n.oncomplete=function(){t(i._manifestVersionFound)};var r={sceneUrl:e,data:this._manifestVersionFound},o=n.objectStore("versions").put(r);o.onsuccess=function(){},o.onerror=function(){m.a.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){m.a.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)},e.prototype.loadFile=function(t,i,n,r,o){var a=this,s=e._ReturnFullUrlLocation(t),c=function(){a._saveFileAsync(s,i,n,o,r)};this._checkVersionFromDB(s,function(e){-1!==e?a._mustUpdateRessources?a._saveFileAsync(s,i,n,o,r):a._loadFileAsync(s,i,c):r&&r()})},e.prototype._loadFileAsync=function(e,t,i){if(this._isSupported&&this._db){var n,r;n=-1!==e.indexOf(".babylon")?"scenes":"textures";var o=this._db.transaction([n]);o.oncomplete=function(){r?t(r.data):i()},o.onabort=function(){i()};var a=o.objectStore(n).get(e);a.onsuccess=function(e){r=e.target.result},a.onerror=function(){m.a.Error("Error loading file "+e+" from DB."),i()}}else m.a.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()},e.prototype._saveFileAsync=function(t,i,n,r,o){var a=this;if(this._isSupported){var s;s=-1!==t.indexOf(".babylon")?"scenes":"textures";var c,l=new ec.a;l.open("GET",t+"?"+Date.now()),r&&(l.responseType="arraybuffer"),n&&(l.onprogress=n),l.addEventListener("load",function(){if(200===l.status||l.status<400&&e._ValidateXHRData(l,r?6:1))if(c=r?l.response:l.responseText,!a._hasReachedQuota&&a._db){var n,u=a._db.transaction([s],"readwrite");u.onabort=function(e){try{var t=e.srcElement.error;t&&"QuotaExceededError"===t.name&&(a._hasReachedQuota=!0)}catch(e){}i(c)},u.oncomplete=function(){i(c)},n="scenes"===s?{sceneUrl:t,data:c,version:a._manifestVersionFound}:{textureUrl:t,data:c};try{var h=u.objectStore(s).put(n);h.onsuccess=function(){},h.onerror=function(){m.a.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){i(c)}}else i(c);else l.status>=400&&o?o(l):i()},!1),l.addEventListener("error",function(){m.a.Error("error on XHR request."),i()},!1),l.send()}else m.a.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),i()},e._ValidateXHRData=function(e,t){void 0===t&&(t=7);try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){var i=js.GetTGAHeader(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){var n=new Uint8Array(e.response,0,3);return 68===n[0]&&68===n[1]&&83===n[2]}}catch(e){}return!1},e.IsUASupportingBlobStorage=!0,e.IDBStorageEnabled=!1,e._ParseURL=function(e){document.createElement("a").href=e;var t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},e._ReturnFullUrlLocation=function(t){return-1===t.indexOf("http:/")&&-1===t.indexOf("https:/")?e._ParseURL(window.location.href)+t:t},e}(),Su=function(){function e(){this.direction1=new a.e(0,1,0),this.direction2=new a.e(0,1,0),this.minEmitBox=new a.e(-.5,-.5,-.5),this.maxEmitBox=new a.e(.5,.5,.5)}return e.prototype.startDirectionFunction=function(e,t,i,n){var r=L.a.RandomRange(this.direction1.x,this.direction2.x),o=L.a.RandomRange(this.direction1.y,this.direction2.y),s=L.a.RandomRange(this.direction1.z,this.direction2.z);if(n)return t.x=r,t.y=o,void(t.z=s);a.e.TransformNormalFromFloatsToRef(r,o,s,e,t)},e.prototype.startPositionFunction=function(e,t,i,n){var r=L.a.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),o=L.a.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),s=L.a.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(n)return t.x=r,t.y=o,void(t.z=s);a.e.TransformCoordinatesFromFloatsToRef(r,o,s,e,t)},e.prototype.clone=function(){var t=new e;return O.a.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)},e.prototype.getEffectDefines=function(){return"#define BOXEMITTER"},e.prototype.getClassName=function(){return"BoxParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e},e.prototype.parse=function(e){a.e.FromArrayToRef(e.direction1,0,this.direction1),a.e.FromArrayToRef(e.direction2,0,this.direction2),a.e.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),a.e.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)},e}(),Cu=function(){function e(e,t,i){void 0===e&&(e=1),void 0===t&&(t=Math.PI),void 0===i&&(i=0),this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}return Object.defineProperty(e.prototype,"radius",{get:function(){return this._radius},set:function(e){this._radius=e,this._buildHeight()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this._buildHeight()},enumerable:!0,configurable:!0}),e.prototype._buildHeight=function(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1},e.prototype.startDirectionFunction=function(e,t,i,n){if(1===Math.abs(Math.cos(this._angle))){if(n)return t.x=0,t.y=1,void(t.z=0);a.e.TransformNormalFromFloatsToRef(0,1,0,e,t)}else{var r=i.position.subtract(e.getTranslation()).normalize(),o=L.a.RandomRange(0,this.directionRandomizer),s=L.a.RandomRange(0,this.directionRandomizer),c=L.a.RandomRange(0,this.directionRandomizer);if(r.x+=o,r.y+=s,r.z+=c,r.normalize(),n)return void t.copyFrom(r);a.e.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}},e.prototype.startPositionFunction=function(e,t,i,n){var r,o=L.a.RandomRange(0,2*Math.PI);r=this.emitFromSpawnPointOnly?1e-4:1-(r=L.a.RandomRange(0,this.heightRange))*r;var s=this._radius-L.a.RandomRange(0,this._radius*this.radiusRange),c=(s*=r)*Math.sin(o),l=s*Math.cos(o),u=r*this._height;if(n)return t.x=c,t.y=u,void(t.z=l);a.e.TransformCoordinatesFromFloatsToRef(c,u,l,e,t)},e.prototype.clone=function(){var t=new e(this._radius,this._angle,this.directionRandomizer);return O.a.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)},e.prototype.getEffectDefines=function(){var e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e},e.prototype.getClassName=function(){return"ConeParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e},e.prototype.parse=function(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=e.radiusRange,this.heightRange=e.heightRange,this.emitFromSpawnPointOnly=e.emitFromSpawnPointOnly},e}(),Ru=function(){function e(e,t,i,n){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=1),void 0===n&&(n=0),this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=n}return e.prototype.startDirectionFunction=function(e,t,i,n){var r=i.position.subtract(e.getTranslation()).normalize(),o=L.a.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2),s=Math.atan2(r.x,r.z);s+=L.a.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,r.y=o,r.x=Math.sin(s),r.z=Math.cos(s),r.normalize(),n?t.copyFrom(r):a.e.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)},e.prototype.startPositionFunction=function(e,t,i,n){var r=L.a.RandomRange(-this.height/2,this.height/2),o=L.a.RandomRange(0,2*Math.PI),s=L.a.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),c=Math.sqrt(s)*this.radius,l=c*Math.cos(o),u=c*Math.sin(o);n?t.copyFromFloats(l,r,u):a.e.TransformCoordinatesFromFloatsToRef(l,r,u,e,t)},e.prototype.clone=function(){var t=new e(this.radius,this.directionRandomizer);return O.a.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},e.prototype.getEffectDefines=function(){return"#define CYLINDEREMITTER"},e.prototype.getClassName=function(){return"CylinderParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},e.prototype.parse=function(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},e}(),Ou=function(e){function t(t,i,n,r,o){void 0===t&&(t=1),void 0===i&&(i=1),void 0===n&&(n=1),void 0===r&&(r=new a.e(0,1,0)),void 0===o&&(o=new a.e(0,1,0));var s=e.call(this,t,i,n)||this;return s.direction1=r,s.direction2=o,s}return Object(h.d)(t,e),t.prototype.startDirectionFunction=function(e,t,i){var n=L.a.RandomRange(this.direction1.x,this.direction2.x),r=L.a.RandomRange(this.direction1.y,this.direction2.y),o=L.a.RandomRange(this.direction1.z,this.direction2.z);a.e.TransformNormalFromFloatsToRef(n,r,o,e,t)},t.prototype.clone=function(){var e=new t(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return O.a.DeepCopy(this,e),e},t.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},t.prototype.getEffectDefines=function(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"},t.prototype.getClassName=function(){return"CylinderDirectedParticleEmitter"},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t},t.prototype.parse=function(t){e.prototype.parse.call(this,t),this.direction1.copyFrom(t.direction1),this.direction2.copyFrom(t.direction2)},t}(Ru),Mu=function(){function e(e,t,i){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=0),this.radius=e,this.radiusRange=t,this.directionRandomizer=i}return e.prototype.startDirectionFunction=function(e,t,i,n){var r=i.position.subtract(e.getTranslation()).normalize(),o=L.a.RandomRange(0,this.directionRandomizer),s=L.a.RandomRange(0,this.directionRandomizer),c=L.a.RandomRange(0,this.directionRandomizer);r.x+=o,r.y+=s,r.z+=c,r.normalize(),n?t.copyFrom(r):a.e.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)},e.prototype.startPositionFunction=function(e,t,i,n){var r=this.radius-L.a.RandomRange(0,this.radius*this.radiusRange),o=L.a.RandomRange(0,1),s=L.a.RandomRange(0,2*Math.PI),c=Math.acos(2*o-1),l=r*Math.cos(s)*Math.sin(c),u=r*Math.cos(c),h=r*Math.sin(s)*Math.sin(c);n?t.copyFromFloats(l,Math.abs(u),h):a.e.TransformCoordinatesFromFloatsToRef(l,Math.abs(u),h,e,t)},e.prototype.clone=function(){var t=new e(this.radius,this.directionRandomizer);return O.a.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},e.prototype.getEffectDefines=function(){return"#define HEMISPHERICEMITTER"},e.prototype.getClassName=function(){return"HemisphericParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},e.prototype.parse=function(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},e}(),Iu=function(){function e(){this.direction1=new a.e(0,1,0),this.direction2=new a.e(0,1,0)}return e.prototype.startDirectionFunction=function(e,t,i,n){var r=L.a.RandomRange(this.direction1.x,this.direction2.x),o=L.a.RandomRange(this.direction1.y,this.direction2.y),s=L.a.RandomRange(this.direction1.z,this.direction2.z);n?t.copyFromFloats(r,o,s):a.e.TransformNormalFromFloatsToRef(r,o,s,e,t)},e.prototype.startPositionFunction=function(e,t,i,n){n?t.copyFromFloats(0,0,0):a.e.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)},e.prototype.clone=function(){var t=new e;return O.a.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},e.prototype.getEffectDefines=function(){return"#define POINTEMITTER"},e.prototype.getClassName=function(){return"PointParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e},e.prototype.parse=function(e){a.e.FromArrayToRef(e.direction1,0,this.direction1),a.e.FromArrayToRef(e.direction2,0,this.direction2)},e}(),Du=function(){function e(e,t,i){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=0),this.radius=e,this.radiusRange=t,this.directionRandomizer=i}return e.prototype.startDirectionFunction=function(e,t,i,n){var r=i.position.subtract(e.getTranslation()).normalize(),o=L.a.RandomRange(0,this.directionRandomizer),s=L.a.RandomRange(0,this.directionRandomizer),c=L.a.RandomRange(0,this.directionRandomizer);r.x+=o,r.y+=s,r.z+=c,r.normalize(),n?t.copyFrom(r):a.e.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)},e.prototype.startPositionFunction=function(e,t,i,n){var r=this.radius-L.a.RandomRange(0,this.radius*this.radiusRange),o=L.a.RandomRange(0,1),s=L.a.RandomRange(0,2*Math.PI),c=Math.acos(2*o-1),l=r*Math.cos(s)*Math.sin(c),u=r*Math.cos(c),h=r*Math.sin(s)*Math.sin(c);n?t.copyFromFloats(l,u,h):a.e.TransformCoordinatesFromFloatsToRef(l,u,h,e,t)},e.prototype.clone=function(){var t=new e(this.radius,this.directionRandomizer);return O.a.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},e.prototype.getEffectDefines=function(){return"#define SPHEREEMITTER"},e.prototype.getClassName=function(){return"SphereParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},e.prototype.parse=function(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},e}(),wu=function(e){function t(t,i,n){void 0===t&&(t=1),void 0===i&&(i=new a.e(0,1,0)),void 0===n&&(n=new a.e(0,1,0));var r=e.call(this,t)||this;return r.direction1=i,r.direction2=n,r}return Object(h.d)(t,e),t.prototype.startDirectionFunction=function(e,t,i){var n=L.a.RandomRange(this.direction1.x,this.direction2.x),r=L.a.RandomRange(this.direction1.y,this.direction2.y),o=L.a.RandomRange(this.direction1.z,this.direction2.z);a.e.TransformNormalFromFloatsToRef(n,r,o,e,t)},t.prototype.clone=function(){var e=new t(this.radius,this.direction1,this.direction2);return O.a.DeepCopy(this,e),e},t.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},t.prototype.getEffectDefines=function(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"},t.prototype.getClassName=function(){return"SphereDirectedParticleEmitter"},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t},t.prototype.parse=function(t){e.prototype.parse.call(this,t),this.direction1.copyFrom(t.direction1),this.direction2.copyFrom(t.direction2)},t}(Du),Lu=function(){function e(){this.particlePositionGenerator=function(){},this.particleDestinationGenerator=function(){}}return e.prototype.startDirectionFunction=function(e,t,i,n){var r=a.c.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,r);var o=a.c.Vector3[1];r.subtractToRef(i.position,o),o.scaleToRef(1/i.lifeTime,r)}else r.set(0,0,0);n?t.copyFrom(r):a.e.TransformNormalToRef(r,e,t)},e.prototype.startPositionFunction=function(e,t,i,n){var r=a.c.Vector3[0];this.particlePositionGenerator?this.particlePositionGenerator(-1,i,r):r.set(0,0,0),n?t.copyFrom(r):a.e.TransformCoordinatesToRef(r,e,t)},e.prototype.clone=function(){var t=new e;return O.a.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){},e.prototype.getEffectDefines=function(){return"#define CUSTOMEMITTER"},e.prototype.getClassName=function(){return"CustomParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e},e.prototype.parse=function(e){},e}(),Nu=function(){function e(e){this.mesh=e,this._indices=null,this._positions=null,this._normals=null,this._storedNormal=a.e.Zero(),this.direction1=new a.e(0,1,0),this.direction2=new a.e(0,1,0),this.useMeshNormalsForDirection=!0,e&&(this._indices=e.getIndices(),this._positions=e.getVerticesData(en.b.PositionKind),this._normals=e.getVerticesData(en.b.NormalKind))}return e.prototype.startDirectionFunction=function(e,t,i,n){if(this.useMeshNormalsForDirection&&this._normals)a.e.TransformNormalToRef(this._storedNormal,e,t);else{var r=L.a.RandomRange(this.direction1.x,this.direction2.x),o=L.a.RandomRange(this.direction1.y,this.direction2.y),s=L.a.RandomRange(this.direction1.z,this.direction2.z);n?t.copyFromFloats(r,o,s):a.e.TransformNormalFromFloatsToRef(r,o,s,e,t)}},e.prototype.startPositionFunction=function(e,t,i,n){if(this._indices&&this._positions){var r=3*Math.random()*(this._indices.length/3)|0,o=Math.random(),s=Math.random()*(1-o),c=1-o-s,l=this._indices[r],u=this._indices[r+1],h=this._indices[r+2],d=a.c.Vector3[0],f=a.c.Vector3[1],p=a.c.Vector3[2],_=a.c.Vector3[3];a.e.FromArrayToRef(this._positions,3*l,d),a.e.FromArrayToRef(this._positions,3*u,f),a.e.FromArrayToRef(this._positions,3*h,p),_.x=o*d.x+s*f.x+c*p.x,_.y=o*d.y+s*f.y+c*p.y,_.z=o*d.z+s*f.z+c*p.z,n?t.copyFromFloats(_.x,_.y,_.z):a.e.TransformCoordinatesFromFloatsToRef(_.x,_.y,_.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(a.e.FromArrayToRef(this._normals,3*l,d),a.e.FromArrayToRef(this._normals,3*u,f),a.e.FromArrayToRef(this._normals,3*h,p),this._storedNormal.x=o*d.x+s*f.x+c*p.x,this._storedNormal.y=o*d.y+s*f.y+c*p.y,this._storedNormal.z=o*d.z+s*f.z+c*p.z)}},e.prototype.clone=function(){var t=new e(this.mesh);return O.a.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},e.prototype.getEffectDefines=function(){return""},e.prototype.getClassName=function(){return"MeshParticleEmitter"},e.prototype.serialize=function(){var e,t={};return t.type=this.getClassName(),t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t.meshId=null===(e=this.mesh)||void 0===e?void 0:e.id,t.useMeshNormalsForDirection=this.useMeshNormalsForDirection,t},e.prototype.parse=function(e,t){a.e.FromArrayToRef(e.direction1,0,this.direction1),a.e.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&(this.mesh=t.getLastMeshByID(e.meshId)||void 0),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection},e}(),Fu=function(){function e(t){this.animations=[],this.renderingGroupId=0,this.emitter=a.e.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this.noiseStrength=new a.e(10,10,10),this.onAnimationEnd=null,this.blendMode=e.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteRandomStartCell=!1,this.translationPivot=new a.d(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new a.e(0,0,0),this.gravity=a.e.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new s.b(1,1,1,1),this.color2=new s.b(1,1,1,1),this.colorDead=new s.b(0,0,0,1),this.textureMask=new s.b(1,1,1,1),this._isSubEmitter=!1,this.billboardMode=g.a.PARTICLES_BILLBOARDMODE_ALL,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new Yi.b,this.id=t,this.name=t}return Object.defineProperty(e.prototype,"noiseTexture",{get:function(){return this._noiseTexture},set:function(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isAnimationSheetEnabled",{get:function(){return this._isAnimationSheetEnabled},set:function(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())},enumerable:!0,configurable:!0}),e.prototype.getScene=function(){return this._scene},e.prototype._hasTargetStopDurationDependantGradient=function(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0},e.prototype.getDragGradients=function(){return this._dragGradients},e.prototype.getLimitVelocityGradients=function(){return this._limitVelocityGradients},e.prototype.getColorGradients=function(){return this._colorGradients},e.prototype.getSizeGradients=function(){return this._sizeGradients},e.prototype.getColorRemapGradients=function(){return this._colorRemapGradients},e.prototype.getAlphaRemapGradients=function(){return this._alphaRemapGradients},e.prototype.getLifeTimeGradients=function(){return this._lifeTimeGradients},e.prototype.getAngularSpeedGradients=function(){return this._angularSpeedGradients},e.prototype.getVelocityGradients=function(){return this._velocityGradients},e.prototype.getStartSizeGradients=function(){return this._startSizeGradients},e.prototype.getEmitRateGradients=function(){return this._emitRateGradients},Object.defineProperty(e.prototype,"direction1",{get:function(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:a.e.Zero()},set:function(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"direction2",{get:function(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:a.e.Zero()},set:function(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"minEmitBox",{get:function(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:a.e.Zero()},set:function(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maxEmitBox",{get:function(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:a.e.Zero()},set:function(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isBillboardBased",{get:function(){return this._isBillboardBased},set:function(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e)},enumerable:!0,configurable:!0}),e.prototype._attachImageProcessingConfiguration=function(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration=e||this._scene.imageProcessingConfiguration)},e.prototype._reset=function(){},e.prototype._removeGradientAndTexture=function(e,t,i){if(!t)return this;for(var n=0,r=0,o=t;r<o.length;r++){if(o[r].gradient===e){t.splice(n,1);break}n++}return i&&i.dispose(),this},e.prototype.createPointEmitter=function(e,t){var i=new Iu;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i},e.prototype.createHemisphericEmitter=function(e,t){void 0===e&&(e=1),void 0===t&&(t=1);var i=new Mu(e,t);return this.particleEmitterType=i,i},e.prototype.createSphereEmitter=function(e,t){void 0===e&&(e=1),void 0===t&&(t=1);var i=new Du(e,t);return this.particleEmitterType=i,i},e.prototype.createDirectedSphereEmitter=function(e,t,i){void 0===e&&(e=1),void 0===t&&(t=new a.e(0,1,0)),void 0===i&&(i=new a.e(0,1,0));var n=new wu(e,t,i);return this.particleEmitterType=n,n},e.prototype.createCylinderEmitter=function(e,t,i,n){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=1),void 0===n&&(n=0);var r=new Ru(e,t,i,n);return this.particleEmitterType=r,r},e.prototype.createDirectedCylinderEmitter=function(e,t,i,n,r){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=1),void 0===n&&(n=new a.e(0,1,0)),void 0===r&&(r=new a.e(0,1,0));var o=new Ou(e,t,i,n,r);return this.particleEmitterType=o,o},e.prototype.createConeEmitter=function(e,t){void 0===e&&(e=1),void 0===t&&(t=Math.PI/4);var i=new Cu(e,t);return this.particleEmitterType=i,i},e.prototype.createBoxEmitter=function(e,t,i,n){var r=new Su;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=n,r},e.BLENDMODE_ONEONE=0,e.BLENDMODE_STANDARD=1,e.BLENDMODE_ADD=2,e.BLENDMODE_MULTIPLY=3,e.BLENDMODE_MULTIPLYADD=4,e}(),Bu=function(){function e(){}return e.prototype.getColorToRef=function(e){this.color2?s.b.LerpToRef(this.color1,this.color2,Math.random(),e):e.copyFrom(this.color1)},e}(),Uu=function(){},Vu=function(){function e(){}return e.prototype.getFactor=function(){return void 0===this.factor2?this.factor1:this.factor1+(this.factor2-this.factor1)*Math.random()},e}(),ku=function(){function e(){}return e.GetCurrentGradient=function(e,t,i){for(var n=0;n<t.length-1;n++){var r=t[n],o=t[n+1];if(e>=r.gradient&&e<=o.gradient)return void i(r,o,(e-r.gradient)/(o.gradient-r.gradient))}var a=t.length-1;i(t[a],t[a],1)},e}(),zu=function(){function e(t){this.particleSystem=t,this.position=a.e.Zero(),this.direction=a.e.Zero(),this.color=new s.b(0,0,0,0),this.colorStep=new s.b(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new a.d(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new s.b(0,0,0,0),this._currentColor2=new s.b(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=e._Count++,this.particleSystem.isAnimationSheetEnabled&&this.updateCellInfoFromSystem()}return e.prototype.updateCellInfoFromSystem=function(){this.cellIndex=this.particleSystem.startSpriteCellID},e.prototype.updateCellIndex=function(){var e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===t?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);var i=this._initialEndSpriteCellID-this._initialStartSpriteCellID,n=L.a.Clamp(e*t%this.lifeTime/this.lifeTime);this.cellIndex=this._initialStartSpriteCellID+n*i|0},e.prototype._inheritParticleInfoToSubEmitter=function(e){if(e.particleSystem.emitter.position){var t=e.particleSystem.emitter;t.position.copyFrom(this.position),e.inheritDirection&&t.setDirection(this.direction.normalize(),0,Math.PI/2)}else{e.particleSystem.emitter.copyFrom(this.position)}this.direction.scaleToRef(e.inheritedVelocityAmount/2,a.c.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(a.c.Vector3[0])},e.prototype._inheritParticleInfoToSubEmitters=function(){var e=this;this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(function(t){e._inheritParticleInfoToSubEmitter(t)})},e.prototype._reset=function(){this.age=0,this.id=e._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0},e.prototype.copyTo=function(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID),this.particleSystem.useRampGradients&&e.remapData.copyFrom(this.remapData),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))},e._Count=0,e}();!function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(Pu||(Pu={}));var Gu=function(){function e(e){this.particleSystem=e,this.type=Pu.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,e.emitter&&e.emitter.dispose||(e.emitter=new Ke.a("SubemitterSystemEmitter",e.getScene())),e.onDisposeObservable.add(function(){e.emitter&&e.emitter.dispose&&e.emitter.dispose()})}return e.prototype.clone=function(){var t=this.particleSystem.emitter;t?t instanceof a.e?t=t.clone():t instanceof Ke.a&&((t=new Ae.a("",t.getScene())).isVisible=!1):t=new a.e;var i=new e(this.particleSystem.clone("",t));return i.particleSystem.name+="Clone",i.type=this.type,i.inheritDirection=this.inheritDirection,i.inheritedVelocityAmount=this.inheritedVelocityAmount,i.particleSystem._disposeEmitterOnDispose=!0,i.particleSystem.disposeOnStop=!0,i},e.prototype.serialize=function(){var e={};return e.type=this.type,e.inheritDirection=this.inheritDirection,e.inheritedVelocityAmount=this.inheritedVelocityAmount,e.particleSystem=this.particleSystem.serialize(),e},e._ParseParticleSystem=function(e,t,i){throw we.a.WarnImport("ParseParticle")},e.Parse=function(t,i,n){var r=t.particleSystem,o=new e(e._ParseParticleSystem(r,i,n));return o.type=t.type,o.inheritDirection=t.inheritDirection,o.inheritedVelocityAmount=t.inheritedVelocityAmount,o.particleSystem._isSubEmitter=!0,o},e.prototype.dispose=function(){this.particleSystem.dispose()},e}(),ju="\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}";ai.a.ShadersStore.particlesPixelShader=ju;var Wu="\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos;\n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#endif\nvoid main(void) {\nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD\n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition;\nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0);\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0);\n#endif\nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}";ai.a.ShadersStore.particlesVertexShader=Wu;var Xu=function(e){function t(t,i,n,r,c,l){void 0===r&&(r=null),void 0===c&&(c=!1),void 0===l&&(l=.01);var u=e.call(this,t)||this;return u._inheritedVelocityOffset=new a.e,u.onDisposeObservable=new o.c,u._particles=new Array,u._stockParticles=new Array,u._newPartsExcess=0,u._vertexBuffers={},u._scaledColorStep=new s.b(0,0,0,0),u._colorDiff=new s.b(0,0,0,0),u._scaledDirection=a.e.Zero(),u._scaledGravity=a.e.Zero(),u._currentRenderId=-1,u._useInstancing=!1,u._started=!1,u._stopped=!1,u._actualFrame=0,u._currentEmitRate1=0,u._currentEmitRate2=0,u._currentStartSize1=0,u._currentStartSize2=0,u._rawTextureWidth=256,u._useRampGradients=!1,u._disposeEmitterOnDispose=!1,u.isLocal=!1,u.recycleParticle=function(e){var t=u._particles.pop();t!==e&&t.copyTo(e),u._stockParticles.push(t)},u._createParticle=function(){var e;if(0!==u._stockParticles.length?(e=u._stockParticles.pop())._reset():e=new zu(u),u._subEmitters&&u._subEmitters.length>0){var t=u._subEmitters[Math.floor(Math.random()*u._subEmitters.length)];e._attachedSubEmitters=[],t.forEach(function(t){if(t.type===Pu.ATTACHED){var i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}})}return e},u._emitFromParticle=function(e){if(u._subEmitters&&0!==u._subEmitters.length){var t=Math.floor(Math.random()*u._subEmitters.length);u._subEmitters[t].forEach(function(t){if(t.type===Pu.END){var i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=u,u.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}})}},u._capacity=i,u._epsilon=l,u._isAnimationSheetEnabled=c,u._scene=n||R.a.LastCreatedScene,u._attachImageProcessingConfiguration(null),u._customEffect=r,u._scene.particleSystems.push(u),u._useInstancing=u._scene.getEngine().getCaps().instancedArrays,u._createIndexBuffer(),u._createVertexBuffers(),u.particleEmitterType=new Su,u.updateFunction=function(e){var t=null,i=null;u.noiseTexture&&(t=u.noiseTexture.getSize(),i=u.noiseTexture.getContent());for(var n,r=function(){n=e[o];var r=u._scaledUpdateSpeed,c=n.age;if(n.age+=r,n.age>n.lifeTime){var l=n.age-c;r=(n.lifeTime-c)*r/l,n.age=n.lifeTime}var h=n.age/n.lifeTime;u._colorGradients&&u._colorGradients.length>0?ku.GetCurrentGradient(h,u._colorGradients,function(e,t,i){e!==n._currentColorGradient&&(n._currentColor1.copyFrom(n._currentColor2),t.getColorToRef(n._currentColor2),n._currentColorGradient=e),s.b.LerpToRef(n._currentColor1,n._currentColor2,i,n.color)}):(n.colorStep.scaleToRef(r,u._scaledColorStep),n.color.addInPlace(u._scaledColorStep),n.color.a<0&&(n.color.a=0)),u._angularSpeedGradients&&u._angularSpeedGradients.length>0&&ku.GetCurrentGradient(h,u._angularSpeedGradients,function(e,t,i){e!==n._currentAngularSpeedGradient&&(n._currentAngularSpeed1=n._currentAngularSpeed2,n._currentAngularSpeed2=t.getFactor(),n._currentAngularSpeedGradient=e),n.angularSpeed=L.a.Lerp(n._currentAngularSpeed1,n._currentAngularSpeed2,i)}),n.angle+=n.angularSpeed*r;var d=r;if(u._velocityGradients&&u._velocityGradients.length>0&&ku.GetCurrentGradient(h,u._velocityGradients,function(e,t,i){e!==n._currentVelocityGradient&&(n._currentVelocity1=n._currentVelocity2,n._currentVelocity2=t.getFactor(),n._currentVelocityGradient=e),d*=L.a.Lerp(n._currentVelocity1,n._currentVelocity2,i)}),n.direction.scaleToRef(d,u._scaledDirection),u._limitVelocityGradients&&u._limitVelocityGradients.length>0&&ku.GetCurrentGradient(h,u._limitVelocityGradients,function(e,t,i){e!==n._currentLimitVelocityGradient&&(n._currentLimitVelocity1=n._currentLimitVelocity2,n._currentLimitVelocity2=t.getFactor(),n._currentLimitVelocityGradient=e);var r=L.a.Lerp(n._currentLimitVelocity1,n._currentLimitVelocity2,i);n.direction.length()>r&&n.direction.scaleInPlace(u.limitVelocityDamping)}),u._dragGradients&&u._dragGradients.length>0&&ku.GetCurrentGradient(h,u._dragGradients,function(e,t,i){e!==n._currentDragGradient&&(n._currentDrag1=n._currentDrag2,n._currentDrag2=t.getFactor(),n._currentDragGradient=e);var r=L.a.Lerp(n._currentDrag1,n._currentDrag2,i);u._scaledDirection.scaleInPlace(1-r)}),u.isLocal?(n._localPosition.addInPlace(u._scaledDirection),a.e.TransformCoordinatesToRef(n._localPosition,u._emitterWorldMatrix,n.position)):n.position.addInPlace(u._scaledDirection),i&&t&&n._randomNoiseCoordinates1){var f=u._fetchR(n._randomNoiseCoordinates1.x,n._randomNoiseCoordinates1.y,t.width,t.height,i),p=u._fetchR(n._randomNoiseCoordinates1.z,n._randomNoiseCoordinates2.x,t.width,t.height,i),_=u._fetchR(n._randomNoiseCoordinates2.y,n._randomNoiseCoordinates2.z,t.width,t.height,i),m=a.c.Vector3[0],g=a.c.Vector3[1];m.copyFromFloats((2*f-1)*u.noiseStrength.x,(2*p-1)*u.noiseStrength.y,(2*_-1)*u.noiseStrength.z),m.scaleToRef(r,g),n.direction.addInPlace(g)}if(u.gravity.scaleToRef(r,u._scaledGravity),n.direction.addInPlace(u._scaledGravity),u._sizeGradients&&u._sizeGradients.length>0&&ku.GetCurrentGradient(h,u._sizeGradients,function(e,t,i){e!==n._currentSizeGradient&&(n._currentSize1=n._currentSize2,n._currentSize2=t.getFactor(),n._currentSizeGradient=e),n.size=L.a.Lerp(n._currentSize1,n._currentSize2,i)}),u._useRampGradients&&(u._colorRemapGradients&&u._colorRemapGradients.length>0&&ku.GetCurrentGradient(h,u._colorRemapGradients,function(e,t,i){var r=L.a.Lerp(e.factor1,t.factor1,i),o=L.a.Lerp(e.factor2,t.factor2,i);n.remapData.x=r,n.remapData.y=o-r}),u._alphaRemapGradients&&u._alphaRemapGradients.length>0&&ku.GetCurrentGradient(h,u._alphaRemapGradients,function(e,t,i){var r=L.a.Lerp(e.factor1,t.factor1,i),o=L.a.Lerp(e.factor2,t.factor2,i);n.remapData.z=r,n.remapData.w=o-r})),u._isAnimationSheetEnabled&&n.updateCellIndex(),n._inheritParticleInfoToSubEmitters(),n.age>=n.lifeTime)return u._emitFromParticle(n),n._attachedSubEmitters&&(n._attachedSubEmitters.forEach(function(e){e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()}),n._attachedSubEmitters=null),u.recycleParticle(n),o--,"continue"},o=0;o<e.length;o++)r()},u}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useRampGradients",{get:function(){return this._useRampGradients},set:function(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"particles",{get:function(){return this._particles},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"ParticleSystem"},t.prototype._addFactorGradient=function(e,t,i,n){var r=new Vu;r.gradient=t,r.factor1=i,r.factor2=n,e.push(r),e.sort(function(e,t){return e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0})},t.prototype._removeFactorGradient=function(e,t){if(e)for(var i=0,n=0,r=e;n<r.length;n++){if(r[n].gradient===t){e.splice(i,1);break}i++}},t.prototype.addLifeTimeGradient=function(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this},t.prototype.removeLifeTimeGradient=function(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this},t.prototype.addSizeGradient=function(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this},t.prototype.removeSizeGradient=function(e){return this._removeFactorGradient(this._sizeGradients,e),this},t.prototype.addColorRemapGradient=function(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this},t.prototype.removeColorRemapGradient=function(e){return this._removeFactorGradient(this._colorRemapGradients,e),this},t.prototype.addAlphaRemapGradient=function(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this},t.prototype.removeAlphaRemapGradient=function(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this},t.prototype.addAngularSpeedGradient=function(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this},t.prototype.removeAngularSpeedGradient=function(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this},t.prototype.addVelocityGradient=function(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this},t.prototype.removeVelocityGradient=function(e){return this._removeFactorGradient(this._velocityGradients,e),this},t.prototype.addLimitVelocityGradient=function(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this},t.prototype.removeLimitVelocityGradient=function(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this},t.prototype.addDragGradient=function(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this},t.prototype.removeDragGradient=function(e){return this._removeFactorGradient(this._dragGradients,e),this},t.prototype.addEmitRateGradient=function(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this},t.prototype.removeEmitRateGradient=function(e){return this._removeFactorGradient(this._emitRateGradients,e),this},t.prototype.addStartSizeGradient=function(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this},t.prototype.removeStartSizeGradient=function(e){return this._removeFactorGradient(this._emitRateGradients,e),this},t.prototype._createRampGradientTexture=function(){if(this._rampGradients&&this._rampGradients.length&&!this._rampGradientsTexture){for(var e=new Uint8Array(4*this._rawTextureWidth),t=s.c.Color3[0],i=0;i<this._rawTextureWidth;i++){var n=i/this._rawTextureWidth;ku.GetCurrentGradient(n,this._rampGradients,function(n,r,o){s.a.LerpToRef(n.color,r.color,o,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255})}this._rampGradientsTexture=rt.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,et.a.NEAREST_SAMPLINGMODE)}},t.prototype.getRampGradients=function(){return this._rampGradients},t.prototype.addRampGradient=function(e,t){this._rampGradients||(this._rampGradients=[]);var i=new Uu;return i.gradient=e,i.color=t,this._rampGradients.push(i),this._rampGradients.sort(function(e,t){return e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0}),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture(),this},t.prototype.removeRampGradient=function(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this},t.prototype.addColorGradient=function(e,t,i){this._colorGradients||(this._colorGradients=[]);var n=new Bu;return n.gradient=e,n.color1=t,n.color2=i,this._colorGradients.push(n),this._colorGradients.sort(function(e,t){return e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0}),this},t.prototype.removeColorGradient=function(e){if(!this._colorGradients)return this;for(var t=0,i=0,n=this._colorGradients;i<n.length;i++){if(n[i].gradient===e){this._colorGradients.splice(t,1);break}t++}return this},t.prototype._fetchR=function(e,t,i,n,r){return r[4*(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*n%n|0)*i)]/255},t.prototype._reset=function(){this._resetEffect()},t.prototype._resetEffect=function(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._createVertexBuffers()},t.prototype._createVertexBuffers=function(){this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&this.billboardMode!==t.BILLBOARDMODE_STRETCHED||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);var e=this._scene.getEngine();this._vertexData=new Float32Array(this._capacity*this._vertexBufferSize*(this._useInstancing?1:4)),this._vertexBuffer=new en.a(e,this._vertexData,!0,this._vertexBufferSize);var i=0,n=this._vertexBuffer.createVertexBuffer(en.b.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[en.b.PositionKind]=n,i+=3;var r=this._vertexBuffer.createVertexBuffer(en.b.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[en.b.ColorKind]=r,i+=4;var o=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=o,i+=1;var a,s=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=s,i+=2,this._isAnimationSheetEnabled){var c=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=c,i+=1}if(!this._isBillboardBased||this.billboardMode===t.BILLBOARDMODE_STRETCHED){var l=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=l,i+=3}if(this._useRampGradients){var u=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=u,i+=4}if(this._useInstancing){var h=new Float32Array([0,0,1,0,1,1,0,1]);this._spriteBuffer=new en.a(e,h,!1,2),a=this._spriteBuffer.createVertexBuffer("offset",0,2)}else a=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=a},t.prototype._createIndexBuffer=function(){if(!this._useInstancing){for(var e=[],t=0,i=0;i<this._capacity;i++)e.push(t),e.push(t+1),e.push(t+2),e.push(t),e.push(t+2),e.push(t+3),t+=4;this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}},t.prototype.getCapacity=function(){return this._capacity},t.prototype.isAlive=function(){return this._alive},t.prototype.isStarted=function(){return this._started},t.prototype._prepareSubEmitterInternalArray=function(){var e=this;this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach(function(i){i instanceof t?e._subEmitters.push([new Gu(i)]):i instanceof Gu?e._subEmitters.push([i]):i instanceof Array&&e._subEmitters.push(i)})},t.prototype.start=function(e){var t=this;if(void 0===e&&(e=this.startDelay),!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e)setTimeout(function(){t.start(0)},e);else{if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=new Array),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){this.emitter instanceof Ke.a&&this.emitter.computeWorldMatrix(!0);var i=this.noiseTexture;if(i&&i.onGeneratedObservable)i.onGeneratedObservable.addOnce(function(){setTimeout(function(){for(var e=0;e<t.preWarmCycles;e++)t.animate(!0),i.render()})});else for(var n=0;n<this.preWarmCycles;n++)this.animate(!0)}this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this.getScene().beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}},t.prototype.stop=function(e){void 0===e&&(e=!0),this._stopped=!0,e&&this._stopSubEmitters()},t.prototype.reset=function(){this._stockParticles=[],this._particles=[]},t.prototype._appendParticleVertex=function(e,i,n,r){var o=e*this._vertexBufferSize;if(this._vertexData[o++]=i.position.x+this.worldOffset.x,this._vertexData[o++]=i.position.y+this.worldOffset.y,this._vertexData[o++]=i.position.z+this.worldOffset.z,this._vertexData[o++]=i.color.r,this._vertexData[o++]=i.color.g,this._vertexData[o++]=i.color.b,this._vertexData[o++]=i.color.a,this._vertexData[o++]=i.angle,this._vertexData[o++]=i.scale.x*i.size,this._vertexData[o++]=i.scale.y*i.size,this._isAnimationSheetEnabled&&(this._vertexData[o++]=i.cellIndex),this._isBillboardBased)this.billboardMode===t.BILLBOARDMODE_STRETCHED&&(this._vertexData[o++]=i.direction.x,this._vertexData[o++]=i.direction.y,this._vertexData[o++]=i.direction.z);else if(i._initialDirection){var s=i._initialDirection;this.isLocal&&(a.e.TransformNormalToRef(s,this._emitterWorldMatrix,a.c.Vector3[0]),s=a.c.Vector3[0]),0===s.x&&0===s.z&&(s.x=.001),this._vertexData[o++]=s.x,this._vertexData[o++]=s.y,this._vertexData[o++]=s.z}else{var c=i.direction;this.isLocal&&(a.e.TransformNormalToRef(c,this._emitterWorldMatrix,a.c.Vector3[0]),c=a.c.Vector3[0]),0===c.x&&0===c.z&&(c.x=.001),this._vertexData[o++]=c.x,this._vertexData[o++]=c.y,this._vertexData[o++]=c.z}this._useRampGradients&&(this._vertexData[o++]=i.remapData.x,this._vertexData[o++]=i.remapData.y,this._vertexData[o++]=i.remapData.z,this._vertexData[o++]=i.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===n?n=this._epsilon:1===n&&(n=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon)),this._vertexData[o++]=n,this._vertexData[o++]=r)},t.prototype._stopSubEmitters=function(){this.activeSubSystems&&(this.activeSubSystems.forEach(function(e){e.stop(!0)}),this.activeSubSystems=new Array)},t.prototype._removeFromRoot=function(){if(this._rootParticleSystem){var e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}},t.prototype._update=function(e){var t,i=this;if(this._alive=this._particles.length>0,this.emitter.position){var n=this.emitter;this._emitterWorldMatrix=n.getWorldMatrix()}else{var r=this.emitter;this._emitterWorldMatrix=a.a.Translation(r.x,r.y,r.z)}this.updateFunction(this._particles);for(var o,c=function(){if(l._particles.length===l._capacity)return"break";if(t=l._createParticle(),l._particles.push(t),l.targetStopDuration&&l._lifeTimeGradients&&l._lifeTimeGradients.length>0){var e=L.a.Clamp(l._actualFrame/l.targetStopDuration);ku.GetCurrentGradient(e,l._lifeTimeGradients,function(i,n){var r=i,o=n,a=r.getFactor(),s=o.getFactor(),c=(e-r.gradient)/(o.gradient-r.gradient);t.lifeTime=L.a.Lerp(a,s,c)})}else t.lifeTime=L.a.RandomRange(l.minLifeTime,l.maxLifeTime);var n=L.a.RandomRange(l.minEmitPower,l.maxEmitPower);if(l.startPositionFunction?l.startPositionFunction(l._emitterWorldMatrix,t.position,t,l.isLocal):l.particleEmitterType.startPositionFunction(l._emitterWorldMatrix,t.position,t,l.isLocal),l.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),a.e.TransformCoordinatesToRef(t._localPosition,l._emitterWorldMatrix,t.position)),l.startDirectionFunction?l.startDirectionFunction(l._emitterWorldMatrix,t.direction,t,l.isLocal):l.particleEmitterType.startDirectionFunction(l._emitterWorldMatrix,t.direction,t,l.isLocal),0===n?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(n),l._sizeGradients&&0!==l._sizeGradients.length?(t._currentSizeGradient=l._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,l._sizeGradients.length>1?t._currentSize2=l._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=L.a.RandomRange(l.minSize,l.maxSize),t.scale.copyFromFloats(L.a.RandomRange(l.minScaleX,l.maxScaleX),L.a.RandomRange(l.minScaleY,l.maxScaleY)),l._startSizeGradients&&l._startSizeGradients[0]&&l.targetStopDuration){var r=l._actualFrame/l.targetStopDuration;ku.GetCurrentGradient(r,l._startSizeGradients,function(e,n,r){e!==i._currentStartSizeGradient&&(i._currentStartSize1=i._currentStartSize2,i._currentStartSize2=n.getFactor(),i._currentStartSizeGradient=e);var o=L.a.Lerp(i._currentStartSize1,i._currentStartSize2,r);t.scale.scaleInPlace(o)})}l._angularSpeedGradients&&0!==l._angularSpeedGradients.length?(t._currentAngularSpeedGradient=l._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,l._angularSpeedGradients.length>1?t._currentAngularSpeed2=l._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=L.a.RandomRange(l.minAngularSpeed,l.maxAngularSpeed),t.angle=L.a.RandomRange(l.minInitialRotation,l.maxInitialRotation),l._velocityGradients&&l._velocityGradients.length>0&&(t._currentVelocityGradient=l._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),l._velocityGradients.length>1?t._currentVelocity2=l._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),l._limitVelocityGradients&&l._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=l._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),l._limitVelocityGradients.length>1?t._currentLimitVelocity2=l._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),l._dragGradients&&l._dragGradients.length>0&&(t._currentDragGradient=l._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),l._dragGradients.length>1?t._currentDrag2=l._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),l._colorGradients&&0!==l._colorGradients.length?(t._currentColorGradient=l._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),l._colorGradients.length>1?l._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color)):(o=L.a.RandomRange(0,1),s.b.LerpToRef(l.color1,l.color2,o,t.color),l.colorDead.subtractToRef(t.color,l._colorDiff),l._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)),l._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=l.startSpriteCellID,t._initialEndSpriteCellID=l.endSpriteCellID),t.direction.addInPlace(l._inheritedVelocityOffset),l._useRampGradients&&(t.remapData=new a.f(0,1,0,1)),l.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new a.e(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new a.e(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()},l=this,u=0;u<e;u++){if("break"===c())break}},t._GetAttributeNamesOrOptions=function(e,t,i){void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1);var n=[en.b.PositionKind,en.b.ColorKind,"angle","offset","size"];return e&&n.push("cellIndex"),t||n.push("direction"),i&&n.push("remapData"),n},t._GetEffectCreationOptions=function(e){void 0===e&&(e=!1);var t=["invView","view","projection","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","textureMask","translationPivot","eyePosition"];return e&&t.push("particlesInfos"),t},t.prototype._getEffect=function(e){if(this._customEffect)return this._customEffect;var i=[];if(this._scene.clipPlane&&i.push("#define CLIPPLANE"),this._scene.clipPlane2&&i.push("#define CLIPPLANE2"),this._scene.clipPlane3&&i.push("#define CLIPPLANE3"),this._scene.clipPlane4&&i.push("#define CLIPPLANE4"),this._scene.clipPlane5&&i.push("#define CLIPPLANE5"),this._scene.clipPlane6&&i.push("#define CLIPPLANE6"),this._isAnimationSheetEnabled&&i.push("#define ANIMATESHEET"),e===t.BLENDMODE_MULTIPLY&&i.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&i.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(i.push("#define BILLBOARD"),this.billboardMode){case t.BILLBOARDMODE_Y:i.push("#define BILLBOARDY");break;case t.BILLBOARDMODE_STRETCHED:i.push("#define BILLBOARDSTRETCHED");break;case t.BILLBOARDMODE_ALL:}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),i.push(this._imageProcessingConfigurationDefines.toString()));var n=i.join("\n");if(this._cachedDefines!==n){this._cachedDefines=n;var r=t._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==t.BILLBOARDMODE_STRETCHED,this._useRampGradients),o=t._GetEffectCreationOptions(this._isAnimationSheetEnabled),a=["diffuseSampler","rampSampler"];Yi.a&&(Yi.a.PrepareUniforms(o,this._imageProcessingConfigurationDefines),Yi.a.PrepareSamplers(a,this._imageProcessingConfigurationDefines)),this._effect=this._scene.getEngine().createEffect("particles",r,o,a,n)}return this._effect},t.prototype.animate=function(e){var t=this;if(void 0===e&&(e=!1),this._started){if(!e){if(!this.isReady())return;if(this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}var i;if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:this._scene.getAnimationRatio()),this.manualEmitCount>-1)i=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{var n=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){var r=this._actualFrame/this.targetStopDuration;ku.GetCurrentGradient(r,this._emitRateGradients,function(e,i,r){e!==t._currentEmitRateGradient&&(t._currentEmitRate1=t._currentEmitRate2,t._currentEmitRate2=i.getFactor(),t._currentEmitRateGradient=e),n=L.a.Lerp(t._currentEmitRate1,t._currentEmitRate2,r)})}i=n*this._scaledUpdateSpeed>>0,this._newPartsExcess+=n*this._scaledUpdateSpeed-i}if(this._newPartsExcess>1&&(i+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?i=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(i),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene._toBeDisposed.push(this))),!e){for(var o=0,a=0;a<this._particles.length;a++){var s=this._particles[a];this._appendParticleVertices(o,s),o+=this._useInstancing?1:4}this._vertexBuffer&&this._vertexBuffer.update(this._vertexData)}0===this.manualEmitCount&&this.disposeOnStop&&this.stop()}},t.prototype._appendParticleVertices=function(e,t){this._appendParticleVertex(e++,t,0,0),this._useInstancing||(this._appendParticleVertex(e++,t,1,0),this._appendParticleVertex(e++,t,1,1),this._appendParticleVertex(e++,t,0,1))},t.prototype.rebuild=function(){for(var e in this._createIndexBuffer(),this._vertexBuffer&&this._vertexBuffer._rebuild(),this._vertexBuffers)this._vertexBuffers[e]._rebuild()},t.prototype.isReady=function(){if(!(this.emitter&&this._imageProcessingConfiguration.isReady()&&this.particleTexture&&this.particleTexture.isReady()))return!1;if(this.blendMode!==t.BLENDMODE_MULTIPLYADD){if(!this._getEffect(this.blendMode).isReady())return!1}else{if(!this._getEffect(t.BLENDMODE_MULTIPLY).isReady())return!1;if(!this._getEffect(t.BLENDMODE_ADD).isReady())return!1}return!0},t.prototype._render=function(e){var i=this._getEffect(e),n=this._scene.getEngine();n.enableEffect(i);var r=this._scene.getViewMatrix();if(i.setTexture("diffuseSampler",this.particleTexture),i.setMatrix("view",r),i.setMatrix("projection",this._scene.getProjectionMatrix()),this._isAnimationSheetEnabled&&this.particleTexture){var o=this.particleTexture.getBaseSize();i.setFloat3("particlesInfos",this.spriteCellWidth/o.width,this.spriteCellHeight/o.height,o.width/this.spriteCellWidth)}if(i.setVector2("translationPivot",this.translationPivot),i.setFloat4("textureMask",this.textureMask.r,this.textureMask.g,this.textureMask.b,this.textureMask.a),this._isBillboardBased){var a=this._scene.activeCamera;i.setVector3("eyePosition",a.globalPosition)}if(this._rampGradientsTexture&&i.setTexture("rampSampler",this._rampGradientsTexture),this._scene.clipPlane||this._scene.clipPlane2||this._scene.clipPlane3||this._scene.clipPlane4||this._scene.clipPlane5||this._scene.clipPlane6){var s=r.clone();s.invert(),i.setMatrix("invView",s),io.a.BindClipPlane(i,this._scene)}switch(n.bindBuffers(this._vertexBuffers,this._indexBuffer,i),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(i),e){case t.BLENDMODE_ADD:n.setAlphaMode(g.a.ALPHA_ADD);break;case t.BLENDMODE_ONEONE:n.setAlphaMode(g.a.ALPHA_ONEONE);break;case t.BLENDMODE_STANDARD:n.setAlphaMode(g.a.ALPHA_COMBINE);break;case t.BLENDMODE_MULTIPLY:n.setAlphaMode(g.a.ALPHA_MULTIPLY)}return this._useInstancing?n.drawArraysType(Ca.a.TriangleFanDrawMode,0,4,this._particles.length):n.drawElementsType(Ca.a.TriangleFillMode,0,6*this._particles.length),this._particles.length},t.prototype.render=function(){if(!this.isReady()||!this._particles.length)return 0;var e=this._scene.getEngine();e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0);var i=0;return this.blendMode===t.BLENDMODE_MULTIPLYADD&&(i=this._render(t.BLENDMODE_MULTIPLY)+this._render(t.BLENDMODE_ADD)),i=this._render(this.blendMode),e.unbindInstanceAttributes(),e.setAlphaMode(g.a.ALPHA_DISABLE),i},t.prototype.dispose=function(e){if(void 0===e&&(e=!0),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._removeFromRoot(),this._subEmitters&&this._subEmitters.length){for(var t=0;t<this._subEmitters.length;t++)for(var i=0,n=this._subEmitters[t];i<n.length;i++){n[i].dispose()}this._subEmitters=[],this.subEmitters=[]}this._disposeEmitterOnDispose&&this.emitter&&this.emitter.dispose&&this.emitter.dispose(!0),(t=this._scene.particleSystems.indexOf(this))>-1&&this._scene.particleSystems.splice(t,1),this._scene._activeParticleSystems.dispose(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.reset()},t.prototype.clone=function(e,i){var n=null,r=null;if(null!=this.customShader){var o=(r=this.customShader).shaderOptions.defines.length>0?r.shaderOptions.defines.join("\n"):"";n=this._scene.getEngine().createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,o)}else this._customEffect&&(n=this._customEffect);var a=new t(e,this._capacity,this._scene,n);(a.customShader=r,O.a.DeepCopy(this,a,["particles","customShader","noiseTexture","particleTexture","onDisposeObservable"]),void 0===i&&(i=this.emitter),a.noiseTexture=this.noiseTexture,a.emitter=i,this.particleTexture)&&(this.particleTexture instanceof qi?(a.particleTexture=this.particleTexture.clone(),a.particleTexture.getContext().drawImage(this.particleTexture.getContext().canvas,0,0),a.particleTexture.update()):a.particleTexture=new et.a(this.particleTexture.url,this._scene));return this._colorGradients&&this._colorGradients.forEach(function(e){a.addColorGradient(e.gradient,e.color1,e.color2)}),this._dragGradients&&this._dragGradients.forEach(function(e){a.addDragGradient(e.gradient,e.factor1,e.factor2)}),this._angularSpeedGradients&&this._angularSpeedGradients.forEach(function(e){a.addAngularSpeedGradient(e.gradient,e.factor1,e.factor2)}),this._emitRateGradients&&this._emitRateGradients.forEach(function(e){a.addEmitRateGradient(e.gradient,e.factor1,e.factor2)}),this._lifeTimeGradients&&this._lifeTimeGradients.forEach(function(e){a.addLifeTimeGradient(e.gradient,e.factor1,e.factor2)}),this._limitVelocityGradients&&this._limitVelocityGradients.forEach(function(e){a.addLimitVelocityGradient(e.gradient,e.factor1,e.factor2)}),this._sizeGradients&&this._sizeGradients.forEach(function(e){a.addSizeGradient(e.gradient,e.factor1,e.factor2)}),this._startSizeGradients&&this._startSizeGradients.forEach(function(e){a.addStartSizeGradient(e.gradient,e.factor1,e.factor2)}),this._velocityGradients&&this._velocityGradients.forEach(function(e){a.addVelocityGradient(e.gradient,e.factor1,e.factor2)}),this._rampGradients&&this._rampGradients.forEach(function(e){a.addRampGradient(e.gradient,e.color)}),this._colorRemapGradients&&this._colorRemapGradients.forEach(function(e){a.addColorRemapGradient(e.gradient,e.factor1,e.factor2)}),this._alphaRemapGradients&&this._alphaRemapGradients.forEach(function(e){a.addAlphaRemapGradient(e.gradient,e.factor1,e.factor2)}),this.preventAutoStart||a.start(),a},t.prototype.serialize=function(){var e={};if(t._Serialize(e,this),e.textureMask=this.textureMask.asArray(),e.customShader=this.customShader,e.preventAutoStart=this.preventAutoStart,this.subEmitters){e.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(var i=0,n=this._subEmitters;i<n.length;i++){for(var r=[],o=0,a=n[i];o<a.length;o++){var s=a[o];r.push(s.serialize())}e.subEmitters.push(r)}}return e},t._Serialize=function(e,t){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),t.emitter.position){var i=t.emitter;e.emitterId=i.id}else{var n=t.emitter;e.emitter=n.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(e.textureName=t.particleTexture.name,e.invertY=t.particleTexture._invertY),e.isLocal=t.isLocal,N.a.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled;var r=t.getColorGradients();if(r){e.colorGradients=[];for(var o=0,a=r;o<a.length;o++){var s=a[o],c={gradient:s.gradient,color1:s.color1.asArray()};s.color2&&(c.color2=s.color2.asArray()),e.colorGradients.push(c)}}var l=t.getRampGradients();if(l){e.rampGradients=[];for(var u=0,h=l;u<h.length;u++){var d=h[u];c={gradient:d.gradient,color:d.color.asArray()};e.rampGradients.push(c)}e.useRampGradients=t.useRampGradients}var f=t.getColorRemapGradients();if(f){e.colorRemapGradients=[];for(var p=0,_=f;p<_.length;p++){var m=_[p];c={gradient:m.gradient,factor1:m.factor1};void 0!==m.factor2&&(c.factor2=m.factor2),e.colorRemapGradients.push(c)}}var g=t.getAlphaRemapGradients();if(g){e.alphaRemapGradients=[];for(var v=0,y=g;v<y.length;v++){var b=y[v];c={gradient:b.gradient,factor1:b.factor1};void 0!==b.factor2&&(c.factor2=b.factor2),e.alphaRemapGradients.push(c)}}var T=t.getSizeGradients();if(T){e.sizeGradients=[];for(var E=0,x=T;E<x.length;E++){var P=x[E];c={gradient:P.gradient,factor1:P.factor1};void 0!==P.factor2&&(c.factor2=P.factor2),e.sizeGradients.push(c)}}var A=t.getAngularSpeedGradients();if(A){e.angularSpeedGradients=[];for(var S=0,C=A;S<C.length;S++){var R=C[S];c={gradient:R.gradient,factor1:R.factor1};void 0!==R.factor2&&(c.factor2=R.factor2),e.angularSpeedGradients.push(c)}}var O=t.getVelocityGradients();if(O){e.velocityGradients=[];for(var M=0,I=O;M<I.length;M++){var D=I[M];c={gradient:D.gradient,factor1:D.factor1};void 0!==D.factor2&&(c.factor2=D.factor2),e.velocityGradients.push(c)}}var w=t.getDragGradients();if(w){e.dragGradients=[];for(var L=0,F=w;L<F.length;L++){var B=F[L];c={gradient:B.gradient,factor1:B.factor1};void 0!==B.factor2&&(c.factor2=B.factor2),e.dragGradients.push(c)}}var U=t.getEmitRateGradients();if(U){e.emitRateGradients=[];for(var V=0,k=U;V<k.length;V++){var z=k[V];c={gradient:z.gradient,factor1:z.factor1};void 0!==z.factor2&&(c.factor2=z.factor2),e.emitRateGradients.push(c)}}var G=t.getStartSizeGradients();if(G){e.startSizeGradients=[];for(var j=0,W=G;j<W.length;j++){var X=W[j];c={gradient:X.gradient,factor1:X.factor1};void 0!==X.factor2&&(c.factor2=X.factor2),e.startSizeGradients.push(c)}}var H=t.getLifeTimeGradients();if(H){e.lifeTimeGradients=[];for(var Y=0,K=H;Y<K.length;Y++){var Q=K[Y];c={gradient:Q.gradient,factor1:Q.factor1};void 0!==Q.factor2&&(c.factor2=Q.factor2),e.lifeTimeGradients.push(c)}}var q=t.getLimitVelocityGradients();if(q){e.limitVelocityGradients=[];for(var Z=0,J=q;Z<J.length;Z++){var $=J[Z];c={gradient:$.gradient,factor1:$.factor1};void 0!==$.factor2&&(c.factor2=$.factor2),e.limitVelocityGradients.push(c)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())},t._Parse=function(e,t,i,n){if(e.textureName&&(t.particleTexture=new et.a(n+e.textureName,i,!1,void 0===e.invertY||e.invertY),t.particleTexture.name=e.textureName),e.emitterId||0===e.emitterId||void 0!==e.emitter?e.emitterId?t.emitter=i.getLastMeshByID(e.emitterId):t.emitter=a.e.FromArray(e.emitter):t.emitter=a.e.Zero(),t.isLocal=!!e.isLocal,void 0!==e.renderingGroupId&&(t.renderingGroupId=e.renderingGroupId),void 0!==e.isBillboardBased&&(t.isBillboardBased=e.isBillboardBased),void 0!==e.billboardMode&&(t.billboardMode=e.billboardMode),e.animations){for(var r=0;r<e.animations.length;r++){var o=e.animations[r],l=c.a.GetClass("BABYLON.Animation");l&&t.animations.push(l.Parse(o))}t.beginAnimationOnStart=e.beginAnimationOnStart,t.beginAnimationFrom=e.beginAnimationFrom,t.beginAnimationTo=e.beginAnimationTo,t.beginAnimationLoop=e.beginAnimationLoop}if(e.autoAnimate&&i.beginAnimation(t,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),t.startDelay=0|e.startDelay,t.minAngularSpeed=e.minAngularSpeed,t.maxAngularSpeed=e.maxAngularSpeed,t.minSize=e.minSize,t.maxSize=e.maxSize,e.minScaleX&&(t.minScaleX=e.minScaleX,t.maxScaleX=e.maxScaleX,t.minScaleY=e.minScaleY,t.maxScaleY=e.maxScaleY),void 0!==e.preWarmCycles&&(t.preWarmCycles=e.preWarmCycles,t.preWarmStepOffset=e.preWarmStepOffset),void 0!==e.minInitialRotation&&(t.minInitialRotation=e.minInitialRotation,t.maxInitialRotation=e.maxInitialRotation),t.minLifeTime=e.minLifeTime,t.maxLifeTime=e.maxLifeTime,t.minEmitPower=e.minEmitPower,t.maxEmitPower=e.maxEmitPower,t.emitRate=e.emitRate,t.gravity=a.e.FromArray(e.gravity),e.noiseStrength&&(t.noiseStrength=a.e.FromArray(e.noiseStrength)),t.color1=s.b.FromArray(e.color1),t.color2=s.b.FromArray(e.color2),t.colorDead=s.b.FromArray(e.colorDead),t.updateSpeed=e.updateSpeed,t.targetStopDuration=e.targetStopDuration,t.blendMode=e.blendMode,e.colorGradients)for(var u=0,h=e.colorGradients;u<h.length;u++){var d=h[u];t.addColorGradient(d.gradient,s.b.FromArray(d.color1),d.color2?s.b.FromArray(d.color2):void 0)}if(e.rampGradients){for(var f=0,p=e.rampGradients;f<p.length;f++){var _=p[f];t.addRampGradient(_.gradient,s.a.FromArray(_.color))}t.useRampGradients=e.useRampGradients}if(e.colorRemapGradients)for(var m=0,g=e.colorRemapGradients;m<g.length;m++){var v=g[m];t.addColorRemapGradient(v.gradient,void 0!==v.factor1?v.factor1:v.factor,v.factor2)}if(e.alphaRemapGradients)for(var y=0,b=e.alphaRemapGradients;y<b.length;y++){var T=b[y];t.addAlphaRemapGradient(T.gradient,void 0!==T.factor1?T.factor1:T.factor,T.factor2)}if(e.sizeGradients)for(var E=0,x=e.sizeGradients;E<x.length;E++){var P=x[E];t.addSizeGradient(P.gradient,void 0!==P.factor1?P.factor1:P.factor,P.factor2)}if(e.angularSpeedGradients)for(var A=0,S=e.angularSpeedGradients;A<S.length;A++){var C=S[A];t.addAngularSpeedGradient(C.gradient,void 0!==C.factor1?C.factor1:C.factor,C.factor2)}if(e.velocityGradients)for(var R=0,O=e.velocityGradients;R<O.length;R++){var M=O[R];t.addVelocityGradient(M.gradient,void 0!==M.factor1?M.factor1:M.factor,M.factor2)}if(e.dragGradients)for(var I=0,D=e.dragGradients;I<D.length;I++){var w=D[I];t.addDragGradient(w.gradient,void 0!==w.factor1?w.factor1:w.factor,w.factor2)}if(e.emitRateGradients)for(var L=0,N=e.emitRateGradients;L<N.length;L++){var F=N[L];t.addEmitRateGradient(F.gradient,void 0!==F.factor1?F.factor1:F.factor,F.factor2)}if(e.startSizeGradients)for(var B=0,U=e.startSizeGradients;B<U.length;B++){var V=U[B];t.addStartSizeGradient(V.gradient,void 0!==V.factor1?V.factor1:V.factor,V.factor2)}if(e.lifeTimeGradients)for(var k=0,z=e.lifeTimeGradients;k<z.length;k++){var G=z[k];t.addLifeTimeGradient(G.gradient,void 0!==G.factor1?G.factor1:G.factor,G.factor2)}if(e.limitVelocityGradients){for(var j=0,W=e.limitVelocityGradients;j<W.length;j++){var X=W[j];t.addLimitVelocityGradient(X.gradient,void 0!==X.factor1?X.factor1:X.factor,X.factor2)}t.limitVelocityDamping=e.limitVelocityDamping}var H;if(e.noiseTexture&&(t.noiseTexture=$s.Parse(e.noiseTexture,i,n)),e.particleEmitterType){switch(e.particleEmitterType.type){case"SphereParticleEmitter":H=new Du;break;case"SphereDirectedParticleEmitter":H=new wu;break;case"ConeEmitter":case"ConeParticleEmitter":H=new Cu;break;case"CylinderParticleEmitter":H=new Ru;break;case"HemisphericParticleEmitter":H=new Mu;break;case"BoxEmitter":case"BoxParticleEmitter":default:H=new Su}H.parse(e.particleEmitterType,i)}else(H=new Su).parse(e,i);t.particleEmitterType=H,t.startSpriteCellID=e.startSpriteCellID,t.endSpriteCellID=e.endSpriteCellID,t.spriteCellWidth=e.spriteCellWidth,t.spriteCellHeight=e.spriteCellHeight,t.spriteCellChangeSpeed=e.spriteCellChangeSpeed,t.spriteRandomStartCell=e.spriteRandomStartCell},t.Parse=function(e,i,n,r){void 0===r&&(r=!1);var o=e.name,a=null,c=null;if(e.customShader){var l=(c=e.customShader).shaderOptions.defines.length>0?c.shaderOptions.defines.join("\n"):"";a=i.getEngine().createEffectForParticles(c.shaderPath.fragmentElement,c.shaderOptions.uniforms,c.shaderOptions.samplers,l)}var u=new t(o,e.capacity,i,a,e.isAnimationSheetEnabled);if(u.customShader=c,e.id&&(u.id=e.id),e.subEmitters){u.subEmitters=[];for(var h=0,d=e.subEmitters;h<d.length;h++){for(var f=[],p=0,_=d[h];p<_.length;p++){var m=_[p];f.push(Gu.Parse(m,i,n))}u.subEmitters.push(f)}}return t._Parse(e,u,i,n),u.textureMask=s.b.FromArray(e.textureMask),e.preventAutoStart&&(u.preventAutoStart=e.preventAutoStart),r||u.preventAutoStart||u.start(),u},t.BILLBOARDMODE_Y=g.a.PARTICLES_BILLBOARDMODE_Y,t.BILLBOARDMODE_ALL=g.a.PARTICLES_BILLBOARDMODE_ALL,t.BILLBOARDMODE_STRETCHED=g.a.PARTICLES_BILLBOARDMODE_STRETCHED,t}(Fu);Gu._ParseParticleSystem=Xu.Parse;ai.a.ShadersStore.gpuUpdateParticlesPixelShader="#version 300 es\nvoid main() {\ndiscard;\n}\n";var Hu="#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\n#ifdef CUSTOMEMITTER\nin vec3 initialPosition;\n#endif\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\n#ifdef CUSTOMEMITTER\nout vec3 outInitialPosition;\n#endif\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif\n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta;\n\nif (newAge>=life && stopFactor != 0.) {\nvec3 newPosition;\nvec3 newDirection;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=newAge-life;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a;\n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif\n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nnewPosition=vec3(0,0,0);\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nnewPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nnewPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\nnewDirection=newPosition+directionRandomizer*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nnewPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nnewDirection=newPosition+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nnewPosition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\nnewDirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\nnewDirection=normalize(newDirection);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.0001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nnewPosition=vec3(randX,randY,randZ);\n\nif (abs(cos(coneAngle)) == 1.0) {\nnewDirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\nnewDirection=normalize(newPosition+directionRandomizer*randoms3);\n}\n#elif defined(CUSTOMEMITTER)\nnewPosition=initialPosition;\noutInitialPosition=initialPosition;\n#else\n\nnewPosition=vec3(0.,0.,0.);\n\nnewDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(newPosition,1.)).xyz;\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#ifndef BILLBOARD\noutInitialDirection=direction;\n#endif\n#else\nvec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD\noutInitialDirection=initial;\n#endif\n#endif\n#ifdef ANIMATESHEET\noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif\n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#if defined(CUSTOMEMITTER)\noutPosition=position+(direction-position)*ageGradient;\noutInitialPosition=initialPosition;\n#else\noutPosition=position+direction*directionScale;\n#endif\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS\noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif\n#ifndef BILLBOARD\noutInitialDirection=initialDirection;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#else\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET\nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#else\nfloat cellStartOffset=0.;\n#endif\nfloat ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}";ai.a.ShadersStore.gpuUpdateParticlesVertexShader=Hu;var Yu="#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nin float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nin float fClipDistance6;\n#endif";ai.a.IncludesShadersStore.clipPlaneFragmentDeclaration2=Yu;var Ku="#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment>\nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n";ai.a.ShadersStore.gpuRenderParticlesPixelShader=Ku;var Qu="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;\nout float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;\nout float fClipDistance6;\n#endif";ai.a.IncludesShadersStore.clipPlaneVertexDeclaration2=Qu;var qu="#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\nuniform vec3 worldOffset;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn (position+worldOffset)+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn (position+worldOffset)+alignedCorner;\n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=(position+worldOffset)-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0));\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=(position+worldOffset)-eyePosition;\nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0));\n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0);\n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=invView*viewPosition;\n#endif\n#include<clipPlaneVertex>\n}";ai.a.ShadersStore.gpuRenderParticlesVertexShader=qu;var Zu=function(e){function t(t,i,n,r){void 0===r&&(r=!1);var a=e.call(this,t)||this;a.layerMask=268435455,a._accumulatedCount=0,a._targetIndex=0,a._currentRenderId=-1,a._started=!1,a._stopped=!1,a._timeDelta=0,a._actualFrame=0,a._rawTextureWidth=256,a.onDisposeObservable=new o.c,a.forceDepthWrite=!1,a._preWarmDone=!1,a._scene=n||R.a.LastCreatedScene,a._attachImageProcessingConfiguration(null),a._engine=a._scene.getEngine(),i.randomTextureSize||delete i.randomTextureSize;var s=Object(h.a)({capacity:5e4,randomTextureSize:a._engine.getCaps().maxTextureSize},i),c=i;isFinite(c)&&(s.capacity=c),a._capacity=s.capacity,a._activeCount=s.capacity,a._currentActiveCount=0,a._isAnimationSheetEnabled=r,a._scene.particleSystems.push(a),a._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]},a.particleEmitterType=new Su;for(var l=Math.min(a._engine.getCaps().maxTextureSize,s.randomTextureSize),u=[],d=0;d<l;++d)u.push(Math.random()),u.push(Math.random()),u.push(Math.random()),u.push(Math.random());a._randomTexture=new rt(new Float32Array(u),l,1,g.a.TEXTUREFORMAT_RGBA,a._scene,!1,!1,g.a.TEXTURE_NEAREST_SAMPLINGMODE,g.a.TEXTURETYPE_FLOAT),a._randomTexture.wrapU=et.a.WRAP_ADDRESSMODE,a._randomTexture.wrapV=et.a.WRAP_ADDRESSMODE,u=[];for(d=0;d<l;++d)u.push(Math.random()),u.push(Math.random()),u.push(Math.random()),u.push(Math.random());return a._randomTexture2=new rt(new Float32Array(u),l,1,g.a.TEXTUREFORMAT_RGBA,a._scene,!1,!1,g.a.TEXTURE_NEAREST_SAMPLINGMODE,g.a.TEXTURETYPE_FLOAT),a._randomTexture2.wrapU=et.a.WRAP_ADDRESSMODE,a._randomTexture2.wrapV=et.a.WRAP_ADDRESSMODE,a._randomTextureSize=l,a}return Object(h.d)(t,e),Object.defineProperty(t,"IsSupported",{get:function(){return!!R.a.LastCreatedEngine&&R.a.LastCreatedEngine.webGLVersion>1},enumerable:!0,configurable:!0}),t.prototype.getCapacity=function(){return this._capacity},Object.defineProperty(t.prototype,"activeParticleCount",{get:function(){return this._activeCount},set:function(e){this._activeCount=Math.min(e,this._capacity)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isLocal",{get:function(){return!1},set:function(e){},enumerable:!0,configurable:!0}),t.prototype.isReady=function(){return this._updateEffect?!!(this.emitter&&this._updateEffect.isReady()&&this._imageProcessingConfiguration.isReady()&&this._renderEffect.isReady()&&this.particleTexture&&this.particleTexture.isReady()):(this._recreateUpdateEffect(),this._recreateRenderEffect(),!1)},t.prototype.isStarted=function(){return this._started},t.prototype.start=function(e){var t=this;if(void 0===e&&(e=this.startDelay),!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";e?setTimeout(function(){t.start(0)},e):(this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this.getScene().beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop))},t.prototype.stop=function(){this._stopped=!0},t.prototype.reset=function(){this._releaseBuffers(),this._releaseVAOs(),this._currentActiveCount=0,this._targetIndex=0},t.prototype.getClassName=function(){return"GPUParticleSystem"},t.prototype._removeGradientAndTexture=function(t,i,n){return e.prototype._removeGradientAndTexture.call(this,t,i,n),this._releaseBuffers(),this},t.prototype.addColorGradient=function(e,t,i){this._colorGradients||(this._colorGradients=[]);var n=new Bu;return n.gradient=e,n.color1=t,this._colorGradients.push(n),this._colorGradients.sort(function(e,t){return e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0}),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeColorGradient=function(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this},t.prototype._addFactorGradient=function(e,t,i){var n=new Vu;n.gradient=t,n.factor1=i,e.push(n),e.sort(function(e,t){return e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0}),this._releaseBuffers()},t.prototype.addSizeGradient=function(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeSizeGradient=function(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this},t.prototype.addAngularSpeedGradient=function(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeAngularSpeedGradient=function(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this},t.prototype.addVelocityGradient=function(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeVelocityGradient=function(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this},t.prototype.addLimitVelocityGradient=function(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._limitVelocityGradientsTexture&&(this._limitVelocityGradientsTexture.dispose(),this._limitVelocityGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeLimitVelocityGradient=function(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this},t.prototype.addDragGradient=function(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._dragGradientsTexture&&(this._dragGradientsTexture.dispose(),this._dragGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeDragGradient=function(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this},t.prototype.addEmitRateGradient=function(e,t,i){return this},t.prototype.removeEmitRateGradient=function(e){return this},t.prototype.addStartSizeGradient=function(e,t,i){return this},t.prototype.removeStartSizeGradient=function(e){return this},t.prototype.addColorRemapGradient=function(e,t,i){return this},t.prototype.removeColorRemapGradient=function(){return this},t.prototype.addAlphaRemapGradient=function(e,t,i){return this},t.prototype.removeAlphaRemapGradient=function(){return this},t.prototype.addRampGradient=function(e,t){return this},t.prototype.removeRampGradient=function(){return this},t.prototype.getRampGradients=function(){return null},Object.defineProperty(t.prototype,"useRampGradients",{get:function(){return!1},set:function(e){},enumerable:!0,configurable:!0}),t.prototype.addLifeTimeGradient=function(e,t,i){return this},t.prototype.removeLifeTimeGradient=function(e){return this},t.prototype._reset=function(){this._releaseBuffers()},t.prototype._createUpdateVAO=function(e){var t={};t.position=e.createVertexBuffer("position",0,3);var i=3;this.particleEmitterType instanceof Lu&&(t.initialPosition=e.createVertexBuffer("initialPosition",i,3),i+=3),t.age=e.createVertexBuffer("age",i,1),i+=1,t.life=e.createVertexBuffer("life",i,1),i+=1,t.seed=e.createVertexBuffer("seed",i,4),i+=4,t.size=e.createVertexBuffer("size",i,3),i+=3,this._colorGradientsTexture||(t.color=e.createVertexBuffer("color",i,4),i+=4),t.direction=e.createVertexBuffer("direction",i,3),i+=3,this._isBillboardBased||(t.initialDirection=e.createVertexBuffer("initialDirection",i,3),i+=3),this._angularSpeedGradientsTexture?(t.angle=e.createVertexBuffer("angle",i,1),i+=1):(t.angle=e.createVertexBuffer("angle",i,2),i+=2),this._isAnimationSheetEnabled&&(t.cellIndex=e.createVertexBuffer("cellIndex",i,1),i+=1,this.spriteRandomStartCell&&(t.cellStartOffset=e.createVertexBuffer("cellStartOffset",i,1),i+=1)),this.noiseTexture&&(t.noiseCoordinates1=e.createVertexBuffer("noiseCoordinates1",i,3),i+=3,t.noiseCoordinates2=e.createVertexBuffer("noiseCoordinates2",i,3),i+=3);var n=this._engine.recordVertexArrayObject(t,null,this._updateEffect);return this._engine.bindArrayBuffer(null),n},t.prototype._createRenderVAO=function(e,t){var i={};i.position=e.createVertexBuffer("position",0,3,this._attributesStrideSize,!0);var n=3;this.particleEmitterType instanceof Lu&&(n+=3),i.age=e.createVertexBuffer("age",n,1,this._attributesStrideSize,!0),n+=1,i.life=e.createVertexBuffer("life",n,1,this._attributesStrideSize,!0),n+=5,i.size=e.createVertexBuffer("size",n,3,this._attributesStrideSize,!0),n+=3,this._colorGradientsTexture||(i.color=e.createVertexBuffer("color",n,4,this._attributesStrideSize,!0),n+=4),this.billboardMode===Xu.BILLBOARDMODE_STRETCHED&&(i.direction=e.createVertexBuffer("direction",n,3,this._attributesStrideSize,!0)),n+=3,this._isBillboardBased||(i.initialDirection=e.createVertexBuffer("initialDirection",n,3,this._attributesStrideSize,!0),n+=3),i.angle=e.createVertexBuffer("angle",n,1,this._attributesStrideSize,!0),this._angularSpeedGradientsTexture?n++:n+=2,this._isAnimationSheetEnabled&&(i.cellIndex=e.createVertexBuffer("cellIndex",n,1,this._attributesStrideSize,!0),n+=1,this.spriteRandomStartCell&&(i.cellStartOffset=e.createVertexBuffer("cellStartOffset",n,1,this._attributesStrideSize,!0),n+=1)),this.noiseTexture&&(i.noiseCoordinates1=e.createVertexBuffer("noiseCoordinates1",n,3,this._attributesStrideSize,!0),n+=3,i.noiseCoordinates2=e.createVertexBuffer("noiseCoordinates2",n,3,this._attributesStrideSize,!0),n+=3),i.offset=t.createVertexBuffer("offset",0,2),i.uv=t.createVertexBuffer("uv",2,2);var r=this._engine.recordVertexArrayObject(i,null,this._renderEffect);return this._engine.bindArrayBuffer(null),r},t.prototype._initialize=function(e){if(void 0===e&&(e=!1),!this._buffer0||e){var t=this._scene.getEngine(),i=new Array;this._attributesStrideSize=21,this._targetIndex=0,this.particleEmitterType instanceof Lu&&(this._attributesStrideSize+=3),this.isBillboardBased||(this._attributesStrideSize+=3),this._colorGradientsTexture&&(this._attributesStrideSize-=4),this._angularSpeedGradientsTexture&&(this._attributesStrideSize-=1),this._isAnimationSheetEnabled&&(this._attributesStrideSize+=1,this.spriteRandomStartCell&&(this._attributesStrideSize+=1)),this.noiseTexture&&(this._attributesStrideSize+=6);for(var n=this.particleEmitterType instanceof Lu,r=a.c.Vector3[0],o=0;o<this._capacity;o++)i.push(0),i.push(0),i.push(0),n&&(this.particleEmitterType.particlePositionGenerator(o,null,r),i.push(r.x),i.push(r.y),i.push(r.z)),i.push(0),i.push(0),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),i.push(0),i.push(0),i.push(0),this._colorGradientsTexture||(i.push(0),i.push(0),i.push(0),i.push(0)),n?(this.particleEmitterType.particleDestinationGenerator(o,null,r),i.push(r.x),i.push(r.y),i.push(r.z)):(i.push(0),i.push(0),i.push(0)),this.isBillboardBased||(i.push(0),i.push(0),i.push(0)),i.push(0),this._angularSpeedGradientsTexture||i.push(0),this._isAnimationSheetEnabled&&(i.push(0),this.spriteRandomStartCell&&i.push(0)),this.noiseTexture&&(i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()));var s=new Float32Array([.5,.5,1,1,-.5,.5,0,1,-.5,-.5,0,0,.5,-.5,1,0]);this._buffer0=new en.a(t,i,!1,this._attributesStrideSize),this._buffer1=new en.a(t,i,!1,this._attributesStrideSize),this._spriteBuffer=new en.a(t,s,!1,4),this._updateVAO=[],this._updateVAO.push(this._createUpdateVAO(this._buffer0)),this._updateVAO.push(this._createUpdateVAO(this._buffer1)),this._renderVAO=[],this._renderVAO.push(this._createRenderVAO(this._buffer1,this._spriteBuffer)),this._renderVAO.push(this._createRenderVAO(this._buffer0,this._spriteBuffer)),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}},t.prototype._recreateUpdateEffect=function(){var e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";this._isBillboardBased&&(e+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this._updateEffect&&this._updateEffectOptions.defines===e||(this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this.particleEmitterType instanceof Lu&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.defines=e,this._updateEffect=new ai.a("gpuUpdateParticles",this._updateEffectOptions,this._scene.getEngine()))},t.prototype._recreateRenderEffect=function(){var e="";if(this._scene.clipPlane&&(e="\n#define CLIPPLANE"),this._scene.clipPlane2&&(e="\n#define CLIPPLANE2"),this._scene.clipPlane3&&(e="\n#define CLIPPLANE3"),this._scene.clipPlane4&&(e="\n#define CLIPPLANE4"),this._scene.clipPlane5&&(e="\n#define CLIPPLANE5"),this._scene.clipPlane6&&(e="\n#define CLIPPLANE6"),this.blendMode===Xu.BLENDMODE_MULTIPLY&&(e="\n#define BLENDMULTIPLYMODE"),this._isBillboardBased)switch(e+="\n#define BILLBOARD",this.billboardMode){case Xu.BILLBOARDMODE_Y:e+="\n#define BILLBOARDY";break;case Xu.BILLBOARDMODE_STRETCHED:e+="\n#define BILLBOARDSTRETCHED";break;case Xu.BILLBOARDMODE_ALL:}if(this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET"),this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e+="\n"+this._imageProcessingConfigurationDefines.toString()),!this._renderEffect||this._renderEffect.defines!==e){var t=["worldOffset","view","projection","colorDead","invView","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","sheetInfos","translationPivot","eyePosition"],i=["textureSampler","colorGradientSampler"];Yi.a&&(Yi.a.PrepareUniforms(t,this._imageProcessingConfigurationDefines),Yi.a.PrepareSamplers(i,this._imageProcessingConfigurationDefines)),this._renderEffect=new ai.a("gpuRenderParticles",["position","age","life","size","color","offset","uv","direction","initialDirection","angle","cellIndex"],t,i,this._scene.getEngine(),e)}},t.prototype.animate=function(e){void 0===e&&(e=!1),this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:this._scene.getAnimationRatio()),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()},t.prototype._createFactorGradientTexture=function(e,t){var i=this[t];if(e&&e.length&&!i){for(var n=new Float32Array(this._rawTextureWidth),r=0;r<this._rawTextureWidth;r++){var o=r/this._rawTextureWidth;ku.GetCurrentGradient(o,e,function(e,t,i){n[r]=L.a.Lerp(e.factor1,t.factor1,i)})}this[t]=rt.CreateRTexture(n,this._rawTextureWidth,1,this._scene,!1,!1,et.a.NEAREST_SAMPLINGMODE)}},t.prototype._createSizeGradientTexture=function(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")},t.prototype._createAngularSpeedGradientTexture=function(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")},t.prototype._createVelocityGradientTexture=function(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")},t.prototype._createLimitVelocityGradientTexture=function(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")},t.prototype._createDragGradientTexture=function(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")},t.prototype._createColorGradientTexture=function(){if(this._colorGradients&&this._colorGradients.length&&!this._colorGradientsTexture){for(var e=new Uint8Array(4*this._rawTextureWidth),t=s.c.Color4[0],i=0;i<this._rawTextureWidth;i++){var n=i/this._rawTextureWidth;ku.GetCurrentGradient(n,this._colorGradients,function(n,r,o){s.b.LerpToRef(n.color1,r.color1,o,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a})}this._colorGradientsTexture=rt.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,et.a.NEAREST_SAMPLINGMODE)}},t.prototype.render=function(e){if(void 0===e&&(e=!1),!this._started)return 0;if(this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture(),this._recreateUpdateEffect(),this._recreateRenderEffect(),!this.isReady())return 0;if(!e){if(!this._preWarmDone&&this.preWarmCycles){for(var t=0;t<this.preWarmCycles;t++)this.animate(!0),this.render(!0);this._preWarmDone=!0}if(this._currentRenderId===this._scene.getFrameId())return 0;this._currentRenderId=this._scene.getFrameId()}if(this._initialize(),this._accumulatedCount+=this.emitRate*this._timeDelta,this._accumulatedCount>1){var i=0|this._accumulatedCount;this._accumulatedCount-=i,this._currentActiveCount=Math.min(this._activeCount,this._currentActiveCount+i)}if(!this._currentActiveCount)return 0;var n;if(this._engine.enableEffect(this._updateEffect),this._engine.setState(!1),this._updateEffect.setFloat("currentCount",this._currentActiveCount),this._updateEffect.setFloat("timeDelta",this._timeDelta),this._updateEffect.setFloat("stopFactor",this._stopped?0:1),this._updateEffect.setTexture("randomSampler",this._randomTexture),this._updateEffect.setTexture("randomSampler2",this._randomTexture2),this._updateEffect.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateEffect.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateEffect.setDirectColor4("color1",this.color1),this._updateEffect.setDirectColor4("color2",this.color2)),this._updateEffect.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateEffect.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateEffect.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateEffect.setVector3("gravity",this.gravity),this._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._sizeGradientsTexture),this._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._angularSpeedGradientsTexture),this._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._velocityGradientsTexture),this._limitVelocityGradientsTexture&&(this._updateEffect.setTexture("limitVelocityGradientSampler",this._limitVelocityGradientsTexture),this._updateEffect.setFloat("limitVelocityDamping",this.limitVelocityDamping)),this._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._dragGradientsTexture),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateEffect),this._isAnimationSheetEnabled&&this._updateEffect.setFloat3("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed),this.noiseTexture&&(this._updateEffect.setTexture("noiseSampler",this.noiseTexture),this._updateEffect.setVector3("noiseStrength",this.noiseStrength)),this.emitter.position){n=this.emitter.getWorldMatrix()}else{var r=this.emitter;n=a.a.Translation(r.x,r.y,r.z)}if(this._updateEffect.setMatrix("emitterWM",n),this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex],null),this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer()),this._engine.setRasterizerState(!1),this._engine.beginTransformFeedback(!0),this._engine.drawArraysType(Ca.a.PointListDrawMode,0,this._currentActiveCount),this._engine.endTransformFeedback(),this._engine.setRasterizerState(!0),this._engine.bindTransformFeedbackBuffer(null),!e){this._engine.enableEffect(this._renderEffect);var o=this._scene.getViewMatrix();if(this._renderEffect.setMatrix("view",o),this._renderEffect.setMatrix("projection",this._scene.getProjectionMatrix()),this._renderEffect.setTexture("textureSampler",this.particleTexture),this._renderEffect.setVector2("translationPivot",this.translationPivot),this._renderEffect.setVector3("worldOffset",this.worldOffset),this._colorGradientsTexture?this._renderEffect.setTexture("colorGradientSampler",this._colorGradientsTexture):this._renderEffect.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){var s=this.particleTexture.getBaseSize();this._renderEffect.setFloat3("sheetInfos",this.spriteCellWidth/s.width,this.spriteCellHeight/s.height,s.width/this.spriteCellWidth)}if(this._isBillboardBased){var c=this._scene.activeCamera;this._renderEffect.setVector3("eyePosition",c.globalPosition)}if(this._scene.clipPlane||this._scene.clipPlane2||this._scene.clipPlane3||this._scene.clipPlane4||this._scene.clipPlane5||this._scene.clipPlane6){var l=o.clone();l.invert(),this._renderEffect.setMatrix("invView",l),io.a.BindClipPlane(this._renderEffect,this._scene)}switch(this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._renderEffect),this.blendMode){case Xu.BLENDMODE_ADD:this._engine.setAlphaMode(g.a.ALPHA_ADD);break;case Xu.BLENDMODE_ONEONE:this._engine.setAlphaMode(g.a.ALPHA_ONEONE);break;case Xu.BLENDMODE_STANDARD:this._engine.setAlphaMode(g.a.ALPHA_COMBINE);break;case Xu.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(g.a.ALPHA_MULTIPLY)}this.forceDepthWrite&&this._engine.setDepthWrite(!0),this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex],null),this._engine.drawArraysType(Ca.a.TriangleFanDrawMode,0,4,this._currentActiveCount),this._engine.setAlphaMode(g.a.ALPHA_DISABLE)}this._targetIndex++,2===this._targetIndex&&(this._targetIndex=0);var u=this._sourceBuffer;return this._sourceBuffer=this._targetBuffer,this._targetBuffer=u,this._currentActiveCount},t.prototype.rebuild=function(){this._initialize(!0)},t.prototype._releaseBuffers=function(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null)},t.prototype._releaseVAOs=function(){if(this._updateVAO){for(var e=0;e<this._updateVAO.length;e++)this._engine.releaseVertexArrayObject(this._updateVAO[e]);this._updateVAO=[];for(e=0;e<this._renderVAO.length;e++)this._engine.releaseVertexArrayObject(this._renderVAO[e]);this._renderVAO=[]}},t.prototype.dispose=function(e){void 0===e&&(e=!0);var t=this._scene.particleSystems.indexOf(this);t>-1&&this._scene.particleSystems.splice(t,1),this._releaseBuffers(),this._releaseVAOs(),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._limitVelocityGradientsTexture&&(this._limitVelocityGradientsTexture.dispose(),this._limitVelocityGradientsTexture=null),this._dragGradientsTexture&&(this._dragGradientsTexture.dispose(),this._dragGradientsTexture=null),this._randomTexture&&(this._randomTexture.dispose(),this._randomTexture=null),this._randomTexture2&&(this._randomTexture2.dispose(),this._randomTexture2=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t.prototype.clone=function(e,i){var n=new t(e,{capacity:this._capacity,randomTextureSize:this._randomTextureSize},this._scene);return O.a.DeepCopy(this,n,["particles","customShader","noiseTexture","particleTexture","onDisposeObservable"]),void 0===i&&(i=this.emitter),n.emitter=i,this.particleTexture&&(n.particleTexture=new et.a(this.particleTexture.url,this._scene)),n.noiseTexture=this.noiseTexture,this._colorGradients&&this._colorGradients.forEach(function(e){n.addColorGradient(e.gradient,e.color1,e.color2)}),this._dragGradients&&this._dragGradients.forEach(function(e){n.addDragGradient(e.gradient,e.factor1)}),this._angularSpeedGradients&&this._angularSpeedGradients.forEach(function(e){n.addAngularSpeedGradient(e.gradient,e.factor1)}),this._emitRateGradients&&this._emitRateGradients.forEach(function(e){n.addEmitRateGradient(e.gradient,e.factor1,e.factor2)}),this._lifeTimeGradients&&this._lifeTimeGradients.forEach(function(e){n.addLifeTimeGradient(e.gradient,e.factor1,e.factor2)}),this._limitVelocityGradients&&this._limitVelocityGradients.forEach(function(e){n.addLimitVelocityGradient(e.gradient,e.factor1)}),this._sizeGradients&&this._sizeGradients.forEach(function(e){n.addSizeGradient(e.gradient,e.factor1)}),this._startSizeGradients&&this._startSizeGradients.forEach(function(e){n.addStartSizeGradient(e.gradient,e.factor1,e.factor2)}),this._velocityGradients&&this._velocityGradients.forEach(function(e){n.addVelocityGradient(e.gradient,e.factor1)}),this._rampGradients&&this._rampGradients.forEach(function(e){n.addRampGradient(e.gradient,e.color)}),this._colorRemapGradients&&this._colorRemapGradients.forEach(function(e){n.addColorRemapGradient(e.gradient,e.factor1,e.factor2)}),this._alphaRemapGradients&&this._alphaRemapGradients.forEach(function(e){n.addAlphaRemapGradient(e.gradient,e.factor1,e.factor2)}),n},t.prototype.serialize=function(){var e={};return Xu._Serialize(e,this),e.activeParticleCount=this.activeParticleCount,e},t.Parse=function(e,i,n,r){void 0===r&&(r=!1);var o=new t(e.name,{capacity:e.capacity,randomTextureSize:e.randomTextureSize},i);return e.activeParticleCount&&(o.activeParticleCount=e.activeParticleCount),Xu._Parse(e,o,i,n),e.preventAutoStart&&(o.preventAutoStart=e.preventAutoStart),r||o.preventAutoStart||o.start(),o},t}(Fu),Ju=function(){function e(){this.systems=new Array}return Object.defineProperty(e.prototype,"emitterNode",{get:function(){return this._emitterNode},enumerable:!0,configurable:!0}),e.prototype.setEmitterAsSphere=function(e,t,i){this._emitterNode&&this._emitterNode.dispose(),this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};var n=Rr.a.CreateSphere("emitterSphere",{diameter:e.diameter,segments:e.segments},i);n.renderingGroupId=t;var r=new Ki.a("emitterSphereMaterial",i);r.emissiveColor=e.color,n.material=r;for(var o=0,a=this.systems;o<a.length;o++){a[o].emitter=n}this._emitterNode=n},e.prototype.start=function(e){for(var t=0,i=this.systems;t<i.length;t++){var n=i[t];e&&(n.emitter=e),n.start()}},e.prototype.dispose=function(){for(var e=0,t=this.systems;e<t.length;e++){t[e].dispose()}this.systems=[],this._emitterNode&&(this._emitterNode.dispose(),this._emitterNode=null)},e.prototype.serialize=function(){for(var e={systems:[]},t=0,i=this.systems;t<i.length;t++){var n=i[t];e.systems.push(n.serialize())}return this._emitterNode&&(e.emitter=this._emitterCreationOptions),e},e.Parse=function(t,i,n){void 0===n&&(n=!1);var r=new e,o=this.BaseAssetsUrl+"/textures/";i=i||R.a.LastCreatedScene;for(var a=0,c=t.systems;a<c.length;a++){var l=c[a];r.systems.push(n?Zu.Parse(l,i,o,!0):Xu.Parse(l,i,o,!0))}if(t.emitter){var u=t.emitter.options;switch(t.emitter.kind){case"Sphere":r.setEmitterAsSphere({diameter:u.diameter,segments:u.segments,color:s.a.FromArray(u.color)},t.emitter.renderingGroupId,i)}}return r},e.BaseAssetsUrl="https://assets.babylonjs.com/particles",e}(),$u=function(){function e(){}return e.CreateDefault=function(e,t,i,n){var r;return void 0===t&&(t=500),void 0===n&&(n=!1),(r=n?new Zu("default system",{capacity:t},i):new Xu("default system",t,i)).emitter=e,r.particleTexture=new et.a("https://www.babylonjs.com/assets/Flare.png",r.getScene()),r.createConeEmitter(.1,Math.PI/4),r.color1=new s.b(1,1,1,1),r.color2=new s.b(1,1,1,1),r.colorDead=new s.b(1,1,1,0),r.minSize=.1,r.maxSize=.1,r.minEmitPower=2,r.maxEmitPower=2,r.updateSpeed=1/60,r.emitRate=30,r},e.CreateAsync=function(t,i,n){void 0===n&&(n=!1),i||(i=R.a.LastCreatedScene);var r={};return i._addPendingData(r),new Promise(function(o,a){if(n&&!Zu.IsSupported)return i._removePendingData(r),a("Particle system with GPU is not supported.");De.b.LoadFile(e.BaseAssetsUrl+"/systems/"+t+".json",function(e){i._removePendingData(r);var t=JSON.parse(e.toString());return o(Ju.Parse(t,i,n))},void 0,void 0,void 0,function(){return i._removePendingData(r),a("An error occured while the creation of your particle system. Check if your type '"+t+"' exists.")})})},e.ExportSet=function(e){for(var t=new Ju,i=0,n=e;i<n.length;i++){var r=n[i];t.systems.push(r)}return t},e.BaseAssetsUrl=Ju.BaseAssetsUrl,e}();n.a.AddParser(Fe.a.NAME_PARTICLESYSTEM,function(e,t,i,r){var o=n.a.GetIndividualParser(Fe.a.NAME_PARTICLESYSTEM);if(o&&void 0!==e.particleSystems&&null!==e.particleSystems)for(var a=0,s=e.particleSystems.length;a<s;a++){var c=e.particleSystems[a];i.particleSystems.push(o(c,t,r))}}),n.a.AddIndividualParser(Fe.a.NAME_PARTICLESYSTEM,function(e,t,i){return e.activeParticleCount?Zu.Parse(e,t,i):Xu.Parse(e,t,i)}),Oe.a.prototype.createEffectForParticles=function(e,t,i,n,r,o,a){void 0===t&&(t=[]),void 0===i&&(i=[]),void 0===n&&(n="");var s=Xu._GetAttributeNamesOrOptions(),c=Xu._GetEffectCreationOptions();return-1===n.indexOf(" BILLBOARD")&&(n+="\n#define BILLBOARD\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:"particles",fragmentElement:e},s,c.concat(t),i,n,r,o,a)},Ae.a.prototype.getEmittedParticleSystems=function(){for(var e=new Array,t=0;t<this.getScene().particleSystems.length;t++){var i=this.getScene().particleSystems[t];i.emitter===this&&e.push(i)}return e},Ae.a.prototype.getHierarchyEmittedParticleSystems=function(){var e=new Array,t=this.getDescendants();t.push(this);for(var i=0;i<this.getScene().particleSystems.length;i++){var n=this.getScene().particleSystems[i],r=n.emitter;r.position&&-1!==t.indexOf(r)&&e.push(n)}return e};var eh,th=function(){function e(e,t,i,n,r,o,c,l,u,h){void 0===u&&(u=null),void 0===h&&(h=null),this.idx=0,this.id=0,this.color=new s.b(1,1,1,1),this.position=a.e.Zero(),this.rotation=a.e.Zero(),this.scaling=a.e.One(),this.uvs=new a.f(0,0,1,1),this.velocity=a.e.Zero(),this.pivot=a.e.Zero(),this.translateFromPivot=!1,this.alive=!0,this.isVisible=!0,this._pos=0,this._ind=0,this.shapeId=0,this.idxInShape=0,this._stillInvisible=!1,this._rotationMatrix=[1,0,0,0,1,0,0,0,1],this.parentId=null,this.materialIndex=null,this.cullingStrategy=Ke.a.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this._globalPosition=a.e.Zero(),this.idx=e,this.id=t,this._pos=i,this._ind=n,this._model=r,this.shapeId=o,this.idxInShape=c,this._sps=l,u&&(this._modelBoundingInfo=u,this._boundingInfo=new Pn.a(u.minimum,u.maximum)),null!==h&&(this.materialIndex=h)}return e.prototype.copyToRef=function(e){return e.position.copyFrom(this.position),e.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(e.rotationQuaternion?e.rotationQuaternion.copyFrom(this.rotationQuaternion):e.rotationQuaternion=this.rotationQuaternion.clone()),e.scaling.copyFrom(this.scaling),this.color&&(e.color?e.color.copyFrom(this.color):e.color=this.color.clone()),e.uvs.copyFrom(this.uvs),e.velocity.copyFrom(this.velocity),e.pivot.copyFrom(this.pivot),e.translateFromPivot=this.translateFromPivot,e.alive=this.alive,e.isVisible=this.isVisible,e.parentId=this.parentId,e.cullingStrategy=this.cullingStrategy,null!==this.materialIndex&&(e.materialIndex=this.materialIndex),this},Object.defineProperty(e.prototype,"scale",{get:function(){return this.scaling},set:function(e){this.scaling=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"quaternion",{get:function(){return this.rotationQuaternion},set:function(e){this.rotationQuaternion=e},enumerable:!0,configurable:!0}),e.prototype.intersectsMesh=function(e){return!(!this._boundingInfo||!e._boundingInfo)&&(this._sps._bSphereOnly?An.a.Intersects(this._boundingInfo.boundingSphere,e._boundingInfo.boundingSphere):this._boundingInfo.intersects(e._boundingInfo,!1))},e.prototype.isInFrustum=function(e){return null!==this._boundingInfo&&this._boundingInfo.isInFrustum(e,this.cullingStrategy)},e.prototype.getRotationMatrix=function(e){var t;if(this.rotationQuaternion)t=this.rotationQuaternion;else{t=a.c.Quaternion[0];var i=this.rotation;a.b.RotationYawPitchRollToRef(i.y,i.x,i.z,t)}t.toRotationMatrix(e)},e}(),ih=function(e,t,i,n,r,o,a,s,c){this._indicesLength=0,this.shapeID=e,this._shape=t,this._indices=i,this._indicesLength=i.length,this._shapeUV=o,this._shapeColors=r,this._normals=n,this._positionFunction=a,this._vertexFunction=s,this._material=c},nh=function(e,t,i){this.ind=0,this.indicesLength=0,this.sqDistance=0,this.materialIndex=0,this.ind=e,this.indicesLength=t,this.materialIndex=i},rh=function(){function e(e,t,i){this.particles=new Array,this.nbParticles=0,this.billboard=!1,this.recomputeNormals=!1,this.counter=0,this.vars={},this._bSphereOnly=!1,this._bSphereRadiusFactor=1,this._positions=new Array,this._indices=new Array,this._normals=new Array,this._colors=new Array,this._uvs=new Array,this._index=0,this._updatable=!0,this._pickable=!1,this._isVisibilityBoxLocked=!1,this._alwaysVisible=!1,this._depthSort=!1,this._expandable=!1,this._shapeCounter=0,this._copy=new th(0,0,0,0,null,0,0,this),this._color=new s.b(0,0,0,0),this._computeParticleColor=!0,this._computeParticleTexture=!0,this._computeParticleRotation=!0,this._computeParticleVertex=!1,this._computeBoundingBox=!1,this._depthSortParticles=!0,this._mustUnrotateFixedNormals=!1,this._particlesIntersect=!1,this._needs32Bits=!1,this._isNotBuilt=!0,this._lastParticleId=0,this._idxOfId=[],this._multimaterialEnabled=!1,this._useModelMaterial=!1,this._depthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},this._materialSortFunction=function(e,t){return e.materialIndex-t.materialIndex},this._autoUpdateSubMeshes=!1,this.name=e,this._scene=t||R.a.LastCreatedScene,this._camera=t.activeCamera,this._pickable=!!i&&i.isPickable,this._depthSort=!!i&&i.enableDepthSort,this._multimaterialEnabled=!!i&&i.enableMultiMaterial,this._useModelMaterial=!!i&&i.useModelMaterial,this._multimaterialEnabled=!!this._useModelMaterial||this._multimaterialEnabled,this._expandable=!!i&&i.expandable,this._particlesIntersect=!!i&&i.particleIntersection,this._bSphereOnly=!!i&&i.boundingSphereOnly,this._bSphereRadiusFactor=i&&i.bSphereRadiusFactor?i.bSphereRadiusFactor:1,i&&void 0!==i.updatable?this._updatable=i.updatable:this._updatable=!0,this._pickable&&(this.pickedParticles=[]),(this._depthSort||this._multimaterialEnabled)&&(this.depthSortedParticles=[]),this._multimaterialEnabled&&(this._multimaterial=new fs.a(this.name+"MultiMaterial",this._scene),this._materials=[],this._materialIndexesById={})}return e.prototype.buildMesh=function(){if(!this._isNotBuilt&&this.mesh)return this.mesh;if(0===this.nbParticles&&!this.mesh){var e=Zl.CreateDisc("",{radius:1,tessellation:3},this._scene);this.addShape(e,1),e.dispose()}if(this._indices32=this._needs32Bits?new Uint32Array(this._indices):new Uint16Array(this._indices),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),!this.mesh){var t=new Ae.a(this.name,this._scene);this.mesh=t}!this._updatable&&this._multimaterialEnabled&&this._sortParticlesByMaterial(),this.recomputeNormals&&$i.a.ComputeNormals(this._positions32,this._indices32,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals),this._mustUnrotateFixedNormals&&this._unrotateFixedNormals();var i=new $i.a;return i.indices=this._depthSort?this._indices:this._indices32,i.set(this._positions32,en.b.PositionKind),i.set(this._normals32,en.b.NormalKind),this._uvs32.length>0&&i.set(this._uvs32,en.b.UVKind),this._colors32.length>0&&i.set(this._colors32,en.b.ColorKind),i.applyToMesh(this.mesh,this._updatable),this.mesh.isPickable=this._pickable,this._multimaterialEnabled&&this.setMultiMaterial(this._materials),this._expandable||(this._depthSort||this._multimaterialEnabled||(this._indices=null),this._positions=null,this._normals=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0)),this._isNotBuilt=!1,this.recomputeNormals=!1,this.mesh},e.prototype.digest=function(e,t){var i=t&&t.facetNb||1,n=t&&t.number||0,r=t&&t.delta||0,o=e.getVerticesData(en.b.PositionKind),s=e.getIndices(),c=e.getVerticesData(en.b.UVKind),l=e.getVerticesData(en.b.ColorKind),u=e.getVerticesData(en.b.NormalKind),h=t&&t.storage?t.storage:null,d=0,f=s.length/3;n?(n=n>f?f:n,i=Math.round(f/n),r=0):i=i>f?f:i;for(var p=[],_=[],m=[],g=[],v=[],y=a.e.Zero(),b=i;d<f;){d>f-(i=b+Math.floor((1+r)*Math.random()))&&(i=f-d),p.length=0,_.length=0,m.length=0,g.length=0,v.length=0;for(var T=0,E=3*d;E<3*(d+i);E++){m.push(T);var x=s[E],P=3*x;if(p.push(o[P],o[P+1],o[P+2]),_.push(u[P],u[P+1],u[P+2]),c){var A=2*x;g.push(c[A],c[A+1])}if(l){var S=4*x;v.push(l[S],l[S+1],l[S+2],l[S+3])}T++}var C,R=this.nbParticles,O=this._posToShape(p),M=this._uvsToShapeUV(g),I=Array.from(m),D=Array.from(v),w=Array.from(_);for(y.copyFromFloats(0,0,0),C=0;C<O.length;C++)y.addInPlace(O[C]);y.scaleInPlace(1/O.length);var L,N=new a.e(1/0,1/0,1/0),F=new a.e(-1/0,-1/0,-1/0);for(C=0;C<O.length;C++)O[C].subtractInPlace(y),N.minimizeInPlaceFromFloats(O[C].x,O[C].y,O[C].z),F.maximizeInPlaceFromFloats(O[C].x,O[C].y,O[C].z);this._particlesIntersect&&(L=new Pn.a(N,F));var B=null;this._useModelMaterial&&(B=e.material?e.material:this._setDefaultMaterial());var U=new ih(this._shapeCounter,O,I,w,D,M,null,null,B),V=this._positions.length,k=this._indices.length;this._meshBuilder(this._index,k,O,this._positions,I,this._indices,g,this._uvs,D,this._colors,w,this._normals,R,0,null,U),this._addParticle(R,this._lastParticleId,V,k,U,this._shapeCounter,0,L,h),this.particles[this.nbParticles].position.addInPlace(y),h||(this._index+=O.length,R++,this.nbParticles++,this._lastParticleId++),this._shapeCounter++,d+=i}return this._isNotBuilt=!0,this},e.prototype._unrotateFixedNormals=function(){for(var e=0,t=0,i=a.c.Vector3[0],n=a.c.Quaternion[0],r=a.c.Matrix[0],o=0;o<this.particles.length;o++){var s=this.particles[o],c=s._model._shape;if(s.rotationQuaternion)s.rotationQuaternion.conjugateToRef(n);else{var l=s.rotation;a.b.RotationYawPitchRollToRef(l.y,l.x,l.z,n),n.conjugateInPlace()}n.toRotationMatrix(r);for(var u=0;u<c.length;u++)t=e+3*u,a.e.TransformNormalFromFloatsToRef(this._normals32[t],this._normals32[t+1],this._normals32[t+2],r,i),i.toArray(this._fixedNormal32,t);e=t+3}},e.prototype._resetCopy=function(){var e=this._copy;e.position.setAll(0),e.rotation.setAll(0),e.rotationQuaternion=null,e.scaling.setAll(1),e.uvs.copyFromFloats(0,0,1,1),e.color=null,e.translateFromPivot=!1,e.materialIndex=null},e.prototype._meshBuilder=function(e,t,i,n,r,o,s,c,l,u,h,d,f,p,_,m){var g,v=0,y=0,b=0;this._resetCopy();var T=this._copy,E=!(!_||!_.storage);if(T.idx=f,T.idxInShape=p,this._useModelMaterial){var x=m._material.uniqueId,P=this._materialIndexesById;P.hasOwnProperty(x)||(P[x]=this._materials.length,this._materials.push(m._material));var A=P[x];T.materialIndex=A}if(_&&_.positionFunction&&(_.positionFunction(T,f,p),this._mustUnrotateFixedNormals=!0),E)return T;var S=a.c.Matrix[0],C=a.c.Vector3[0],R=a.c.Vector3[1],O=a.c.Vector3[2],M=a.c.Vector3[3];a.a.IdentityToRef(S),T.getRotationMatrix(S),T.pivot.multiplyToRef(T.scaling,M),T.translateFromPivot?O.setAll(0):O.copyFrom(M);var I=_&&_.vertexFunction;for(g=0;g<i.length;g++){if(C.copyFrom(i[g]),I&&_.vertexFunction(T,C,g),C.multiplyInPlace(T.scaling).subtractInPlace(M),a.e.TransformCoordinatesToRef(C,S,R),R.addInPlace(O).addInPlace(T.position),n.push(R.x,R.y,R.z),s){var D=T.uvs;c.push((D.z-D.x)*s[v]+D.x,(D.w-D.y)*s[v+1]+D.y),v+=2}if(T.color)this._color=T.color;else{var w=this._color;l&&void 0!==l[y]?(w.r=l[y],w.g=l[y+1],w.b=l[y+2],w.a=l[y+3]):(w.r=1,w.g=1,w.b=1,w.a=1)}u.push(this._color.r,this._color.g,this._color.b,this._color.a),y+=4,!this.recomputeNormals&&h&&(a.e.TransformNormalFromFloatsToRef(h[b],h[b+1],h[b+2],S,C),d.push(C.x,C.y,C.z),b+=3)}for(g=0;g<r.length;g++){var L=e+r[g];o.push(L),L>65535&&(this._needs32Bits=!0)}if(this._pickable){var N=r.length/3;for(g=0;g<N;g++)this.pickedParticles.push({idx:f,faceId:g})}if(this._depthSort||this._multimaterialEnabled){var F=null!==T.materialIndex?T.materialIndex:0;this.depthSortedParticles.push(new nh(t,r.length,F))}return T},e.prototype._posToShape=function(e){for(var t=[],i=0;i<e.length;i+=3)t.push(a.e.FromArray(e,i));return t},e.prototype._uvsToShapeUV=function(e){var t=[];if(e)for(var i=0;i<e.length;i++)t.push(e[i]);return t},e.prototype._addParticle=function(e,t,i,n,r,o,a,s,c){void 0===s&&(s=null),void 0===c&&(c=null);var l=new th(e,t,i,n,r,o,a,this,s);return(c||this.particles).push(l),l},e.prototype.addShape=function(e,t,i){var n=e.getVerticesData(en.b.PositionKind),r=e.getIndices(),o=e.getVerticesData(en.b.UVKind),a=e.getVerticesData(en.b.ColorKind),s=e.getVerticesData(en.b.NormalKind);this.recomputeNormals=!s;var c=Array.from(r),l=Array.from(s),u=a?Array.from(a):[],h=i&&i.storage?i.storage:null,d=null;this._particlesIntersect&&(d=e.getBoundingInfo());var f=this._posToShape(n),p=this._uvsToShapeUV(o),_=i?i.positionFunction:null,m=i?i.vertexFunction:null,g=null;this._useModelMaterial&&(g=e.material?e.material:this._setDefaultMaterial());for(var v=new ih(this._shapeCounter,f,c,l,u,p,_,m,g),y=0;y<t;y++)this._insertNewParticle(this.nbParticles,y,v,f,r,o,a,s,d,h,i);return this._shapeCounter++,this._isNotBuilt=!0,this._shapeCounter-1},e.prototype._rebuildParticle=function(e,t){void 0===t&&(t=!1),this._resetCopy();var i=this._copy;e._model._positionFunction&&e._model._positionFunction(i,e.idx,e.idxInShape);var n=a.c.Matrix[0],r=a.c.Vector3[0],o=a.c.Vector3[1],s=a.c.Vector3[2],c=a.c.Vector3[3];i.getRotationMatrix(n),e.pivot.multiplyToRef(e.scaling,c),i.translateFromPivot?s.copyFromFloats(0,0,0):s.copyFrom(c);for(var l=e._model._shape,u=0;u<l.length;u++)r.copyFrom(l[u]),e._model._vertexFunction&&e._model._vertexFunction(i,r,u),r.multiplyInPlace(i.scaling).subtractInPlace(c),a.e.TransformCoordinatesToRef(r,n,o),o.addInPlace(s).addInPlace(i.position).toArray(this._positions32,e._pos+3*u);t&&(e.position.setAll(0),e.rotation.setAll(0),e.rotationQuaternion=null,e.scaling.setAll(1),e.uvs.setAll(0),e.pivot.setAll(0),e.translateFromPivot=!1,e.parentId=null)},e.prototype.rebuildMesh=function(e){void 0===e&&(e=!1);for(var t=0;t<this.particles.length;t++)this._rebuildParticle(this.particles[t],e);return this.mesh.updateVerticesData(en.b.PositionKind,this._positions32,!1,!1),this},e.prototype.removeParticles=function(e,t){var i=t-e+1;if(!this._expandable||i<=0||i>=this.nbParticles||!this._updatable)return[];var n=this.particles,r=this.nbParticles;if(t<r-1)for(var o=t+1,a=n[o]._pos-n[e]._pos,s=n[o]._ind-n[e]._ind,c=o;c<r;c++){var l=n[c];l._pos-=a,l._ind-=s}var u=n.splice(e,i);this._positions.length=0,this._indices.length=0,this._colors.length=0,this._uvs.length=0,this._normals.length=0,this._index=0,this._idxOfId.length=0,(this._depthSort||this._multimaterialEnabled)&&(this.depthSortedParticles=[]);for(var h=0,d=n.length,f=0;f<d;f++){var p=n[f],_=p._model,m=_._shape,g=_._indices,v=_._normals,y=_._shapeColors,b=_._shapeUV;p.idx=f,this._idxOfId[p.id]=f,this._meshBuilder(this._index,h,m,this._positions,g,this._indices,b,this._uvs,y,this._colors,v,this._normals,p.idx,p.idxInShape,null,_),this._index+=m.length,h+=g.length}return this.nbParticles-=i,this._isNotBuilt=!0,u},e.prototype.insertParticlesFromArray=function(e){if(!this._expandable)return this;for(var t=0,i=e[0].shapeId,n=e.length,r=0;r<n;r++){var o=e[r],a=o._model,s=a._shape,c=a._indices,l=a._shapeUV,u=a._shapeColors,h=a._normals,d=!h;this.recomputeNormals=d||this.recomputeNormals;var f=o._boundingInfo,p=this._insertNewParticle(this.nbParticles,t,a,s,c,l,u,h,f,null,null);o.copyToRef(p),t++,i!=o.shapeId&&(i=o.shapeId,t=0)}return this._isNotBuilt=!0,this},e.prototype._insertNewParticle=function(e,t,i,n,r,o,a,s,c,l,u){var h=this._positions.length,d=this._indices.length,f=this._meshBuilder(this._index,d,n,this._positions,r,this._indices,o,this._uvs,a,this._colors,s,this._normals,e,t,u,i),p=null;return this._updatable&&((p=this._addParticle(this.nbParticles,this._lastParticleId,h,d,i,this._shapeCounter,t,c,l)).position.copyFrom(f.position),p.rotation.copyFrom(f.rotation),f.rotationQuaternion&&(p.rotationQuaternion?p.rotationQuaternion.copyFrom(f.rotationQuaternion):p.rotationQuaternion=f.rotationQuaternion.clone()),f.color&&(p.color?p.color.copyFrom(f.color):p.color=f.color.clone()),p.scaling.copyFrom(f.scaling),p.uvs.copyFrom(f.uvs),null!==f.materialIndex&&(p.materialIndex=f.materialIndex),this.expandable&&(this._idxOfId[p.id]=p.idx)),l||(this._index+=n.length,this.nbParticles++,this._lastParticleId++),p},e.prototype.setParticles=function(e,t,i){if(void 0===e&&(e=0),void 0===t&&(t=this.nbParticles-1),void 0===i&&(i=!0),!this._updatable||this._isNotBuilt)return this;this.beforeUpdateParticles(e,t,i);var n=a.c.Matrix[0],r=a.c.Matrix[1],o=this.mesh,s=this._colors32,c=this._positions32,l=this._normals32,u=this._uvs32,h=this._indices32,d=this._indices,f=this._fixedNormal32,p=a.c.Vector3,_=p[5].copyFromFloats(1,0,0),m=p[6].copyFromFloats(0,1,0),g=p[7].copyFromFloats(0,0,1),v=p[8].setAll(Number.MAX_VALUE),y=p[9].setAll(-Number.MAX_VALUE),b=p[10].setAll(0);if((this.billboard||this._depthSort)&&(this.mesh.computeWorldMatrix(!0),this.mesh._worldMatrix.invertToRef(r)),this.billboard){var T=p[0];this._camera.getDirectionToRef(Z.a.Z,T),a.e.TransformNormalToRef(T,r,g),g.normalize();var E=this._camera.getViewMatrix(!0);a.e.TransformNormalFromFloatsToRef(E.m[1],E.m[5],E.m[9],r,m),a.e.CrossToRef(m,g,_),m.normalize(),_.normalize()}this._depthSort&&a.e.TransformCoordinatesToRef(this._camera.globalPosition,r,b),a.a.IdentityToRef(n);var x=0,P=0,A=0,S=0,C=0,R=0,O=0;if(this.mesh.isFacetDataEnabled&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){var M=this.mesh._boundingInfo;M&&(v.copyFrom(M.minimum),y.copyFrom(M.maximum))}var I=(P=this.particles[e]._pos)/3|0;S=4*I,R=2*I;for(var D=e;D<=t;D++){var w=this.particles[D];this.updateParticle(w);var L=w._model._shape,N=w._model._shapeUV,F=w._rotationMatrix,B=w.position,U=w.rotation,V=w.scaling,k=w._globalPosition;if(this._depthSort&&this._depthSortParticles){var z=this.depthSortedParticles[D];z.ind=w._ind,z.indicesLength=w._model._indicesLength,z.sqDistance=a.e.DistanceSquared(w.position,b)}if(!w.alive||w._stillInvisible&&!w.isVisible)P+=3*(O=L.length),S+=4*O,R+=2*O;else{if(w.isVisible){w._stillInvisible=!1;var G=p[12];if(w.pivot.multiplyToRef(V,G),this.billboard&&(U.x=0,U.y=0),(this._computeParticleRotation||this.billboard)&&w.getRotationMatrix(n),null!==w.parentId){var j=this.getParticleById(w.parentId);if(j){var W=j._rotationMatrix,X=j._globalPosition,H=B.x*W[1]+B.y*W[4]+B.z*W[7],Y=B.x*W[0]+B.y*W[3]+B.z*W[6],K=B.x*W[2]+B.y*W[5]+B.z*W[8];if(k.x=X.x+Y,k.y=X.y+H,k.z=X.z+K,this._computeParticleRotation||this.billboard){var Q=n.m;F[0]=Q[0]*W[0]+Q[1]*W[3]+Q[2]*W[6],F[1]=Q[0]*W[1]+Q[1]*W[4]+Q[2]*W[7],F[2]=Q[0]*W[2]+Q[1]*W[5]+Q[2]*W[8],F[3]=Q[4]*W[0]+Q[5]*W[3]+Q[6]*W[6],F[4]=Q[4]*W[1]+Q[5]*W[4]+Q[6]*W[7],F[5]=Q[4]*W[2]+Q[5]*W[5]+Q[6]*W[8],F[6]=Q[8]*W[0]+Q[9]*W[3]+Q[10]*W[6],F[7]=Q[8]*W[1]+Q[9]*W[4]+Q[10]*W[7],F[8]=Q[8]*W[2]+Q[9]*W[5]+Q[10]*W[8]}}else w.parentId=null}else if(k.x=B.x,k.y=B.y,k.z=B.z,this._computeParticleRotation||this.billboard){Q=n.m;F[0]=Q[0],F[1]=Q[1],F[2]=Q[2],F[3]=Q[4],F[4]=Q[5],F[5]=Q[6],F[6]=Q[8],F[7]=Q[9],F[8]=Q[10]}var q=p[11];for(w.translateFromPivot?q.setAll(0):q.copyFrom(G),O=0;O<L.length;O++){x=P+3*O,A=S+4*O,C=R+2*O,(T=p[0]).copyFrom(L[O]),this._computeParticleVertex&&this.updateParticleVertex(w,T,O);var J=T.x*V.x-G.x,$=T.y*V.y-G.y,ee=T.z*V.z-G.z;Y=J*F[0]+$*F[3]+ee*F[6],H=J*F[1]+$*F[4]+ee*F[7],K=J*F[2]+$*F[5]+ee*F[8];Y+=q.x,H+=q.y,K+=q.z;var te=c[x]=k.x+_.x*Y+m.x*H+g.x*K,ie=c[x+1]=k.y+_.y*Y+m.y*H+g.y*K,ne=c[x+2]=k.z+_.z*Y+m.z*H+g.z*K;if(this._computeBoundingBox&&(v.minimizeInPlaceFromFloats(te,ie,ne),y.maximizeInPlaceFromFloats(te,ie,ne)),!this._computeParticleVertex){var re=f[x],oe=f[x+1],ae=f[x+2],se=re*F[0]+oe*F[3]+ae*F[6],ce=re*F[1]+oe*F[4]+ae*F[7],le=re*F[2]+oe*F[5]+ae*F[8];l[x]=_.x*se+m.x*ce+g.x*le,l[x+1]=_.y*se+m.y*ce+g.y*le,l[x+2]=_.z*se+m.z*ce+g.z*le}if(this._computeParticleColor&&w.color){var ue=w.color,he=this._colors32;he[A]=ue.r,he[A+1]=ue.g,he[A+2]=ue.b,he[A+3]=ue.a}if(this._computeParticleTexture){var de=w.uvs;u[C]=N[2*O]*(de.z-de.x)+de.x,u[C+1]=N[2*O+1]*(de.w-de.y)+de.y}}}else for(w._stillInvisible=!0,O=0;O<L.length;O++){if(A=S+4*O,C=R+2*O,c[x=P+3*O]=c[x+1]=c[x+2]=0,l[x]=l[x+1]=l[x+2]=0,this._computeParticleColor&&w.color){ue=w.color;s[A]=ue.r,s[A+1]=ue.g,s[A+2]=ue.b,s[A+3]=ue.a}if(this._computeParticleTexture){de=w.uvs;u[C]=N[2*O]*(de.z-de.x)+de.x,u[C+1]=N[2*O+1]*(de.w-de.y)+de.y}}if(this._particlesIntersect){var fe=w._boundingInfo,pe=fe.boundingBox,_e=fe.boundingSphere,me=w._modelBoundingInfo;if(!this._bSphereOnly){var ge=me.boundingBox.vectors,ve=p[1],ye=p[2];ve.setAll(Number.MAX_VALUE),ye.setAll(-Number.MAX_VALUE);for(var be=0;be<8;be++){var Te=ge[be].x*V.x,Ee=ge[be].y*V.y,xe=ge[be].z*V.z,Pe=(Y=Te*F[0]+Ee*F[3]+xe*F[6],H=Te*F[1]+Ee*F[4]+xe*F[7],K=Te*F[2]+Ee*F[5]+xe*F[8],B.x+_.x*Y+m.x*H+g.x*K),Ae=B.y+_.y*Y+m.y*H+g.y*K,Se=B.z+_.z*Y+m.z*H+g.z*K;ve.minimizeInPlaceFromFloats(Pe,Ae,Se),ye.maximizeInPlaceFromFloats(Pe,Ae,Se)}pe.reConstruct(ve,ye,o._worldMatrix)}var Ce=me.minimum.multiplyToRef(V,p[1]),Re=me.maximum.multiplyToRef(V,p[2]),Oe=Re.addToRef(Ce,p[3]).scaleInPlace(.5).addInPlace(k),Me=Re.subtractToRef(Ce,p[4]).scaleInPlace(.5*this._bSphereRadiusFactor),Ie=Oe.subtractToRef(Me,p[1]),De=Oe.addToRef(Me,p[2]);_e.reConstruct(Ie,De,o._worldMatrix)}P=x+3,S=A+4,R=C+2}}if(i){if(this._computeParticleColor&&o.updateVerticesData(en.b.ColorKind,s,!1,!1),this._computeParticleTexture&&o.updateVerticesData(en.b.UVKind,u,!1,!1),o.updateVerticesData(en.b.PositionKind,c,!1,!1),!o.areNormalsFrozen||o.isFacetDataEnabled){if(this._computeParticleVertex||o.isFacetDataEnabled){var we=o.isFacetDataEnabled?o.getFacetDataParameters():null;$i.a.ComputeNormals(c,h,l,we);for(var Le=0;Le<l.length;Le++)f[Le]=l[Le]}o.areNormalsFrozen||o.updateVerticesData(en.b.NormalKind,l,!1,!1)}if(this._depthSort&&this._depthSortParticles){var Ne=this.depthSortedParticles;Ne.sort(this._depthSortFunction);for(var Fe=Ne.length,Be=0,Ue=0;Ue<Fe;Ue++){var Ve=Ne[Ue].indicesLength,ke=Ne[Ue].ind;for(Le=0;Le<Ve;Le++)h[Be]=d[ke+Le],Be++}o.updateIndices(h)}}return this._computeBoundingBox&&(o._boundingInfo?o._boundingInfo.reConstruct(v,y,o._worldMatrix):o._boundingInfo=new Pn.a(v,y,o._worldMatrix)),this._autoUpdateSubMeshes&&this.computeSubMeshes(),this.afterUpdateParticles(e,t,i),this},e.prototype.dispose=function(){this.mesh.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._indices32=null,this._positions32=null,this._normals32=null,this._fixedNormal32=null,this._uvs32=null,this._colors32=null,this.pickedParticles=null},e.prototype.getParticleById=function(e){var t=this.particles[e];if(t&&t.id==e)return t;var i=this.particles,n=this._idxOfId[e];if(void 0!==n)return i[n];for(var r=0,o=this.nbParticles;r<o;){var a=i[r];if(a.id==e)return a;r++}return null},e.prototype.getParticlesByShapeId=function(e){var t=[];return this.getParticlesByShapeIdToRef(e,t),t},e.prototype.getParticlesByShapeIdToRef=function(e,t){t.length=0;for(var i=0;i<this.nbParticles;i++){var n=this.particles[i];n.shapeId==e&&t.push(n)}return this},e.prototype.computeSubMeshes=function(){if(!this.mesh||!this._multimaterialEnabled)return this;var e=this.depthSortedParticles;if(this.particles.length>0)for(var t=0;t<this.particles.length;t++){var i=this.particles[t];i.materialIndex||(i.materialIndex=0);var n=e[t];n.materialIndex=i.materialIndex,n.ind=i._ind,n.indicesLength=i._model._indicesLength}this._sortParticlesByMaterial();var r=this._indicesByMaterial,o=this._materialIndexes,a=this.mesh;a.subMeshes=[];for(var s=a.getTotalVertices(),c=0;c<o.length;c++){var l=r[c],u=r[c+1]-l,h=o[c];new zl.b(h,0,s,l,u,a)}return this},e.prototype._sortParticlesByMaterial=function(){var e=[0];this._indicesByMaterial=e;var t=[];this._materialIndexes=t;var i=this.depthSortedParticles;i.sort(this._materialSortFunction);var n=i.length,r=this._indices32,o=this._indices,a=0,s=i[0].materialIndex;t.push(s);for(var c=0;c<n;c++){var l=i[c],u=l.indicesLength,h=l.ind;l.materialIndex!==s&&(s=l.materialIndex,e.push(a),t.push(s));for(var d=0;d<u;d++)r[a]=o[h+d],a++}return e.push(r.length),this._updatable&&this.mesh.updateIndices(r),this},e.prototype._setMaterialIndexesById=function(){this._materialIndexesById={};for(var e=0;e<this._materials.length;e++){var t=this._materials[e].uniqueId;this._materialIndexesById[t]=e}},e.prototype._filterUniqueMaterialId=function(e){return e.filter(function(e,t,i){return i.indexOf(e)===t})},e.prototype._setDefaultMaterial=function(){return this._defaultMaterial||(this._defaultMaterial=new Ki.a(this.name+"DefaultMaterial",this._scene)),this._defaultMaterial},e.prototype.refreshVisibleSize=function(){return this._isVisibilityBoxLocked||this.mesh.refreshBoundingInfo(),this},e.prototype.setVisibilityBox=function(e){var t=e/2;this.mesh._boundingInfo=new Pn.a(new a.e(-t,-t,-t),new a.e(t,t,t))},Object.defineProperty(e.prototype,"isAlwaysVisible",{get:function(){return this._alwaysVisible},set:function(e){this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isVisibilityBoxLocked",{get:function(){return this._isVisibilityBoxLocked},set:function(e){this._isVisibilityBoxLocked=e,this.mesh.getBoundingInfo().isLocked=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"computeParticleRotation",{get:function(){return this._computeParticleRotation},set:function(e){this._computeParticleRotation=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"computeParticleColor",{get:function(){return this._computeParticleColor},set:function(e){this._computeParticleColor=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"computeParticleTexture",{get:function(){return this._computeParticleTexture},set:function(e){this._computeParticleTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"computeParticleVertex",{get:function(){return this._computeParticleVertex},set:function(e){this._computeParticleVertex=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"computeBoundingBox",{get:function(){return this._computeBoundingBox},set:function(e){this._computeBoundingBox=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"depthSortParticles",{get:function(){return this._depthSortParticles},set:function(e){this._depthSortParticles=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"expandable",{get:function(){return this._expandable},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"multimaterialEnabled",{get:function(){return this._multimaterialEnabled},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useModelMaterial",{get:function(){return this._useModelMaterial},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"materials",{get:function(){return this._materials},enumerable:!0,configurable:!0}),e.prototype.setMultiMaterial=function(e){this._materials=this._filterUniqueMaterialId(e),this._setMaterialIndexesById(),this._multimaterial&&this._multimaterial.dispose(),this._multimaterial=new fs.a(this.name+"MultiMaterial",this._scene);for(var t=0;t<this._materials.length;t++)this._multimaterial.subMaterials.push(this._materials[t]);this.computeSubMeshes(),this.mesh.material=this._multimaterial},Object.defineProperty(e.prototype,"multimaterial",{get:function(){return this._multimaterial},set:function(e){this._multimaterial=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"autoUpdateSubMeshes",{get:function(){return this._autoUpdateSubMeshes},set:function(e){this._autoUpdateSubMeshes=e},enumerable:!0,configurable:!0}),e.prototype.initParticles=function(){},e.prototype.recycleParticle=function(e){return e},e.prototype.updateParticle=function(e){return e},e.prototype.updateParticleVertex=function(e,t,i){return t},e.prototype.beforeUpdateParticles=function(e,t,i){},e.prototype.afterUpdateParticles=function(e,t,i){},e}(),oh=function(){function e(e,t,i,n,r){this.idx=0,this.color=new s.b(1,1,1,1),this.position=a.e.Zero(),this.rotation=a.e.Zero(),this.uv=new a.d(0,0),this.velocity=a.e.Zero(),this.pivot=a.e.Zero(),this.translateFromPivot=!1,this._pos=0,this._ind=0,this.groupId=0,this.idxInGroup=0,this._stillInvisible=!1,this._rotationMatrix=[1,0,0,0,1,0,0,0,1],this.parentId=null,this._globalPosition=a.e.Zero(),this.idx=e,this._group=t,this.groupId=i,this.idxInGroup=n,this._pcs=r}return Object.defineProperty(e.prototype,"size",{get:function(){return this.size},set:function(e){this.size=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"quaternion",{get:function(){return this.rotationQuaternion},set:function(e){this.rotationQuaternion=e},enumerable:!0,configurable:!0}),e.prototype.intersectsMesh=function(e,t){if(!e._boundingInfo)return!1;if(t=t||!1)return e.getBoundingInfo().boundingSphere.intersectsPoint(this.position.add(this._pcs.mesh.position));var i,n,r,o,a,s;i=e.getBoundingInfo().boundingBox.maximumWorld.x,n=e.getBoundingInfo().boundingBox.minimumWorld.x,r=e.getBoundingInfo().boundingBox.maximumWorld.y,o=e.getBoundingInfo().boundingBox.minimumWorld.y,a=e.getBoundingInfo().boundingBox.maximumWorld.z,s=e.getBoundingInfo().boundingBox.minimumWorld.z;var c=this.position.x+this._pcs.mesh.position.x,l=this.position.y+this._pcs.mesh.position.y,u=this.position.z+this._pcs.mesh.position.z;return n<=c&&c<=i&&o<=l&&l<=r&&s<=u&&u<=a},e.prototype.getRotationMatrix=function(e){var t;if(this.rotationQuaternion)t=this.rotationQuaternion;else{t=a.c.Quaternion[0];var i=this.rotation;a.b.RotationYawPitchRollToRef(i.y,i.x,i.z,t)}t.toRotationMatrix(e)},e}(),ah=function(e,t){this.groupID=e,this._positionFunction=t};!function(e){e[e.Color=2]="Color",e[e.UV=1]="UV",e[e.Random=0]="Random",e[e.Stated=3]="Stated"}(eh||(eh={}));var sh=function(){function e(e,t,i,n){this.particles=new Array,this.nbParticles=0,this.counter=0,this.vars={},this._promises=[],this._positions=new Array,this._indices=new Array,this._normals=new Array,this._colors=new Array,this._uvs=new Array,this._updatable=!0,this._isVisibilityBoxLocked=!1,this._alwaysVisible=!1,this._groups=new Array,this._groupCounter=0,this._computeParticleColor=!0,this._computeParticleTexture=!0,this._computeParticleRotation=!0,this._computeBoundingBox=!1,this._isReady=!1,this.name=e,this._size=t,this._scene=i||R.a.LastCreatedScene,n&&void 0!==n.updatable?this._updatable=n.updatable:this._updatable=!0}return e.prototype.buildMeshAsync=function(){var e=this;return Promise.all(this._promises).then(function(){return e._isReady=!0,e._buildMesh()})},e.prototype._buildMesh=function(){0===this.nbParticles&&this.addPoints(1),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors);var e=new $i.a;e.set(this._positions32,en.b.PositionKind),this._uvs32.length>0&&e.set(this._uvs32,en.b.UVKind);var t=0;this._colors32.length>0&&(t=1,e.set(this._colors32,en.b.ColorKind));var i=new Ae.a(this.name,this._scene);e.applyToMesh(i,this._updatable),this.mesh=i,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);var n=new Ki.a("point cloud material",this._scene);return n.emissiveColor=new s.a(t,t,t),n.disableLighting=!0,n.pointsCloud=!0,n.pointSize=this._size,i.material=n,new Promise(function(e){return e(i)})},e.prototype._addParticle=function(e,t,i,n){var r=new oh(e,t,i,n,this);return this.particles.push(r),r},e.prototype._randomUnitVector=function(e){e.position=new a.e(Math.random(),Math.random(),Math.random()),e.color=new s.b(1,1,1,1)},e.prototype._getColorIndicesForCoord=function(e,t,i,n){var r=e._groupImageData,o=i*(4*n)+4*t,a=[o,o+1,o+2,o+3],c=a[1],l=a[2],u=a[3],h=r[a[0]],d=r[c],f=r[l],p=r[u];return new s.b(h/255,d/255,f/255,p)},e.prototype._setPointsColorOrUV=function(e,t,i,n,r,o,c){i&&e.updateFacetData();var l=2*e.getBoundingInfo().boundingSphere.radius,u=e.getVerticesData(en.b.PositionKind),h=e.getIndices(),d=e.getVerticesData(en.b.UVKind),f=e.getVerticesData(en.b.ColorKind),p=a.e.Zero();e.computeWorldMatrix();var _=e.getWorldMatrix();if(!_.isIdentity())for(var m=0;m<u.length/3;m++)a.e.TransformCoordinatesFromFloatsToRef(u[3*m],u[3*m+1],u[3*m+2],_,p),u[3*m]=p.x,u[3*m+1]=p.y,u[3*m+2]=p.z;var g,v,y=0,b=0,T=0,E=0,x=0,P=0,A=0,S=0,C=0,R=0,O=0,M=0,I=0,D=0,w=a.e.Zero(),N=a.e.Zero(),F=a.e.Zero(),B=a.e.Zero(),U=a.e.Zero(),V=0,k=0,z=0,G=0,j=0,W=0,X=a.d.Zero(),H=a.d.Zero(),Y=a.d.Zero(),K=a.d.Zero(),Q=a.d.Zero(),q=0,Z=0,J=0,$=0,ee=0,te=0,ie=0,ne=0,re=0,oe=0,ae=0,se=0,ce=a.f.Zero(),le=a.f.Zero(),ue=a.f.Zero(),he=a.f.Zero(),de=a.f.Zero(),fe=0,pe=0;c=c||0;var _e,me=new a.f(0,0,0,0),ge=a.e.Zero(),ve=a.e.Zero(),ye=a.e.Zero(),be=0,Te=a.e.Zero(),Ee=0,xe=0,Pe=new Ht.a(a.e.Zero(),new a.e(1,0,0)),Ae=a.e.Zero();for(b=0;b<h.length/3;b++){var Se,Ce,Re,Oe,Me,Ie,De,we;T=h[3*b],E=h[3*b+1],x=h[3*b+2],P=u[3*T],A=u[3*T+1],S=u[3*T+2],C=u[3*E],R=u[3*E+1],O=u[3*E+2],M=u[3*x],I=u[3*x+1],D=u[3*x+2],w.set(P,A,S),N.set(C,R,O),F.set(M,I,D),N.subtractToRef(w,B),F.subtractToRef(N,U),d&&(V=d[2*T],k=d[2*T+1],z=d[2*E],G=d[2*E+1],j=d[2*x],W=d[2*x+1],X.set(V,k),H.set(z,G),Y.set(j,W),H.subtractToRef(X,K),Y.subtractToRef(H,Q)),f&&n&&(q=f[4*T],Z=f[4*T+1],J=f[4*T+2],$=f[4*T+3],ee=f[4*E],te=f[4*E+1],ie=f[4*E+2],ne=f[4*E+3],re=f[4*x],oe=f[4*x+1],ae=f[4*x+2],se=f[4*x+3],ce.set(q,Z,J,$),le.set(ee,te,ie,ne),ue.set(re,oe,ae,se),le.subtractToRef(ce,he),ue.subtractToRef(le,de));for(var Le,Ne,Fe=new s.a(0,0,0),Be=new s.a(0,0,0),Ue=0;Ue<t._groupDensity[b];Ue++)y=this.particles.length,this._addParticle(y,t,this._groupCounter,b+Ue),Ne=this.particles[y],fe=L.a.RandomRange(0,1),pe=L.a.RandomRange(0,1),g=w.add(B.scale(fe)).add(U.scale(fe*pe)),i&&(ge=e.getFacetNormal(b).normalize().scale(-1),ve=B.clone().normalize(),ye=a.e.Cross(ge,ve),be=L.a.RandomRange(0,2*Math.PI),Te=ve.scale(Math.cos(be)).add(ye.scale(Math.sin(be))),be=L.a.RandomRange(.1,Math.PI/2),Ae=Te.scale(Math.cos(be)).add(ge.scale(Math.sin(be))),Pe.origin=g.add(Ae.scale(1e-5)),Pe.direction=Ae,Pe.length=l,(_e=Pe.intersectsMesh(e)).hit&&(xe=_e.pickedPoint.subtract(g).length(),Ee=L.a.RandomRange(0,1)*xe,g.addInPlace(Ae.scale(Ee)))),Ne.position=g.clone(),this._positions.push(Ne.position.x,Ne.position.y,Ne.position.z),void 0!==n?d&&(v=X.add(K.scale(fe)).add(Q.scale(fe*pe)),n?r&&null!==t._groupImageData?(Se=t._groupImgWidth,Ce=t._groupImgHeight,Le=this._getColorIndicesForCoord(t,Math.round(v.x*Se),Math.round(v.y*Ce),Se),Ne.color=Le,this._colors.push(Le.r,Le.g,Le.b,Le.a)):f?(me=ce.add(he.scale(fe)).add(de.scale(fe*pe)),Ne.color=new s.b(me.x,me.y,me.z,me.w),this._colors.push(me.x,me.y,me.z,me.w)):(me=ce.set(Math.random(),Math.random(),Math.random(),1),Ne.color=new s.b(me.x,me.y,me.z,me.w),this._colors.push(me.x,me.y,me.z,me.w)):(Ne.uv=v.clone(),this._uvs.push(Ne.uv.x,Ne.uv.y))):(o?(Fe.set(o.r,o.g,o.b),Re=L.a.RandomRange(-c,c),Oe=L.a.RandomRange(-c,c),Me=(we=Fe.toHSV()).r,(Ie=we.g+Re)<0&&(Ie=0),Ie>1&&(Ie=1),(De=we.b+Oe)<0&&(De=0),De>1&&(De=1),s.a.HSVtoRGBToRef(Me,Ie,De,Be),me.set(Be.r,Be.g,Be.b,1)):me=ce.set(Math.random(),Math.random(),Math.random(),1),Ne.color=new s.b(me.x,me.y,me.z,me.w),this._colors.push(me.x,me.y,me.z,me.w))}},e.prototype._colorFromTexture=function(e,t,i){var n=this;if(null===e.material)return m.a.Warn(e.name+"has no material."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);var r=e.material.getActiveTextures();if(0===r.length)return m.a.Warn(e.name+"has no useable texture."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);var o=e.clone();o.setEnabled(!1),this._promises.push(new Promise(function(e){jn.a.WhenAllReady(r,function(){var a=t._textureNb;return a<0&&(a=0),a>r.length-1&&(a=r.length-1),t._groupImageData=r[a].readPixels(),t._groupImgWidth=r[a].getSize().width,t._groupImgHeight=r[a].getSize().height,n._setPointsColorOrUV(o,t,i,!0,!0),o.dispose(),e()})}))},e.prototype._calculateDensity=function(e,t,i){for(var n,r,o,s,c,l,u,h,d,f,p,_,m,g,v,y,b,T=new Array,E=a.e.Zero(),x=a.e.Zero(),P=a.e.Zero(),A=a.e.Zero(),S=a.e.Zero(),C=a.e.Zero(),R=new Array,O=0,M=i.length/3,I=0;I<M;I++)n=i[3*I],r=i[3*I+1],o=i[3*I+2],s=t[3*n],c=t[3*n+1],l=t[3*n+2],u=t[3*r],h=t[3*r+1],d=t[3*r+2],f=t[3*o],p=t[3*o+1],_=t[3*o+2],E.set(s,c,l),x.set(u,h,d),P.set(f,p,_),x.subtractToRef(E,A),P.subtractToRef(x,S),P.subtractToRef(E,C),y=((m=A.length())+(g=S.length())+(v=C.length()))/2,O+=b=Math.sqrt(y*(y-m)*(y-g)*(y-v)),R[I]=b;var D=0;for(I=0;I<M;I++)T[I]=Math.floor(e*R[I]/O),D+=T[I];var w=e-D,L=Math.floor(w/M),N=w%M;L>0&&(T=T.map(function(e){return e+L}));for(I=0;I<N;I++)T[I]+=1;return T},e.prototype.addPoints=function(e,t){void 0===t&&(t=this._randomUnitVector);for(var i,n=new ah(this._groupCounter,t),r=this.nbParticles,o=0;o<e;o++)i=this._addParticle(r,n,this._groupCounter,o),n&&n._positionFunction&&n._positionFunction(i,r,o),this._positions.push(i.position.x,i.position.y,i.position.z),i.color&&this._colors.push(i.color.r,i.color.g,i.color.b,i.color.a),i.uv&&this._uvs.push(i.uv.x,i.uv.y),r++;return this.nbParticles+=e,this._groupCounter++,this._groupCounter},e.prototype.addSurfacePoints=function(e,t,i,n,r){var o=i||eh.Random;(isNaN(o)||o<0||o>3)&&(o=eh.Random);var a=e.getVerticesData(en.b.PositionKind),c=e.getIndices();this._groups.push(this._groupCounter);var l=new ah(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,a,c),o===eh.Color?l._textureNb=n||0:n=n||new s.b(1,1,1,1),o){case eh.Color:this._colorFromTexture(e,l,!1);break;case eh.UV:this._setPointsColorOrUV(e,l,!1,!1,!1);break;case eh.Random:this._setPointsColorOrUV(e,l,!1);break;case eh.Stated:this._setPointsColorOrUV(e,l,!1,void 0,void 0,n,r)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1},e.prototype.addVolumePoints=function(e,t,i,n,r){var o=i||eh.Random;(isNaN(o)||o<0||o>3)&&(o=eh.Random);var a=e.getVerticesData(en.b.PositionKind),c=e.getIndices();this._groups.push(this._groupCounter);var l=new ah(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,a,c),o===eh.Color?l._textureNb=n||0:n=n||new s.b(1,1,1,1),o){case eh.Color:this._colorFromTexture(e,l,!0);break;case eh.UV:this._setPointsColorOrUV(e,l,!0,!1,!1);break;case eh.Random:this._setPointsColorOrUV(e,l,!0);break;case eh.Stated:this._setPointsColorOrUV(e,l,!0,void 0,void 0,n,r)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1},e.prototype.setParticles=function(e,t,i){if(void 0===e&&(e=0),void 0===t&&(t=this.nbParticles-1),void 0===i&&(i=!0),!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(e,t,i);var n=a.c.Matrix[0],r=this.mesh,o=this._colors32,s=this._positions32,c=this._uvs32,l=a.c.Vector3,u=l[5].copyFromFloats(1,0,0),h=l[6].copyFromFloats(0,1,0),d=l[7].copyFromFloats(0,0,1),f=l[8].setAll(Number.MAX_VALUE),p=l[9].setAll(-Number.MAX_VALUE);a.a.IdentityToRef(n);var _=0;if(this.mesh.isFacetDataEnabled&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){var m=this.mesh._boundingInfo;m&&(f.copyFrom(m.minimum),p.copyFrom(m.maximum))}_=0;for(var g=0,v=0,y=0,b=e;b<=t;b++){var T=this.particles[b];g=3*(_=T.idx),v=4*_,y=2*_,this.updateParticle(T);var E=T._rotationMatrix,x=T.position,P=T._globalPosition;if(this._computeParticleRotation&&T.getRotationMatrix(n),null!==T.parentId){var A=this.particles[T.parentId],S=A._rotationMatrix,C=A._globalPosition,R=x.x*S[1]+x.y*S[4]+x.z*S[7],O=x.x*S[0]+x.y*S[3]+x.z*S[6],M=x.x*S[2]+x.y*S[5]+x.z*S[8];if(P.x=C.x+O,P.y=C.y+R,P.z=C.z+M,this._computeParticleRotation){var I=n.m;E[0]=I[0]*S[0]+I[1]*S[3]+I[2]*S[6],E[1]=I[0]*S[1]+I[1]*S[4]+I[2]*S[7],E[2]=I[0]*S[2]+I[1]*S[5]+I[2]*S[8],E[3]=I[4]*S[0]+I[5]*S[3]+I[6]*S[6],E[4]=I[4]*S[1]+I[5]*S[4]+I[6]*S[7],E[5]=I[4]*S[2]+I[5]*S[5]+I[6]*S[8],E[6]=I[8]*S[0]+I[9]*S[3]+I[10]*S[6],E[7]=I[8]*S[1]+I[9]*S[4]+I[10]*S[7],E[8]=I[8]*S[2]+I[9]*S[5]+I[10]*S[8]}}else if(P.x=0,P.y=0,P.z=0,this._computeParticleRotation){I=n.m;E[0]=I[0],E[1]=I[1],E[2]=I[2],E[3]=I[4],E[4]=I[5],E[5]=I[6],E[6]=I[8],E[7]=I[9],E[8]=I[10]}var D=l[11];T.translateFromPivot?D.setAll(0):D.copyFrom(T.pivot);var w=l[0];w.copyFrom(T.position);var L=w.x-T.pivot.x,N=w.y-T.pivot.y,F=w.z-T.pivot.z,B=L*E[0]+N*E[3]+F*E[6],U=L*E[1]+N*E[4]+F*E[7],V=L*E[2]+N*E[5]+F*E[8];B+=D.x,U+=D.y,V+=D.z;var k=s[g]=P.x+u.x*B+h.x*U+d.x*V,z=s[g+1]=P.y+u.y*B+h.y*U+d.y*V,G=s[g+2]=P.z+u.z*B+h.z*U+d.z*V;if(this._computeBoundingBox&&(f.minimizeInPlaceFromFloats(k,z,G),p.maximizeInPlaceFromFloats(k,z,G)),this._computeParticleColor&&T.color){var j=T.color,W=this._colors32;W[v]=j.r,W[v+1]=j.g,W[v+2]=j.b,W[v+3]=j.a}if(this._computeParticleTexture&&T.uv){var X=T.uv,H=this._uvs32;H[y]=X.x,H[y+1]=X.y}}return i&&(this._computeParticleColor&&r.updateVerticesData(en.b.ColorKind,o,!1,!1),this._computeParticleTexture&&r.updateVerticesData(en.b.UVKind,c,!1,!1),r.updateVerticesData(en.b.PositionKind,s,!1,!1)),this._computeBoundingBox&&(r._boundingInfo?r._boundingInfo.reConstruct(f,p,r._worldMatrix):r._boundingInfo=new Pn.a(f,p,r._worldMatrix)),this.afterUpdateParticles(e,t,i),this},e.prototype.dispose=function(){this.mesh.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._indices32=null,this._positions32=null,this._uvs32=null,this._colors32=null},e.prototype.refreshVisibleSize=function(){return this._isVisibilityBoxLocked||this.mesh.refreshBoundingInfo(),this},e.prototype.setVisibilityBox=function(e){var t=e/2;this.mesh._boundingInfo=new Pn.a(new a.e(-t,-t,-t),new a.e(t,t,t))},Object.defineProperty(e.prototype,"isAlwaysVisible",{get:function(){return this._alwaysVisible},set:function(e){this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"computeParticleRotation",{set:function(e){this._computeParticleRotation=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"computeParticleColor",{get:function(){return this._computeParticleColor},set:function(e){this._computeParticleColor=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"computeParticleTexture",{get:function(){return this._computeParticleTexture},set:function(e){this._computeParticleTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"computeBoundingBox",{get:function(){return this._computeBoundingBox},set:function(e){this._computeBoundingBox=e},enumerable:!0,configurable:!0}),e.prototype.initParticles=function(){},e.prototype.recycleParticle=function(e){return e},e.prototype.updateParticle=function(e){return e},e.prototype.beforeUpdateParticles=function(e,t,i){},e.prototype.afterUpdateParticles=function(e,t,i){},e}();K.a.prototype.getPhysicsEngine=function(){return this._physicsEngine},K.a.prototype.enablePhysics=function(e,t){if(void 0===e&&(e=null),this._physicsEngine)return!0;var i=this._getComponent(Fe.a.NAME_PHYSICSENGINE);i||(i=new uh(this),this._addComponent(i));try{return this._physicsEngine=new Ts(e,t),this._physicsTimeAccumulator=0,!0}catch(e){return m.a.Error(e.message),!1}},K.a.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},K.a.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},K.a.prototype.deleteCompoundImpostor=function(e){var t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},K.a.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){var t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}},Object.defineProperty(Ke.a.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(e){var t=this;this._physicsImpostor!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add(function(){t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)})))},enumerable:!0,configurable:!0}),Ke.a.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},Ke.a.prototype.applyImpulse=function(e,t){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(e,t),this):this},Ke.a.prototype.setPhysicsLinkWith=function(e,t,i,n){return this.physicsImpostor&&e.physicsImpostor?(this.physicsImpostor.createJoint(e.physicsImpostor,bs.e.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:n}),this):this};var ch,lh,uh=function(){function e(e){var t=this;this.name=Fe.a.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new o.c,this.scene.onAfterPhysicsObservable=new o.c,this.scene.getDeterministicFrameTime=function(){return t.scene._physicsEngine?1e3*t.scene._physicsEngine.getTimeStep():1e3/60}}return e.prototype.register=function(){},e.prototype.rebuild=function(){},e.prototype.dispose=function(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()},e}(),hh=function(){function e(e){this._scene=e,this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine||m.a.Warn("Physics engine not enabled. Please enable the physics before you can use the methods.")}return e.prototype.applyRadialExplosionImpulse=function(e,t,i,n){if(!this._physicsEngine)return m.a.Warn("Physics engine not enabled. Please enable the physics before you call this method."),null;var r=this._physicsEngine.getImpostors();if(0===r.length)return null;"number"==typeof t&&((t=new mh).radius=t,t.strength=i||t.strength,t.falloff=n||t.falloff);var o=new dh(this._scene,t),a=Array();return r.forEach(function(t){var i=o.getImpostorHitData(t,e);i&&(t.applyImpulse(i.force,i.contactPoint),a.push({impostor:t,hitData:i}))}),o.triggerAffectedImpostorsCallback(a),o.dispose(!1),o},e.prototype.applyRadialExplosionForce=function(e,t,i,n){if(!this._physicsEngine)return m.a.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;var r=this._physicsEngine.getImpostors();if(0===r.length)return null;"number"==typeof t&&((t=new mh).radius=t,t.strength=i||t.strength,t.falloff=n||t.falloff);var o=new dh(this._scene,t),a=Array();return r.forEach(function(t){var i=o.getImpostorHitData(t,e);i&&(t.applyForce(i.force,i.contactPoint),a.push({impostor:t,hitData:i}))}),o.triggerAffectedImpostorsCallback(a),o.dispose(!1),o},e.prototype.gravitationalField=function(e,t,i,n){if(!this._physicsEngine)return m.a.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(0===this._physicsEngine.getImpostors().length)return null;"number"==typeof t&&((t=new mh).radius=t,t.strength=i||t.strength,t.falloff=n||t.falloff);var r=new fh(this,this._scene,e,t);return r.dispose(!1),r},e.prototype.updraft=function(e,t,i,n,r){if(!this._physicsEngine)return m.a.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(0===this._physicsEngine.getImpostors().length)return null;"number"==typeof t&&((t=new gh).radius=t,t.strength=i||t.strength,t.height=n||t.height,t.updraftMode=r||t.updraftMode);var o=new ph(this._scene,e,t);return o.dispose(!1),o},e.prototype.vortex=function(e,t,i,n){if(!this._physicsEngine)return m.a.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(0===this._physicsEngine.getImpostors().length)return null;"number"==typeof t&&((t=new vh).radius=t,t.strength=i||t.strength,t.height=n||t.height);var r=new _h(this._scene,e,t);return r.dispose(!1),r},e}(),dh=function(){function e(e,t){this._scene=e,this._options=t,this._dataFetched=!1,this._options=Object(h.a)(Object(h.a)({},new mh),this._options)}return e.prototype.getData=function(){return this._dataFetched=!0,{sphere:this._sphere}},e.prototype.getImpostorHitData=function(e,t){if(0===e.mass)return null;if(!this._intersectsWithSphere(e,t,this._options.radius))return null;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return null;var i=e.getObjectCenter().subtract(t),n=new Ht.a(t,i,this._options.radius).intersectsMesh(e.object).pickedPoint;if(!n)return null;var r=a.e.Distance(t,n);if(r>this._options.radius)return null;var o=this._options.falloff===ch.Constant?this._options.strength:this._options.strength*(1-r/this._options.radius);return{force:i.multiplyByFloats(o,o,o),contactPoint:n,distanceFromOrigin:r}},e.prototype.triggerAffectedImpostorsCallback=function(e){this._options.affectedImpostorsCallback&&this._options.affectedImpostorsCallback(e)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._sphere.dispose():setTimeout(function(){t._dataFetched||t._sphere.dispose()},0)},e.prototype._prepareSphere=function(){this._sphere||(this._sphere=Rr.a.CreateSphere("radialExplosionEventSphere",this._options.sphere,this._scene),this._sphere.isVisible=!1)},e.prototype._intersectsWithSphere=function(e,t,i){var n=e.object;return this._prepareSphere(),this._sphere.position=t,this._sphere.scaling=new a.e(2*i,2*i,2*i),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(n,!0)},e}(),fh=function(){function e(e,t,i,n){this._physicsHelper=e,this._scene=t,this._origin=i,this._options=n,this._dataFetched=!1,this._options=Object(h.a)(Object(h.a)({},new mh),this._options),this._tickCallback=this._tick.bind(this),this._options.strength=-1*this._options.strength}return e.prototype.getData=function(){return this._dataFetched=!0,{sphere:this._sphere}},e.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},e.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._sphere.dispose():setTimeout(function(){t._dataFetched||t._sphere.dispose()},0)},e.prototype._tick=function(){if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);else{var e=this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);e&&(this._sphere=e.getData().sphere.clone("radialExplosionEventSphereClone"))}},e}(),ph=function(){function e(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=a.e.Zero(),this._originDirection=a.e.Zero(),this._cylinderPosition=a.e.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object(h.a)(Object(h.a)({},new gh),this._options),this._origin.addToRef(new a.e(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new a.e(0,this._options.height,0),this._originTop),this._options.updraftMode===lh.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=this._tick.bind(this),this._prepareCylinder()}return e.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},e.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},e.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),this._cylinder&&(e?this._cylinder.dispose():setTimeout(function(){t._dataFetched||t._cylinder.dispose()},0))},e.prototype.getImpostorHitData=function(e){if(0===e.mass)return null;if(!this._intersectsWithCylinder(e))return null;var t=e.getObjectCenter();if(this._options.updraftMode===lh.Perpendicular)var i=this._originDirection;else i=t.subtract(this._originTop);var n=a.e.Distance(this._origin,t),r=-1*this._options.strength;return{force:i.multiplyByFloats(r,r,r),contactPoint:t,distanceFromOrigin:n}},e.prototype._tick=function(){var e=this;this._physicsEngine.getImpostors().forEach(function(t){var i=e.getImpostorHitData(t);i&&t.applyForce(i.force,i.contactPoint)})},e.prototype._prepareCylinder=function(){this._cylinder||(this._cylinder=an.a.CreateCylinder("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)},e.prototype._intersectsWithCylinder=function(e){var t=e.object;return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(t,!0)},e}(),_h=function(){function e(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=a.e.Zero(),this._cylinderPosition=a.e.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object(h.a)(Object(h.a)({},new vh),this._options),this._origin.addToRef(new a.e(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new a.e(0,this._options.height,0),this._originTop),this._tickCallback=this._tick.bind(this),this._prepareCylinder()}return e.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},e.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},e.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._cylinder.dispose():setTimeout(function(){t._dataFetched||t._cylinder.dispose()},0)},e.prototype.getImpostorHitData=function(e){if(0===e.mass)return null;if(!this._intersectsWithCylinder(e))return null;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return null;var t=e.getObjectCenter(),i=new a.e(this._origin.x,t.y,this._origin.z),n=t.subtract(i),r=new Ht.a(i,n,this._options.radius).intersectsMesh(e.object),o=r.pickedPoint;if(!o)return null;var s=r.distance/this._options.radius,c=o.normalize();if(s>this._options.centripetalForceThreshold&&(c=c.negate()),s>this._options.centripetalForceThreshold)var l=c.x*this._options.centripetalForceMultiplier,u=c.y*this._options.updraftForceMultiplier,h=c.z*this._options.centripetalForceMultiplier;else{var d=a.e.Cross(i,t).normalize();l=(d.x+c.x)*this._options.centrifugalForceMultiplier,u=this._originTop.y*this._options.updraftForceMultiplier,h=(d.z+c.z)*this._options.centrifugalForceMultiplier}var f=new a.e(l,u,h);return{force:f=f.multiplyByFloats(this._options.strength,this._options.strength,this._options.strength),contactPoint:t,distanceFromOrigin:s}},e.prototype._tick=function(){var e=this;this._physicsEngine.getImpostors().forEach(function(t){var i=e.getImpostorHitData(t);i&&t.applyForce(i.force,i.contactPoint)})},e.prototype._prepareCylinder=function(){this._cylinder||(this._cylinder=an.a.CreateCylinder("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)},e.prototype._intersectsWithCylinder=function(e){var t=e.object;return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(t,!0)},e}(),mh=function(){this.radius=5,this.strength=10,this.falloff=ch.Constant,this.sphere={segments:32,diameter:1}},gh=function(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=lh.Center},vh=function(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02};!function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"}(ch||(ch={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(lh||(lh={}));var yh="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void)\n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11));\nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}";ai.a.ShadersStore.blackAndWhitePixelShader=yh;var bh=function(e){function t(t,i,n,r,o,a){var s=e.call(this,t,"blackAndWhite",["degree"],null,i,n,r,o,a)||this;return s.degree=1,s.onApplyObservable.add(function(e){e.setFloat("degree",s.degree)}),s}return Object(h.d)(t,e),t}(ui),Th=function(){function e(e,t,i,n){this._name=t,this._singleInstance=n||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}return Object.defineProperty(e.prototype,"isSupported",{get:function(){for(var e in this._postProcesses)if(this._postProcesses.hasOwnProperty(e))for(var t=this._postProcesses[e],i=0;i<t.length;i++)if(!t[i].isSupported)return!1;return!0},enumerable:!0,configurable:!0}),e.prototype._update=function(){},e.prototype._attachCameras=function(e){var t,i=this,n=De.b.MakeArray(e||this._cameras);if(n)for(var r=0;r<n.length;r++){var o=n[r],a=o.name;if(t=this._singleInstance?0:a,!this._postProcesses[t]){var s=this._getPostProcesses();s&&(this._postProcesses[t]=Array.isArray(s)?s:[s])}this._indicesForCamera[a]||(this._indicesForCamera[a]=[]),this._postProcesses[t].forEach(function(e){var t=o.attachPostProcess(e);i._indicesForCamera[a].push(t)}),this._cameras[a]||(this._cameras[a]=o)}},e.prototype._detachCameras=function(e){var t=De.b.MakeArray(e||this._cameras);if(t)for(var i=0;i<t.length;i++){var n=t[i],r=n.name,o=this._postProcesses[this._singleInstance?0:r];o&&o.forEach(function(e){n.detachPostProcess(e)}),this._cameras[r]&&(this._cameras[r]=null)}},e.prototype._enable=function(e){var t=this,i=De.b.MakeArray(e||this._cameras);if(i)for(var n=0;n<i.length;n++)for(var r=i[n],o=r.name,a=0;a<this._indicesForCamera[o].length;a++)void 0!==r._postProcesses[this._indicesForCamera[o][a]]&&null!==r._postProcesses[this._indicesForCamera[o][a]]||this._postProcesses[this._singleInstance?0:o].forEach(function(e){i[n].attachPostProcess(e,t._indicesForCamera[o][a])})},e.prototype._disable=function(e){var t=De.b.MakeArray(e||this._cameras);if(t)for(var i=0;i<t.length;i++){var n=t[i],r=n.name;this._postProcesses[this._singleInstance?0:r].forEach(function(e){n.detachPostProcess(e)})}},e.prototype.getPostProcesses=function(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null},e}(),Eh="#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}";ai.a.ShadersStore.extractHighlightsPixelShader=Eh;var xh=function(e){function t(t,i,n,r,o,a,s,c){void 0===s&&(s=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1);var l=e.call(this,t,"extractHighlights",["threshold","exposure"],null,i,n,r,o,a,null,s,void 0,null,c)||this;return l.threshold=.9,l._exposure=1,l._inputPostProcess=null,l.onApplyObservable.add(function(e){l._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",l._inputPostProcess),e.setFloat("threshold",Math.pow(l.threshold,re.b)),e.setFloat("exposure",l._exposure)}),l}return Object(h.d)(t,e),t}(ui),Ph="uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight);\n}\n";ai.a.ShadersStore.bloomMergePixelShader=Ph;var Ah=function(e){function t(t,i,n,r,o,a,s,c,l,u,h){void 0===u&&(u=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=!1);var d=e.call(this,t,"bloomMerge",["bloomWeight"],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2","bloomBlur"],o,a,s,c,l,null,u,void 0,null,!0)||this;return d.weight=r,d.onApplyObservable.add(function(e){e.setTextureFromPostProcess("textureSampler",i),e.setTextureFromPostProcessOutput("bloomBlur",n),e.setFloat("bloomWeight",d.weight)}),h||d.updateEffect(),d}return Object(h.d)(t,e),t}(ui),Sh=function(e){function t(t,i,n,r,o,s){void 0===o&&(o=0),void 0===s&&(s=!1);var c=e.call(this,t.getEngine(),"bloom",function(){return c._effects},!0)||this;return c.bloomScale=i,c._effects=[],c._downscale=new xh("highlights",1,null,et.a.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,o,s),c._blurX=new Zr("horizontal blur",new a.d(1,0),10,i,null,et.a.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,o,void 0,s),c._blurX.alwaysForcePOT=!0,c._blurX.autoClear=!1,c._blurY=new Zr("vertical blur",new a.d(0,1),10,i,null,et.a.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,o,void 0,s),c._blurY.alwaysForcePOT=!0,c._blurY.autoClear=!1,c.kernel=r,c._effects=[c._downscale,c._blurX,c._blurY],c._merge=new Ah("bloomMerge",c._downscale,c._blurY,n,i,null,et.a.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,o,s),c._merge.autoClear=!1,c._effects.push(c._merge),c}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"threshold",{get:function(){return this._downscale.threshold},set:function(e){this._downscale.threshold=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weight",{get:function(){return this._merge.weight},set:function(e){this._merge.weight=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernel",{get:function(){return this._blurX.kernel/this.bloomScale},set:function(e){this._blurX.kernel=e*this.bloomScale,this._blurY.kernel=e*this.bloomScale},enumerable:!0,configurable:!0}),t.prototype.disposeEffects=function(e){for(var t=0;t<this._effects.length;t++)this._effects[t].dispose(e)},t.prototype._updateEffects=function(){for(var e=0;e<this._effects.length;e++)this._effects[e].updateEffect()},t.prototype._isReady=function(){for(var e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0},t}(Th),Ch="\nuniform sampler2D textureSampler;\n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}";ai.a.ShadersStore.chromaticAberrationPixelShader=Ch;var Rh=function(e){function t(t,i,n,r,o,s,c,l,u,h){void 0===u&&(u=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=!1);var d=e.call(this,t,"chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],r,o,s,c,l,null,u,void 0,null,h)||this;return d.aberrationAmount=30,d.radialIntensity=0,d.direction=new a.d(.707,.707),d.centerPosition=new a.d(.5,.5),d.onApplyObservable.add(function(e){e.setFloat("chromatic_aberration",d.aberrationAmount),e.setFloat("screen_width",i),e.setFloat("screen_height",n),e.setFloat("radialIntensity",d.radialIntensity),e.setFloat2("direction",d.direction.x,d.direction.y),e.setFloat2("centerPosition",d.centerPosition.x,d.centerPosition.y)}),d}return Object(h.d)(t,e),t}(ui),Oh="\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0;\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n";ai.a.ShadersStore.circleOfConfusionPixelShader=Oh;var Mh=function(e){function t(t,i,n,r,o,a,s,c,l){void 0===c&&(c=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===l&&(l=!1);var u=e.call(this,t,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],n,r,o,a,s,null,c,void 0,null,l)||this;return u.lensSize=50,u.fStop=1.4,u.focusDistance=2e3,u.focalLength=50,u._depthTexture=null,u._depthTexture=i,u.onApplyObservable.add(function(e){if(u._depthTexture){e.setTexture("depthSampler",u._depthTexture);var t=u.lensSize/u.fStop*u.focalLength/(u.focusDistance-u.focalLength);e.setFloat("focusDistance",u.focusDistance),e.setFloat("cocPrecalculation",t),e.setFloat2("cameraMinMaxZ",u._depthTexture.activeCamera.minZ,u._depthTexture.activeCamera.maxZ)}else m.a.Warn("No depth texture set on CircleOfConfusionPostProcess")}),u}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"depthTexture",{set:function(e){this._depthTexture=e},enumerable:!0,configurable:!0}),t}(ui),Ih="\nuniform sampler2D textureSampler;\nuniform sampler2D colorTable;\n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0;\n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width;\nfloat slicePixelSize=sliceSize/width;\nfloat sliceInnerSize=slicePixelSize*(width-1.0);\nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}";ai.a.ShadersStore.colorCorrectionPixelShader=Ih;var Dh=function(e){function t(t,i,n,r,o,a,s){var c=e.call(this,t,"colorCorrection",null,["colorTable"],n,r,o,a,s)||this;return c._colorTableTexture=new et.a(i,r.getScene(),!0,!1,et.a.TRILINEAR_SAMPLINGMODE),c._colorTableTexture.anisotropicFilteringLevel=1,c._colorTableTexture.wrapU=et.a.CLAMP_ADDRESSMODE,c._colorTableTexture.wrapV=et.a.CLAMP_ADDRESSMODE,c.onApply=function(e){e.setTexture("colorTable",c._colorTableTexture)},c}return Object(h.d)(t,e),t}(ui),wh="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}";ai.a.ShadersStore.convolutionPixelShader=wh;var Lh=function(e){function t(t,i,n,r,o,a,s,c){void 0===c&&(c=g.a.TEXTURETYPE_UNSIGNED_INT);var l=e.call(this,t,"convolution",["kernel","screenSize"],null,n,r,o,a,s,null,c)||this;return l.kernel=i,l.onApply=function(e){e.setFloat2("screenSize",l.width,l.height),e.setArray("kernel",l.kernel)},l}return Object(h.d)(t,e),t.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],t.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],t.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],t.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],t.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],t.GaussianKernel=[0,1,0,1,1,1,0,1,0],t}(ui),Nh=function(e){function t(t,i,n,r,o,a,s,c,l,u,h,d,f){void 0===c&&(c=null),void 0===l&&(l=et.a.BILINEAR_SAMPLINGMODE),void 0===d&&(d=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===f&&(f=!1);var p=e.call(this,t,n,r,o,a,l=g.a.TEXTURE_BILINEAR_SAMPLINGMODE,u,h,d=g.a.TEXTURETYPE_UNSIGNED_INT,"#define DOF 1\r\n",f)||this;return p.direction=n,p.onApplyObservable.add(function(e){null!=c&&e.setTextureFromPostProcess("textureSampler",c),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",s),i.activeCamera&&e.setFloat2("cameraMinMaxZ",i.activeCamera.minZ,i.activeCamera.maxZ)}),p}return Object(h.d)(t,e),t}(Zr),Fh="uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n";ai.a.ShadersStore.depthOfFieldMergePixelShader=Fh;var Bh,Uh=function(){},Vh=function(e){function t(t,i,n,r,o,a,s,c,l,u,h){void 0===u&&(u=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=!1);var d=e.call(this,t,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],o,a,s,c,l,null,u,void 0,null,!0)||this;return d.blurSteps=r,d.onApplyObservable.add(function(e){e.setTextureFromPostProcess("textureSampler",i),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",n),r.forEach(function(t,i){e.setTextureFromPostProcessOutput("blurStep"+(r.length-i-1),t)})}),h||d.updateEffect(),d}return Object(h.d)(t,e),t.prototype.updateEffect=function(t,i,n,r,o,a){void 0===t&&(t=null),void 0===i&&(i=null),void 0===n&&(n=null),t||(t="",t+="#define BLUR_LEVEL "+(this.blurSteps.length-1)+"\n"),e.prototype.updateEffect.call(this,t,i,n,r,o,a)},t}(ui);!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(Bh||(Bh={}));var kh=function(e){function t(t,i,n,r,o){void 0===n&&(n=Bh.Low),void 0===r&&(r=0),void 0===o&&(o=!1);var s=e.call(this,t.getEngine(),"depth of field",function(){return s._effects},!0)||this;s._effects=[],s._circleOfConfusion=new Mh("circleOfConfusion",i,1,null,et.a.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,r,o),s._depthOfFieldBlurY=[],s._depthOfFieldBlurX=[];var c=1,l=15;switch(n){case Bh.High:c=3,l=51;break;case Bh.Medium:c=2,l=31;break;default:l=15,c=1}for(var u=l/Math.pow(2,c-1),h=1,d=0;d<c;d++){var f=new Nh("verticle blur",t,new a.d(0,1),u,h,null,s._circleOfConfusion,0==d?s._circleOfConfusion:null,et.a.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,r,o);f.autoClear=!1,h=.75/Math.pow(2,d);var p=new Nh("horizontal blur",t,new a.d(1,0),u,h,null,s._circleOfConfusion,null,et.a.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,r,o);p.autoClear=!1,s._depthOfFieldBlurY.push(f),s._depthOfFieldBlurX.push(p)}s._effects=[s._circleOfConfusion];for(d=0;d<s._depthOfFieldBlurX.length;d++)s._effects.push(s._depthOfFieldBlurY[d]),s._effects.push(s._depthOfFieldBlurX[d]);return s._dofMerge=new Vh("dofMerge",s._circleOfConfusion,s._circleOfConfusion,s._depthOfFieldBlurX,h,null,et.a.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,r,o),s._dofMerge.autoClear=!1,s._effects.push(s._dofMerge),s}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"focalLength",{get:function(){return this._circleOfConfusion.focalLength},set:function(e){this._circleOfConfusion.focalLength=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fStop",{get:function(){return this._circleOfConfusion.fStop},set:function(e){this._circleOfConfusion.fStop=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"focusDistance",{get:function(){return this._circleOfConfusion.focusDistance},set:function(e){this._circleOfConfusion.focusDistance=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"lensSize",{get:function(){return this._circleOfConfusion.lensSize},set:function(e){this._circleOfConfusion.lensSize=e},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"DepthOfFieldEffect"},Object.defineProperty(t.prototype,"depthTexture",{set:function(e){this._circleOfConfusion.depthTexture=e},enumerable:!0,configurable:!0}),t.prototype.disposeEffects=function(e){for(var t=0;t<this._effects.length;t++)this._effects[t].dispose(e)},t.prototype._updateEffects=function(){for(var e=0;e<this._effects.length;e++)this._effects[e].updateEffect()},t.prototype._isReady=function(){for(var e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0},t}(Th),zh="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}";ai.a.ShadersStore.displayPassPixelShader=zh;var Gh=function(e){function t(t,i,n,r,o,a){return e.call(this,t,"displayPass",["passSampler"],["passSampler"],i,n,r,o,a)||this}return Object(h.d)(t,e),t}(ui),jh="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}";ai.a.ShadersStore.filterPixelShader=jh;var Wh=function(e){function t(t,i,n,r,o,a,s){var c=e.call(this,t,"filter",["kernelMatrix"],null,n,r,o,a,s)||this;return c.kernelMatrix=i,c.onApply=function(e){e.setMatrix("kernelMatrix",c.kernelMatrix)},c}return Object(h.d)(t,e),t}(ui),Xh="uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped)\n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan)\n{\nlumaS=lumaE;\n}\nif (horzSpan)\n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan)\n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN)\n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN)\n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN)\n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP)\n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan)\n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped)\n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}";ai.a.ShadersStore.fxaaPixelShader=Xh;var Hh="\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}";ai.a.ShadersStore.fxaaVertexShader=Hh;var Yh=function(e){function t(t,i,n,r,o,a,s){void 0===n&&(n=null),void 0===s&&(s=g.a.TEXTURETYPE_UNSIGNED_INT);var c=e.call(this,t,"fxaa",["texelSize"],null,i,n,r||et.a.BILINEAR_SAMPLINGMODE,o,a,null,s,"fxaa",void 0,!0)||this,l=c._getDefines();return c.updateEffect(l),c.onApplyObservable.add(function(e){var t=c.texelSize;e.setFloat2("texelSize",t.x,t.y)}),c}return Object(h.d)(t,e),t.prototype._getDefines=function(){var e=this.getEngine();if(!e)return null;var t=e.getGlInfo();return t&&t.renderer&&t.renderer.toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null},t}(ui),Kh="#include<helperFunctions>\n\nuniform sampler2D textureSampler;\n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}";ai.a.ShadersStore.grainPixelShader=Kh;var Qh=function(e){function t(t,i,n,r,o,a,s,c){void 0===s&&(s=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1);var l=e.call(this,t,"grain",["intensity","animatedSeed"],[],i,n,r,o,a,null,s,void 0,null,c)||this;return l.intensity=30,l.animated=!1,l.onApplyObservable.add(function(e){e.setFloat("intensity",l.intensity),e.setFloat("animatedSeed",l.animated?Math.random()+1:1)}),l}return Object(h.d)(t,e),t}(ui),qh="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void)\n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a);\n}";ai.a.ShadersStore.highlightsPixelShader=qh;var Zh=function(e){function t(t,i,n,r,o,a,s){return void 0===s&&(s=g.a.TEXTURETYPE_UNSIGNED_INT),e.call(this,t,"highlights",null,null,i,n,r,o,a,null,s)||this}return Object(h.d)(t,e),t}(ui);ai.a.IncludesShadersStore.mrtFragmentDeclaration="#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n";var Jh="#extension GL_EXT_draw_buffers : require\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\nprecision highp float;\nprecision highp int;\n#ifdef BUMP\nvarying mat4 vWorldView;\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#ifdef NEED_UV\nvarying vec2 vUV;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef REFLECTIVITY\nvarying vec2 vReflectivityUV;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef ALPHATEST\nuniform sampler2D diffuseSampler;\n#endif\n#include<mrtFragmentDeclaration>[RENDER_TARGET_COUNT]\n#include<bumpFragmentFunctions>\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\n#ifdef BUMP\nvec3 normalW=normalize(vNormalW);\n#include<bumpFragment>\ngl_FragData[1]=vec4(normalize(vec3(vWorldView*vec4(normalW,0.0))),1.0);\n#else\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n#endif\n#ifdef POSITION\ngl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\nvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\nvec2 velocity=abs(a-b);\nvelocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;\ngl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);\n#endif\n#ifdef REFLECTIVITY\n#ifdef HAS_SPECULAR\n\nvec4 reflectivity=texture2D(reflectivitySampler,vReflectivityUV);\n#elif HAS_REFLECTIVITY\n\nvec4 reflectivity=vec4(texture2D(reflectivitySampler,vReflectivityUV).rgb,1.0);\n#else\nvec4 reflectivity=vec4(0.0,0.0,0.0,1.0);\n#endif\ngl_FragData[REFLECTIVITY_INDEX]=reflectivity;\n#endif\n}";ai.a.ShadersStore.geometryPixelShader=Jh;var $h="precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef NEED_UV\nvarying vec2 vUV;\n#ifdef ALPHATEST\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef BUMP\nuniform mat4 bumpMatrix;\nvarying vec2 vBumpUV;\n#endif\n#ifdef REFLECTIVITY\nuniform mat4 reflectivityMatrix;\nvarying vec2 vReflectivityUV;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef BUMP\nvarying mat4 vWorldView;\n#endif\n#ifdef BUMP\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nuniform mat4 previousWorld;\nuniform mat4 previousViewProjection;\n#ifdef BONES_VELOCITY_ENABLED\n#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mPreviousBones[BonesPerMesh];\n#endif\n#endif\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\nvec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\n\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvPreviousPosition=previousViewProjection*previousWorld*vec4(positionUpdated,1.0);\n#endif\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(positionUpdated,1.0));\n#ifdef BUMP\nvWorldView=view*finalWorld;\nvNormalW=normalUpdated;\n#else\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));\n#endif\nvViewPos=view*pos;\n#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;\npreviousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*previousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*previousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n#if defined(POSITION) || defined(BUMP)\nvPositionW=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#ifdef NEED_UV\n#ifdef UV1\n#ifdef ALPHATEST\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#else\nvUV=uv;\n#endif\n#ifdef BUMP\nvBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#endif\n#ifdef UV2\n#ifdef ALPHATEST\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#else\nvUV=uv2;\n#endif\n#ifdef BUMP\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#endif\n#include<bumpVertex>\n}\n";ai.a.ShadersStore.geometryVertexShader=$h;var ed=function(){function e(t,i){void 0===i&&(i=1),this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._scene=t,this._ratio=i,e._SceneComponentInitialization(this._scene),this._createRenderTargets()}return Object.defineProperty(e.prototype,"renderList",{set:function(e){this._multiRenderTarget.renderList=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isSupported",{get:function(){return this._multiRenderTarget.isSupported},enumerable:!0,configurable:!0}),e.prototype.getTextureIndex=function(t){switch(t){case e.POSITION_TEXTURE_TYPE:return this._positionIndex;case e.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case e.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;default:return-1}},Object.defineProperty(e.prototype,"enablePosition",{get:function(){return this._enablePosition},set:function(e){this._enablePosition=e,this.dispose(),this._createRenderTargets()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"enableVelocity",{get:function(){return this._enableVelocity},set:function(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this.dispose(),this._createRenderTargets()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"enableReflectivity",{get:function(){return this._enableReflectivity},set:function(e){this._enableReflectivity=e,this.dispose(),this._createRenderTargets()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scene",{get:function(){return this._scene},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"ratio",{get:function(){return this._ratio},enumerable:!0,configurable:!0}),e.prototype.isReady=function(e,t){var i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;var n=[],r=[en.b.PositionKind,en.b.NormalKind],o=e.getMesh();if(i){var a=!1;i.needAlphaBlending()&&(n.push("#define ALPHATEST"),a=!0),i.bumpTexture&&Ki.a.BumpTextureEnabled&&(n.push("#define BUMP"),a=!0),this._enableReflectivity&&(i instanceof Ki.a&&i.specularTexture?(n.push("#define HAS_SPECULAR"),a=!0):i instanceof zo&&i.reflectivityTexture&&(n.push("#define HAS_REFLECTIVITY"),a=!0)),a&&(n.push("#define NEED_UV"),o.isVerticesDataPresent(en.b.UVKind)&&(r.push(en.b.UVKind),n.push("#define UV1")),o.isVerticesDataPresent(en.b.UV2Kind)&&(r.push(en.b.UV2Kind),n.push("#define UV2")))}this._enablePosition&&(n.push("#define POSITION"),n.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(n.push("#define VELOCITY"),n.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(o)&&n.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(n.push("#define REFLECTIVITY"),n.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),o.useBones&&o.computeBonesUsingShaders?(r.push(en.b.MatricesIndicesKind),r.push(en.b.MatricesWeightsKind),o.numBoneInfluencers>4&&(r.push(en.b.MatricesIndicesExtraKind),r.push(en.b.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),n.push("#define BonesPerMesh "+(o.skeleton?o.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0");var s=o.morphTargetManager,c=0;s&&s.numInfluencers>0&&(c=s.numInfluencers,n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+c),io.a.PrepareAttributesForMorphTargetsInfluencers(r,o,c)),t&&(n.push("#define INSTANCES"),io.a.PushAttributesForInstances(r)),n.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length);var l=n.join("\n");return this._cachedDefines!==l&&(this._cachedDefines=l,this._effect=this._scene.getEngine().createEffect("geometry",r,["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","morphTargetInfluences","bumpMatrix","reflectivityMatrix","vTangentSpaceParams","vBumpInfos"],["diffuseSampler","bumpSampler","reflectivitySampler"],l,void 0,void 0,void 0,{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:c})),this._effect.isReady()},e.prototype.getGBuffer=function(){return this._multiRenderTarget},Object.defineProperty(e.prototype,"samples",{get:function(){return this._multiRenderTarget.samples},set:function(e){this._multiRenderTarget.samples=e},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this.getGBuffer().dispose()},e.prototype._createRenderTargets=function(){var e=this,t=this._scene.getEngine(),i=2;if(this._enablePosition&&(this._positionIndex=i,i++),this._enableVelocity&&(this._velocityIndex=i,i++),this._enableReflectivity&&(this._reflectivityIndex=i,i++),this._multiRenderTarget=new qs("gBuffer",{width:t.getRenderWidth()*this._ratio,height:t.getRenderHeight()*this._ratio},i,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:g.a.TEXTURETYPE_FLOAT}),this.isSupported){this._multiRenderTarget.wrapU=et.a.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=et.a.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null,this._multiRenderTarget.onClearObservable.add(function(e){e.clear(new s.b(0,0,0,1),!0,!0,!0)});var n=function(t){var i=t.getRenderingMesh(),n=e._scene,r=n.getEngine(),o=t.getMaterial();if(o){if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,e._enableVelocity&&!e._previousTransformationMatrices[i.uniqueId]&&(e._previousTransformationMatrices[i.uniqueId]={world:a.a.Identity(),viewProjection:n.getTransformMatrix()},i.skeleton)){var s=i.skeleton.getTransformMatrices(i);e._previousBonesTransformationMatrices[i.uniqueId]=e._copyBonesTransformationMatrices(s,new Float32Array(s.length))}r.setState(o.backFaceCulling,0,!1,n.useRightHandedSystem);var c=i._getInstancesRenderList(t._id);if(!c.mustReturn){var l=r.getCaps().instancedArrays&&null!==c.visibleInstances[t._id];if(e.isReady(t,l)){if(r.enableEffect(e._effect),i._bind(t,e._effect,o.fillMode),e._effect.setMatrix("viewProjection",n.getTransformMatrix()),e._effect.setMatrix("view",n.getViewMatrix()),o){if(o.needAlphaTesting()){var u=o.getAlphaTestTexture();u&&(e._effect.setTexture("diffuseSampler",u),e._effect.setMatrix("diffuseMatrix",u.getTextureMatrix()))}o.bumpTexture&&n.getEngine().getCaps().standardDerivatives&&Ki.a.BumpTextureEnabled&&(e._effect.setFloat3("vBumpInfos",o.bumpTexture.coordinatesIndex,1/o.bumpTexture.level,o.parallaxScaleBias),e._effect.setMatrix("bumpMatrix",o.bumpTexture.getTextureMatrix()),e._effect.setTexture("bumpSampler",o.bumpTexture),e._effect.setFloat2("vTangentSpaceParams",o.invertNormalMapX?-1:1,o.invertNormalMapY?-1:1)),e._enableReflectivity&&(o instanceof Ki.a&&o.specularTexture?(e._effect.setMatrix("reflectivityMatrix",o.specularTexture.getTextureMatrix()),e._effect.setTexture("reflectivitySampler",o.specularTexture)):o instanceof zo&&o.reflectivityTexture&&(e._effect.setMatrix("reflectivityMatrix",o.reflectivityTexture.getTextureMatrix()),e._effect.setTexture("reflectivitySampler",o.reflectivityTexture)))}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&(e._effect.setMatrices("mBones",i.skeleton.getTransformMatrices(i)),e._enableVelocity&&e._effect.setMatrices("mPreviousBones",e._previousBonesTransformationMatrices[i.uniqueId])),io.a.BindMorphTargetParameters(i,e._effect),e._enableVelocity&&(e._effect.setMatrix("previousWorld",e._previousTransformationMatrices[i.uniqueId].world),e._effect.setMatrix("previousViewProjection",e._previousTransformationMatrices[i.uniqueId].viewProjection)),i._processRendering(t,e._effect,o.fillMode,c,l,function(t,i){return e._effect.setMatrix("world",i)})}e._enableVelocity&&(e._previousTransformationMatrices[i.uniqueId].world=i.getWorldMatrix().clone(),e._previousTransformationMatrices[i.uniqueId].viewProjection=e._scene.getTransformMatrix().clone(),i.skeleton&&e._copyBonesTransformationMatrices(i.skeleton.getTransformMatrices(i),e._previousBonesTransformationMatrices[i.uniqueId]))}}};this._multiRenderTarget.customRenderFunction=function(i,r,o,a){var s;if(a.length){for(t.setColorWrite(!1),s=0;s<a.length;s++)n(a.data[s]);t.setColorWrite(!0)}for(s=0;s<i.length;s++)n(i.data[s]);for(s=0;s<r.length;s++)n(r.data[s]);if(e.renderTransparentMeshes)for(s=0;s<o.length;s++)n(o.data[s])}}},e.prototype._copyBonesTransformationMatrices=function(e,t){for(var i=0;i<e.length;i++)t[i]=e[i];return t},e.POSITION_TEXTURE_TYPE=1,e.VELOCITY_TEXTURE_TYPE=2,e.REFLECTIVITY_TEXTURE_TYPE=3,e._SceneComponentInitialization=function(e){throw we.a.WarnImport("GeometryBufferRendererSceneComponent")},e}();Object.defineProperty(K.a.prototype,"geometryBufferRenderer",{get:function(){this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),K.a.prototype.enableGeometryBufferRenderer=function(e){return void 0===e&&(e=1),this._geometryBufferRenderer?this._geometryBufferRenderer:(this._geometryBufferRenderer=new ed(this,e),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null),this._geometryBufferRenderer)},K.a.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};var td=function(){function e(e){this.name=Fe.a.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}return e.prototype.register=function(){this.scene._gatherRenderTargetsStage.registerStep(Fe.a.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){},e.prototype._gatherRenderTargets=function(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())},e}();ed._SceneComponentInitialization=function(e){var t=e._getComponent(Fe.a.NAME_GEOMETRYBUFFERRENDERER);t||(t=new td(e),e._addComponent(t))};var id="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D velocitySampler;\nuniform float motionStrength;\nuniform float motionScale;\nuniform vec2 screenSize;\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\nvec2 texelSize=1.0/screenSize;\nvec2 velocityColor=texture2D(velocitySampler,vUV).rg*2.0-1.0;\nvec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0));\nvelocity*=motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint samplesCount=int(clamp(speed,1.0,SAMPLES));\nvelocity=normalize(velocity)*texelSize;\nfloat hlim=float(-samplesCount)*0.5+0.5;\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(SAMPLES); ++i)\n{\nif (i>=samplesCount)\nbreak;\nvec2 offset=vUV+velocity*(hlim+float(i));\nresult+=texture2D(textureSampler,offset);\n}\ngl_FragColor=result/float(samplesCount);\ngl_FragColor.a=1.0;\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";ai.a.ShadersStore.motionBlurPixelShader=id;var nd=function(e){function t(t,i,n,r,o,s,c,l,u){void 0===l&&(l=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===u&&(u=!1);var h=e.call(this,t,"motionBlur",["motionStrength","motionScale","screenSize"],["velocitySampler"],n,r,o,s,c,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0",l,void 0,null,u)||this;return h.motionStrength=1,h._motionBlurSamples=32,h._geometryBufferRenderer=i.enableGeometryBufferRenderer(),h._geometryBufferRenderer?(h._geometryBufferRenderer.enableVelocity=!0,h.onApply=function(e){if(e.setVector2("screenSize",new a.d(h.width,h.height)),e.setFloat("motionScale",i.getAnimationRatio()),e.setFloat("motionStrength",h.motionStrength),h._geometryBufferRenderer){var t=h._geometryBufferRenderer.getTextureIndex(ed.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",h._geometryBufferRenderer.getGBuffer().textures[t])}}):(m.a.Warn("Multiple Render Target support needed to compute object based motion blur"),h.updateEffect()),h}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"motionBlurSamples",{get:function(){return this._motionBlurSamples},set:function(e){this._motionBlurSamples=e,this._geometryBufferRenderer&&this.updateEffect("#define GEOMETRY_SUPPORTED\n#define SAMPLES "+e.toFixed(1))},enumerable:!0,configurable:!0}),t.prototype.excludeSkinnedMesh=function(e){this._geometryBufferRenderer&&e.skeleton&&this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity.push(e)},t.prototype.removeExcludedSkinnedMesh=function(e){if(this._geometryBufferRenderer&&e.skeleton){var t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity.indexOf(e);-1!==t&&this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity.splice(t,1)}},t.prototype.dispose=function(t){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),e.prototype.dispose.call(this,t)},t}(ui),rd="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}";ai.a.ShadersStore.refractionPixelShader=rd;var od=function(e){function t(t,i,n,r,o,a,s,c,l,u){var h=e.call(this,t,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],a,s,c,l,u)||this;return h.color=n,h.depth=r,h.colorLevel=o,h._ownRefractionTexture=!0,h.onActivateObservable.add(function(e){h._refTexture=h._refTexture||new et.a(i,e.getScene())}),h.onApplyObservable.add(function(e){e.setColor3("baseColor",h.color),e.setFloat("depth",h.depth),e.setFloat("colorLevel",h.colorLevel),e.setTexture("refractionSampler",h._refTexture)}),h}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"refractionTexture",{get:function(){return this._refTexture},set:function(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1},enumerable:!0,configurable:!0}),t.prototype.dispose=function(t){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),e.prototype.dispose.call(this,t)},t}(ui),ad="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}";ai.a.ShadersStore.sharpenPixelShader=ad;var sd=function(e){function t(t,i,n,r,o,a,s,c){void 0===s&&(s=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1);var l=e.call(this,t,"sharpen",["sharpnessAmounts","screenSize"],null,i,n,r,o,a,null,s,void 0,null,c)||this;return l.colorAmount=1,l.edgeAmount=.3,l.onApply=function(e){e.setFloat2("screenSize",l.width,l.height),e.setFloat2("sharpnessAmounts",l.edgeAmount,l.colorAmount)},l}return Object(h.d)(t,e),t}(ui),cd=function(){function e(e,t){this.engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}return Object.defineProperty(e.prototype,"name",{get:function(){return this._name},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cameras",{get:function(){return this._cameras},enumerable:!0,configurable:!0}),e.prototype.getClassName=function(){return"PostProcessRenderPipeline"},Object.defineProperty(e.prototype,"isSupported",{get:function(){for(var e in this._renderEffects)if(this._renderEffects.hasOwnProperty(e)&&!this._renderEffects[e].isSupported)return!1;return!0},enumerable:!0,configurable:!0}),e.prototype.addEffect=function(e){this._renderEffects[e._name]=e},e.prototype._rebuild=function(){},e.prototype._enableEffect=function(e,t){var i=this._renderEffects[e];i&&i._enable(De.b.MakeArray(t||this._cameras))},e.prototype._disableEffect=function(e,t){var i=this._renderEffects[e];i&&i._disable(De.b.MakeArray(t||this._cameras))},e.prototype._attachCameras=function(e,t){var i=De.b.MakeArray(e||this._cameras);if(i){var n,r=[];for(n=0;n<i.length;n++){var o=i[n],a=o.name;-1===this._cameras.indexOf(o)?this._cameras[a]=o:t&&r.push(n)}for(n=0;n<r.length;n++)e.splice(r[n],1);for(var s in this._renderEffects)this._renderEffects.hasOwnProperty(s)&&this._renderEffects[s]._attachCameras(i)}},e.prototype._detachCameras=function(e){var t=De.b.MakeArray(e||this._cameras);if(t){for(var i in this._renderEffects)this._renderEffects.hasOwnProperty(i)&&this._renderEffects[i]._detachCameras(t);for(var n=0;n<t.length;n++)this._cameras.splice(this._cameras.indexOf(t[n]),1)}},e.prototype._update=function(){for(var e in this._renderEffects)this._renderEffects.hasOwnProperty(e)&&this._renderEffects[e]._update();for(var t=0;t<this._cameras.length;t++){var i=this._cameras[t].name;this._renderEffectsForIsolatedPass[i]&&this._renderEffectsForIsolatedPass[i]._update()}},e.prototype._reset=function(){this._renderEffects={},this._renderEffectsForIsolatedPass=new Array},e.prototype._enableMSAAOnFirstPostProcess=function(e){if(1===this.engine.webGLVersion)return!1;var t=Object.keys(this._renderEffects);if(t.length>0){var i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0},e.prototype.dispose=function(){},Object(h.c)([Object(N.c)()],e.prototype,"_name",void 0),e}(),ld=function(){function e(){this._renderPipelines={}}return Object.defineProperty(e.prototype,"supportedPipelines",{get:function(){var e=[];for(var t in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(t)){var i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e},enumerable:!0,configurable:!0}),e.prototype.addPipeline=function(e){this._renderPipelines[e._name]=e},e.prototype.attachCamerasToRenderPipeline=function(e,t,i){void 0===i&&(i=!1);var n=this._renderPipelines[e];n&&n._attachCameras(t,i)},e.prototype.detachCamerasFromRenderPipeline=function(e,t){var i=this._renderPipelines[e];i&&i._detachCameras(t)},e.prototype.enableEffectInPipeline=function(e,t,i){var n=this._renderPipelines[e];n&&n._enableEffect(t,i)},e.prototype.disableEffectInPipeline=function(e,t,i){var n=this._renderPipelines[e];n&&n._disableEffect(t,i)},e.prototype.update=function(){for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}},e.prototype._rebuild=function(){for(var e in this._renderPipelines){if(this._renderPipelines.hasOwnProperty(e))this._renderPipelines[e]._rebuild()}},e.prototype.dispose=function(){for(var e in this._renderPipelines){if(this._renderPipelines.hasOwnProperty(e))this._renderPipelines[e].dispose()}},e}();Object.defineProperty(K.a.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){var e=this._getComponent(Fe.a.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new ud(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new ld}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});var ud=function(){function e(e){this.name=Fe.a.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}return e.prototype.register=function(){this.scene._gatherRenderTargetsStage.registerStep(Fe.a.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)},e.prototype.rebuild=function(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()},e.prototype.dispose=function(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()},e.prototype._gatherRenderTargets=function(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()},e}(),hd=function(e){function t(t,i,n,r,o){void 0===t&&(t=""),void 0===i&&(i=!0),void 0===n&&(n=R.a.LastCreatedScene),void 0===o&&(o=!0);var a=e.call(this,n.getEngine(),t)||this;a._camerasToBeAttached=[],a.SharpenPostProcessId="SharpenPostProcessEffect",a.ImageProcessingPostProcessId="ImageProcessingPostProcessEffect",a.FxaaPostProcessId="FxaaPostProcessEffect",a.ChromaticAberrationPostProcessId="ChromaticAberrationPostProcessEffect",a.GrainPostProcessId="GrainPostProcessEffect",a._glowLayer=null,a.animations=[],a._imageProcessingConfigurationObserver=null,a._sharpenEnabled=!1,a._bloomEnabled=!1,a._depthOfFieldEnabled=!1,a._depthOfFieldBlurLevel=Bh.Low,a._fxaaEnabled=!1,a._imageProcessingEnabled=!0,a._bloomScale=.5,a._chromaticAberrationEnabled=!1,a._grainEnabled=!1,a._buildAllowed=!0,a._resizeObserver=null,a._hardwareScaleLevel=1,a._bloomKernel=64,a._bloomWeight=.15,a._bloomThreshold=.9,a._samples=1,a._hasCleared=!1,a._prevPostProcess=null,a._prevPrevPostProcess=null,a._depthOfFieldSceneObserver=null,a._cameras=r||n.cameras,a._cameras=a._cameras.slice(),a._camerasToBeAttached=a._cameras.slice(),a._buildAllowed=o,a._scene=n;var s=a._scene.getEngine().getCaps();a._hdr=i&&(s.textureHalfFloatRender||s.textureFloatRender),a._hdr?s.textureHalfFloatRender?a._defaultPipelineTextureType=g.a.TEXTURETYPE_HALF_FLOAT:s.textureFloatRender&&(a._defaultPipelineTextureType=g.a.TEXTURETYPE_FLOAT):a._defaultPipelineTextureType=g.a.TEXTURETYPE_UNSIGNED_INT,n.postProcessRenderPipelineManager.addPipeline(a);var c=a._scene.getEngine();return a.sharpen=new sd("sharpen",1,null,et.a.BILINEAR_SAMPLINGMODE,c,!1,a._defaultPipelineTextureType,!0),a._sharpenEffect=new Th(c,a.SharpenPostProcessId,function(){return a.sharpen},!0),a.depthOfField=new kh(a._scene,null,a._depthOfFieldBlurLevel,a._defaultPipelineTextureType,!0),a.bloom=new Sh(a._scene,a._bloomScale,a._bloomWeight,a.bloomKernel,a._defaultPipelineTextureType,!0),a.chromaticAberration=new Rh("ChromaticAberration",c.getRenderWidth(),c.getRenderHeight(),1,null,et.a.BILINEAR_SAMPLINGMODE,c,!1,a._defaultPipelineTextureType,!0),a._chromaticAberrationEffect=new Th(c,a.ChromaticAberrationPostProcessId,function(){return a.chromaticAberration},!0),a.grain=new Qh("Grain",1,null,et.a.BILINEAR_SAMPLINGMODE,c,!1,a._defaultPipelineTextureType,!0),a._grainEffect=new Th(c,a.GrainPostProcessId,function(){return a.grain},!0),a._resizeObserver=c.onResizeObservable.add(function(){a._hardwareScaleLevel=c.getHardwareScalingLevel(),a.bloomKernel=a.bloomKernel}),a._imageProcessingConfigurationObserver=a._scene.imageProcessingConfiguration.onUpdateParameters.add(function(){a.bloom._downscale._exposure=a._scene.imageProcessingConfiguration.exposure}),a._buildPipeline(),a}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"sharpenEnabled",{get:function(){return this._sharpenEnabled},set:function(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bloomKernel",{get:function(){return this._bloomKernel},set:function(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bloomWeight",{get:function(){return this._bloomWeight},set:function(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bloomThreshold",{get:function(){return this._bloomThreshold},set:function(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bloomScale",{get:function(){return this._bloomScale},set:function(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bloomEnabled",{get:function(){return this._bloomEnabled},set:function(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())},enumerable:!0,configurable:!0}),t.prototype._rebuildBloom=function(){var e=this.bloom;this.bloom=new Sh(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(var t=0;t<this._cameras.length;t++)e.disposeEffects(this._cameras[t])},Object.defineProperty(t.prototype,"depthOfFieldEnabled",{get:function(){return this._depthOfFieldEnabled},set:function(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"depthOfFieldBlurLevel",{get:function(){return this._depthOfFieldBlurLevel},set:function(e){if(this._depthOfFieldBlurLevel!==e){this._depthOfFieldBlurLevel=e;var t=this.depthOfField;this.depthOfField=new kh(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(var i=0;i<this._cameras.length;i++)t.disposeEffects(this._cameras[i]);this._buildPipeline()}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fxaaEnabled",{get:function(){return this._fxaaEnabled},set:function(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"samples",{get:function(){return this._samples},set:function(e){this._samples!==e&&(this._samples=e,this._buildPipeline())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageProcessingEnabled",{get:function(){return this._imageProcessingEnabled},set:function(e){this._imageProcessingEnabled!==e&&(this._imageProcessingEnabled=e,this._buildPipeline())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"glowLayerEnabled",{get:function(){return null!=this._glowLayer},set:function(e){e&&!this._glowLayer?this._glowLayer=new La("",this._scene):!e&&this._glowLayer&&(this._glowLayer.dispose(),this._glowLayer=null)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"glowLayer",{get:function(){return this._glowLayer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"chromaticAberrationEnabled",{get:function(){return this._chromaticAberrationEnabled},set:function(e){this._chromaticAberrationEnabled!==e&&(this._chromaticAberrationEnabled=e,this._buildPipeline())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"grainEnabled",{get:function(){return this._grainEnabled},set:function(e){this._grainEnabled!==e&&(this._grainEnabled=e,this._buildPipeline())},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"DefaultRenderingPipeline"},t.prototype.prepare=function(){var e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e},t.prototype._setAutoClearAndTextureSharing=function(e,t){void 0===t&&(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)},t.prototype._buildPipeline=function(){var e=this;if(this._buildAllowed){this._scene.autoClear=!0;var t=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(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(var i=0,n=this._cameras;i<n.length;i++){var r=n[i];(o=this._scene.enableDepthRenderer(r)).useOnlyInActiveCamera=!0}this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add(function(t){e._cameras.indexOf(t.activeCamera)>-1&&(e.depthOfField.depthTexture=t.enableDepthRenderer(t.activeCamera).getDepthMap())})}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);var o=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=o.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 Ji("imageProcessing",1,null,et.a.BILINEAR_SAMPLINGMODE,t,!1,this._defaultPipelineTextureType),this._hdr?(this.addEffect(new Th(t,this.ImageProcessingPostProcessId,function(){return e.imageProcessing},!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1),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 Yh("fxaa",1,null,et.a.BILINEAR_SAMPLINGMODE,t,!1,this._defaultPipelineTextureType),this.addEffect(new Th(t,this.FxaaPostProcessId,function(){return e.fxaa},!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&m.a.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}},t.prototype._disposePostProcesses=function(e){void 0===e&&(e=!1);for(var t=0;t<this._cameras.length;t++){var 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)},t.prototype.addCamera=function(e){this._camerasToBeAttached.push(e),this._buildPipeline()},t.prototype.removeCamera=function(e){var t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()},t.prototype.dispose=function(){this._disposePostProcesses(!0),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._scene.autoClear=!0,this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver),e.prototype.dispose.call(this)},t.prototype.serialize=function(){var e=N.a.Serialize(this);return e.customType="DefaultRenderingPipeline",e},t.Parse=function(e,i,n){return N.a.Parse(function(){return new t(e._name,e._name._hdr,i)},e,i,n)},Object(h.c)([Object(N.c)()],t.prototype,"sharpenEnabled",null),Object(h.c)([Object(N.c)()],t.prototype,"bloomKernel",null),Object(h.c)([Object(N.c)()],t.prototype,"_bloomWeight",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_bloomThreshold",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_hdr",void 0),Object(h.c)([Object(N.c)()],t.prototype,"bloomWeight",null),Object(h.c)([Object(N.c)()],t.prototype,"bloomThreshold",null),Object(h.c)([Object(N.c)()],t.prototype,"bloomScale",null),Object(h.c)([Object(N.c)()],t.prototype,"bloomEnabled",null),Object(h.c)([Object(N.c)()],t.prototype,"depthOfFieldEnabled",null),Object(h.c)([Object(N.c)()],t.prototype,"depthOfFieldBlurLevel",null),Object(h.c)([Object(N.c)()],t.prototype,"fxaaEnabled",null),Object(h.c)([Object(N.c)()],t.prototype,"samples",null),Object(h.c)([Object(N.c)()],t.prototype,"imageProcessingEnabled",null),Object(h.c)([Object(N.c)()],t.prototype,"glowLayerEnabled",null),Object(h.c)([Object(N.c)()],t.prototype,"chromaticAberrationEnabled",null),Object(h.c)([Object(N.c)()],t.prototype,"grainEnabled",null),t}(cd);c.a.RegisteredTypes["BABYLON.DefaultRenderingPipeline"]=hd;var dd="\nuniform sampler2D textureSampler;\n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}";ai.a.ShadersStore.lensHighlightsPixelShader=dd;var fd="\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance;\nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1\n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight;\n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV);\nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height);\nfloat depth=texture2D(depthSampler,distorted_coords).r;\nfloat distance=near+(far-near)*depth;\nvec4 color=texture2D(textureSampler,vUV);\n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n";ai.a.ShadersStore.depthOfFieldPixelShader=fd;var pd=function(e){function t(t,i,n,r,o){void 0===r&&(r=1);var a=e.call(this,n.getEngine(),t)||this;return a.LensChromaticAberrationEffect="LensChromaticAberrationEffect",a.HighlightsEnhancingEffect="HighlightsEnhancingEffect",a.LensDepthOfFieldEffect="LensDepthOfFieldEffect",a._pentagonBokehIsEnabled=!1,a._scene=n,a._depthTexture=n.enableDepthRenderer().getDepthMap(),i.grain_texture?a._grainTexture=i.grain_texture:a._createGrainTexture(),a._edgeBlur=i.edge_blur?i.edge_blur:0,a._grainAmount=i.grain_amount?i.grain_amount:0,a._chromaticAberration=i.chromatic_aberration?i.chromatic_aberration:0,a._distortion=i.distortion?i.distortion:0,a._highlightsGain=void 0!==i.dof_gain?i.dof_gain:-1,a._highlightsThreshold=i.dof_threshold?i.dof_threshold:1,a._dofDistance=void 0!==i.dof_focus_distance?i.dof_focus_distance:-1,a._dofAperture=i.dof_aperture?i.dof_aperture:1,a._dofDarken=i.dof_darken?i.dof_darken:0,a._dofPentagon=void 0===i.dof_pentagon||i.dof_pentagon,a._blurNoise=void 0===i.blur_noise||i.blur_noise,a._createChromaticAberrationPostProcess(r),a._createHighlightsPostProcess(r),a._createDepthOfFieldPostProcess(r/4),a.addEffect(new Th(n.getEngine(),a.LensChromaticAberrationEffect,function(){return a._chromaticAberrationPostProcess},!0)),a.addEffect(new Th(n.getEngine(),a.HighlightsEnhancingEffect,function(){return a._highlightsPostProcess},!0)),a.addEffect(new Th(n.getEngine(),a.LensDepthOfFieldEffect,function(){return a._depthOfFieldPostProcess},!0)),-1===a._highlightsGain&&a._disableEffect(a.HighlightsEnhancingEffect,null),n.postProcessRenderPipelineManager.addPipeline(a),o&&n.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(t,o),a}return Object(h.d)(t,e),t.prototype.getClassName=function(){return"LensRenderingPipeline"},Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"edgeBlur",{get:function(){return this._edgeBlur},set:function(e){this.setEdgeBlur(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"grainAmount",{get:function(){return this._grainAmount},set:function(e){this.setGrainAmount(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"chromaticAberration",{get:function(){return this._chromaticAberration},set:function(e){this.setChromaticAberration(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dofAperture",{get:function(){return this._dofAperture},set:function(e){this.setAperture(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"edgeDistortion",{get:function(){return this._distortion},set:function(e){this.setEdgeDistortion(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dofDistortion",{get:function(){return this._dofDistance},set:function(e){this.setFocusDistance(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"darkenOutOfFocus",{get:function(){return this._dofDarken},set:function(e){this.setDarkenOutOfFocus(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"blurNoise",{get:function(){return this._blurNoise},set:function(e){this._blurNoise=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pentagonBokeh",{get:function(){return this._pentagonBokehIsEnabled},set:function(e){e?this.enablePentagonBokeh():this.disablePentagonBokeh()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsGain",{get:function(){return this._highlightsGain},set:function(e){this.setHighlightsGain(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsThreshold",{get:function(){return this._highlightsThreshold},set:function(e){this.setHighlightsThreshold(e)},enumerable:!0,configurable:!0}),t.prototype.setEdgeBlur=function(e){this._edgeBlur=e},t.prototype.disableEdgeBlur=function(){this._edgeBlur=0},t.prototype.setGrainAmount=function(e){this._grainAmount=e},t.prototype.disableGrain=function(){this._grainAmount=0},t.prototype.setChromaticAberration=function(e){this._chromaticAberration=e},t.prototype.disableChromaticAberration=function(){this._chromaticAberration=0},t.prototype.setEdgeDistortion=function(e){this._distortion=e},t.prototype.disableEdgeDistortion=function(){this._distortion=0},t.prototype.setFocusDistance=function(e){this._dofDistance=e},t.prototype.disableDepthOfField=function(){this._dofDistance=-1},t.prototype.setAperture=function(e){this._dofAperture=e},t.prototype.setDarkenOutOfFocus=function(e){this._dofDarken=e},t.prototype.enablePentagonBokeh=function(){this._highlightsPostProcess.updateEffect("#define PENTAGON\n"),this._pentagonBokehIsEnabled=!0},t.prototype.disablePentagonBokeh=function(){this._pentagonBokehIsEnabled=!1,this._highlightsPostProcess.updateEffect()},t.prototype.enableNoiseBlur=function(){this._blurNoise=!0},t.prototype.disableNoiseBlur=function(){this._blurNoise=!1},t.prototype.setHighlightsGain=function(e){this._highlightsGain=e},t.prototype.setHighlightsThreshold=function(e){-1===this._highlightsGain&&(this._highlightsGain=1),this._highlightsThreshold=e},t.prototype.disableHighlights=function(){this._highlightsGain=-1},t.prototype.dispose=function(e){void 0===e&&(e=!1),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),this._chromaticAberrationPostProcess=null,this._highlightsPostProcess=null,this._depthOfFieldPostProcess=null,this._grainTexture.dispose(),e&&this._scene.disableDepthRenderer()},t.prototype._createChromaticAberrationPostProcess=function(e){var t=this;this._chromaticAberrationPostProcess=new ui("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],e,null,et.a.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._chromaticAberrationPostProcess.onApply=function(e){e.setFloat("chromatic_aberration",t._chromaticAberration),e.setFloat("screen_width",t._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",t._scene.getEngine().getRenderHeight()),e.setFloat("radialIntensity",1),e.setFloat2("direction",17,17),e.setFloat2("centerPosition",.5,.5)}},t.prototype._createHighlightsPostProcess=function(e){var t=this;this._highlightsPostProcess=new ui("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],e,null,et.a.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,this._dofPentagon?"#define PENTAGON\n":""),this._highlightsPostProcess.onApply=function(e){e.setFloat("gain",t._highlightsGain),e.setFloat("threshold",t._highlightsThreshold),e.setTextureFromPostProcess("textureSampler",t._chromaticAberrationPostProcess),e.setFloat("screen_width",t._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",t._scene.getEngine().getRenderHeight())}},t.prototype._createDepthOfFieldPostProcess=function(e){var t=this;this._depthOfFieldPostProcess=new ui("LensDepthOfField","depthOfField",["grain_amount","blur_noise","screen_width","screen_height","distortion","dof_enabled","screen_distance","aperture","darken","edge_blur","highlights","near","far"],["depthSampler","grainSampler","highlightsSampler"],e,null,et.a.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._depthOfFieldPostProcess.onApply=function(e){e.setTexture("depthSampler",t._depthTexture),e.setTexture("grainSampler",t._grainTexture),e.setTextureFromPostProcess("textureSampler",t._highlightsPostProcess),e.setTextureFromPostProcess("highlightsSampler",t._depthOfFieldPostProcess),e.setFloat("grain_amount",t._grainAmount),e.setBool("blur_noise",t._blurNoise),e.setFloat("screen_width",t._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",t._scene.getEngine().getRenderHeight()),e.setFloat("distortion",t._distortion),e.setBool("dof_enabled",-1!==t._dofDistance),e.setFloat("screen_distance",1/(.1-1/t._dofDistance)),e.setFloat("aperture",t._dofAperture),e.setFloat("darken",t._dofDarken),e.setFloat("edge_blur",t._edgeBlur),e.setBool("highlights",-1!==t._highlightsGain),t._scene.activeCamera&&(e.setFloat("near",t._scene.activeCamera.minZ),e.setFloat("far",t._scene.activeCamera.maxZ))}},t.prototype._createGrainTexture=function(){this._grainTexture=new qi("LensNoiseTexture",512,this._scene,!1,et.a.BILINEAR_SAMPLINGMODE),this._grainTexture.wrapU=et.a.WRAP_ADDRESSMODE,this._grainTexture.wrapV=et.a.WRAP_ADDRESSMODE;for(var e,t,i,n=this._grainTexture.getContext(),r=0;r<512;r++)for(var o=0;o<512;o++)e=Math.floor(255*(t=.42,i=.58,Math.random()*(i-t)+t)),n.fillStyle="rgb("+e+", "+e+", "+e+")",n.fillRect(r,o,1,1);this._grainTexture.update(!1)},t}(cd),_d="\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb;\nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n";ai.a.ShadersStore.ssao2PixelShader=_d;var md="uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n";ai.a.ShadersStore.ssaoCombinePixelShader=md;var gd=function(e){function t(t,i,n,r){var o=e.call(this,i.getEngine(),t)||this;if(o.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",o.SSAORenderEffect="SSAORenderEffect",o.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",o.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",o.SSAOCombineRenderEffect="SSAOCombineRenderEffect",o.totalStrength=1,o.maxZ=100,o.minZAspect=.2,o._samples=8,o._textureSamples=1,o._expensiveBlur=!0,o.radius=2,o.base=0,o._bits=new Uint32Array(1),o._scene=i,o._ratio=n,!o.isSupported)return m.a.Error("SSAO 2 needs WebGL 2 support."),o;var a=o._ratio.ssaoRatio||n,s=o._ratio.blurRatio||n,c=i.enableGeometryBufferRenderer();return o._createRandomTexture(),o._depthTexture=c.getGBuffer().textures[0],o._normalTexture=c.getGBuffer().textures[1],o._originalColorPostProcess=new fi("SSAOOriginalSceneColor",1,null,et.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1),o._originalColorPostProcess.samples=o.textureSamples,o._createSSAOPostProcess(1),o._createBlurPostProcess(a,s),o._createSSAOCombinePostProcess(s),o.addEffect(new Th(i.getEngine(),o.SSAOOriginalSceneColorEffect,function(){return o._originalColorPostProcess},!0)),o.addEffect(new Th(i.getEngine(),o.SSAORenderEffect,function(){return o._ssaoPostProcess},!0)),o.addEffect(new Th(i.getEngine(),o.SSAOBlurHRenderEffect,function(){return o._blurHPostProcess},!0)),o.addEffect(new Th(i.getEngine(),o.SSAOBlurVRenderEffect,function(){return o._blurVPostProcess},!0)),o.addEffect(new Th(i.getEngine(),o.SSAOCombineRenderEffect,function(){return o._ssaoCombinePostProcess},!0)),i.postProcessRenderPipelineManager.addPipeline(o),r&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(t,r),o}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"samples",{get:function(){return this._samples},set:function(e){this._ssaoPostProcess.updateEffect("#define SAMPLES "+e+"\n#define SSAO"),this._samples=e,this._sampleSphere=this._generateHemisphere()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"textureSamples",{get:function(){return this._textureSamples},set:function(e){this._textureSamples=e,this._originalColorPostProcess.samples=e,this._blurHPostProcess.samples=e,this._blurVPostProcess.samples=e,this._ssaoPostProcess.samples=e,this._ssaoCombinePostProcess.samples=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"expensiveBlur",{get:function(){return this._expensiveBlur},set:function(e){this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE "+(e?"1":"0")+"\n",null,["textureSampler","depthSampler"]),this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE "+(e?"1":"0")+"\n",null,["textureSampler","depthSampler"]),this._expensiveBlur=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"IsSupported",{get:function(){var e=R.a.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"SSAO2RenderingPipeline"},t.prototype.dispose=function(t){void 0===t&&(t=!1);for(var i=0;i<this._scene.cameras.length;i++){var n=this._scene.cameras[i];this._originalColorPostProcess.dispose(n),this._ssaoPostProcess.dispose(n),this._blurHPostProcess.dispose(n),this._blurVPostProcess.dispose(n),this._ssaoCombinePostProcess.dispose(n)}this._randomTexture.dispose(),t&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),e.prototype.dispose.call(this)},t.prototype._createBlurPostProcess=function(e,t){var i=this;this._samplerOffsets=[];for(var n=this.expensiveBlur,r=-8;r<8;r++)this._samplerOffsets.push(2*r+.5);this._blurHPostProcess=new ui("BlurH","ssao2",["outSize","samplerOffsets","near","far","radius"],["depthSampler"],e,null,et.a.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE "+(n?"1":"0")+"\n"),this._blurHPostProcess.onApply=function(e){i._scene.activeCamera&&(e.setFloat("outSize",i._ssaoCombinePostProcess.width>0?i._ssaoCombinePostProcess.width:i._originalColorPostProcess.width),e.setFloat("near",i._scene.activeCamera.minZ),e.setFloat("far",i._scene.activeCamera.maxZ),e.setFloat("radius",i.radius),e.setTexture("depthSampler",i._depthTexture),e.setArray("samplerOffsets",i._samplerOffsets))},this._blurVPostProcess=new ui("BlurV","ssao2",["outSize","samplerOffsets","near","far","radius"],["depthSampler"],t,null,et.a.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE "+(n?"1":"0")+"\n"),this._blurVPostProcess.onApply=function(e){i._scene.activeCamera&&(e.setFloat("outSize",i._ssaoCombinePostProcess.height>0?i._ssaoCombinePostProcess.height:i._originalColorPostProcess.height),e.setFloat("near",i._scene.activeCamera.minZ),e.setFloat("far",i._scene.activeCamera.maxZ),e.setFloat("radius",i.radius),e.setTexture("depthSampler",i._depthTexture),e.setArray("samplerOffsets",i._samplerOffsets))},this._blurHPostProcess.samples=this.textureSamples,this._blurVPostProcess.samples=this.textureSamples},t.prototype._rebuild=function(){e.prototype._rebuild.call(this)},t.prototype._radicalInverse_VdC=function(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,2.3283064365386963e-10*this._bits[0]},t.prototype._hammersley=function(e,t){return[e/t,this._radicalInverse_VdC(e)]},t.prototype._hemisphereSample_uniform=function(e,t){var i=2*t*Math.PI,n=1-(.85*e+.15),r=Math.sqrt(1-n*n);return new a.e(Math.cos(i)*r,Math.sin(i)*r,n)},t.prototype._generateHemisphere=function(){for(var e,t=this.samples,i=[],n=0;n<t;){if(t<16)e=this._hemisphereSample_uniform(Math.random(),Math.random());else{var r=this._hammersley(n,t);e=this._hemisphereSample_uniform(r[0],r[1])}i.push(e.x,e.y,e.z),n++}return i},t.prototype._createSSAOPostProcess=function(e){var t=this,i=this.samples;this._sampleSphere=this._generateHemisphere(),this._ssaoPostProcess=new ui("ssao2","ssao2",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","base","range","projection","near","far","texelSize","xViewport","yViewport","maxZ","minZAspect"],["randomSampler","normalSampler"],e,null,et.a.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES "+i+"\n#define SSAO"),this._ssaoPostProcess.onApply=function(e){t._scene.activeCamera&&(e.setArray3("sampleSphere",t._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/t.samples),e.setFloat("totalStrength",t.totalStrength),e.setFloat2("texelSize",1/t._ssaoPostProcess.width,1/t._ssaoPostProcess.height),e.setFloat("radius",t.radius),e.setFloat("maxZ",t.maxZ),e.setFloat("minZAspect",t.minZAspect),e.setFloat("base",t.base),e.setFloat("near",t._scene.activeCamera.minZ),e.setFloat("far",t._scene.activeCamera.maxZ),e.setFloat("xViewport",Math.tan(t._scene.activeCamera.fov/2)*t._scene.getEngine().getAspectRatio(t._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(t._scene.activeCamera.fov/2)),e.setMatrix("projection",t._scene.getProjectionMatrix()),e.setTexture("textureSampler",t._depthTexture),e.setTexture("normalSampler",t._normalTexture),e.setTexture("randomSampler",t._randomTexture))},this._ssaoPostProcess.samples=this.textureSamples},t.prototype._createSSAOCombinePostProcess=function(e){var t=this;this._ssaoCombinePostProcess=new ui("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,et.a.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=function(e){var i=t._scene.activeCamera.viewport;e.setVector4("viewport",a.c.Vector4[0].copyFromFloats(i.x,i.y,i.width,i.height)),e.setTextureFromPostProcess("originalColor",t._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples},t.prototype._createRandomTexture=function(){this._randomTexture=new qi("SSAORandomTexture",128,this._scene,!1,et.a.TRILINEAR_SAMPLINGMODE),this._randomTexture.wrapU=et.a.WRAP_ADDRESSMODE,this._randomTexture.wrapV=et.a.WRAP_ADDRESSMODE;for(var e=this._randomTexture.getContext(),t=function(e,t){return Math.random()*(t-e)+e},i=a.e.Zero(),n=0;n<128;n++)for(var r=0;r<128;r++)i.x=t(0,1),i.y=t(0,1),i.z=0,i.normalize(),i.scaleInPlace(255),i.x=Math.floor(i.x),i.y=Math.floor(i.y),e.fillStyle="rgb("+i.x+", "+i.y+", "+i.z+")",e.fillRect(n,r,1,1);this._randomTexture.update(!1)},t.prototype.serialize=function(){var e=N.a.Serialize(this);return e.customType="SSAO2RenderingPipeline",e},t.Parse=function(e,i,n){return N.a.Parse(function(){return new t(e._name,i,e._ratio)},e,i,n)},Object(h.c)([Object(N.c)()],t.prototype,"totalStrength",void 0),Object(h.c)([Object(N.c)()],t.prototype,"maxZ",void 0),Object(h.c)([Object(N.c)()],t.prototype,"minZAspect",void 0),Object(h.c)([Object(N.c)("samples")],t.prototype,"_samples",void 0),Object(h.c)([Object(N.c)("textureSamples")],t.prototype,"_textureSamples",void 0),Object(h.c)([Object(N.c)()],t.prototype,"_ratio",void 0),Object(h.c)([Object(N.c)("expensiveBlur")],t.prototype,"_expensiveBlur",void 0),Object(h.c)([Object(N.c)()],t.prototype,"radius",void 0),Object(h.c)([Object(N.c)()],t.prototype,"base",void 0),t}(cd);c.a.RegisteredTypes["BABYLON.SSAO2RenderingPipeline"]=gd;var vd="\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n";ai.a.ShadersStore.ssaoPixelShader=vd;var yd=function(e){function t(t,i,n,r){var o=e.call(this,i.getEngine(),t)||this;o.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",o.SSAORenderEffect="SSAORenderEffect",o.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",o.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",o.SSAOCombineRenderEffect="SSAOCombineRenderEffect",o.totalStrength=1,o.radius=1e-4,o.area=.0075,o.fallOff=1e-6,o.base=.5,o._firstUpdate=!0,o._scene=i,o._createRandomTexture(),o._depthTexture=i.enableDepthRenderer().getDepthMap();var a=n.ssaoRatio||n,s=n.combineRatio||n;return o._originalColorPostProcess=new fi("SSAOOriginalSceneColor",s,null,et.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1),o._createSSAOPostProcess(a),o._createBlurPostProcess(a),o._createSSAOCombinePostProcess(s),o.addEffect(new Th(i.getEngine(),o.SSAOOriginalSceneColorEffect,function(){return o._originalColorPostProcess},!0)),o.addEffect(new Th(i.getEngine(),o.SSAORenderEffect,function(){return o._ssaoPostProcess},!0)),o.addEffect(new Th(i.getEngine(),o.SSAOBlurHRenderEffect,function(){return o._blurHPostProcess},!0)),o.addEffect(new Th(i.getEngine(),o.SSAOBlurVRenderEffect,function(){return o._blurVPostProcess},!0)),o.addEffect(new Th(i.getEngine(),o.SSAOCombineRenderEffect,function(){return o._ssaoCombinePostProcess},!0)),i.postProcessRenderPipelineManager.addPipeline(o),r&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(t,r),o}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"SSAORenderingPipeline"},t.prototype.dispose=function(t){void 0===t&&(t=!1);for(var i=0;i<this._scene.cameras.length;i++){var n=this._scene.cameras[i];this._originalColorPostProcess.dispose(n),this._ssaoPostProcess.dispose(n),this._blurHPostProcess.dispose(n),this._blurVPostProcess.dispose(n),this._ssaoCombinePostProcess.dispose(n)}this._randomTexture.dispose(),t&&this._scene.disableDepthRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),e.prototype.dispose.call(this)},t.prototype._createBlurPostProcess=function(e){var t=this;this._blurHPostProcess=new Zr("BlurH",new a.d(1,0),16,e,null,et.a.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,g.a.TEXTURETYPE_UNSIGNED_INT),this._blurVPostProcess=new Zr("BlurV",new a.d(0,1),16,e,null,et.a.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,g.a.TEXTURETYPE_UNSIGNED_INT),this._blurHPostProcess.onActivateObservable.add(function(){var e=t._blurHPostProcess.width/t._scene.getEngine().getRenderWidth();t._blurHPostProcess.kernel=16*e}),this._blurVPostProcess.onActivateObservable.add(function(){var e=t._blurVPostProcess.height/t._scene.getEngine().getRenderHeight();t._blurVPostProcess.kernel=16*e})},t.prototype._rebuild=function(){this._firstUpdate=!0,e.prototype._rebuild.call(this)},t.prototype._createSSAOPostProcess=function(e){var t=this,i=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271];this._ssaoPostProcess=new ui("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,et.a.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.onApply=function(e){t._firstUpdate&&(e.setArray3("sampleSphere",i),e.setFloat("samplesFactor",1/16),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",t.totalStrength),e.setFloat("radius",t.radius),e.setFloat("area",t.area),e.setFloat("fallOff",t.fallOff),e.setFloat("base",t.base),e.setTexture("textureSampler",t._depthTexture),e.setTexture("randomSampler",t._randomTexture)}},t.prototype._createSSAOCombinePostProcess=function(e){var t=this;this._ssaoCombinePostProcess=new ui("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,et.a.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=function(e){e.setVector4("viewport",a.c.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",t._originalColorPostProcess)}},t.prototype._createRandomTexture=function(){this._randomTexture=new qi("SSAORandomTexture",512,this._scene,!1,et.a.TRILINEAR_SAMPLINGMODE),this._randomTexture.wrapU=et.a.WRAP_ADDRESSMODE,this._randomTexture.wrapV=et.a.WRAP_ADDRESSMODE;for(var e=this._randomTexture.getContext(),t=function(e,t){return Math.random()*(t-e)+e},i=a.e.Zero(),n=0;n<512;n++)for(var r=0;r<512;r++)i.x=Math.floor(255*t(-1,1)),i.y=Math.floor(255*t(-1,1)),i.z=Math.floor(255*t(-1,1)),e.fillStyle="rgb("+i.x+", "+i.y+", "+i.z+")",e.fillRect(n,r,1,1);this._randomTexture.update(!1)},Object(h.c)([Object(N.c)()],t.prototype,"totalStrength",void 0),Object(h.c)([Object(N.c)()],t.prototype,"radius",void 0),Object(h.c)([Object(N.c)()],t.prototype,"area",void 0),Object(h.c)([Object(N.c)()],t.prototype,"fallOff",void 0),Object(h.c)([Object(N.c)()],t.prototype,"base",void 0),t}(cd),bd="\n\nuniform sampler2D textureSampler;\nuniform sampler2D normalSampler;\nuniform sampler2D positionSampler;\nuniform sampler2D reflectivitySampler;\nuniform mat4 view;\nuniform mat4 projection;\nuniform float step;\nuniform float strength;\nuniform float threshold;\nuniform float roughnessFactor;\nuniform float reflectionSpecularFalloffExponent;\n\nvarying vec2 vUV;\n\nstruct ReflectionInfo {\nvec3 color;\nvec4 coords;\n};\n\nvec3 fresnelSchlick(float cosTheta,vec3 F0)\n{\nreturn F0+(1.0-F0)*pow(1.0-cosTheta,5.0);\n}\n\nReflectionInfo smoothReflectionInfo(vec3 dir,vec3 hitCoord)\n{\nReflectionInfo info;\ninfo.color=vec3(0.0);\nvec4 projectedCoord;\nfloat sampledDepth;\nfor(int i=0; i<SMOOTH_STEPS; i++)\n{\nprojectedCoord=projection*vec4(hitCoord,1.0);\nprojectedCoord.xy/=projectedCoord.w;\nprojectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);\nsampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;\nfloat depth=sampledDepth-hitCoord.z;\ndir*=0.5;\nif(depth>0.0)\nhitCoord-=dir;\nelse\nhitCoord+=dir;\ninfo.color+=texture2D(textureSampler,projectedCoord.xy).rgb;\n}\nprojectedCoord=projection*vec4(hitCoord,1.0);\nprojectedCoord.xy/=projectedCoord.w;\nprojectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);\n\ninfo.coords=vec4(projectedCoord.xy,sampledDepth,1.0);\ninfo.color+=texture2D(textureSampler,projectedCoord.xy).rgb;\ninfo.color/=float(SMOOTH_STEPS+1);\nreturn info;\n}\n\nReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)\n{\nReflectionInfo info;\nvec4 projectedCoord;\nfloat sampledDepth;\ndir*=step;\nfor(int i=0; i<REFLECTION_SAMPLES; i++)\n{\nhitCoord+=dir;\nprojectedCoord=projection*vec4(hitCoord,1.0);\nprojectedCoord.xy/=projectedCoord.w;\nprojectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);\nsampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;\nfloat depth=sampledDepth-hitCoord.z;\nif(((depth-dir.z)<threshold) && depth<=0.0)\n{\n#ifdef ENABLE_SMOOTH_REFLECTIONS\nreturn smoothReflectionInfo(dir,hitCoord);\n#else\ninfo.color=texture2D(textureSampler,projectedCoord.xy).rgb;\ninfo.coords=vec4(projectedCoord.xy,sampledDepth,0.0);\nreturn info;\n#endif\n}\n}\ninfo.color=texture2D(textureSampler,projectedCoord.xy).rgb;\ninfo.coords=vec4(projectedCoord.xy,sampledDepth,0.0);\nreturn info;\n}\nvec3 hash(vec3 a)\n{\na=fract(a*0.8);\na+=dot(a,a.yxz+19.19);\nreturn fract((a.xxy+a.yxx)*a.zyx);\n}\nvoid main()\n{\n#ifdef SSR_SUPPORTED\n\nvec3 albedo=texture2D(textureSampler,vUV).rgb;\nfloat spec=texture2D(reflectivitySampler,vUV).r;\nif (spec == 0.0) {\ngl_FragColor=vec4(albedo,1.0);\nreturn;\n}\n\nvec3 normal=(texture2D(normalSampler,vUV)).xyz;\nvec3 position=(view*texture2D(positionSampler,vUV)).xyz;\nvec3 reflected=normalize(reflect(normalize(position),normalize(normal)));\nfloat roughness=1.0-texture2D(reflectivitySampler,vUV).a;\nvec3 jitt=mix(vec3(0.0),hash(position),roughness)*roughnessFactor;\nReflectionInfo info=getReflectionInfo(jitt+reflected,position);\n\nvec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-info.coords.xy));\nfloat screenEdgefactor=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);\n\nvec3 F0=vec3(0.04);\nF0=mix(F0,albedo,spec);\nvec3 fresnel=fresnelSchlick(max(dot(normalize(normal),normalize(position)),0.0),F0);\n\nfloat reflectionMultiplier=clamp(pow(spec*strength,reflectionSpecularFalloffExponent)*screenEdgefactor*reflected.z,0.0,0.9);\nfloat albedoMultiplier=1.0-reflectionMultiplier;\nvec3 SSR=info.color*fresnel;\ngl_FragColor=vec4((albedo*albedoMultiplier)+(SSR*reflectionMultiplier),1.0);\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";ai.a.ShadersStore.screenSpaceReflectionPixelShader=bd;var Td=function(e){function t(t,i,n,r,o,a,s,c,l){void 0===c&&(c=g.a.TEXTURETYPE_UNSIGNED_INT),void 0===l&&(l=!1);var u=e.call(this,t,"screenSpaceReflection",["projection","view","threshold","reflectionSpecularFalloffExponent","strength","step","roughnessFactor"],["textureSampler","normalSampler","positionSampler","reflectivitySampler"],n,r,o,a,s,"#define SSR_SUPPORTED\n#define REFLECTION_SAMPLES 64\n#define SMOOTH_STEPS 5\n",c,void 0,null,l)||this;u.threshold=1.2,u.strength=1,u.reflectionSpecularFalloffExponent=3,u.step=1,u.roughnessFactor=.2,u._enableSmoothReflections=!1,u._reflectionSamples=64,u._smoothSteps=5;var h=i.enableGeometryBufferRenderer();return h&&h.isSupported&&(h.enablePosition=!0,h.enableReflectivity=!0,u._geometryBufferRenderer=h),u._updateEffectDefines(),u.onApply=function(e){if(h){var t=h.getTextureIndex(ed.POSITION_TEXTURE_TYPE),n=h.getTextureIndex(ed.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",h.getGBuffer().textures[1]),e.setTexture("positionSampler",h.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",h.getGBuffer().textures[n]);var r=i.activeCamera;if(r){var o=r.getViewMatrix(),a=r.getProjectionMatrix();e.setMatrix("projection",a),e.setMatrix("view",o),e.setFloat("threshold",u.threshold),e.setFloat("reflectionSpecularFalloffExponent",u.reflectionSpecularFalloffExponent),e.setFloat("strength",u.strength),e.setFloat("step",u.step),e.setFloat("roughnessFactor",u.roughnessFactor)}}},u}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"enableSmoothReflections",{get:function(){return this._enableSmoothReflections},set:function(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"reflectionSamples",{get:function(){return this._reflectionSamples},set:function(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"smoothSteps",{get:function(){return this._smoothSteps},set:function(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())},enumerable:!0,configurable:!0}),t.prototype._updateEffectDefines=function(){var e=[];this._geometryBufferRenderer&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),e.push("#define REFLECTION_SAMPLES "+(this._reflectionSamples>>0)),e.push("#define SMOOTH_STEPS "+(this._smoothSteps>>0)),this.updateEffect(e.join("\n"))},Object(h.c)([Object(N.c)()],t.prototype,"threshold",void 0),Object(h.c)([Object(N.c)()],t.prototype,"strength",void 0),Object(h.c)([Object(N.c)()],t.prototype,"reflectionSpecularFalloffExponent",void 0),Object(h.c)([Object(N.c)()],t.prototype,"step",void 0),Object(h.c)([Object(N.c)()],t.prototype,"roughnessFactor",void 0),Object(h.c)([Object(N.c)()],t.prototype,"enableSmoothReflections",null),Object(h.c)([Object(N.c)()],t.prototype,"reflectionSamples",null),Object(h.c)([Object(N.c)()],t.prototype,"smoothSteps",null),t}(ui),Ed="uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\n#include<packingFunctions>\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\n#ifndef AUTO_EXPOSURE\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\n#endif\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n";ai.a.ShadersStore.standardPixelShader=Ed;var xd=function(e){function t(t,i,n,r,o){void 0===r&&(r=null);var a=e.call(this,i.getEngine(),t)||this;return a.downSampleX4PostProcess=null,a.brightPassPostProcess=null,a.blurHPostProcesses=[],a.blurVPostProcesses=[],a.textureAdderPostProcess=null,a.volumetricLightPostProcess=null,a.volumetricLightSmoothXPostProcess=null,a.volumetricLightSmoothYPostProcess=null,a.volumetricLightMergePostProces=null,a.volumetricLightFinalPostProcess=null,a.luminancePostProcess=null,a.luminanceDownSamplePostProcesses=[],a.hdrPostProcess=null,a.textureAdderFinalPostProcess=null,a.lensFlareFinalPostProcess=null,a.hdrFinalPostProcess=null,a.lensFlarePostProcess=null,a.lensFlareComposePostProcess=null,a.motionBlurPostProcess=null,a.depthOfFieldPostProcess=null,a.fxaaPostProcess=null,a.screenSpaceReflectionPostProcess=null,a.brightThreshold=1,a.blurWidth=512,a.horizontalBlur=!1,a.lensTexture=null,a.volumetricLightCoefficient=.2,a.volumetricLightPower=4,a.volumetricLightBlurScale=64,a.sourceLight=null,a.hdrMinimumLuminance=1,a.hdrDecreaseRate=.5,a.hdrIncreaseRate=.5,a.lensColorTexture=null,a.lensFlareStrength=20,a.lensFlareGhostDispersal=1.4,a.lensFlareHaloWidth=.7,a.lensFlareDistortionStrength=16,a.lensFlareBlurWidth=512,a.lensStarTexture=null,a.lensFlareDirtTexture=null,a.depthOfFieldDistance=10,a.depthOfFieldBlurWidth=64,a.animations=[],a._currentDepthOfFieldSource=null,a._fixedExposure=1,a._currentExposure=1,a._hdrAutoExposure=!1,a._hdrCurrentLuminance=1,a._motionStrength=1,a._isObjectBasedMotionBlur=!1,a._camerasToBeAttached=[],a._bloomEnabled=!1,a._depthOfFieldEnabled=!1,a._vlsEnabled=!1,a._lensFlareEnabled=!1,a._hdrEnabled=!1,a._motionBlurEnabled=!1,a._fxaaEnabled=!1,a._screenSpaceReflectionsEnabled=!1,a._motionBlurSamples=64,a._volumetricLightStepsCount=50,a._samples=1,a._cameras=o||i.cameras,a._cameras=a._cameras.slice(),a._camerasToBeAttached=a._cameras.slice(),a._scene=i,a._basePostProcess=r,a._ratio=n,a._floatTextureType=i.getEngine().getCaps().textureFloatRender?g.a.TEXTURETYPE_FLOAT:g.a.TEXTURETYPE_HALF_FLOAT,i.postProcessRenderPipelineManager.addPipeline(a),a._buildPipeline(),a}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"exposure",{get:function(){return this._fixedExposure},set:function(e){this._fixedExposure=e,this._currentExposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hdrAutoExposure",{get:function(){return this._hdrAutoExposure},set:function(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){var t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join("\n"))}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"motionStrength",{get:function(){return this._motionStrength},set:function(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"objectBasedMotionBlur",{get:function(){return this._isObjectBasedMotionBlur},set:function(e){var t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"BloomEnabled",{get:function(){return this._bloomEnabled},set:function(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"DepthOfFieldEnabled",{get:function(){return this._depthOfFieldEnabled},set:function(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"LensFlareEnabled",{get:function(){return this._lensFlareEnabled},set:function(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"HDREnabled",{get:function(){return this._hdrEnabled},set:function(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"VLSEnabled",{get:function(){return this._vlsEnabled},set:function(e){if(this._vlsEnabled!==e){if(e)if(!this._scene.enableGeometryBufferRenderer())return void m.a.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");this._vlsEnabled=e,this._buildPipeline()}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"MotionBlurEnabled",{get:function(){return this._motionBlurEnabled},set:function(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fxaaEnabled",{get:function(){return this._fxaaEnabled},set:function(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"screenSpaceReflectionsEnabled",{get:function(){return this._screenSpaceReflectionsEnabled},set:function(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"volumetricLightStepsCount",{get:function(){return this._volumetricLightStepsCount},set:function(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"motionBlurSamples",{get:function(){return this._motionBlurSamples},set:function(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"samples",{get:function(){return this._samples},set:function(e){this._samples!==e&&(this._samples=e,this._buildPipeline())},enumerable:!0,configurable:!0}),t.prototype._buildPipeline=function(){var e=this,t=this._ratio,i=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new Td("HDRPass",i,t,null,et.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(function(){e._currentDepthOfFieldSource=e.screenSpaceReflectionPostProcess}),this.addEffect(new Th(i.getEngine(),"HDRScreenSpaceReflections",function(){return e.screenSpaceReflectionPostProcess},!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new ui("HDRPass","standard",[],[],t,null,et.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add(function(){e._currentDepthOfFieldSource=e.originalPostProcess}),this.addEffect(new Th(i.getEngine(),"HDRPassPostProcess",function(){return e.originalPostProcess},!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(i,t/4),this._createBrightPassPostProcess(i,t/4),this._createBlurPostProcesses(i,t/4,1),this._createTextureAdderPostProcess(i,t),this.textureAdderFinalPostProcess=new ui("HDRDepthOfFieldSource","standard",[],[],t,null,et.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,"#define PASS_POST_PROCESS",g.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Th(i.getEngine(),"HDRBaseDepthOfFieldSource",function(){return e.textureAdderFinalPostProcess},!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(i,t),this.volumetricLightFinalPostProcess=new ui("HDRVLSFinal","standard",[],[],t,null,et.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,"#define PASS_POST_PROCESS",g.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Th(i.getEngine(),"HDRVLSFinal",function(){return e.volumetricLightFinalPostProcess},!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(i,t),this.lensFlareFinalPostProcess=new ui("HDRPostLensFlareDepthOfFieldSource","standard",[],[],t,null,et.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,"#define PASS_POST_PROCESS",g.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Th(i.getEngine(),"HDRPostLensFlareDepthOfFieldSource",function(){return e.lensFlareFinalPostProcess},!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(i,this._floatTextureType),this._createHdrPostProcess(i,t),this.hdrFinalPostProcess=new ui("HDRPostHDReDepthOfFieldSource","standard",[],[],t,null,et.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,"#define PASS_POST_PROCESS",g.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Th(i.getEngine(),"HDRPostHDReDepthOfFieldSource",function(){return e.hdrFinalPostProcess},!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(i,t/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(i,t)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(i,t),this._fxaaEnabled&&(this.fxaaPostProcess=new Yh("fxaa",1,null,et.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,g.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Th(i.getEngine(),"HDRFxaa",function(){return e.fxaaPostProcess},!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&m.a.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")},t.prototype._createDownSampleX4PostProcess=function(e,t){var i=this,n=new Array(32);this.downSampleX4PostProcess=new ui("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,et.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=function(e){for(var t=0,r=i.downSampleX4PostProcess.width,o=i.downSampleX4PostProcess.height,a=-2;a<2;a++)for(var s=-2;s<2;s++)n[t]=(a+.5)*(1/r),n[t+1]=(s+.5)*(1/o),t+=2;e.setArray2("dsOffsets",n)},this.addEffect(new Th(e.getEngine(),"HDRDownSampleX4",function(){return i.downSampleX4PostProcess},!0))},t.prototype._createBrightPassPostProcess=function(e,t){var i=this,n=new Array(8);this.brightPassPostProcess=new ui("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,et.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=function(e){var t=1/i.brightPassPostProcess.width,r=1/i.brightPassPostProcess.height;n[0]=-.5*t,n[1]=.5*r,n[2]=.5*t,n[3]=.5*r,n[4]=-.5*t,n[5]=-.5*r,n[6]=.5*t,n[7]=-.5*r,e.setArray2("dsOffsets",n),e.setFloat("brightThreshold",i.brightThreshold)},this.addEffect(new Th(e.getEngine(),"HDRBrightPass",function(){return i.brightPassPostProcess},!0))},t.prototype._createBlurPostProcesses=function(e,t,i,n){var r=this;void 0===n&&(n="blurWidth");var o=e.getEngine(),s=new Zr("HDRBlurH_"+i,new a.d(1,0),this[n],t,null,et.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),c=new Zr("HDRBlurV_"+i,new a.d(0,1),this[n],t,null,et.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);s.onActivateObservable.add(function(){var e=s.width/o.getRenderWidth();s.kernel=r[n]*e}),c.onActivateObservable.add(function(){var e=c.height/o.getRenderHeight();c.kernel=r.horizontalBlur?64*e:r[n]*e}),this.addEffect(new Th(e.getEngine(),"HDRBlurH"+i,function(){return s},!0)),this.addEffect(new Th(e.getEngine(),"HDRBlurV"+i,function(){return c},!0)),this.blurHPostProcesses.push(s),this.blurVPostProcesses.push(c)},t.prototype._createTextureAdderPostProcess=function(e,t){var i=this;this.textureAdderPostProcess=new ui("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,et.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",i._vlsEnabled?i._currentDepthOfFieldSource:i.originalPostProcess),e.setTexture("lensSampler",i.lensTexture),e.setFloat("exposure",i._currentExposure),i._currentDepthOfFieldSource=i.textureAdderFinalPostProcess},this.addEffect(new Th(e.getEngine(),"HDRTextureAdder",function(){return i.textureAdderPostProcess},!0))},t.prototype._createVolumetricLightPostProcess=function(e,t){var i=this,n=e.enableGeometryBufferRenderer();n.enablePosition=!0;var r=n.getGBuffer();this.volumetricLightPostProcess=new ui("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,et.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));var o=a.d.Zero();this.volumetricLightPostProcess.onApply=function(e){if(i.sourceLight&&i.sourceLight.getShadowGenerator()&&i._scene.activeCamera){var t=i.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",r.textures[2]),e.setColor3("sunColor",i.sourceLight.diffuse),e.setVector3("sunDirection",i.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",i._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",i.volumetricLightCoefficient),e.setFloat("scatteringPower",i.volumetricLightPower),o.x=i.sourceLight.getDepthMinZ(i._scene.activeCamera),o.y=i.sourceLight.getDepthMaxZ(i._scene.activeCamera),e.setVector2("depthValues",o)}},this.addEffect(new Th(e.getEngine(),"HDRVLS",function(){return i.volumetricLightPostProcess},!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new ui("HDRVLSMerge","standard",[],["originalSampler"],t,null,et.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=function(e){e.setTextureFromPostProcess("originalSampler",i._bloomEnabled?i.textureAdderFinalPostProcess:i.originalPostProcess),i._currentDepthOfFieldSource=i.volumetricLightFinalPostProcess},this.addEffect(new Th(e.getEngine(),"HDRVLSMerge",function(){return i.volumetricLightMergePostProces},!0))},t.prototype._createLuminancePostProcesses=function(e,i){var n=this,r=Math.pow(3,t.LuminanceSteps);this.luminancePostProcess=new ui("HDRLuminance","standard",["lumOffsets"],[],{width:r,height:r},null,et.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",i);var o=[];this.luminancePostProcess.onApply=function(e){var t=1/n.luminancePostProcess.width,i=1/n.luminancePostProcess.height;o[0]=-.5*t,o[1]=.5*i,o[2]=.5*t,o[3]=.5*i,o[4]=-.5*t,o[5]=-.5*i,o[6]=.5*t,o[7]=-.5*i,e.setArray2("lumOffsets",o)},this.addEffect(new Th(e.getEngine(),"HDRLuminance",function(){return n.luminancePostProcess},!0));for(var s=t.LuminanceSteps-1;s>=0;s--){r=Math.pow(3,s);var c="#define LUMINANCE_DOWN_SAMPLE\n";0===s&&(c+="#define FINAL_DOWN_SAMPLER");var l=new ui("HDRLuminanceDownSample"+s,"standard",["dsOffsets","halfDestPixelSize"],[],{width:r,height:r},null,et.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,c,i);this.luminanceDownSamplePostProcesses.push(l)}var u=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach(function(t,i){var r=new Array(18);t.onApply=function(e){if(u){for(var o=0,a=-1;a<2;a++)for(var s=-1;s<2;s++)r[o]=a/u.width,r[o+1]=s/u.height,o+=2;e.setArray2("dsOffsets",r),e.setFloat("halfDestPixelSize",.5/u.width),u=i===n.luminanceDownSamplePostProcesses.length-1?n.luminancePostProcess:t}},i===n.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=function(){var t=e.getEngine().readPixels(0,0,1,1),i=new a.f(1/16581375,1/65025,1/255,1);n._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100}),n.addEffect(new Th(e.getEngine(),"HDRLuminanceDownSample"+i,function(){return t},!0))})},t.prototype._createHdrPostProcess=function(e,t){var i=this,n=["#define HDR"];this._hdrAutoExposure&&n.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new ui("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,et.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,n.join("\n"),g.a.TEXTURETYPE_UNSIGNED_INT);var r=1,o=0,a=0;this.hdrPostProcess.onApply=function(t){if(t.setTextureFromPostProcess("textureAdderSampler",i._currentDepthOfFieldSource),o+=e.getEngine().getDeltaTime(),r<0)r=i._hdrCurrentLuminance;else{var n=(a-o)/1e3;i._hdrCurrentLuminance<r+i.hdrDecreaseRate*n?r+=i.hdrDecreaseRate*n:i._hdrCurrentLuminance>r-i.hdrIncreaseRate*n?r-=i.hdrIncreaseRate*n:r=i._hdrCurrentLuminance}i.hdrAutoExposure?i._currentExposure=i._fixedExposure/r:(r=L.a.Clamp(r,i.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",r)),a=o,i._currentDepthOfFieldSource=i.hdrFinalPostProcess},this.addEffect(new Th(e.getEngine(),"HDR",function(){return i.hdrPostProcess},!0))},t.prototype._createLensFlarePostProcess=function(e,t){var i=this;this.lensFlarePostProcess=new ui("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,et.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",g.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Th(e.getEngine(),"HDRLensFlare",function(){return i.lensFlarePostProcess},!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new ui("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,et.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",g.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Th(e.getEngine(),"HDRLensFlareCompose",function(){return i.lensFlareComposePostProcess},!0));var n=new a.d(0,0);this.lensFlarePostProcess.onApply=function(e){e.setTextureFromPostProcess("textureSampler",i._bloomEnabled?i.blurHPostProcesses[0]:i.originalPostProcess),e.setTexture("lensColorSampler",i.lensColorTexture),e.setFloat("strength",i.lensFlareStrength),e.setFloat("ghostDispersal",i.lensFlareGhostDispersal),e.setFloat("haloWidth",i.lensFlareHaloWidth),n.x=i.lensFlarePostProcess.width,n.y=i.lensFlarePostProcess.height,e.setVector2("resolution",n),e.setFloat("distortionStrength",i.lensFlareDistortionStrength)};var r=a.a.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),o=a.a.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=function(e){if(i._scene.activeCamera){e.setTextureFromPostProcess("otherSampler",i.lensFlarePostProcess),e.setTexture("lensDirtSampler",i.lensFlareDirtTexture),e.setTexture("lensStarSampler",i.lensStarTexture);var t=i._scene.activeCamera.getViewMatrix().getRow(0),n=i._scene.activeCamera.getViewMatrix().getRow(2),s=a.e.Dot(t.toVector3(),new a.e(1,0,0))+a.e.Dot(n.toVector3(),new a.e(0,0,1));s*=4;var c=a.a.FromValues(.5*Math.cos(s),-Math.sin(s),0,0,Math.sin(s),.5*Math.cos(s),0,0,0,0,1,0,0,0,0,1),l=o.multiply(c).multiply(r);e.setMatrix("lensStarMatrix",l),i._currentDepthOfFieldSource=i.lensFlareFinalPostProcess}}},t.prototype._createDepthOfFieldPostProcess=function(e,t){var i=this;this.depthOfFieldPostProcess=new ui("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,et.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",g.a.TEXTURETYPE_UNSIGNED_INT),this.depthOfFieldPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",i._currentDepthOfFieldSource),e.setTexture("depthSampler",i._getDepthTexture()),e.setFloat("distance",i.depthOfFieldDistance)},this.addEffect(new Th(e.getEngine(),"HDRDepthOfField",function(){return i.depthOfFieldPostProcess},!0))},t.prototype._createMotionBlurPostProcess=function(e,t){var i=this;if(this._isObjectBasedMotionBlur){var n=new nd("HDRMotionBlur",e,t,null,et.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,g.a.TEXTURETYPE_UNSIGNED_INT);n.motionStrength=this.motionStrength,n.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=n}else{this.motionBlurPostProcess=new ui("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,et.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),g.a.TEXTURETYPE_UNSIGNED_INT);var r=0,o=a.a.Identity(),s=a.a.Identity(),c=a.a.Identity(),l=a.d.Zero();this.motionBlurPostProcess.onApply=function(t){(c=e.getProjectionMatrix().multiply(e.getViewMatrix())).invertToRef(s),t.setMatrix("inverseViewProjection",s),t.setMatrix("prevViewProjection",o),o=c,l.x=i.motionBlurPostProcess.width,l.y=i.motionBlurPostProcess.height,t.setVector2("screenSize",l),r=e.getEngine().getFps()/60,t.setFloat("motionScale",r),t.setFloat("motionStrength",i.motionStrength),t.setTexture("depthSampler",i._getDepthTexture())}}this.addEffect(new Th(e.getEngine(),"HDRMotionBlur",function(){return i.motionBlurPostProcess},!0))},t.prototype._getDepthTexture=function(){return this._scene.getEngine().getCaps().drawBuffersExtension?this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]:this._scene.enableDepthRenderer().getDepthMap()},t.prototype._disposePostProcesses=function(){for(var e=0;e<this._cameras.length;e++){var t=this._cameras[e];this.originalPostProcess&&this.originalPostProcess.dispose(t),this.screenSpaceReflectionPostProcess&&this.screenSpaceReflectionPostProcess.dispose(t),this.downSampleX4PostProcess&&this.downSampleX4PostProcess.dispose(t),this.brightPassPostProcess&&this.brightPassPostProcess.dispose(t),this.textureAdderPostProcess&&this.textureAdderPostProcess.dispose(t),this.volumetricLightPostProcess&&this.volumetricLightPostProcess.dispose(t),this.volumetricLightSmoothXPostProcess&&this.volumetricLightSmoothXPostProcess.dispose(t),this.volumetricLightSmoothYPostProcess&&this.volumetricLightSmoothYPostProcess.dispose(t),this.volumetricLightMergePostProces&&this.volumetricLightMergePostProces.dispose(t),this.volumetricLightFinalPostProcess&&this.volumetricLightFinalPostProcess.dispose(t),this.lensFlarePostProcess&&this.lensFlarePostProcess.dispose(t),this.lensFlareComposePostProcess&&this.lensFlareComposePostProcess.dispose(t);for(var i=0;i<this.luminanceDownSamplePostProcesses.length;i++)this.luminanceDownSamplePostProcesses[i].dispose(t);this.luminancePostProcess&&this.luminancePostProcess.dispose(t),this.hdrPostProcess&&this.hdrPostProcess.dispose(t),this.hdrFinalPostProcess&&this.hdrFinalPostProcess.dispose(t),this.depthOfFieldPostProcess&&this.depthOfFieldPostProcess.dispose(t),this.motionBlurPostProcess&&this.motionBlurPostProcess.dispose(t),this.fxaaPostProcess&&this.fxaaPostProcess.dispose(t);for(i=0;i<this.blurHPostProcesses.length;i++)this.blurHPostProcesses[i].dispose(t);for(i=0;i<this.blurVPostProcesses.length;i++)this.blurVPostProcesses[i].dispose(t)}this.originalPostProcess=null,this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.textureAdderPostProcess=null,this.textureAdderFinalPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.luminancePostProcess=null,this.hdrPostProcess=null,this.hdrFinalPostProcess=null,this.depthOfFieldPostProcess=null,this.motionBlurPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.luminanceDownSamplePostProcesses=[],this.blurHPostProcesses=[],this.blurVPostProcesses=[]},t.prototype.dispose=function(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),e.prototype.dispose.call(this)},t.prototype.serialize=function(){var e=N.a.Serialize(this);return this.sourceLight&&(e.sourceLightId=this.sourceLight.id),this.screenSpaceReflectionPostProcess&&(e.screenSpaceReflectionPostProcess=N.a.Serialize(this.screenSpaceReflectionPostProcess)),e.customType="StandardRenderingPipeline",e},t.Parse=function(e,i,n){var r=N.a.Parse(function(){return new t(e._name,i,e._ratio)},e,i,n);return e.sourceLightId&&(r.sourceLight=i.getLightByID(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&N.a.Parse(function(){return r.screenSpaceReflectionPostProcess},e.screenSpaceReflectionPostProcess,i,n),r},t.LuminanceSteps=6,Object(h.c)([Object(N.c)()],t.prototype,"brightThreshold",void 0),Object(h.c)([Object(N.c)()],t.prototype,"blurWidth",void 0),Object(h.c)([Object(N.c)()],t.prototype,"horizontalBlur",void 0),Object(h.c)([Object(N.c)()],t.prototype,"exposure",null),Object(h.c)([Object(N.m)("lensTexture")],t.prototype,"lensTexture",void 0),Object(h.c)([Object(N.c)()],t.prototype,"volumetricLightCoefficient",void 0),Object(h.c)([Object(N.c)()],t.prototype,"volumetricLightPower",void 0),Object(h.c)([Object(N.c)()],t.prototype,"volumetricLightBlurScale",void 0),Object(h.c)([Object(N.c)()],t.prototype,"hdrMinimumLuminance",void 0),Object(h.c)([Object(N.c)()],t.prototype,"hdrDecreaseRate",void 0),Object(h.c)([Object(N.c)()],t.prototype,"hdrIncreaseRate",void 0),Object(h.c)([Object(N.c)()],t.prototype,"hdrAutoExposure",null),Object(h.c)([Object(N.m)("lensColorTexture")],t.prototype,"lensColorTexture",void 0),Object(h.c)([Object(N.c)()],t.prototype,"lensFlareStrength",void 0),Object(h.c)([Object(N.c)()],t.prototype,"lensFlareGhostDispersal",void 0),Object(h.c)([Object(N.c)()],t.prototype,"lensFlareHaloWidth",void 0),Object(h.c)([Object(N.c)()],t.prototype,"lensFlareDistortionStrength",void 0),Object(h.c)([Object(N.c)()],t.prototype,"lensFlareBlurWidth",void 0),Object(h.c)([Object(N.m)("lensStarTexture")],t.prototype,"lensStarTexture",void 0),Object(h.c)([Object(N.m)("lensFlareDirtTexture")],t.prototype,"lensFlareDirtTexture",void 0),Object(h.c)([Object(N.c)()],t.prototype,"depthOfFieldDistance",void 0),Object(h.c)([Object(N.c)()],t.prototype,"depthOfFieldBlurWidth",void 0),Object(h.c)([Object(N.c)()],t.prototype,"motionStrength",null),Object(h.c)([Object(N.c)()],t.prototype,"objectBasedMotionBlur",null),Object(h.c)([Object(N.c)()],t.prototype,"_ratio",void 0),Object(h.c)([Object(N.c)()],t.prototype,"BloomEnabled",null),Object(h.c)([Object(N.c)()],t.prototype,"DepthOfFieldEnabled",null),Object(h.c)([Object(N.c)()],t.prototype,"LensFlareEnabled",null),Object(h.c)([Object(N.c)()],t.prototype,"HDREnabled",null),Object(h.c)([Object(N.c)()],t.prototype,"VLSEnabled",null),Object(h.c)([Object(N.c)()],t.prototype,"MotionBlurEnabled",null),Object(h.c)([Object(N.c)()],t.prototype,"fxaaEnabled",null),Object(h.c)([Object(N.c)()],t.prototype,"screenSpaceReflectionsEnabled",null),Object(h.c)([Object(N.c)()],t.prototype,"volumetricLightStepsCount",null),Object(h.c)([Object(N.c)()],t.prototype,"motionBlurSamples",null),Object(h.c)([Object(N.c)()],t.prototype,"samples",null),t}(cd);c.a.RegisteredTypes["BABYLON.StandardRenderingPipeline"]=xd;var Pd="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb);\nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm);\ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}";ai.a.ShadersStore.tonemapPixelShader=Pd;var Ad;!function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(Ad||(Ad={}));var Sd=function(e){function t(t,i,n,r,o,a,s){void 0===o&&(o=g.a.TEXTURE_BILINEAR_SAMPLINGMODE),void 0===s&&(s=g.a.TEXTURETYPE_UNSIGNED_INT);var c=e.call(this,t,"tonemap",["_ExposureAdjustment"],null,1,r,o,a,!0,null,s)||this;c._operator=i,c.exposureAdjustment=n;var l="#define ";return c._operator===Ad.Hable?l+="HABLE_TONEMAPPING":c._operator===Ad.Reinhard?l+="REINHARD_TONEMAPPING":c._operator===Ad.HejiDawson?l+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":c._operator===Ad.Photographic&&(l+="PHOTOGRAPHIC_TONEMAPPING"),c.updateEffect(l),c.onApply=function(e){e.setFloat("_ExposureAdjustment",c.exposureAdjustment)},c}return Object(h.d)(t,e),t}(ui),Cd="uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n";ai.a.ShadersStore.volumetricLightScatteringPixelShader=Cd;var Rd="\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1)\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n";ai.a.ShadersStore.volumetricLightScatteringPassVertexShader=Rd;var Od="#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n";ai.a.ShadersStore.volumetricLightScatteringPassPixelShader=Od;var Md=function(e){function t(i,n,r,o,s,c,l,u,h){void 0===s&&(s=100),void 0===c&&(c=et.a.BILINEAR_SAMPLINGMODE);var d=e.call(this,i,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],n.postProcessRatio||n,r,c,l,u,"#define NUM_SAMPLES "+s)||this;return d._screenCoordinates=a.d.Zero(),d.customMeshPosition=a.e.Zero(),d.useCustomMeshPosition=!1,d.invert=!0,d.excludedMeshes=new Array,d.exposure=.3,d.decay=.96815,d.weight=.58767,d.density=.926,l=(h=null===r?h:r.getScene()).getEngine(),d._viewPort=new ki.a(0,0,1,1).toGlobal(l.getRenderWidth(),l.getRenderHeight()),d.mesh=null!==o?o:t.CreateDefaultMesh("VolumetricLightScatteringMesh",h),d._createPass(h,n.passRatio||n),d.onActivate=function(e){d.isSupported||d.dispose(e),d.onActivate=null},d.onApplyObservable.add(function(e){d._updateMeshScreenCoordinates(h),e.setTexture("lightScatteringSampler",d._volumetricLightScatteringRTT),e.setFloat("exposure",d.exposure),e.setFloat("decay",d.decay),e.setFloat("weight",d.weight),e.setFloat("density",d.density),e.setVector2("meshPositionOnScreen",d._screenCoordinates)}),d}return Object(h.d)(t,e),Object.defineProperty(t.prototype,"useDiffuseColor",{get:function(){return m.a.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1},set:function(e){m.a.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"VolumetricLightScatteringPostProcess"},t.prototype._isReady=function(e,t){var i=e.getMesh();if(i===this.mesh&&i.material)return i.material.isReady(i);var n=[],r=[en.b.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&n.push("#define ALPHATEST"),i.isVerticesDataPresent(en.b.UVKind)&&(r.push(en.b.UVKind),n.push("#define UV1")),i.isVerticesDataPresent(en.b.UV2Kind)&&(r.push(en.b.UV2Kind),n.push("#define UV2"))),i.useBones&&i.computeBonesUsingShaders?(r.push(en.b.MatricesIndicesKind),r.push(en.b.MatricesWeightsKind),n.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),n.push("#define BonesPerMesh "+(i.skeleton?i.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),t&&(n.push("#define INSTANCES"),io.a.PushAttributesForInstances(r));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._volumetricLightScatteringPass=i.getScene().getEngine().createEffect("volumetricLightScatteringPass",r,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],a,void 0,void 0,void 0,{maxSimultaneousMorphTargets:i.numBoneInfluencers})),this._volumetricLightScatteringPass.isReady()},t.prototype.setCustomMeshPosition=function(e){this.customMeshPosition=e},t.prototype.getCustomMeshPosition=function(){return this.customMeshPosition},t.prototype.dispose=function(t){var i=t.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==i&&t.getScene().customRenderTargets.splice(i,1),this._volumetricLightScatteringRTT.dispose(),e.prototype.dispose.call(this,t)},t.prototype.getPass=function(){return this._volumetricLightScatteringRTT},t.prototype._meshExcluded=function(e){return this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)},t.prototype._createPass=function(e,t){var i=this,n=e.getEngine();this._volumetricLightScatteringRTT=new Fi("volumetricLightScatteringMap",{width:n.getRenderWidth()*t,height:n.getRenderHeight()*t},e,!1,!0,g.a.TEXTURETYPE_UNSIGNED_INT),this._volumetricLightScatteringRTT.wrapU=et.a.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=et.a.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;var r=this.getCamera();r?r.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);var o,a=function(e){var t=e.getRenderingMesh();if(!i._meshExcluded(t)){t._internalAbstractMeshDataInfo._isActiveIntermediate=!1;var n=e.getMaterial();if(n){var r=t.getScene(),o=r.getEngine();o.setState(n.backFaceCulling);var a=t._getInstancesRenderList(e._id);if(!a.mustReturn){var s=o.getCaps().instancedArrays&&null!==a.visibleInstances[e._id];if(i._isReady(e,s)){var c=i._volumetricLightScatteringPass;if(t===i.mesh&&(c=e.effect?e.effect:n.getEffect()),o.enableEffect(c),t._bind(e,c,n.fillMode),t===i.mesh)n.bind(t.getWorldMatrix(),t);else{if(i._volumetricLightScatteringPass.setMatrix("viewProjection",r.getTransformMatrix()),n&&n.needAlphaTesting()){var l=n.getAlphaTestTexture();i._volumetricLightScatteringPass.setTexture("diffuseSampler",l),l&&i._volumetricLightScatteringPass.setMatrix("diffuseMatrix",l.getTextureMatrix())}t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&i._volumetricLightScatteringPass.setMatrices("mBones",t.skeleton.getTransformMatrices(t))}t._processRendering(e,i._volumetricLightScatteringPass,Ca.a.TriangleFillMode,a,s,function(e,t){return c.setMatrix("world",t)})}}}}},c=new s.b(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function(){o=e.clearColor,e.clearColor=c}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function(){e.clearColor=o}),this._volumetricLightScatteringRTT.customRenderFunction=function(t,i,n,r){var o,s=e.getEngine();if(r.length){for(s.setColorWrite(!1),o=0;o<r.length;o++)a(r.data[o]);s.setColorWrite(!0)}for(o=0;o<t.length;o++)a(t.data[o]);for(o=0;o<i.length;o++)a(i.data[o]);if(n.length){for(o=0;o<n.length;o++){var c=n.data[o],l=c.getBoundingInfo();l&&e.activeCamera&&(c._alphaIndex=c.getMesh().alphaIndex,c._distanceToCamera=l.boundingSphere.centerWorld.subtract(e.activeCamera.position).length())}var u=n.data.slice(0,n.length);for(u.sort(function(e,t){return e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0}),s.setAlphaMode(g.a.ALPHA_COMBINE),o=0;o<u.length;o++)a(u[o]);s.setAlphaMode(g.a.ALPHA_DISABLE)}}},t.prototype._updateMeshScreenCoordinates=function(e){var t,i=e.getTransformMatrix();t=this.useCustomMeshPosition?this.customMeshPosition:this.attachedNode?this.attachedNode.position:this.mesh.parent?this.mesh.getAbsolutePosition():this.mesh.position;var n=a.e.Project(t,a.a.Identity(),i,this._viewPort);this._screenCoordinates.x=n.x/this._viewPort.width,this._screenCoordinates.y=n.y/this._viewPort.height,this.invert&&(this._screenCoordinates.y=1-this._screenCoordinates.y)},t.CreateDefaultMesh=function(e,t){var i=Ae.a.CreatePlane(e,1,t);i.billboardMode=Ke.a.BILLBOARDMODE_ALL;var n=new Ki.a(e+"Material",t);return n.emissiveColor=new s.a(1,1,1),i.material=n,i},Object(h.c)([Object(N.o)()],t.prototype,"customMeshPosition",void 0),Object(h.c)([Object(N.c)()],t.prototype,"useCustomMeshPosition",void 0),Object(h.c)([Object(N.c)()],t.prototype,"invert",void 0),Object(h.c)([Object(N.k)()],t.prototype,"mesh",void 0),Object(h.c)([Object(N.c)()],t.prototype,"excludedMeshes",void 0),Object(h.c)([Object(N.c)()],t.prototype,"exposure",void 0),Object(h.c)([Object(N.c)()],t.prototype,"decay",void 0),Object(h.c)([Object(N.c)()],t.prototype,"weight",void 0),Object(h.c)([Object(N.c)()],t.prototype,"density",void 0),t}(ui);i(148),i(149);Object.defineProperty(K.a.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),K.a.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new Id(this)),this._boundingBoxRenderer},Object.defineProperty(Ke.a.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});var Id=function(){function e(e){this.name=Fe.a.NAME_BOUNDINGBOXRENDERER,this.frontColor=new s.a(1,1,1),this.backColor=new s.a(.1,.1,.1),this.showBackLines=!0,this.renderList=new oi.a(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this)}return e.prototype.register=function(){this.scene._beforeEvaluateActiveMeshStage.registerStep(Fe.a.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._activeMeshStage.registerStep(Fe.a.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER,this,this._activeMesh),this.scene._evaluateSubMeshStage.registerStep(Fe.a.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(Fe.a.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)},e.prototype._evaluateSubMesh=function(e,t){if(e.showSubMeshesBoundingBox){var i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}},e.prototype._activeMesh=function(e,t){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){var i=e.getBoundingInfo();i.boundingBox._tag=t.renderingGroupId,this.renderList.push(i.boundingBox)}},e.prototype._prepareRessources=function(){if(!this._colorShader){this._colorShader=new ks.a("colorShader",this.scene,"color",{attributes:[en.b.PositionKind],uniforms:["world","viewProjection","color"]}),this._colorShader.reservedDataStore={hidden:!0};var e=this.scene.getEngine(),t=$i.a.CreateBox({size:1});this._vertexBuffers[en.b.PositionKind]=new en.b(e,t.positions,en.b.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices}},e.prototype._createIndexBuffer=function(){var e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])},e.prototype.rebuild=function(){var e=this._vertexBuffers[en.b.PositionKind];e&&e._rebuild(),this._createIndexBuffer()},e.prototype.reset=function(){this.renderList.reset()},e.prototype.render=function(e){if(0!==this.renderList.length&&(this._prepareRessources(),this._colorShader.isReady())){var t=this.scene.getEngine();t.setDepthWrite(!1),this._colorShader._preBind();for(var i=0;i<this.renderList.length;i++){var n=this.renderList.data[i];if(n._tag===e){var r=n.minimum,o=n.maximum.subtract(r),s=r.add(o.scale(.5)),c=a.a.Scaling(o.x,o.y,o.z).multiply(a.a.Translation(s.x,s.y,s.z)).multiply(n.getWorldMatrix());t.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),this.showBackLines&&(t.setDepthFunctionToGreaterOrEqual(),this.scene.resetCachedMaterial(),this._colorShader.setColor4("color",this.backColor.toColor4()),this._colorShader.bind(c),t.drawElementsType(Ca.a.LineListDrawMode,0,24)),t.setDepthFunctionToLess(),this.scene.resetCachedMaterial(),this._colorShader.setColor4("color",this.frontColor.toColor4()),this._colorShader.bind(c),t.drawElementsType(Ca.a.LineListDrawMode,0,24)}}this._colorShader.unbind(),t.setDepthFunctionToLessOrEqual(),t.setDepthWrite(!0)}},e.prototype.renderOcclusionBoundingBox=function(e){if(this._prepareRessources(),this._colorShader.isReady()&&e._boundingInfo){var t=this.scene.getEngine();this._fillIndexBuffer||(this._fillIndexBuffer=t.createIndexBuffer(this._fillIndexData)),t.setDepthWrite(!1),t.setColorWrite(!1),this._colorShader._preBind();var i=e._boundingInfo.boundingBox,n=i.minimum,r=i.maximum.subtract(n),o=n.add(r.scale(.5)),s=a.a.Scaling(r.x,r.y,r.z).multiply(a.a.Translation(o.x,o.y,o.z)).multiply(i.getWorldMatrix());t.bindBuffers(this._vertexBuffers,this._fillIndexBuffer,this._colorShader.getEffect()),t.setDepthFunctionToLess(),this.scene.resetCachedMaterial(),this._colorShader.bind(s),t.drawElementsType(Ca.a.TriangleFillMode,0,36),this._colorShader.unbind(),t.setDepthFunctionToLessOrEqual(),t.setDepthWrite(!0),t.setColorWrite(!0)}},e.prototype.dispose=function(){if(this._colorShader){this.renderList.dispose(),this._colorShader.dispose();var e=this._vertexBuffers[en.b.PositionKind];e&&(e.dispose(),this._vertexBuffers[en.b.PositionKind]=null),this.scene.getEngine()._releaseBuffer(this._indexBuffer),this._fillIndexBuffer&&(this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer),this._fillIndexBuffer=null)}},e}();K.a.prototype.enableDepthRenderer=function(e,t){if(void 0===t&&(t=!1),!(e=e||this.activeCamera))throw"No camera available to enable depth renderer";if(this._depthRenderer||(this._depthRenderer={}),!this._depthRenderer[e.id]){var i=0;i=this.getEngine().getCaps().textureHalfFloatRender?g.a.TEXTURETYPE_HALF_FLOAT:this.getEngine().getCaps().textureFloatRender?g.a.TEXTURETYPE_FLOAT:g.a.TEXTURETYPE_UNSIGNED_BYTE,this._depthRenderer[e.id]=new $a(this,i,e,t)}return this._depthRenderer[e.id]},K.a.prototype.disableDepthRenderer=function(e){(e=e||this.activeCamera)&&this._depthRenderer&&this._depthRenderer[e.id]&&(this._depthRenderer[e.id].dispose(),delete this._depthRenderer[e.id])};var Dd=function(){function e(e){this.name=Fe.a.NAME_DEPTHRENDERER,this.scene=e}return e.prototype.register=function(){this.scene._gatherRenderTargetsStage.registerStep(Fe.a.STEP_GATHERRENDERTARGETS_DEPTHRENDERER,this,this._gatherRenderTargets),this.scene._gatherActiveCameraRenderTargetsStage.registerStep(Fe.a.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER,this,this._gatherActiveCameraRenderTargets)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){for(var e in this.scene._depthRenderer)this.scene._depthRenderer[e].dispose()},e.prototype._gatherRenderTargets=function(e){if(this.scene._depthRenderer)for(var t in this.scene._depthRenderer){var i=this.scene._depthRenderer[t];i.enabled&&!i.useOnlyInActiveCamera&&e.push(i.getDepthMap())}},e.prototype._gatherActiveCameraRenderTargets=function(e){if(this.scene._depthRenderer)for(var t in this.scene._depthRenderer){var i=this.scene._depthRenderer[t];i.enabled&&i.useOnlyInActiveCamera&&this.scene.activeCamera.id===t&&e.push(i.getDepthMap())}},e}();$a._SceneComponentInitialization=function(e){var t=e._getComponent(Fe.a.NAME_DEPTHRENDERER);t||(t=new Dd(e),e._addComponent(t))};var wd="uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}";ai.a.ShadersStore.linePixelShader=wd;var Ld="\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}";ai.a.ShadersStore.lineVertexShader=Ld;Ke.a.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},Ke.a.prototype.enableEdgesRendering=function(e,t){return void 0===e&&(e=.95),void 0===t&&(t=!1),this.disableEdgesRendering(),this._edgesRenderer=new Fd(this,e,t),this},Object.defineProperty(Ke.a.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),ql.b.prototype.enableEdgesRendering=function(e,t){return void 0===e&&(e=.95),void 0===t&&(t=!1),this.disableEdgesRendering(),this._edgesRenderer=new Bd(this,e,t),this},ql.a.prototype.enableEdgesRendering=function(e,t){return void 0===e&&(e=.95),void 0===t&&(t=!1),ql.b.prototype.enableEdgesRendering.apply(this,arguments),this};var Nd=function(){this.edges=new Array,this.edgesConnectedCount=0},Fd=function(){function e(e,t,i,n){var r=this;void 0===t&&(t=.95),void 0===i&&(i=!1),void 0===n&&(n=!0),this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this._source=e,this._checkVerticesInsteadOfIndices=i,this._epsilon=t,this._prepareRessources(),n&&this._generateEdgesLines(),this._meshRebuildObserver=this._source.onRebuildObservable.add(function(){r._rebuild()}),this._meshDisposeObserver=this._source.onDisposeObservable.add(function(){r.dispose()})}return e.prototype._prepareRessources=function(){this._lineShader||(this._lineShader=new ks.a("lineShader",this._source.getScene(),"line",{attributes:["position","normal"],uniforms:["worldViewProjection","color","width","aspectRatio"]}),this._lineShader.disableDepthWrite=!0,this._lineShader.backFaceCulling=!1)},e.prototype._rebuild=function(){var e=this._buffers[en.b.PositionKind];e&&e._rebuild(),(e=this._buffers[en.b.NormalKind])&&e._rebuild();var t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)},e.prototype.dispose=function(){this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);var e=this._buffers[en.b.PositionKind];e&&(e.dispose(),this._buffers[en.b.PositionKind]=null),(e=this._buffers[en.b.NormalKind])&&(e.dispose(),this._buffers[en.b.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose()},e.prototype._processEdgeForAdjacencies=function(e,t,i,n,r){return e===i&&t===n||e===n&&t===i?0:e===n&&t===r||e===r&&t===n?1:e===r&&t===i||e===i&&t===r?2:-1},e.prototype._processEdgeForAdjacenciesWithVertices=function(e,t,i,n,r){return e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(n)||e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(i)?0:e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(r)||e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(n)?1:e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(i)||e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(r)?2:-1},e.prototype._checkEdge=function(e,t,i,n,r){var o;void 0===t?o=!0:o=a.e.Dot(i[e],i[t])<this._epsilon;o&&this.createLine(n,r,this._linesPositions.length/3)},e.prototype.createLine=function(e,t,i){this._linesPositions.push(e.x,e.y,e.z,e.x,e.y,e.z,t.x,t.y,t.z,t.x,t.y,t.z),this._linesNormals.push(t.x,t.y,t.z,-1,t.x,t.y,t.z,1,e.x,e.y,e.z,-1,e.x,e.y,e.z,1),this._linesIndices.push(i,i+1,i+2,i,i+2,i+3)},e.prototype._generateEdgesLines=function(){var e=this._source.getVerticesData(en.b.PositionKind),t=this._source.getIndices();if(t&&e){var i,n,r=new Array,o=new Array;for(i=0;i<t.length;i+=3){n=new Nd;var s=t[i],c=t[i+1],l=t[i+2];n.p0=new a.e(e[3*s],e[3*s+1],e[3*s+2]),n.p1=new a.e(e[3*c],e[3*c+1],e[3*c+2]),n.p2=new a.e(e[3*l],e[3*l+1],e[3*l+2]);var u=a.e.Cross(n.p1.subtract(n.p0),n.p2.subtract(n.p1));u.normalize(),o.push(u),r.push(n)}for(i=0;i<r.length;i++){n=r[i];for(var h=i+1;h<r.length;h++){var d=r[h];if(3===n.edgesConnectedCount)break;if(3!==d.edgesConnectedCount)for(var f=t[3*h],p=t[3*h+1],_=t[3*h+2],m=0;m<3;m++){var g=0;if(void 0===n.edges[m]){switch(m){case 0:g=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(n.p0,n.p1,d.p0,d.p1,d.p2):this._processEdgeForAdjacencies(t[3*i],t[3*i+1],f,p,_);break;case 1:g=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(n.p1,n.p2,d.p0,d.p1,d.p2):this._processEdgeForAdjacencies(t[3*i+1],t[3*i+2],f,p,_);break;case 2:g=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(n.p2,n.p0,d.p0,d.p1,d.p2):this._processEdgeForAdjacencies(t[3*i+2],t[3*i],f,p,_)}if(-1!==g&&(n.edges[m]=h,d.edges[g]=i,n.edgesConnectedCount++,d.edgesConnectedCount++,3===n.edgesConnectedCount))break}}}}for(i=0;i<r.length;i++){var v=r[i];this._checkEdge(i,v.edges[0],o,v.p0,v.p1),this._checkEdge(i,v.edges[1],o,v.p1,v.p2),this._checkEdge(i,v.edges[2],o,v.p2,v.p0)}var y=this._source.getScene().getEngine();this._buffers[en.b.PositionKind]=new en.b(y,this._linesPositions,en.b.PositionKind,!1),this._buffers[en.b.NormalKind]=new en.b(y,this._linesNormals,en.b.NormalKind,!1,!1,4),this._ib=y.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}},e.prototype.isReady=function(){return this._lineShader.isReady()},e.prototype.render=function(){var e=this._source.getScene();if(this.isReady()&&e.activeCamera){var t=e.getEngine();this._lineShader._preBind(),1!==this._source.edgesColor.a?t.setAlphaMode(g.a.ALPHA_COMBINE):t.setAlphaMode(g.a.ALPHA_DISABLE),t.bindBuffers(this._buffers,this._ib,this._lineShader.getEffect()),e.resetCachedMaterial(),this._lineShader.setColor4("color",this._source.edgesColor),e.activeCamera.mode===Qe.a.ORTHOGRAPHIC_CAMERA?this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForOrthographic):this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForPerspective),this._lineShader.setFloat("aspectRatio",t.getAspectRatio(e.activeCamera)),this._lineShader.bind(this._source.getWorldMatrix()),t.drawElementsType(Ca.a.TriangleFillMode,0,this._indicesCount),this._lineShader.unbind()}},e}(),Bd=function(e){function t(t,i,n){void 0===i&&(i=.95),void 0===n&&(n=!1);var r=e.call(this,t,i,n,!1)||this;return r._generateEdgesLines(),r}return Object(h.d)(t,e),t.prototype._generateEdgesLines=function(){var e=this._source.getVerticesData(en.b.PositionKind),t=this._source.getIndices();if(t&&e){for(var i=a.c.Vector3[0],n=a.c.Vector3[1],r=t.length-1,o=0,s=0;o<r;o+=2,s+=4)a.e.FromArrayToRef(e,3*t[o],i),a.e.FromArrayToRef(e,3*t[o+1],n),this.createLine(i,n,s);var c=this._source.getScene().getEngine();this._buffers[en.b.PositionKind]=new en.b(c,this._linesPositions,en.b.PositionKind,!1),this._buffers[en.b.NormalKind]=new en.b(c,this._linesNormals,en.b.NormalKind,!1,!1,4),this._ib=c.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}},t}(Fd),Ud="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}";ai.a.ShadersStore.outlinePixelShader=Ud;var Vd="\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 positionUpdated=position;\nvec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n";ai.a.ShadersStore.outlineVertexShader=Vd;K.a.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new kd(this)),this._outlineRenderer},Object.defineProperty(Ae.a.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(Ae.a.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});var kd=function(){function e(e){this.name=Fe.a.NAME_OUTLINERENDERER,this.zOffset=1,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this)}return e.prototype.register=function(){this.scene._beforeRenderingMeshStage.registerStep(Fe.a.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(Fe.a.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){},e.prototype.render=function(e,t,i){var n=this;void 0===i&&(i=!1);var r=this.scene,o=r.getEngine(),a=o.getCaps().instancedArrays&&null!==t.visibleInstances[e._id]&&void 0!==t.visibleInstances[e._id];if(this.isReady(e,a)){var s=e.getRenderingMesh(),c=e.getMaterial();if(c&&r.activeCamera){if(o.enableEffect(this._effect),c.useLogarithmicDepth&&this._effect.setFloat("logarithmicDepthConstant",2/(Math.log(r.activeCamera.maxZ+1)/Math.LN2)),this._effect.setFloat("offset",i?0:s.outlineWidth),this._effect.setColor4("color",i?s.overlayColor:s.outlineColor,i?s.overlayAlpha:c.alpha),this._effect.setMatrix("viewProjection",r.getTransformMatrix()),s.useBones&&s.computeBonesUsingShaders&&s.skeleton&&this._effect.setMatrices("mBones",s.skeleton.getTransformMatrices(s)),io.a.BindMorphTargetParameters(s,this._effect),s._bind(e,this._effect,c.fillMode),c&&c.needAlphaTesting()){var l=c.getAlphaTestTexture();l&&(this._effect.setTexture("diffuseSampler",l),this._effect.setMatrix("diffuseMatrix",l.getTextureMatrix()))}o.setZOffset(-this.zOffset),s._processRendering(e,this._effect,c.fillMode,t,a,function(e,t){n._effect.setMatrix("world",t)}),o.setZOffset(0)}}},e.prototype.isReady=function(e,t){var i=[],n=[en.b.PositionKind,en.b.NormalKind],r=e.getMesh(),o=e.getMaterial();o&&(o.needAlphaTesting()&&(i.push("#define ALPHATEST"),r.isVerticesDataPresent(en.b.UVKind)&&(n.push(en.b.UVKind),i.push("#define UV1")),r.isVerticesDataPresent(en.b.UV2Kind)&&(n.push(en.b.UV2Kind),i.push("#define UV2"))),o.useLogarithmicDepth&&i.push("#define LOGARITHMICDEPTH")),r.useBones&&r.computeBonesUsingShaders?(n.push(en.b.MatricesIndicesKind),n.push(en.b.MatricesWeightsKind),r.numBoneInfluencers>4&&(n.push(en.b.MatricesIndicesExtraKind),n.push(en.b.MatricesWeightsExtraKind)),i.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),i.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):i.push("#define NUM_BONE_INFLUENCERS 0");var a=r.morphTargetManager,s=0;a&&a.numInfluencers>0&&(s=a.numInfluencers,i.push("#define MORPHTARGETS"),i.push("#define NUM_MORPH_INFLUENCERS "+s),io.a.PrepareAttributesForMorphTargetsInfluencers(n,r,s)),t&&(i.push("#define INSTANCES"),io.a.PushAttributesForInstances(n));var c=i.join("\n");return this._cachedDefines!==c&&(this._cachedDefines=c,this._effect=this.scene.getEngine().createEffect("outline",n,["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences"],["diffuseSampler"],c,void 0,void 0,void 0,{maxSimultaneousMorphTargets:s})),this._effect.isReady()},e.prototype._beforeRenderingMesh=function(t,i,n){if(this._savedDepthWrite=this._engine.getDepthWrite(),t.renderOutline){var r=i.getMaterial();r&&r.needAlphaBlending()&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(g.a.REPLACE),this._engine.setStencilFunction(g.a.ALWAYS),this._engine.setStencilMask(e._StencilReference),this._engine.setStencilFunctionReference(e._StencilReference),this.render(i,n,!0),this._engine.setColorWrite(!0),this._engine.setStencilFunction(g.a.NOTEQUAL)),this._engine.setDepthWrite(!1),this.render(i,n),this._engine.setDepthWrite(this._savedDepthWrite),r&&r.needAlphaBlending()&&this._engine.restoreStencilState()}},e.prototype._afterRenderingMesh=function(e,t,i){if(e.renderOverlay){var n=this._engine.getAlphaMode(),r=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(g.a.ALPHA_COMBINE),this.render(t,i,!0),this._engine.setAlphaMode(n),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=r}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i),this._engine.setColorWrite(!0))},e._StencilReference=4,e}(),zd=i(134),Gd=function(){function e(e,t){this.name=e,this.color=new s.b(1,1,1,1),this.width=1,this.height=1,this.angle=0,this.invertU=0,this.invertV=0,this.animations=new Array,this.isPickable=!1,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this.isVisible=!0,this._manager=t,this._manager.sprites.push(this),this.position=a.e.Zero()}return Object.defineProperty(e.prototype,"size",{get:function(){return this.width},set:function(e){this.width=e,this.height=e},enumerable:!0,configurable:!0}),e.prototype.playAnimation=function(e,t,i,n,r){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=n,this._animationStarted=!0,e<t?this._direction=1:(this._direction=-1,this._toIndex=e,this._fromIndex=t),this.cellIndex=e,this._time=0,this._onAnimationEnd=r},e.prototype.stopAnimation=function(){this._animationStarted=!1},e.prototype._animate=function(e){this._animationStarted&&(this._time+=e,this._time>this._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex<this._fromIndex)&&(this._loopAnimation?this.cellIndex=this._direction>0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()))))},e.prototype.dispose=function(){for(var e=0;e<this._manager.sprites.length;e++)this._manager.sprites[e]==this&&this._manager.sprites.splice(e,1)},e}();K.a.prototype._internalPickSprites=function(e,t,i,n){if(!bn.a)return null;var r=null;if(!n){if(!this.activeCamera)return null;n=this.activeCamera}if(this.spriteManagers.length>0)for(var o=0;o<this.spriteManagers.length;o++){var a=this.spriteManagers[o];if(a.isPickable){var s=a.intersects(e,n,t,i);if(s&&s.hit&&(i||null==r||!(s.distance>=r.distance))&&(r=s,i))break}}return r||new bn.a},K.a.prototype._internalMultiPickSprites=function(e,t,i){if(!bn.a)return null;var n=new Array;if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers.length>0)for(var r=0;r<this.spriteManagers.length;r++){var o=this.spriteManagers[r];if(o.isPickable){var a=o.multiIntersects(e,i,t);null!==a&&(n=n.concat(a))}}return n},K.a.prototype.pickSprite=function(e,t,i,n,r){return this.createPickingRayInCameraSpaceToRef(e,t,this._tempSpritePickingRay,r),this._internalPickSprites(this._tempSpritePickingRay,i,n,r)},K.a.prototype.pickSpriteWithRay=function(e,t,i,n){if(!this._tempSpritePickingRay)return null;if(!n){if(!this.activeCamera)return null;n=this.activeCamera}return Ht.a.TransformToRef(e,n.getViewMatrix(),this._tempSpritePickingRay),this._internalPickSprites(this._tempSpritePickingRay,t,i,n)},K.a.prototype.multiPickSprite=function(e,t,i,n){return this.createPickingRayInCameraSpaceToRef(e,t,this._tempSpritePickingRay,n),this._internalMultiPickSprites(this._tempSpritePickingRay,i,n)},K.a.prototype.multiPickSpriteWithRay=function(e,t,i){if(!this._tempSpritePickingRay)return null;if(!i){if(!this.activeCamera)return null;i=this.activeCamera}return Ht.a.TransformToRef(e,i.getViewMatrix(),this._tempSpritePickingRay),this._internalMultiPickSprites(this._tempSpritePickingRay,t,i)},K.a.prototype.setPointerOverSprite=function(e){this._pointerOverSprite!==e&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(g.a.ACTION_OnPointerOutTrigger,u.a.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=e,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(g.a.ACTION_OnPointerOverTrigger,u.a.CreateNewFromSprite(this._pointerOverSprite,this)))},K.a.prototype.getPointerOverSprite=function(){return this._pointerOverSprite};var jd=function(){function e(e){this.name=Fe.a.NAME_SPRITE,this.scene=e,this.scene.spriteManagers=new Array,this.scene._tempSpritePickingRay=Ht.a?Ht.a.Zero():null,this.scene.onBeforeSpritesRenderingObservable=new o.c,this.scene.onAfterSpritesRenderingObservable=new o.c,this._spritePredicate=function(e){return!!e.actionManager&&(e.isPickable&&e.actionManager.hasPointerTriggers)}}return e.prototype.register=function(){this.scene._pointerMoveStage.registerStep(Fe.a.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(Fe.a.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(Fe.a.STEP_POINTERUP_SPRITE,this,this._pointerUp)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();for(var e=this.scene.spriteManagers;e.length;)e[0].dispose()},e.prototype._pickSpriteButKeepRay=function(e,t,i,n,r){var o=this.scene.pickSprite(t,i,this._spritePredicate,n,r);return o&&(o.ray=e?e.ray:null),o},e.prototype._pointerMove=function(e,t,i,n,r){var o=this.scene;return n?o.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,o.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(o.setPointerOverSprite(i.pickedSprite),o.doNotHandleCursors||(o._pointerOverSprite&&o._pointerOverSprite.actionManager&&o._pointerOverSprite.actionManager.hoverCursor?r.style.cursor=o._pointerOverSprite.actionManager.hoverCursor:r.style.cursor=o.hoverCursor)):o.setPointerOverSprite(null),i},e.prototype._pointerDown=function(e,t,i,n){var r=this.scene;if(r._pickedDownSprite=null,r.spriteManagers.length>0&&(i=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(r._pickedDownSprite=i.pickedSprite,n.button){case 0:i.pickedSprite.actionManager.processTrigger(g.a.ACTION_OnLeftPickTrigger,u.a.CreateNewFromSprite(i.pickedSprite,r,n));break;case 1:i.pickedSprite.actionManager.processTrigger(g.a.ACTION_OnCenterPickTrigger,u.a.CreateNewFromSprite(i.pickedSprite,r,n));break;case 2:i.pickedSprite.actionManager.processTrigger(g.a.ACTION_OnRightPickTrigger,u.a.CreateNewFromSprite(i.pickedSprite,r,n))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(g.a.ACTION_OnPickDownTrigger,u.a.CreateNewFromSprite(i.pickedSprite,r,n))}return i},e.prototype._pointerUp=function(e,t,i,n){var r=this.scene;if(r.spriteManagers.length>0){var o=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0);o&&(o.hit&&o.pickedSprite&&o.pickedSprite.actionManager&&(o.pickedSprite.actionManager.processTrigger(g.a.ACTION_OnPickUpTrigger,u.a.CreateNewFromSprite(o.pickedSprite,r,n)),o.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||o.pickedSprite.actionManager.processTrigger(g.a.ACTION_OnPickTrigger,u.a.CreateNewFromSprite(o.pickedSprite,r,n)))),r._pickedDownSprite&&r._pickedDownSprite.actionManager&&r._pickedDownSprite!==o.pickedSprite&&r._pickedDownSprite.actionManager.processTrigger(g.a.ACTION_OnPickOutTrigger,u.a.CreateNewFromSprite(r._pickedDownSprite,r,n)))}return i},e}(),Wd="uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest)\n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}";ai.a.ShadersStore.spritesPixelShader=Wd;var Xd="\nattribute vec4 position;\nattribute vec4 options;\nattribute vec2 inverts;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) {\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz;\nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0);\n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));\nvec2 uvPlace=cellInfo.xy;\nvec2 uvSize=cellInfo.zw;\nvUV.x=uvPlace.x+uvSize.x*uvOffset.x;\nvUV.y=uvPlace.y+uvSize.y*uvOffset.y;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}";ai.a.ShadersStore.spritesVertexShader=Xd;var Hd=function(){function e(e,t,i,n,r,a,s,c,l){if(void 0===a&&(a=.01),void 0===s&&(s=et.a.TRILINEAR_SAMPLINGMODE),void 0===c&&(c=!1),void 0===l&&(l=null),this.name=e,this.sprites=new Array,this.renderingGroupId=0,this.layerMask=268435455,this.fogEnabled=!0,this.isPickable=!1,this._packedAndReady=!1,this.onDisposeObservable=new o.c,this._vertexBuffers={},this._blendMode=g.a.ALPHA_COMBINE,this.disableDepthWrite=!1,r._getComponent(Fe.a.NAME_SPRITE)||r._addComponent(new jd(r)),this._capacity=i,this._fromPacked=c,this._spriteTexture=new et.a(t,r,!0,!1,s),this._spriteTexture.wrapU=et.a.CLAMP_ADDRESSMODE,this._spriteTexture.wrapV=et.a.CLAMP_ADDRESSMODE,n.width&&n.height)this.cellWidth=n.width,this.cellHeight=n.height;else{if(void 0===n)return;this.cellWidth=n,this.cellHeight=n}this._epsilon=a,this._scene=r,this._scene.spriteManagers.push(this);for(var u=[],h=0,d=0;d<i;d++)u.push(h),u.push(h+1),u.push(h+2),u.push(h),u.push(h+2),u.push(h+3),h+=4;this._indexBuffer=r.getEngine().createIndexBuffer(u),this._vertexData=new Float32Array(18*i*4),this._buffer=new en.a(r.getEngine(),this._vertexData,!0,18);var f=this._buffer.createVertexBuffer(en.b.PositionKind,0,4),p=this._buffer.createVertexBuffer("options",4,4),_=this._buffer.createVertexBuffer("inverts",8,2),m=this._buffer.createVertexBuffer("cellInfo",10,4),v=this._buffer.createVertexBuffer(en.b.ColorKind,14,4);this._vertexBuffers[en.b.PositionKind]=f,this._vertexBuffers.options=p,this._vertexBuffers.inverts=_,this._vertexBuffers.cellInfo=m,this._vertexBuffers[en.b.ColorKind]=v,this._effectBase=this._scene.getEngine().createEffect("sprites",[en.b.PositionKind,"options","inverts","cellInfo",en.b.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],""),this._effectFog=this._scene.getEngine().createEffect("sprites",[en.b.PositionKind,"options","inverts","cellInfo",en.b.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],"#define FOG"),this._fromPacked&&this._makePacked(t,l)}return Object.defineProperty(e.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"texture",{get:function(){return this._spriteTexture},set:function(e){this._spriteTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"blendMode",{get:function(){return this._blendMode},set:function(e){this._blendMode=e},enumerable:!0,configurable:!0}),e.prototype._makePacked=function(e,t){var i=this;if(null!==t)try{var n=void 0;if((n="string"==typeof t?JSON.parse(t):t).frames.length){for(var r={},o=0;o<n.frames.length;o++){var a=n.frames[o];if("string"!=typeof Object.keys(a)[0])throw new Error("Invalid JSON Format.  Check the frame values and make sure the name is the first parameter.");r[a[Object.keys(a)[0]]]=a}n.frames=r}var s=Reflect.ownKeys(n.frames);this._spriteMap=s,this._packedAndReady=!0,this._cellData=n.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON from string. Spritesheet managed with constant cell size.")}else{var c=/\./g,l=void 0;do{l=c.lastIndex,c.test(e)}while(c.lastIndex>0);var u=e.substring(0,l-1)+".json",h=new XMLHttpRequest;h.open("GET",u,!0),h.onerror=function(){m.a.Error("JSON ERROR: Unable to load JSON file."),i._fromPacked=!1,i._packedAndReady=!1},h.onload=function(){try{var e=JSON.parse(h.response),t=Reflect.ownKeys(e.frames);i._spriteMap=t,i._packedAndReady=!0,i._cellData=e.frames}catch(e){throw i._fromPacked=!1,i._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}},h.send()}},e.prototype._appendSpriteVertex=function(e,t,i,n,r){var o=18*e;if(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===n?n=this._epsilon:1===n&&(n=1-this._epsilon),this._vertexData[o]=t.position.x,this._vertexData[o+1]=t.position.y,this._vertexData[o+2]=t.position.z,this._vertexData[o+3]=t.angle,this._vertexData[o+4]=t.width,this._vertexData[o+5]=t.height,this._vertexData[o+6]=i,this._vertexData[o+7]=n,this._vertexData[o+8]=t.invertU?1:0,this._vertexData[o+9]=t.invertV?1:0,this._packedAndReady){t.cellRef||(t.cellIndex=0);var a=t.cellIndex;"number"==typeof a&&isFinite(a)&&Math.floor(a)===a&&(t.cellRef=this._spriteMap[t.cellIndex]),this._vertexData[o+10]=this._cellData[t.cellRef].frame.x/r.width,this._vertexData[o+11]=this._cellData[t.cellRef].frame.y/r.height,this._vertexData[o+12]=this._cellData[t.cellRef].frame.w/r.width,this._vertexData[o+13]=this._cellData[t.cellRef].frame.h/r.height}else{t.cellIndex||(t.cellIndex=0);var s=r.width/this.cellWidth,c=t.cellIndex/s>>0;this._vertexData[o+10]=(t.cellIndex-c*s)*this.cellWidth/r.width,this._vertexData[o+11]=c*this.cellHeight/r.height,this._vertexData[o+12]=this.cellWidth/r.width,this._vertexData[o+13]=this.cellHeight/r.height}this._vertexData[o+14]=t.color.r,this._vertexData[o+15]=t.color.g,this._vertexData[o+16]=t.color.b,this._vertexData[o+17]=t.color.a},e.prototype.intersects=function(e,t,i,n){for(var r=Math.min(this._capacity,this.sprites.length),o=a.e.Zero(),s=a.e.Zero(),c=Number.MAX_VALUE,l=null,u=a.c.Vector3[0],h=a.c.Vector3[1],d=t.getViewMatrix(),f=0;f<r;f++){var p=this.sprites[f];if(p){if(i){if(!i(p))continue}else if(!p.isPickable)continue;if(a.e.TransformCoordinatesToRef(p.position,d,h),o.copyFromFloats(h.x-p.width/2,h.y-p.height/2,h.z),s.copyFromFloats(h.x+p.width/2,h.y+p.height/2,h.z),e.intersectsBoxMinMax(o,s)){var _=a.e.Distance(h,e.origin);if(c>_&&(c=_,l=p,n))break}}}if(l){var m=new bn.a;d.invertToRef(a.c.Matrix[0]),m.hit=!0,m.pickedSprite=l,m.distance=c;var g=a.c.Vector3[2];return g.copyFrom(e.direction),g.normalize(),g.scaleInPlace(c),e.origin.addToRef(g,u),m.pickedPoint=a.e.TransformCoordinates(u,a.c.Matrix[0]),m}return null},e.prototype.multiIntersects=function(e,t,i){for(var n,r=Math.min(this._capacity,this.sprites.length),o=a.e.Zero(),s=a.e.Zero(),c=[],l=a.c.Vector3[0].copyFromFloats(0,0,0),u=a.c.Vector3[1].copyFromFloats(0,0,0),h=t.getViewMatrix(),d=0;d<r;d++){var f=this.sprites[d];if(f){if(i){if(!i(f))continue}else if(!f.isPickable)continue;if(a.e.TransformCoordinatesToRef(f.position,h,u),o.copyFromFloats(u.x-f.width/2,u.y-f.height/2,u.z),s.copyFromFloats(u.x+f.width/2,u.y+f.height/2,u.z),e.intersectsBoxMinMax(o,s)){n=a.e.Distance(u,e.origin);var p=new bn.a;c.push(p),h.invertToRef(a.c.Matrix[0]),p.hit=!0,p.pickedSprite=f,p.distance=n;var _=a.c.Vector3[2];_.copyFrom(e.direction),_.normalize(),_.scaleInPlace(n),e.origin.addToRef(_,l),p.pickedPoint=a.e.TransformCoordinates(l,a.c.Matrix[0])}}}return c},e.prototype.render=function(){if(this._effectBase.isReady()&&this._effectFog.isReady()&&this._spriteTexture&&this._spriteTexture.isReady()&&this.sprites.length&&(!this._fromPacked||this._packedAndReady&&this._spriteMap&&this._cellData)){for(var e=this._scene.getEngine(),t=this._spriteTexture.getBaseSize(),i=e.getDeltaTime(),n=Math.min(this._capacity,this.sprites.length),r=0,o=!0,a=0;a<n;a++){var s=this.sprites[a];s&&s.isVisible&&(o=!1,s._animate(i),this._appendSpriteVertex(r++,s,0,0,t),this._appendSpriteVertex(r++,s,1,0,t),this._appendSpriteVertex(r++,s,1,1,t),this._appendSpriteVertex(r++,s,0,1,t))}if(!o){this._buffer.update(this._vertexData);var c=this._effectBase;this._scene.fogEnabled&&this._scene.fogMode!==K.a.FOGMODE_NONE&&this.fogEnabled&&(c=this._effectFog),e.enableEffect(c);var l=this._scene.getViewMatrix();c.setTexture("diffuseSampler",this._spriteTexture),c.setMatrix("view",l),c.setMatrix("projection",this._scene.getProjectionMatrix()),this._scene.fogEnabled&&this._scene.fogMode!==K.a.FOGMODE_NONE&&this.fogEnabled&&(c.setFloat4("vFogInfos",this._scene.fogMode,this._scene.fogStart,this._scene.fogEnd,this._scene.fogDensity),c.setColor3("vFogColor",this._scene.fogColor)),e.bindBuffers(this._vertexBuffers,this._indexBuffer,c),e.setDepthFunctionToLessOrEqual(),this.disableDepthWrite||(c.setBool("alphaTest",!0),e.setColorWrite(!1),e.drawElementsType(Ca.a.TriangleFillMode,0,r/4*6),e.setColorWrite(!0),c.setBool("alphaTest",!1)),e.setAlphaMode(this._blendMode),e.drawElementsType(Ca.a.TriangleFillMode,0,r/4*6),e.setAlphaMode(g.a.ALPHA_DISABLE)}}},e.prototype.dispose=function(){this._buffer&&(this._buffer.dispose(),this._buffer=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._spriteTexture&&(this._spriteTexture.dispose(),this._spriteTexture=null);var e=this._scene.spriteManagers.indexOf(this);this._scene.spriteManagers.splice(e,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},e}(),Yd="precision highp float;\nvarying vec3 vPosition;\nvarying vec2 vUV;\nvarying vec2 tUV;\nuniform float time;\nuniform float spriteCount;\nuniform sampler2D spriteSheet;\nuniform vec2 spriteMapSize;\nuniform vec2 outputSize;\nuniform vec2 stageSize;\nuniform sampler2D frameMap;\nuniform sampler2D tileMaps[LAYERS];\nuniform sampler2D animationMap;\nuniform vec3 colorMul;\nfloat mt;\nconst float fdStep=1./4.;\nconst float aFrameSteps=1./MAX_ANIMATION_FRAMES;\nmat4 getFrameData(float frameID){\nfloat fX=frameID/spriteCount;\nreturn mat4(\ntexture2D(frameMap,vec2(fX,0.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*1.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*2.),0.),\nvec4(0.)\n);\n}\nvoid main(){\nvec4 color=vec4(0.);\nvec2 tileUV=fract(tUV);\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\nvec2 tileID=floor(tUV);\nvec2 sheetUnits=1./spriteMapSize;\nfloat spriteUnits=1./spriteCount;\nvec2 stageUnits=1./stageSize;\nfor(int i=0; i<LAYERS; i++) {\nfloat frameID;\n#define LAYER_ID_SWITCH\nvec4 animationData=texture2D(animationMap,vec2((frameID+0.5)/spriteCount,0.),0.);\nif(animationData.y>0.) {\nmt=mod(time*animationData.z,1.0);\nfor(float f=0.; f<MAX_ANIMATION_FRAMES; f++){\nif(animationData.y>mt){\nframeID=animationData.x;\nbreak;\n}\nanimationData=texture2D(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);\n}\n}\n\nmat4 frameData=getFrameData(frameID+0.5);\nvec2 frameSize=(frameData[0].wz)/spriteMapSize;\nvec2 offset=frameData[0].xy*sheetUnits;\nvec2 ratio=frameData[2].xy/frameData[0].wz;\n\nif (frameData[2].z == 1.){\ntileUV.xy=tileUV.yx;\n}\nif (i == 0){\ncolor=texture2D(spriteSheet,tileUV*frameSize+offset);\n} else {\nvec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);\nfloat alpha=min(color.a+nc.a,1.0);\nvec3 mixed=mix(color.xyz,nc.xyz,nc.a);\ncolor=vec4(mixed,alpha);\n}\n}\ncolor.xyz*=colorMul;\ngl_FragColor=color;\n}";ai.a.ShadersStore.spriteMapPixelShader=Yd;var Kd="precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\nattribute vec2 uv;\n\nvarying vec3 vPosition;\nvarying vec2 vUV;\nvarying vec2 tUV;\nvarying vec2 stageUnits;\nvarying vec2 levelUnits;\nvarying vec2 tileID;\n\nuniform float time;\nuniform mat4 worldViewProjection;\nuniform vec2 outputSize;\nuniform vec2 stageSize;\nuniform vec2 spriteMapSize;\nuniform float stageScale;\nvoid main() {\nvec4 p=vec4( position,1. );\nvPosition=p.xyz;\nvUV=uv;\ntUV=uv*stageSize;\ngl_Position=worldViewProjection*p;\n}";ai.a.ShadersStore.spriteMapVertexShader=Kd;var Qd,qd=function(){function e(e,t,i,n,r){var o=this;this.name=e,this.sprites=[],this.atlasJSON=t,this.sprites=this.atlasJSON.frames,this.spriteSheet=i,this.options=n,n.stageSize=n.stageSize||new a.d(1,1),n.outputSize=n.outputSize||n.stageSize,n.outputPosition=n.outputPosition||a.e.Zero(),n.outputRotation=n.outputRotation||a.e.Zero(),n.layerCount=n.layerCount||1,n.maxAnimationFrames=n.maxAnimationFrames||0,n.baseTile=n.baseTile||0,n.flipU=n.flipU||!1,n.colorMultiply=n.colorMultiply||new a.e(1,1,1),this._scene=r,this._frameMap=this._createFrameBuffer(),this._tileMaps=new Array;for(var s=0;s<n.layerCount;s++)this._tileMaps.push(this._createTileBuffer(null,s));this._animationMap=this._createTileAnimationBuffer(null);var c=[];c.push("#define LAYERS "+n.layerCount),n.flipU&&c.push("#define FLIPU"),c.push("#define MAX_ANIMATION_FRAMES "+n.maxAnimationFrames+".0");var l,u=ai.a.ShadersStore.spriteMapPixelShader;if(1===this._scene.getEngine().webGLVersion){l="";for(s=0;s<n.layerCount;s++)l+="if ("+s+" == i) { frameID = texture2D(tileMaps["+s+"], (tileID + 0.5) / stageSize, 0.).x; }"}else{l="switch(i) {";for(s=0;s<n.layerCount;s++)l+="case "+s+" : frameID = texture(tileMaps["+s+"], (tileID + 0.5) / stageSize, 0.).x;",l+="break;";l+="}"}ai.a.ShadersStore["spriteMap"+this.name+"PixelShader"]=u.replace("#define LAYER_ID_SWITCH",l),this._material=new ks.a("spriteMap:"+this.name,this._scene,{vertex:"spriteMap",fragment:"spriteMap"+this.name},{defines:c,attributes:["position","normal","uv"],uniforms:["worldViewProjection","time","stageSize","outputSize","spriteMapSize","spriteCount","time","colorMul","mousePosition","curTile","flipU"],samplers:["spriteSheet","frameMap","tileMaps","animationMap"],needAlphaBlending:!0}),this._time=0,this._material.setFloat("spriteCount",this.spriteCount),this._material.setVector2("stageSize",n.stageSize),this._material.setVector2("outputSize",n.outputSize),this._material.setTexture("spriteSheet",this.spriteSheet),this._material.setVector2("spriteMapSize",new a.d(1,1)),this._material.setVector3("colorMul",n.colorMultiply);var h=0,d=function(){o.spriteSheet&&o.spriteSheet.isReady()&&o.spriteSheet._texture?o._material.setVector2("spriteMapSize",new a.d(o.spriteSheet._texture.baseWidth||1,o.spriteSheet._texture.baseHeight||1)):h<100&&setTimeout(function(){h++,d()},100)};d(),this._material.setVector3("colorMul",n.colorMultiply),this._material.setTexture("frameMap",this._frameMap),this._material.setTextureArray("tileMaps",this._tileMaps),this._material.setTexture("animationMap",this._animationMap),this._material.setFloat("time",this._time),this._output=Ae.a.CreatePlane(e+":output",1,r,!0),this._output.scaling.x=n.outputSize.x,this._output.scaling.y=n.outputSize.y;this._scene.onBeforeRenderObservable.add(function(){o._time+=o._scene.getEngine().getDeltaTime(),o._material.setFloat("time",o._time)}),this._output.material=this._material}return Object.defineProperty(e.prototype,"spriteCount",{get:function(){return this.sprites.length},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"position",{get:function(){return this._output.position},set:function(e){this._output.position=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rotation",{get:function(){return this._output.rotation},set:function(e){this._output.rotation=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"animationMap",{get:function(){return this._animationMap},set:function(e){var t=e._texture._bufferView,i=this._createTileAnimationBuffer(t);this._animationMap.dispose(),this._animationMap=i,this._material.setTexture("animationMap",this._animationMap)},enumerable:!0,configurable:!0}),e.prototype.getTileID=function(){var e=this.getMousePosition();return e.multiplyInPlace(this.options.stageSize||a.d.Zero()),e.x=Math.floor(e.x),e.y=Math.floor(e.y),e},e.prototype.getMousePosition=function(){var e=this._output,t=this._scene.pick(this._scene.pointerX,this._scene.pointerY,function(t){return t===e});if(!t||!t.hit||!t.getTextureCoordinates)return new a.d(-1,-1);var i=t.getTextureCoordinates();return i||new a.d(-1,-1)},e.prototype._createFrameBuffer=function(){for(var e=new Array,t=0;t<this.spriteCount;t++)e.push(0,0,0,0),e.push(0,0,0,0),e.push(0,0,0,0),e.push(0,0,0,0);for(t=0;t<this.spriteCount;t++){var i=this.sprites[t].frame,n=this.sprites[t].spriteSourceSize,r=this.sprites[t].sourceSize,o=this.sprites[t].rotated?1:0,a=this.sprites[t].trimmed?1:0;e[4*t]=i.x,e[4*t+1]=i.y,e[4*t+2]=i.w,e[4*t+3]=i.h,e[4*t+4*this.spriteCount]=n.x,e[4*t+1+4*this.spriteCount]=n.y,e[4*t+3+4*this.spriteCount]=n.h,e[4*t+8*this.spriteCount]=r.w,e[4*t+1+8*this.spriteCount]=r.h,e[4*t+2+8*this.spriteCount]=o,e[4*t+3+8*this.spriteCount]=a}var s=new Float32Array(e);return rt.CreateRGBATexture(s,this.spriteCount,4,this._scene,!1,!1,et.a.NEAREST_NEAREST,Oe.a.TEXTURETYPE_FLOAT)},e.prototype._createTileBuffer=function(e,t){void 0===t&&(t=0);var i=new Array,n=this.options.stageSize.y||0,r=this.options.stageSize.x||0;if(e)i=e;else{var o=this.options.baseTile;0!=t&&(o=0);for(var a=0;a<n;a++)for(var s=0;s<4*r;s+=4)i.push(o,0,0,0)}var c=new Float32Array(i);return rt.CreateRGBATexture(c,r,n,this._scene,!1,!1,et.a.NEAREST_NEAREST,Oe.a.TEXTURETYPE_FLOAT)},e.prototype.changeTiles=function(e,t,i){var n;if(void 0===e&&(e=0),void 0===i&&(i=0),null!==(n=this._tileMaps[e]._texture._bufferView)){var r=new Array;t instanceof a.d?r.push(t):r=t;for(var o=this.options.stageSize.x||0,s=0;s<r.length;s++){var c=r[s];c.x=Math.floor(c.x),c.y=Math.floor(c.y),n[4*c.x+c.y*(4*o)]=i}var l=this._createTileBuffer(n);this._tileMaps[e].dispose(),this._tileMaps[e]=l,this._material.setTextureArray("tileMap",this._tileMaps)}},e.prototype._createTileAnimationBuffer=function(e){var t,i=new Array;if(e)t=e;else{for(var n=0;n<this.spriteCount;n++){i.push(0,0,0,0);for(var r=1;r<(this.options.maxAnimationFrames||4);)i.push(0,0,0,0),r++}t=new Float32Array(i)}return rt.CreateRGBATexture(t,this.spriteCount,this.options.maxAnimationFrames||4,this._scene,!1,!1,et.a.NEAREST_NEAREST,Oe.a.TEXTURETYPE_FLOAT)},e.prototype.addAnimationToTile=function(e,t,i,n,r){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1);var o=this._animationMap._texture._bufferView,a=4*e+4*this.spriteCount*t;if(o){o[a]=i,o[a+1]=n,o[a+2]=r;var s=this._createTileAnimationBuffer(o);this._animationMap.dispose(),this._animationMap=s,this._material.setTexture("animationMap",this._animationMap)}},e.prototype.saveTileMaps=function(){for(var e="",t=0;t<this._tileMaps.length;t++)t>0&&(e+="\n\r"),e+=this._tileMaps[t]._texture._bufferView.toString();var i=document.createElement("a");i.href="data:octet/stream;charset=utf-8,"+encodeURI(e),i.target="_blank",i.download=this.name+".tilemaps",i.click(),i.remove()},e.prototype.loadTileMaps=function(e){var t=this,i=new XMLHttpRequest;i.open("GET",e);var n=this.options.layerCount||0;i.onload=function(){for(var e=i.response.split("\n\r"),r=0;r<n;r++){var o=e[r].split(",").map(Number),a=t._createTileBuffer(o);t._tileMaps[r].dispose(),t._tileMaps[r]=a}t._material.setTextureArray("tileMap",t._tileMaps)},i.send()},e.prototype.dispose=function(){this._output.dispose(),this._material.dispose(),this._animationMap.dispose(),this._tileMaps.forEach(function(e){e.dispose()}),this._frameMap.dispose()},e}(),Zd=function(e){function t(t,i,n,r,o,a,s){void 0===o&&(o=null),void 0===a&&(a=.01),void 0===s&&(s=et.a.TRILINEAR_SAMPLINGMODE);var c=e.call(this,t,i,n,64,r,a,s,!0,o)||this;return c.name=t,c}return Object(h.d)(t,e),t}(Hd),Jd=i(129),$d=i(127),ef=i(128),tf=i(125);!function(e){e[e.INIT=0]="INIT",e[e.RUNNING=1]="RUNNING",e[e.DONE=2]="DONE",e[e.ERROR=3]="ERROR"}(Qd||(Qd={}));var nf,rf=function(){function e(e){this.name=e,this._isCompleted=!1,this._taskState=Qd.INIT}return Object.defineProperty(e.prototype,"isCompleted",{get:function(){return this._isCompleted},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"taskState",{get:function(){return this._taskState},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"errorObject",{get:function(){return this._errorObject},enumerable:!0,configurable:!0}),e.prototype._setErrorObject=function(e,t){this._errorObject||(this._errorObject={message:e,exception:t})},e.prototype.run=function(e,t,i){var n=this;this._taskState=Qd.RUNNING,this.runTask(e,function(){n.onDoneCallback(t,i)},function(e,t){n.onErrorCallback(i,e,t)})},e.prototype.runTask=function(e,t,i){throw new Error("runTask is not implemented")},e.prototype.reset=function(){this._taskState=Qd.INIT},e.prototype.onErrorCallback=function(e,t,i){this._taskState=Qd.ERROR,this._errorObject={message:t,exception:i},this.onError&&this.onError(this,t,i),e()},e.prototype.onDoneCallback=function(e,t){try{this._taskState=Qd.DONE,this._isCompleted=!0,this.onSuccess&&this.onSuccess(this),e()}catch(e){this.onErrorCallback(t,"Task is done, error executing success callback(s)",e)}},e}(),of=function(e,t,i){this.remainingCount=e,this.totalCount=t,this.task=i},af=function(e){function t(t,i,n,r){var o=e.call(this,t)||this;return o.name=t,o.meshesNames=i,o.rootUrl=n,o.sceneFilename=r,o}return Object(h.d)(t,e),t.prototype.runTask=function(e,t,i){var n=this;pr.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,e,function(e,i,r,o){n.loadedMeshes=e,n.loadedParticleSystems=i,n.loadedSkeletons=r,n.loadedAnimationGroups=o,t()},null,function(e,t,n){i(t,n)})},t}(rf),sf=function(e){function t(t,i){var n=e.call(this,t)||this;return n.name=t,n.url=i,n}return Object(h.d)(t,e),t.prototype.runTask=function(e,t,i){var n=this;e._loadFile(this.url,function(e){n.text=e,t()},void 0,!1,!1,function(e,t){e&&i(e.status+" "+e.statusText,t)})},t}(rf),cf=function(e){function t(t,i){var n=e.call(this,t)||this;return n.name=t,n.url=i,n}return Object(h.d)(t,e),t.prototype.runTask=function(e,t,i){var n=this;e._loadFile(this.url,function(e){n.data=e,t()},void 0,!0,!0,function(e,t){e&&i(e.status+" "+e.statusText,t)})},t}(rf),lf=function(e){function t(t,i){var n=e.call(this,t)||this;return n.name=t,n.url=i,n}return Object(h.d)(t,e),t.prototype.runTask=function(e,t,i){var n=this,r=new Image;De.b.SetCorsBehavior(this.url,r),r.onload=function(){n.image=r,t()},r.onerror=function(e){i("Error loading image",e)},r.src=this.url},t}(rf),uf=function(e){function t(t,i,n,r,o){void 0===o&&(o=et.a.TRILINEAR_SAMPLINGMODE);var a=e.call(this,t)||this;return a.name=t,a.url=i,a.noMipmap=n,a.invertY=r,a.samplingMode=o,a}return Object(h.d)(t,e),t.prototype.runTask=function(e,t,i){this.texture=new et.a(this.url,e,this.noMipmap,this.invertY,this.samplingMode,function(){t()},function(e,t){i(e,t)})},t}(rf),hf=function(e){function t(t,i,n,r,o){var a=e.call(this,t)||this;return a.name=t,a.url=i,a.extensions=n,a.noMipmap=r,a.files=o,a}return Object(h.d)(t,e),t.prototype.runTask=function(e,t,i){this.texture=new to(this.url,e,this.extensions,this.noMipmap,this.files,function(){t()},function(e,t){i(e,t)})},t}(rf),df=function(e){function t(t,i,n,r,o,a,s){void 0===r&&(r=!1),void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=!1);var c=e.call(this,t)||this;return c.name=t,c.url=i,c.size=n,c.noMipmap=r,c.generateHarmonics=o,c.gammaSpace=a,c.reserved=s,c}return Object(h.d)(t,e),t.prototype.runTask=function(e,t,i){this.texture=new ms(this.url,e,this.size,this.noMipmap,this.generateHarmonics,this.gammaSpace,this.reserved,function(){t()},function(e,t){i(e,t)})},t}(rf),ff=function(e){function t(t,i,n,r,o){void 0===r&&(r=!1),void 0===o&&(o=!0);var a=e.call(this,t)||this;return a.name=t,a.url=i,a.size=n,a.noMipmap=r,a.gammaSpace=o,a}return Object(h.d)(t,e),t.prototype.runTask=function(e,t,i){this.texture=new Gs(this.url,e,this.size,this.noMipmap,this.gammaSpace,function(){t()},function(e,t){i(e,t)})},t}(rf),pf=function(){function e(e){this._isLoading=!1,this._tasks=new Array,this._waitingTasksCount=0,this._totalTasksCount=0,this.onTaskSuccessObservable=new o.c,this.onTaskErrorObservable=new o.c,this.onTasksDoneObservable=new o.c,this.onProgressObservable=new o.c,this.useDefaultLoadingScreen=!0,this.autoHideLoadingUI=!0,this._scene=e}return e.prototype.addMeshTask=function(e,t,i,n){var r=new af(e,t,i,n);return this._tasks.push(r),r},e.prototype.addTextFileTask=function(e,t){var i=new sf(e,t);return this._tasks.push(i),i},e.prototype.addBinaryFileTask=function(e,t){var i=new cf(e,t);return this._tasks.push(i),i},e.prototype.addImageTask=function(e,t){var i=new lf(e,t);return this._tasks.push(i),i},e.prototype.addTextureTask=function(e,t,i,n,r){void 0===r&&(r=et.a.TRILINEAR_SAMPLINGMODE);var o=new uf(e,t,i,n,r);return this._tasks.push(o),o},e.prototype.addCubeTextureTask=function(e,t,i,n,r){var o=new hf(e,t,i,n,r);return this._tasks.push(o),o},e.prototype.addHDRCubeTextureTask=function(e,t,i,n,r,o,a){void 0===n&&(n=!1),void 0===r&&(r=!0),void 0===o&&(o=!1),void 0===a&&(a=!1);var s=new df(e,t,i,n,r,o,a);return this._tasks.push(s),s},e.prototype.addEquiRectangularCubeTextureAssetTask=function(e,t,i,n,r){void 0===n&&(n=!1),void 0===r&&(r=!0);var o=new ff(e,t,i,n,r);return this._tasks.push(o),o},e.prototype.removeTask=function(e){var t=this._tasks.indexOf(e);t>-1&&this._tasks.splice(t,1)},e.prototype._decreaseWaitingTasksCount=function(e){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,e),this.onProgressObservable.notifyObservers(new of(this._waitingTasksCount,this._totalTasksCount,e))}catch(e){m.a.Error("Error running progress callbacks."),console.log(e)}if(0===this._waitingTasksCount){try{var t=this._tasks.slice();this.onFinish&&this.onFinish(t);for(var i=0,n=t;i<n.length;i++){if((e=n[i]).taskState===Qd.DONE){var r=this._tasks.indexOf(e);r>-1&&this._tasks.splice(r,1)}}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(e){m.a.Error("Error running tasks-done callbacks."),console.log(e)}this._isLoading=!1,this.autoHideLoadingUI&&this._scene.getEngine().hideLoadingUI()}},e.prototype._runTask=function(e){var t=this,i=function(i,n){e._setErrorObject(i,n),t.onTaskError&&t.onTaskError(e),t.onTaskErrorObservable.notifyObservers(e),t._decreaseWaitingTasksCount(e)};e.run(this._scene,function(){try{t.onTaskSuccess&&t.onTaskSuccess(e),t.onTaskSuccessObservable.notifyObservers(e),t._decreaseWaitingTasksCount(e)}catch(e){i("Error executing task success callbacks",e)}},i)},e.prototype.reset=function(){return this._isLoading=!1,this._tasks=new Array,this},e.prototype.load=function(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,0===this._waitingTasksCount)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(var e=0;e<this._tasks.length;e++){var t=this._tasks[e];t.taskState===Qd.INIT&&this._runTask(t)}return this},e.prototype.loadAsync=function(){var e=this;return new Promise(function(t,i){e._isLoading?t():(e.onTasksDoneObservable.addOnce(function(e){e&&e.length?i(e):t()}),e.load())})},e}(),_f=function(){function e(){var e=this;this.promise=new Promise(function(t,i){e._resolve=t,e._reject=i})}return Object.defineProperty(e.prototype,"resolve",{get:function(){return this._resolve},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"reject",{get:function(){return this._reject},enumerable:!0,configurable:!0}),e}(),mf=function(){function e(e,t){this._meshesOrigins=[],this._toCenterVectors=[],this._scaledDirection=a.e.Zero(),this._newPosition=a.e.Zero(),this._centerPosition=a.e.Zero(),this._meshes=e.slice(),t?this._centerMesh=t:this._setCenterMesh();var i=this._meshes.indexOf(this._centerMesh);i>=0&&this._meshes.splice(i,1),this._centerPosition=this._centerMesh.getAbsolutePosition().clone();for(var n=0;n<this._meshes.length;n++)if(this._meshes[n]){var r=this._meshes[n];this._meshesOrigins[n]=r.getAbsolutePosition().clone(),this._toCenterVectors[n]=a.e.Zero(),r._boundingInfo&&this._centerMesh._boundingInfo&&r._boundingInfo.boundingBox.centerWorld.subtractToRef(this._centerMesh._boundingInfo.boundingBox.centerWorld,this._toCenterVectors[n])}}return e.prototype._setCenterMesh=function(){for(var e=a.e.Zero(),t=a.e.Zero(),i=Number.MAX_VALUE,n=0;n<this._meshes.length;n++){if(this._meshes[n])(o=(r=this._meshes[n]).getBoundingInfo())&&t.addInPlace(o.boundingBox.centerWorld)}e=t.scale(1/this._meshes.length);for(n=0;n<this._meshes.length;n++){var r,o;if(this._meshes[n])if(o=(r=this._meshes[n]).getBoundingInfo()){var s=o.boundingBox.centerWorld.subtract(e).lengthSquared();s<i&&(this._centerMesh=r,i=s)}}},e.prototype.getClassName=function(){return"MeshExploder"},e.prototype.getMeshes=function(){var e=this._meshes.slice();return e.unshift(this._centerMesh),e},e.prototype.explode=function(e){void 0===e&&(e=1);for(var t=0;t<this._meshes.length;t++)this._meshes[t]&&this._meshesOrigins[t]&&this._toCenterVectors[t]&&(this._toCenterVectors[t].scaleToRef(e,this._scaledDirection),this._meshesOrigins[t].addToRef(this._scaledDirection,this._newPosition),this._meshes[t].setAbsolutePosition(this._newPosition));this._centerMesh.setAbsolutePosition(this._centerPosition)},e}(),gf=function(){function e(e,t,i,n,r,o,a,s,c){this.onProcessFileCallback=function(){return!0},this._engine=e,this._currentScene=t,this._sceneLoadedCallback=i,this._progressCallback=n,this._additionalRenderLoopLogicCallback=r,this._textureLoadingCallback=o,this._startingProcessingFilesCallback=a,this._onReloadCallback=s,this._errorCallback=c}return Object.defineProperty(e,"FilesToLoad",{get:function(){return hr.a.FilesToLoad},enumerable:!0,configurable:!0}),e.prototype.monitorElementForDragNDrop=function(e){var t=this;e&&(this._elementToMonitor=e,this._dragEnterHandler=function(e){t.drag(e)},this._dragOverHandler=function(e){t.drag(e)},this._dropHandler=function(e){t.drop(e)},this._elementToMonitor.addEventListener("dragenter",this._dragEnterHandler,!1),this._elementToMonitor.addEventListener("dragover",this._dragOverHandler,!1),this._elementToMonitor.addEventListener("drop",this._dropHandler,!1))},e.prototype.dispose=function(){this._elementToMonitor&&(this._elementToMonitor.removeEventListener("dragenter",this._dragEnterHandler),this._elementToMonitor.removeEventListener("dragover",this._dragOverHandler),this._elementToMonitor.removeEventListener("drop",this._dropHandler))},e.prototype.renderFunction=function(){if(this._additionalRenderLoopLogicCallback&&this._additionalRenderLoopLogicCallback(),this._currentScene){if(this._textureLoadingCallback){var e=this._currentScene.getWaitingItemsCount();e>0&&this._textureLoadingCallback(e)}this._currentScene.render()}},e.prototype.drag=function(e){e.stopPropagation(),e.preventDefault()},e.prototype.drop=function(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)},e.prototype._traverseFolder=function(e,t,i,n){var r=this,o=e.createReader(),a=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");o.readEntries(function(e){i.count+=e.length;for(var o=0,s=e;o<s.length;o++){var c=s[o];c.isFile?c.file(function(e){e.correctName=a+e.name,t.push(e),0==--i.count&&n()}):c.isDirectory&&r._traverseFolder(c,t,i,n)}--i.count&&n()})},e.prototype._processFiles=function(t){for(var i=0;i<t.length;i++){var n=t[i].correctName.toLowerCase(),r=n.split(".").pop();this.onProcessFileCallback(t[i],n,r)&&("babylon"!==r&&"stl"!==r&&"obj"!==r&&"gltf"!==r&&"glb"!==r||-1!==n.indexOf(".binary.babylon")||-1!==n.indexOf(".incremental.babylon")||(this._sceneFileToLoad=t[i]),e.FilesToLoad[n]=t[i])}},e.prototype.loadFiles=function(e){var t=this;if(e&&e.dataTransfer&&e.dataTransfer.files&&(this._filesToLoad=e.dataTransfer.files),e&&e.target&&e.target.files&&(this._filesToLoad=e.target.files),this._filesToLoad&&0!==this._filesToLoad.length&&(this._startingProcessingFilesCallback&&this._startingProcessingFilesCallback(this._filesToLoad),this._filesToLoad&&this._filesToLoad.length>0)){for(var i=new Array,n=[],r=e.dataTransfer?e.dataTransfer.items:null,o=0;o<this._filesToLoad.length;o++){var a=this._filesToLoad[o],s=a.name.toLowerCase(),c=void 0;if(a.correctName=s,r){var l=r[o];l.getAsEntry?c=l.getAsEntry():l.webkitGetAsEntry&&(c=l.webkitGetAsEntry())}c&&c.isDirectory?n.push(c):i.push(a)}if(0===n.length)this._processFiles(i),this._processReload();else for(var u={count:n.length},h=0,d=n;h<d.length;h++){var f=d[h];this._traverseFolder(f,i,u,function(){t._processFiles(i),0===u.count&&t._processReload()})}}},e.prototype._processReload=function(){this._onReloadCallback?this._onReloadCallback(this._sceneFileToLoad):this.reload()},e.prototype.reload=function(){var e=this;this._sceneFileToLoad?(this._currentScene&&(m.a.errorsCount>0&&m.a.ClearLogCache(),this._engine.stopRenderLoop()),pr.LoadAsync("file:",this._sceneFileToLoad,this._engine,function(t){e._progressCallback&&e._progressCallback(t)}).then(function(t){e._currentScene&&e._currentScene.dispose(),e._currentScene=t,e._sceneLoadedCallback&&e._sceneLoadedCallback(e._sceneFileToLoad,e._currentScene),e._currentScene.executeWhenReady(function(){e._engine.runRenderLoop(function(){e.renderFunction()})})}).catch(function(t){e._errorCallback&&e._errorCallback(e._sceneFileToLoad,e._currentScene,t.message)})):m.a.Error("Please provide a valid .babylon file.")},e}(),vf=i(132),yf=i(131),bf=function(){function e(e){void 0===e&&(e=0),this.priority=e}return e.prototype.getDescription=function(){return""},e.prototype.apply=function(e,t){return!0},e}(),Tf=function(e){function t(t,i,n){void 0===t&&(t=0),void 0===i&&(i=1024),void 0===n&&(n=.5);var r=e.call(this,t)||this;return r.priority=t,r.maximumSize=i,r.step=n,r}return Object(h.d)(t,e),t.prototype.getDescription=function(){return"Reducing render target texture size to "+this.maximumSize},t.prototype.apply=function(e,t){for(var i=!0,n=0;n<e.textures.length;n++){var r=e.textures[n];if(r.canRescale&&!r.getContext){var o=r.getSize();Math.max(o.width,o.height)>this.maximumSize&&(r.scale(this.step),i=!1)}}return i},t}(bf),Ef=function(e){function t(t,i,n){void 0===t&&(t=0),void 0===i&&(i=2),void 0===n&&(n=.25);var r=e.call(this,t)||this;return r.priority=t,r.maximumScale=i,r.step=n,r._currentScale=-1,r._directionOffset=1,r}return Object(h.d)(t,e),t.prototype.getDescription=function(){return"Setting hardware scaling level to "+this._currentScale},t.prototype.apply=function(e,t){return-1===this._currentScale&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,e.getEngine().setHardwareScalingLevel(this._currentScale),1===this._directionOffset?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale},t}(bf),xf=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t.prototype.getDescription=function(){return"Turning shadows on/off"},t.prototype.apply=function(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0},t}(bf),Pf=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t.prototype.getDescription=function(){return"Turning post-processes on/off"},t.prototype.apply=function(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0},t}(bf),Af=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t.prototype.getDescription=function(){return"Turning lens flares on/off"},t.prototype.apply=function(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0},t}(bf),Sf=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t.prototype.getDescription=function(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"},t.prototype.apply=function(e,t){return!this.onApply||this.onApply(e,t)},t}(bf),Cf=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t.prototype.getDescription=function(){return"Turning particles on/off"},t.prototype.apply=function(e,t){return e.particlesEnabled=t.isInImprovementMode,!0},t}(bf),Rf=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(h.d)(t,e),t.prototype.getDescription=function(){return"Turning render targets off"},t.prototype.apply=function(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0},t}(bf),Of=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._canBeMerged=function(e){if(!(e instanceof Ae.a))return!1;var t=e;return!t.isDisposed()&&(!(!t.isVisible||!t.isEnabled())&&(!(t.instances.length>0)&&(!t.skeleton&&!t.hasLODLevels)))},t}return Object(h.d)(t,e),Object.defineProperty(t,"UpdateSelectionTree",{get:function(){return t._UpdateSelectionTree},set:function(e){t._UpdateSelectionTree=e},enumerable:!0,configurable:!0}),t.prototype.getDescription=function(){return"Merging similar meshes together"},t.prototype.apply=function(e,i,n){for(var r=e.meshes.slice(0),o=r.length,a=0;a<o;a++){var s=new Array,c=r[a];if(this._canBeMerged(c)){s.push(c);for(var l=a+1;l<o;l++){var u=r[l];this._canBeMerged(u)&&(u.material===c.material&&u.checkCollisions===c.checkCollisions&&(s.push(u),o--,r.splice(l,1),l--))}s.length<2||Ae.a.MergeMeshes(s,void 0,!0)}}var h=e;return h.createOrUpdateSelectionOctree&&(null!=n?n&&h.createOrUpdateSelectionOctree():t.UpdateSelectionTree&&h.createOrUpdateSelectionOctree()),!0},t._UpdateSelectionTree=!1,t}(bf),Mf=function(){function e(e,t){void 0===e&&(e=60),void 0===t&&(t=2e3),this.targetFrameRate=e,this.trackerDuration=t,this.optimizations=new Array}return e.prototype.addOptimization=function(e){return this.optimizations.push(e),this},e.prototype.addCustomOptimization=function(e,t,i){void 0===i&&(i=0);var n=new Sf(i);return n.onApply=e,n.onGetDescription=t,this.optimizations.push(n),this},e.LowDegradationAllowed=function(t){var i=new e(t),n=0;return i.addOptimization(new Of(n)),i.addOptimization(new xf(n)),i.addOptimization(new Af(n)),n++,i.addOptimization(new Pf(n)),i.addOptimization(new Cf(n)),n++,i.addOptimization(new Tf(n,1024)),i},e.ModerateDegradationAllowed=function(t){var i=new e(t),n=0;return i.addOptimization(new Of(n)),i.addOptimization(new xf(n)),i.addOptimization(new Af(n)),n++,i.addOptimization(new Pf(n)),i.addOptimization(new Cf(n)),n++,i.addOptimization(new Tf(n,512)),n++,i.addOptimization(new Rf(n)),n++,i.addOptimization(new Ef(n,2)),i},e.HighDegradationAllowed=function(t){var i=new e(t),n=0;return i.addOptimization(new Of(n)),i.addOptimization(new xf(n)),i.addOptimization(new Af(n)),n++,i.addOptimization(new Pf(n)),i.addOptimization(new Cf(n)),n++,i.addOptimization(new Tf(n,256)),n++,i.addOptimization(new Rf(n)),n++,i.addOptimization(new Ef(n,4)),i},e}(),If=function(){function e(e,t,i,n){var r=this;if(void 0===i&&(i=!0),void 0===n&&(n=!1),this._isRunning=!1,this._currentPriorityLevel=0,this._targetFrameRate=60,this._trackerDuration=2e3,this._currentFrameRate=0,this._improvementMode=!1,this.onSuccessObservable=new o.c,this.onNewOptimizationAppliedObservable=new o.c,this.onFailureObservable=new o.c,this._options=t||new Mf,this._options.targetFrameRate&&(this._targetFrameRate=this._options.targetFrameRate),this._options.trackerDuration&&(this._trackerDuration=this._options.trackerDuration),i)for(var a=0,s=0,c=this._options.optimizations;s<c.length;s++){c[s].priority=a++}this._improvementMode=n,this._scene=e||R.a.LastCreatedScene,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(function(){r._sceneDisposeObserver=null,r.dispose()})}return Object.defineProperty(e.prototype,"isInImprovementMode",{get:function(){return this._improvementMode},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentPriorityLevel",{get:function(){return this._currentPriorityLevel},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentFrameRate",{get:function(){return this._currentFrameRate},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"targetFrameRate",{get:function(){return this._targetFrameRate},set:function(e){this._targetFrameRate=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trackerDuration",{get:function(){return this._trackerDuration},set:function(e){this._trackerDuration=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"optimizations",{get:function(){return this._options.optimizations},enumerable:!0,configurable:!0}),e.prototype.stop=function(){this._isRunning=!1},e.prototype.reset=function(){this._currentPriorityLevel=0},e.prototype.start=function(){var e=this;this._isRunning||(this._isRunning=!0,this._scene.executeWhenReady(function(){setTimeout(function(){e._checkCurrentState()},e._trackerDuration)}))},e.prototype._checkCurrentState=function(){var e=this;if(this._isRunning){var t=this._scene,i=this._options;if(this._currentFrameRate=Math.round(t.getEngine().getFps()),this._improvementMode&&this._currentFrameRate<=this._targetFrameRate||!this._improvementMode&&this._currentFrameRate>=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);for(var n=!0,r=!0,o=0;o<i.optimizations.length;o++){var a=i.optimizations[o];a.priority===this._currentPriorityLevel&&(r=!1,n=n&&a.apply(t,this),this.onNewOptimizationAppliedObservable.notifyObservers(a))}if(r)return this._isRunning=!1,void this.onFailureObservable.notifyObservers(this);n&&this._currentPriorityLevel++,t.executeWhenReady(function(){setTimeout(function(){e._checkCurrentState()},e._trackerDuration)})}},e.prototype.dispose=function(){this.stop(),this.onSuccessObservable.clear(),this.onFailureObservable.clear(),this.onNewOptimizationAppliedObservable.clear(),this._sceneDisposeObserver&&this._scene.onDisposeObservable.remove(this._sceneDisposeObserver)},e.OptimizeAsync=function(t,i,n,r){var o=new e(t,i||Mf.ModerateDegradationAllowed(),!1);return n&&o.onSuccessObservable.add(function(){n()}),r&&o.onFailureObservable.add(function(){r()}),o.start(),o},e}(),Df=[],wf=function(e,t){Df[e.id]||e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),Df[e.id]=!0)},Lf=function(e,t){var i={},n=e._geometry;return n&&(e.getScene().getGeometryByID(n.id)||wf(n,t.geometries)),e.serialize&&e.serialize(i),i},Nf=function(){function e(){}return e.ClearCache=function(){Df=[]},e.Serialize=function(t){var i,n,r,o={};if(e.ClearCache(),o.useDelayedTextureLoading=t.useDelayedTextureLoading,o.autoClear=t.autoClear,o.clearColor=t.clearColor.asArray(),o.ambientColor=t.ambientColor.asArray(),o.gravity=t.gravity.asArray(),o.collisionsEnabled=t.collisionsEnabled,t.fogMode&&0!==t.fogMode&&(o.fogMode=t.fogMode,o.fogColor=t.fogColor.asArray(),o.fogStart=t.fogStart,o.fogEnd=t.fogEnd,o.fogDensity=t.fogDensity),t.isPhysicsEnabled()){var a=t.getPhysicsEngine();a&&(o.physicsEnabled=!0,o.physicsGravity=a.gravity.asArray(),o.physicsEngine=a.getPhysicsPluginName())}t.metadata&&(o.metadata=t.metadata),o.morphTargetManagers=[];for(var s=0,c=t.meshes;s<c.length;s++){var l=(y=c[s]).morphTargetManager;l&&o.morphTargetManagers.push(l.serialize())}for(o.lights=[],i=0;i<t.lights.length;i++)(n=t.lights[i]).doNotSerialize||o.lights.push(n.serialize());for(o.cameras=[],i=0;i<t.cameras.length;i++){var u=t.cameras[i];u.doNotSerialize||o.cameras.push(u.serialize())}if(t.activeCamera&&(o.activeCameraID=t.activeCamera.id),N.a.AppendSerializedAnimations(t,o),t.animationGroups&&t.animationGroups.length>0){o.animationGroups=[];for(var h=0;h<t.animationGroups.length;h++){var d=t.animationGroups[h];o.animationGroups.push(d.serialize())}}if(t.reflectionProbes&&t.reflectionProbes.length>0)for(o.reflectionProbes=[],i=0;i<t.reflectionProbes.length;i++){var f=t.reflectionProbes[i];o.reflectionProbes.push(f.serialize())}for(o.materials=[],o.multiMaterials=[],i=0;i<t.materials.length;i++)(r=t.materials[i]).doNotSerialize||o.materials.push(r.serialize());for(o.multiMaterials=[],i=0;i<t.multiMaterials.length;i++){var p=t.multiMaterials[i];o.multiMaterials.push(p.serialize())}for(t.environmentTexture&&(o.environmentTexture=t.environmentTexture.name),o.environmentIntensity=t.environmentIntensity,o.skeletons=[],i=0;i<t.skeletons.length;i++){var _=t.skeletons[i];_.doNotSerialize||o.skeletons.push(_.serialize())}for(o.transformNodes=[],i=0;i<t.transformNodes.length;i++)t.transformNodes[i].doNotSerialize||o.transformNodes.push(t.transformNodes[i].serialize());o.geometries={},o.geometries.boxes=[],o.geometries.spheres=[],o.geometries.cylinders=[],o.geometries.toruses=[],o.geometries.grounds=[],o.geometries.planes=[],o.geometries.torusKnots=[],o.geometries.vertexData=[],Df=[];var m=t.getGeometries();for(i=0;i<m.length;i++){var v=m[i];v.isReady()&&wf(v,o.geometries)}for(o.meshes=[],i=0;i<t.meshes.length;i++){var y;if((y=t.meshes[i])instanceof Ae.a){var b=y;b.doNotSerialize||b.delayLoadState!==g.a.DELAYLOADSTATE_LOADED&&b.delayLoadState!==g.a.DELAYLOADSTATE_NONE||o.meshes.push(Lf(b,o))}}for(o.particleSystems=[],i=0;i<t.particleSystems.length;i++)o.particleSystems.push(t.particleSystems[i].serialize());t.actionManager&&(o.actions=t.actionManager.serialize("scene"));for(var T=0,E=t._serializableComponents;T<E.length;T++){E[T].serialize(o)}return o},e.SerializeMesh=function(t,i,n){void 0===i&&(i=!1),void 0===n&&(n=!1);var r={};if(e.ClearCache(),t=t instanceof Array?t:[t],i||n)for(var o=0;o<t.length;++o)n&&t[o].getDescendants().forEach(function(e){e instanceof Ae.a&&t.indexOf(e)<0&&!e.doNotSerialize&&t.push(e)}),i&&t[o].parent&&t.indexOf(t[o].parent)<0&&!t[o].parent.doNotSerialize&&t.push(t[o].parent);return t.forEach(function(e){!function(e,t){if(e.delayLoadState===g.a.DELAYLOADSTATE_LOADED||e.delayLoadState===g.a.DELAYLOADSTATE_NONE){if(e.material&&!e.material.doNotSerialize)if(e.material instanceof fs.a){if(t.multiMaterials=t.multiMaterials||[],t.materials=t.materials||[],!t.multiMaterials.some(function(t){return t.id===e.material.id})){t.multiMaterials.push(e.material.serialize());for(var i=function(e){e&&(t.materials.some(function(t){return t.id===e.id})||t.materials.push(e.serialize()))},n=0,r=e.material.subMaterials;n<r.length;n++)i(r[n])}}else t.materials=t.materials||[],t.materials.some(function(t){return t.id===e.material.id})||t.materials.push(e.material.serialize());var o=e._geometry;o&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),wf(o,t.geometries)),e.skeleton&&!e.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(e.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(Lf(e,t))}}(e,r)}),r},e}(),Ff=i(35),Bf=function(){function e(){}return e.CreateResizedCopy=function(e,t,i,n){void 0===n&&(n=!0);var r=e.getScene(),o=r.getEngine(),a=new Fi("resized"+e.name,{width:t,height:i},r,!e.noMipmap,!0,e._texture.type,!1,e.samplingMode,!1);a.wrapU=e.wrapU,a.wrapV=e.wrapV,a.uOffset=e.uOffset,a.vOffset=e.vOffset,a.uScale=e.uScale,a.vScale=e.vScale,a.uAng=e.uAng,a.vAng=e.vAng,a.wAng=e.wAng,a.coordinatesIndex=e.coordinatesIndex,a.level=e.level,a.anisotropicFilteringLevel=e.anisotropicFilteringLevel,a._texture.isReady=!1,e.wrapU=et.a.CLAMP_ADDRESSMODE,e.wrapV=et.a.CLAMP_ADDRESSMODE;var s=new fi("pass",1,null,n?et.a.BILINEAR_SAMPLINGMODE:et.a.NEAREST_SAMPLINGMODE,o,!1,g.a.TEXTURETYPE_UNSIGNED_INT);return s.getEffect().executeWhenCompiled(function(){s.onApply=function(t){t.setTexture("textureSampler",e)};var t=a.getInternalTexture();t&&(r.postProcessManager.directRender([s],t),o.unBindFramebuffer(t),a.disposeFramebufferObjects(),s.dispose(),t.isReady=!0)}),a},e}(),Uf=function(){function e(t,i){if(void 0===i&&(i=null),!e.IsSupported(t))throw"Your browser does not support recording so far.";var n=t.getRenderingCanvas();if(!n)throw"The babylon engine must have a canvas to be recorded";this._canvas=n,this._canvas.isRecording=!1,this._options=Object(h.a)(Object(h.a)({},e._defaultOptions),i);var r=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(var o=0,a=this._options.audioTracks;o<a.length;o++){var s=a[o];r.addTrack(s)}this._mediaRecorder=new MediaRecorder(r,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=this._handleDataAvailable.bind(this),this._mediaRecorder.onerror=this._handleError.bind(this),this._mediaRecorder.onstop=this._handleStop.bind(this)}return e.IsSupported=function(e){var t=e.getRenderingCanvas();return!!t&&"function"==typeof t.captureStream},Object.defineProperty(e.prototype,"isRecording",{get:function(){return!!this._canvas&&this._canvas.isRecording},enumerable:!0,configurable:!0}),e.prototype.stopRecording=function(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())},e.prototype.startRecording=function(e,t){var i=this;if(void 0===e&&(e="babylonjs.webm"),void 0===t&&(t=7),!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout(function(){i.stopRecording()},1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise(function(e,t){i._resolve=e,i._reject=t})},e.prototype.dispose=function(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null},e.prototype._handleDataAvailable=function(e){e.data.size>0&&this._recordedChunks.push(e.data)},e.prototype._handleError=function(e){if(this.stopRecording(),!this._reject)throw new e.error;this._reject(e.error)},e.prototype._handleStop=function(){this.stopRecording();var e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&De.b.Download(e,this._fileName)},e._defaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3},e}(),Vf=function(){function e(){}return e.CreateScreenshot=function(t,i,n,r,o){void 0===o&&(o="image/png");var a=e._getScreenshotSize(t,i,n),s=a.height,c=a.width;if(s&&c){De.b._ScreenshotCanvas||(De.b._ScreenshotCanvas=document.createElement("canvas")),De.b._ScreenshotCanvas.width=c,De.b._ScreenshotCanvas.height=s;var l=De.b._ScreenshotCanvas.getContext("2d"),u=t.getRenderWidth()/t.getRenderHeight(),h=c,d=h/u;d>s&&(h=(d=s)*u);var f=Math.max(0,c-h)/2,p=Math.max(0,s-d)/2,_=t.getRenderingCanvas();l&&_&&l.drawImage(_,f,p,h,d),De.b.EncodeScreenshotCanvasData(r,o)}else m.a.Error("Invalid 'size' parameter !")},e.CreateScreenshotAsync=function(t,i,n,r){return void 0===r&&(r="image/png"),new Promise(function(o,a){e.CreateScreenshot(t,i,n,function(e){void 0!==e?o(e):a(new Error("Data is undefined"))},r)})},e.CreateScreenshotUsingRenderTarget=function(t,i,n,r,o,a,s,c,l){void 0===o&&(o="image/png"),void 0===a&&(a=1),void 0===s&&(s=!1),void 0===l&&(l=!1);var u=e._getScreenshotSize(t,i,n),h=u.height,d=u.width,f={width:d,height:h};if(h&&d){var p=i.getScene(),_=null;p.activeCamera!==i&&(_=p.activeCamera,p.activeCamera=i);var v=t.getRenderingCanvas();if(v){var y={width:v.width,height:v.height};t.setSize(d,h),p.render();var b=new Fi("screenShot",f,p,!1,!1,g.a.TEXTURETYPE_UNSIGNED_INT,!1,et.a.NEAREST_SAMPLINGMODE);b.renderList=null,b.samples=a,b.renderSprites=l,b.onAfterRenderObservable.add(function(){De.b.DumpFramebuffer(d,h,t,r,o,c)});var T=function(){p.incrementRenderId(),p.resetCachedMaterial(),b.render(!0),b.dispose(),_&&(p.activeCamera=_),t.setSize(y.width,y.height),i.getProjectionMatrix(!0)};if(s){var E=new Yh("antialiasing",1,p.activeCamera);b.addPostProcess(E),E.getEffect().isReady()?T():E.getEffect().onCompiled=function(){T()}}else T()}else m.a.Error("No rendering canvas found !")}else m.a.Error("Invalid 'size' parameter !")},e.CreateScreenshotUsingRenderTargetAsync=function(t,i,n,r,o,a,s,c){return void 0===r&&(r="image/png"),void 0===o&&(o=1),void 0===a&&(a=!1),void 0===c&&(c=!1),new Promise(function(l,u){e.CreateScreenshotUsingRenderTarget(t,i,n,function(e){void 0!==e?l(e):u(new Error("Data is undefined"))},r,o,a,s,c)})},e._getScreenshotSize=function(e,t,i){var n=0,r=0;if("object"==typeof i){var o=i.precision?Math.abs(i.precision):1;i.width&&i.height?(n=i.height*o,r=i.width*o):i.width&&!i.height?(r=i.width*o,n=Math.round(r/e.getAspectRatio(t))):i.height&&!i.width?(n=i.height*o,r=Math.round(n*e.getAspectRatio(t))):(r=Math.round(e.getRenderWidth()*o),n=Math.round(r/e.getAspectRatio(t)))}else isNaN(i)||(n=i,r=i);return r&&(r=Math.floor(r)),n&&(n=Math.floor(n)),{height:0|n,width:0|r}},e}();De.b.CreateScreenshot=Vf.CreateScreenshot,De.b.CreateScreenshotAsync=Vf.CreateScreenshotAsync,De.b.CreateScreenshotUsingRenderTarget=Vf.CreateScreenshotUsingRenderTarget,De.b.CreateScreenshotUsingRenderTargetAsync=Vf.CreateScreenshotUsingRenderTargetAsync,function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String"}(nf||(nf={}));var kf=i(126),zf=function(){function e(e){this.byteOffset=0,this.buffer=e}return e.prototype.loadAsync=function(e){var t=this;return delete this._dataView,delete this._dataByteOffset,this.buffer.readAsync(this.byteOffset,e).then(function(e){t._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),t._dataByteOffset=0})},e.prototype.readUint32=function(){var e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e},e.prototype.readUint8Array=function(e){var t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t},e.prototype.readString=function(e){return eo.a.Decode(this.readUint8Array(e))},e.prototype.skipBytes=function(e){this._dataByteOffset+=e,this.byteOffset+=e},e}(),Gf=function(e){function t(i,n){void 0===n&&(n={});var r=e.call(this,i)||this;return r.options=n,r._direction=new a.e(0,0,-1),r._mat=new a.a,r._onSelectEnabled=!1,r._origin=new a.e(0,0,0),r.lastNativeXRHitResults=[],r.onHitTestResultObservable=new o.c,r._onHitTestResults=function(e){var t=e.map(function(e){var t=a.a.FromArray(e.hitMatrix);return r._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),r.options.worldParentNode&&t.multiplyToRef(r.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}});r.lastNativeXRHitResults=e,r.onHitTestResultObservable.notifyObservers(t)},r._onSelect=function(e){r._onSelectEnabled&&t.XRHitTestWithSelectEvent(e,r._xrSessionManager.referenceSpace)},r}return Object(h.d)(t,e),t.XRHitTestWithRay=function(e,t,i,n){return e.requestHitTest(t,i).then(function(e){var t=n||function(e){return!!e.hitMatrix};return e.filter(t)})},t.XRHitTestWithSelectEvent=function(e,t){var i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);var n=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,n,t)},t.prototype.attach=function(){return!!e.prototype.attach.call(this)&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)},t.prototype.detach=function(){return!!e.prototype.detach.call(this)&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onHitTestResultObservable.clear()},t.prototype._onXRFrame=function(e){if(this.attached&&!this.options.testOnPointerDownOnly){var i=e.getViewerPose(this._xrSessionManager.referenceSpace);if(i){a.a.FromArrayToRef(i.transform.matrix,0,this._mat),a.e.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),a.e.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();var n=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});t.XRHitTestWithRay(this._xrSessionManager.session,n,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}},t.Name=ea.HIT_TEST,t.Version=1,t}(da);ta.AddWebXRFeature(Gf.Name,function(e,t){return function(){return new Gf(e,t)}},Gf.Version,!0);var jf=0,Wf=function(e){function t(t,i){void 0===i&&(i={});var n=e.call(this,t)||this;return n._options=i,n._enabled=!1,n._lastFrameDetected=new Set,n._onSelect=function(e){if(n._options.addAnchorOnSelect){var t=function(e){if(e.length){var t=e[0],i=new XRRigidTransform(t.hitMatrix);n.addAnchorAtRigidTransformation(i)}};n._hitTestModule&&!n._hitTestModule.options.testOnPointerDownOnly&&t(n._hitTestModule.lastNativeXRHitResults),Gf.XRHitTestWithSelectEvent(e,n._xrSessionManager.referenceSpace).then(t),n._planeDetector}},n._trackedAnchors=[],n.onAnchorAddedObservable=new o.c,n.onAnchorRemovedObservable=new o.c,n.onAnchorUpdatedObservable=new o.c,n}return Object(h.d)(t,e),t.prototype.addAnchorAtRigidTransformation=function(e,t){return(t||this._xrSessionManager.session).createAnchor(e,this._xrSessionManager.referenceSpace)},t.prototype.attach=function(){return!!e.prototype.attach.call(this)&&(this._options.addAnchorOnSelect&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)},t.prototype.detach=function(){return!!e.prototype.detach.call(this)&&(this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()},t.prototype.setHitTestModule=function(e){this._hitTestModule=e},t.prototype.setPlaneDetector=function(e,t){void 0===t&&(t=!0),this._planeDetector=e,this._options.usePlaneDetection=t},t.prototype._onXRFrame=function(e){var t=this;if(this.attached&&this._enabled&&e){var i=e.trackedAnchors;i&&i.size&&(this._trackedAnchors.filter(function(e){return!i.has(e.xrAnchor)}).map(function(e){var i=t._trackedAnchors.indexOf(e);t._trackedAnchors.splice(i,1),t.onAnchorRemovedObservable.notifyObservers(e)}),i.forEach(function(i){if(t._lastFrameDetected.has(i)){if(i.lastChangedTime===t._xrSessionManager.currentTimestamp){var n=t._findIndexInAnchorArray(i),r=t._trackedAnchors[n];t._updateAnchorWithXRFrame(i,r,e),t.onAnchorUpdatedObservable.notifyObservers(r)}}else{var o={id:jf++,xrAnchor:i},a=t._updateAnchorWithXRFrame(i,o,e);t._trackedAnchors.push(a),t.onAnchorAddedObservable.notifyObservers(a)}}),this._lastFrameDetected=i)}},t.prototype._findIndexInAnchorArray=function(e){for(var t=0;t<this._trackedAnchors.length;++t)if(this._trackedAnchors[t].xrAnchor===e)return t;return-1},t.prototype._updateAnchorWithXRFrame=function(e,t,i){var n=i.getPose(e.anchorSpace,this._xrSessionManager.referenceSpace);if(n){var r=t.transformationMatrix||new a.a;a.a.FromArrayToRef(n.transform.matrix,0,r),this._xrSessionManager.scene.useRightHandedSystem||r.toggleModelMatrixHandInPlace(),t.transformationMatrix=r,this._options.worldParentNode&&r.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),r)}return t},t.Name=ea.ANCHOR_SYSTEM,t.Version=1,t}(da),Xf=0,Hf=function(e){function t(t,i){void 0===i&&(i={});var n=e.call(this,t)||this;return n._options=i,n._detectedPlanes=[],n._enabled=!1,n._lastFrameDetected=new Set,n.onPlaneAddedObservable=new o.c,n.onPlaneRemovedObservable=new o.c,n.onPlaneUpdatedObservable=new o.c,n._xrSessionManager.session?n._init():n._xrSessionManager.onXRSessionInit.addOnce(function(){n._init()}),n}return Object(h.d)(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()},t.prototype._onXRFrame=function(e){var t=this;if(this.attached&&this._enabled&&e){var i=e.worldInformation.detectedPlanes;i&&i.size&&(this._detectedPlanes.filter(function(e){return!i.has(e.xrPlane)}).map(function(e){var i=t._detectedPlanes.indexOf(e);t._detectedPlanes.splice(i,1),t.onPlaneRemovedObservable.notifyObservers(e)}),i.forEach(function(i){if(t._lastFrameDetected.has(i)){if(i.lastChangedTime===t._xrSessionManager.currentTimestamp){var n=t.findIndexInPlaneArray(i);o=t._detectedPlanes[n];t._updatePlaneWithXRPlane(i,o,e),t.onPlaneUpdatedObservable.notifyObservers(o)}}else{var r={id:Xf++,xrPlane:i,polygonDefinition:[]},o=t._updatePlaneWithXRPlane(i,r,e);t._detectedPlanes.push(o),t.onPlaneAddedObservable.notifyObservers(o)}}),this._lastFrameDetected=i)}},t.prototype._init=function(){this._xrSessionManager.session.updateWorldTrackingState&&(this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes=[]))},t.prototype._updatePlaneWithXRPlane=function(e,t,i){var n=this;t.polygonDefinition=e.polygon.map(function(e){var t=n._xrSessionManager.scene.useRightHandedSystem?1:-1;return new a.e(e.x,e.y,e.z*t)});var r=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(r){var o=t.transformationMatrix||new a.a;a.a.FromArrayToRef(r.transform.matrix,0,o),this._xrSessionManager.scene.useRightHandedSystem||o.toggleModelMatrixHandInPlace(),t.transformationMatrix=o,this._options.worldParentNode&&o.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),o)}return t},t.prototype.findIndexInPlaneArray=function(e){for(var t=0;t<this._detectedPlanes.length;++t)if(this._detectedPlanes[t].xrPlane===e)return t;return-1},t.Name=ea.PLANE_DETECTION,t.Version=1,t}(da);ta.AddWebXRFeature(Hf.Name,function(e,t){return function(){return new Hf(e,t)}},Hf.Version);var Yf=function(e){function t(t,i){void 0===i&&(i={});var n=e.call(this,t)||this;return n.options=i,n.onBackgroundStateChangedObservable=new o.c,n}return Object(h.d)(t,e),t.prototype.attach=function(){return this._setBackgroundState(!1),e.prototype.attach.call(this)},t.prototype.detach=function(){return this._setBackgroundState(!0),e.prototype.detach.call(this)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onBackgroundStateChangedObservable.clear()},t.prototype._onXRFrame=function(e){},t.prototype._setBackgroundState=function(e){var t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper)if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){var i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){var n=t.getMeshByName("BackgroundPlane");n&&n.setEnabled(e)}}else{var r=t.getMeshByName("BackgroundHelper");r&&r.setEnabled(e)}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach(function(t){return t.setEnabled(e)}),this.onBackgroundStateChangedObservable.notifyObservers(e)},t.Name=ea.BACKGROUND_REMOVER,t.Version=1,t}(da);ta.AddWebXRFeature(Yf.Name,function(e,t){return function(){return new Yf(e,t)}},Yf.Version,!0);var Kf=function(){},Qf=function(e){function t(t,i){var n=e.call(this,t)||this;return n._options=i,n._attachController=function(e){if(!n._controllers[e.uniqueId])if(n._xrSessionManager.scene.isPhysicsEnabled()||m.a.Warn("physics engine not enabled, skipped. Please add this controller manually."),n._options.physicsProperties.useControllerMesh)e.onMotionControllerInitObservable.addOnce(function(t){t.onModelLoadedObservable.addOnce(function(){var i=new ys.a(t.rootMesh,ys.a.MeshImpostor,Object(h.a)({mass:0},n._options.physicsProperties)),r=e.grip||e.pointer;n._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:r.position.clone(),oldRotation:r.rotationQuaternion.clone()}})});else{var t=n._options.physicsProperties.impostorType||ys.a.SphereImpostor,i=n._options.physicsProperties.impostorSize||.1,r=Rr.a.CreateSphere("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});r.isVisible=n._debugMode,r.isPickable=!1,r.rotationQuaternion=new a.b;var o=e.grip||e.pointer;r.position.copyFrom(o.position),r.rotationQuaternion.copyFrom(o.rotationQuaternion);var s=new ys.a(r,t,Object(h.a)({mass:0},n._options.physicsProperties));n._controllers[e.uniqueId]={xrController:e,impostor:s,impostorMesh:r}}},n._controllers={},n._debugMode=!1,n._delta=0,n._lastTimestamp=0,n._tmpQuaternion=new a.b,n._tmpVector=new a.e,n._options.physicsProperties||(n._options.physicsProperties={}),n}return Object(h.d)(t,e),t.prototype._enablePhysicsDebug=function(){var e=this;this._debugMode=!0,Object.keys(this._controllers).forEach(function(t){var i=e._controllers[t];i.impostorMesh&&(i.impostorMesh.isVisible=!0)})},t.prototype.addController=function(e){this._attachController(e)},t.prototype.attach=function(){var t=this;if(!e.prototype.attach.call(this))return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,function(e){t._detachController(e.uniqueId)}),this._options.enableHeadsetImpostor){var i=this._options.headsetImpostorParams||{impostorType:ys.a.SphereImpostor,restitution:.8,impostorSize:.3},n=i.impostorSize||.3;this._headsetMesh=Rr.a.CreateSphere("headset-mesh",{diameterX:"number"==typeof n?n:n.width,diameterY:"number"==typeof n?n:n.height,diameterZ:"number"==typeof n?n:n.depth}),this._headsetMesh.rotationQuaternion=new a.b,this._headsetMesh.isVisible=!1,this._headsetImpostor=new ys.a(this._headsetMesh,i.impostorType,Object(h.a)({mass:0},i))}return!0},t.prototype.detach=function(){var t=this;return!!e.prototype.detach.call(this)&&(Object.keys(this._controllers).forEach(function(e){t._detachController(e)}),this._headsetMesh&&this._headsetMesh.dispose(),!0)},t.prototype.getHeadsetImpostor=function(){return this._headsetImpostor},t.prototype.getImpostorForController=function(e){var t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null},t.prototype.setPhysicsProperties=function(e){this._options.physicsProperties=Object(h.a)(Object(h.a)({},this._options.physicsProperties),e)},t.prototype._onXRFrame=function(e){var t=this;this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.position),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion)),Object.keys(this._controllers).forEach(function(e){var i=t._controllers[e],n=i.xrController.grip||i.xrController.pointer,r=i.oldPos||i.impostorMesh.position,o=i.oldRotation||i.impostorMesh.rotationQuaternion;if(n.position.subtractToRef(r,t._tmpVector),t._tmpVector.scaleInPlace(1e3/t._delta),i.impostor.setLinearVelocity(t._tmpVector),t._debugMode&&console.log(t._tmpVector,"linear"),!o.equalsWithEpsilon(n.rotationQuaternion)){o.conjugateInPlace().multiplyToRef(n.rotationQuaternion,t._tmpQuaternion);var a=Math.sqrt(t._tmpQuaternion.x*t._tmpQuaternion.x+t._tmpQuaternion.y*t._tmpQuaternion.y+t._tmpQuaternion.z*t._tmpQuaternion.z);if(t._tmpVector.set(t._tmpQuaternion.x,t._tmpQuaternion.y,t._tmpQuaternion.z),a<.001)t._tmpVector.scaleInPlace(2);else{var s=2*Math.atan2(a,t._tmpQuaternion.w);t._tmpVector.scaleInPlace(s/(a*(t._delta/1e3)))}i.impostor.setAngularVelocity(t._tmpVector),t._debugMode&&console.log(t._tmpVector,t._tmpQuaternion,"angular")}r.copyFrom(n.position),o.copyFrom(n.rotationQuaternion)})},t.prototype._detachController=function(e){var t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])},t.Name=ea.PHYSICS_CONTROLLERS,t.Version=1,t}(da);ta.AddWebXRFeature(Qf.Name,function(e,t){return function(){return new Qf(e,t)}},Qf.Version,!0);var qf=function(e){function t(t,i,n){var r=e.call(this,t,Zf["left-right"],i,n)||this;return r._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},r.profileId="microsoft-mixed-reality",r}return Object(h.d)(t,e),t.prototype._getFilenameAndPath=function(){return{filename:"left"===this.handness?t.MODEL_LEFT_FILENAME:t.MODEL_RIGHT_FILENAME,path:t.MODEL_BASE_URL+"default/"}},t.prototype._getModelLoadingConstraints=function(){var e=pr.IsPluginForExtensionAvailable(".glb");return e||m.a.Warn("glTF / glb loaded was not registered, using generic controller instead"),e},t.prototype._processLoadedModel=function(e){var t=this;this.rootMesh&&(this.getComponentIds().forEach(function(e,i){if(!t.disableAnimation&&e&&t.rootMesh){var n=t._mapping.buttons[e],r=n.rootNodeName;if(!r)return void m.a.Log("Skipping unknown button at index: "+i+" with mapped name: "+e);var o=t._getChildByName(t.rootMesh,r);if(!o)return void m.a.Warn("Missing button mesh with name: "+r);if(n.valueMesh=t._getImmediateChildByName(o,t._mapping.defaultButton.valueNodeName),n.pressedMesh=t._getImmediateChildByName(o,t._mapping.defaultButton.pressedNodeName),n.unpressedMesh=t._getImmediateChildByName(o,t._mapping.defaultButton.unpressedNodeName),n.valueMesh&&n.pressedMesh&&n.unpressedMesh){var a=t.getComponent(e);a&&a.onButtonStateChangedObservable.add(function(e){t._lerpTransform(n,e.value)},void 0,!0)}else m.a.Warn("Missing button submesh under mesh with name: "+r)}}),this.getComponentIds().forEach(function(e,i){var n=t.getComponent(e);n.isAxes()&&["x-axis","y-axis"].forEach(function(i){if(t.rootMesh){var r=t._mapping.axes[e][i],o=t._getChildByName(t.rootMesh,r.rootNodeName);o?(r.valueMesh=t._getImmediateChildByName(o,t._mapping.defaultAxis.valueNodeName),r.minMesh=t._getImmediateChildByName(o,t._mapping.defaultAxis.minNodeName),r.maxMesh=t._getImmediateChildByName(o,t._mapping.defaultAxis.maxNodeName),r.valueMesh&&r.minMesh&&r.maxMesh?n&&n.onAxisValueChangedObservable.add(function(e){var n="x-axis"===i?e.x:e.y;t._lerpTransform(r,n,!0)},void 0,!0):m.a.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)):m.a.Warn("Missing axis mesh with name: "+r.rootNodeName)}})}))},t.prototype._setRootMesh=function(e){var t;this.rootMesh=new Ae.a(this.profileId+" "+this.handness,this.scene),this.rootMesh.isPickable=!1;for(var i=0;i<e.length;i++){var n=e[i];n.isPickable=!1,n.parent||(t=n)}t&&t.setParent(this.rootMesh),this.rootMesh.rotationQuaternion=a.b.FromEulerAngles(0,Math.PI,0)},t.prototype._updateModel=function(){},t.MODEL_BASE_URL="https://controllers.babylonjs.com/microsoft/",t.MODEL_LEFT_FILENAME="left.glb",t.MODEL_RIGHT_FILENAME="right.glb",t}(ra);ca.RegisterController("windows-mixed-reality",function(e,t){return new qf(t,e.gamepad,e.handedness)});var Zf={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}},Jf=function(e){function t(t,i,n,r,o){void 0===r&&(r=!1),void 0===o&&(o=!1);var a=e.call(this,t,$f[n],i,n)||this;return a._forceLegacyControllers=o,a.profileId="oculus-touch",a}return Object(h.d)(t,e),t.prototype._getFilenameAndPath=function(){return{filename:"left"===this.handness?t.MODEL_LEFT_FILENAME:t.MODEL_RIGHT_FILENAME,path:this._isQuest()?t.QUEST_MODEL_BASE_URL:t.MODEL_BASE_URL}},t.prototype._getModelLoadingConstraints=function(){return!0},t.prototype._processLoadedModel=function(e){var t=this,i=this._isQuest(),n="right"===this.handness?-1:1;this.getComponentIds().forEach(function(e){var r=e&&t.getComponent(e);r&&r.onButtonStateChangedObservable.add(function(r){if(t.rootMesh&&!t.disableAnimation)switch(e){case"xr-standard-trigger":return void(i||(t._modelRootNode.getChildren()[3].rotation.x=.2*-r.value,t._modelRootNode.getChildren()[3].position.y=.005*-r.value,t._modelRootNode.getChildren()[3].position.z=.005*-r.value));case"xr-standard-squeeze":return void(i||(t._modelRootNode.getChildren()[4].position.x=n*r.value*.0035));case"xr-standard-thumbstick":return;case"a-button":case"x-button":return void(i||(r.pressed?t._modelRootNode.getChildren()[1].position.y=-.001:t._modelRootNode.getChildren()[1].position.y=0));case"b-button":case"y-button":return void(i||(r.pressed?t._modelRootNode.getChildren()[2].position.y=-.001:t._modelRootNode.getChildren()[2].position.y=0))}},void 0,!0)})},t.prototype._setRootMesh=function(e){this.rootMesh=new Ae.a(this.profileId+" "+this.handness,this.scene),this.rootMesh.rotationQuaternion=a.b.FromEulerAngles(0,Math.PI,0),e.forEach(function(e){e.isPickable=!1}),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh},t.prototype._updateModel=function(){},t.prototype._isQuest=function(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers},t.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",t.MODEL_LEFT_FILENAME="left.babylon",t.MODEL_RIGHT_FILENAME="right.babylon",t.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",t}(ra);ca.RegisterController("oculus-touch",function(e,t){return new Jf(t,e.gamepad,e.handedness)}),ca.RegisterController("oculus-touch-legacy",function(e,t){return new Jf(t,e.gamepad,e.handedness,!0)});var $f={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}},ep=function(e){function t(t,i,n){var r=e.call(this,t,tp[n],i,n)||this;return r.profileId="htc-vive",r}return Object(h.d)(t,e),t.prototype._getFilenameAndPath=function(){return{filename:t.MODEL_FILENAME,path:t.MODEL_BASE_URL}},t.prototype._getModelLoadingConstraints=function(){return!0},t.prototype._processLoadedModel=function(e){var t=this;this.getComponentIds().forEach(function(e){var i=e&&t.getComponent(e);i&&i.onButtonStateChangedObservable.add(function(i){if(t.rootMesh&&!t.disableAnimation)switch(e){case"xr-standard-trigger":return void(t._modelRootNode.getChildren()[6].rotation.x=.15*-i.value);case"xr-standard-touchpad":case"xr-standard-squeeze":return}},void 0,!0)})},t.prototype._setRootMesh=function(e){this.rootMesh=new Ae.a(this.profileId+" "+this.handness,this.scene),e.forEach(function(e){e.isPickable=!1}),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.rootMesh.rotationQuaternion=a.b.FromEulerAngles(0,Math.PI,0)},t.prototype._updateModel=function(){},t.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",t.MODEL_FILENAME="wand.babylon",t}(ra);ca.RegisterController("htc-vive",function(e,t){return new ep(t,e.gamepad,e.handedness)});var tp={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};i.d(t,"AbstractScene",function(){return n.a}),i.d(t,"AbstractActionManager",function(){return r.a}),i.d(t,"Action",function(){return l}),i.d(t,"ActionEvent",function(){return u.a}),i.d(t,"ActionManager",function(){return M}),i.d(t,"Condition",function(){return d}),i.d(t,"ValueCondition",function(){return f}),i.d(t,"PredicateCondition",function(){return p}),i.d(t,"StateCondition",function(){return _}),i.d(t,"SwitchBooleanAction",function(){return v}),i.d(t,"SetStateAction",function(){return y}),i.d(t,"SetValueAction",function(){return b}),i.d(t,"IncrementValueAction",function(){return T}),i.d(t,"PlayAnimationAction",function(){return E}),i.d(t,"StopAnimationAction",function(){return x}),i.d(t,"DoNothingAction",function(){return P}),i.d(t,"CombineAction",function(){return A}),i.d(t,"ExecuteCodeAction",function(){return S}),i.d(t,"SetParentAction",function(){return C}),i.d(t,"PlaySoundAction",function(){return I}),i.d(t,"StopSoundAction",function(){return D}),i.d(t,"InterpolateValueAction",function(){return z}),i.d(t,"Animatable",function(){return $}),i.d(t,"_IAnimationState",function(){return V}),i.d(t,"Animation",function(){return k}),i.d(t,"TargetedAnimation",function(){return te}),i.d(t,"AnimationGroup",function(){return ie}),i.d(t,"AnimationPropertiesOverride",function(){return ne}),i.d(t,"EasingFunction",function(){return he}),i.d(t,"CircleEase",function(){return de}),i.d(t,"BackEase",function(){return fe}),i.d(t,"BounceEase",function(){return pe}),i.d(t,"CubicEase",function(){return _e}),i.d(t,"ElasticEase",function(){return me}),i.d(t,"ExponentialEase",function(){return ge}),i.d(t,"PowerEase",function(){return ve}),i.d(t,"QuadraticEase",function(){return ye}),i.d(t,"QuarticEase",function(){return be}),i.d(t,"QuinticEase",function(){return Te}),i.d(t,"SineEase",function(){return Ee}),i.d(t,"BezierCurveEase",function(){return xe}),i.d(t,"RuntimeAnimation",function(){return Y}),i.d(t,"AnimationEvent",function(){return Pe}),i.d(t,"AnimationKeyInterpolation",function(){return w}),i.d(t,"AnimationRange",function(){return F}),i.d(t,"KeepAssets",function(){return Se}),i.d(t,"InstantiatedEntries",function(){return Ce}),i.d(t,"AssetContainer",function(){return Re}),i.d(t,"Analyser",function(){return Me}),i.d(t,"AudioEngine",function(){return Ie}),i.d(t,"AudioSceneComponent",function(){return Be}),i.d(t,"Sound",function(){return Le}),i.d(t,"SoundTrack",function(){return Ne}),i.d(t,"WeightedSound",function(){return Ue}),i.d(t,"AutoRotationBehavior",function(){return ke}),i.d(t,"BouncingBehavior",function(){return ze}),i.d(t,"FramingBehavior",function(){return Ge}),i.d(t,"AttachToBoxBehavior",function(){return We}),i.d(t,"FadeInOutBehavior",function(){return Xe}),i.d(t,"MultiPointerScaleBehavior",function(){return Ye}),i.d(t,"PointerDragBehavior",function(){return He.a}),i.d(t,"SixDofDragBehavior",function(){return Ze}),i.d(t,"Bone",function(){return J}),i.d(t,"BoneIKController",function(){return Je}),i.d(t,"BoneLookController",function(){return $e}),i.d(t,"Skeleton",function(){return ot}),i.d(t,"CameraInputTypes",function(){return at}),i.d(t,"CameraInputsManager",function(){return st}),i.d(t,"Camera",function(){return Qe.a}),i.d(t,"TargetCamera",function(){return Lt}),i.d(t,"FreeCamera",function(){return Nt}),i.d(t,"FreeCameraInputsManager",function(){return Ct}),i.d(t,"TouchCamera",function(){return Ft}),i.d(t,"ArcRotateCamera",function(){return Bt}),i.d(t,"ArcRotateCameraInputsManager",function(){return gt}),i.d(t,"DeviceOrientationCamera",function(){return Ut}),i.d(t,"FlyCamera",function(){return kt}),i.d(t,"FlyCameraInputsManager",function(){return Vt}),i.d(t,"FollowCamera",function(){return jt}),i.d(t,"ArcFollowCamera",function(){return Wt}),i.d(t,"FollowCameraInputsManager",function(){return zt}),i.d(t,"GamepadCamera",function(){return ri}),i.d(t,"UniversalCamera",function(){return ni}),i.d(t,"VirtualJoysticksCamera",function(){return Ri}),i.d(t,"ArcRotateCameraGamepadInput",function(){return ht}),i.d(t,"ArcRotateCameraKeyboardMoveInput",function(){return ft}),i.d(t,"ArcRotateCameraMouseWheelInput",function(){return pt}),i.d(t,"ArcRotateCameraPointersInput",function(){return mt}),i.d(t,"ArcRotateCameraVRDeviceOrientationInput",function(){return vt}),i.d(t,"FlyCameraKeyboardInput",function(){return yt}),i.d(t,"FlyCameraMouseInput",function(){return bt}),i.d(t,"FollowCameraKeyboardMoveInput",function(){return Tt}),i.d(t,"FollowCameraMouseWheelInput",function(){return Et}),i.d(t,"FollowCameraPointersInput",function(){return xt}),i.d(t,"FreeCameraDeviceOrientationInput",function(){return Rt}),i.d(t,"FreeCameraGamepadInput",function(){return Ot}),i.d(t,"FreeCameraKeyboardMoveInput",function(){return Pt}),i.d(t,"FreeCameraMouseInput",function(){return At}),i.d(t,"FreeCameraTouchInput",function(){return St}),i.d(t,"FreeCameraVirtualJoystickInput",function(){return wt}),i.d(t,"AnaglyphArcRotateCamera",function(){return gi}),i.d(t,"AnaglyphFreeCamera",function(){return vi}),i.d(t,"AnaglyphGamepadCamera",function(){return yi}),i.d(t,"AnaglyphUniversalCamera",function(){return bi}),i.d(t,"StereoscopicArcRotateCamera",function(){return Pi}),i.d(t,"StereoscopicFreeCamera",function(){return Ai}),i.d(t,"StereoscopicGamepadCamera",function(){return Si}),i.d(t,"StereoscopicUniversalCamera",function(){return Ci}),i.d(t,"VRCameraMetrics",function(){return Oi}),i.d(t,"VRDeviceOrientationArcRotateCamera",function(){return zi}),i.d(t,"VRDeviceOrientationFreeCamera",function(){return Gi}),i.d(t,"VRDeviceOrientationGamepadCamera",function(){return ji}),i.d(t,"OnAfterEnteringVRObservableEvent",function(){return pn}),i.d(t,"VRExperienceHelper",function(){return _n}),i.d(t,"WebVRFreeCamera",function(){return Xi}),i.d(t,"Collider",function(){return vn}),i.d(t,"DefaultCollisionCoordinator",function(){return yn}),i.d(t,"PickingInfo",function(){return bn.a}),i.d(t,"IntersectionInfo",function(){return Tn.a}),i.d(t,"_MeshCollisionData",function(){return En.a}),i.d(t,"BoundingBox",function(){return xn.a}),i.d(t,"BoundingInfo",function(){return Pn.a}),i.d(t,"BoundingSphere",function(){return An.a}),i.d(t,"Ray",function(){return Ht.a}),i.d(t,"Octree",function(){return Cn}),i.d(t,"OctreeBlock",function(){return Sn}),i.d(t,"OctreeSceneComponent",function(){return Rn}),i.d(t,"AxesViewer",function(){return On.AxesViewer}),i.d(t,"BoneAxesViewer",function(){return On.BoneAxesViewer}),i.d(t,"DebugLayerTab",function(){return On.DebugLayerTab}),i.d(t,"DebugLayer",function(){return On.DebugLayer}),i.d(t,"PhysicsViewer",function(){return On.PhysicsViewer}),i.d(t,"RayHelper",function(){return On.RayHelper}),i.d(t,"SkeletonViewer",function(){return On.SkeletonViewer}),i.d(t,"Constants",function(){return g.a}),i.d(t,"ThinEngine",function(){return li.a}),i.d(t,"Engine",function(){return Oe.a}),i.d(t,"EngineStore",function(){return R.a}),i.d(t,"NullEngineOptions",function(){return Mn.b}),i.d(t,"NullEngine",function(){return Mn.a}),i.d(t,"WebGLPipelineContext",function(){return Ln.a}),i.d(t,"WebGL2ShaderProcessor",function(){return Nn.a}),i.d(t,"NativeEngine",function(){return cr}),i.d(t,"_OcclusionDataStorage",function(){return Dn}),i.d(t,"_forceTransformFeedbackToBundle",function(){return!0}),i.d(t,"EngineView",function(){return wn}),i.d(t,"KeyboardEventTypes",function(){return dt.a}),i.d(t,"KeyboardInfo",function(){return dt.b}),i.d(t,"KeyboardInfoPre",function(){return dt.c}),i.d(t,"PointerEventTypes",function(){return Ve.a}),i.d(t,"PointerInfoBase",function(){return Ve.c}),i.d(t,"PointerInfoPre",function(){return Ve.d}),i.d(t,"PointerInfo",function(){return Ve.b}),i.d(t,"ClipboardEventTypes",function(){return lr}),i.d(t,"ClipboardInfo",function(){return ur}),i.d(t,"StickValues",function(){return ct}),i.d(t,"Gamepad",function(){return lt}),i.d(t,"GenericPad",function(){return ut}),i.d(t,"GamepadManager",function(){return ti}),i.d(t,"GamepadSystemSceneComponent",function(){return ii}),i.d(t,"Xbox360Button",function(){return Yt}),i.d(t,"Xbox360Dpad",function(){return Kt}),i.d(t,"Xbox360Pad",function(){return $t}),i.d(t,"DualShockButton",function(){return Zt}),i.d(t,"DualShockDpad",function(){return Jt}),i.d(t,"DualShockPad",function(){return ei}),i.d(t,"DaydreamController",function(){return _r}),i.d(t,"GearVRController",function(){return mr}),i.d(t,"GenericController",function(){return gr}),i.d(t,"OculusTouchController",function(){return vr}),i.d(t,"PoseEnabledControllerType",function(){return Gt}),i.d(t,"PoseEnabledControllerHelper",function(){return Qt}),i.d(t,"PoseEnabledController",function(){return qt}),i.d(t,"ViveController",function(){return yr}),i.d(t,"WebVRController",function(){return Hi}),i.d(t,"WindowsMotionController",function(){return Tr}),i.d(t,"XRWindowsMotionController",function(){return Er}),i.d(t,"AxisDragGizmo",function(){return xr.a}),i.d(t,"AxisScaleGizmo",function(){return Cr}),i.d(t,"BoundingBoxGizmo",function(){return Mr}),i.d(t,"Gizmo",function(){return Ar.a}),i.d(t,"GizmoManager",function(){return Vr}),i.d(t,"PlaneRotationGizmo",function(){return Ir}),i.d(t,"PositionGizmo",function(){return Fr}),i.d(t,"RotationGizmo",function(){return Dr}),i.d(t,"ScaleGizmo",function(){return Ur}),i.d(t,"LightGizmo",function(){return Xr}),i.d(t,"PlaneDragGizmo",function(){return Nr}),i.d(t,"EnvironmentHelper",function(){return _o}),i.d(t,"PhotoDome",function(){return mo}),i.d(t,"_forceSceneHelpersToBundle",function(){return!0}),i.d(t,"VideoDome",function(){return xa}),i.d(t,"EngineInstrumentation",function(){return Aa}),i.d(t,"SceneInstrumentation",function(){return Sa}),i.d(t,"_TimeToken",function(){return In}),i.d(t,"EffectLayer",function(){return Ma}),i.d(t,"EffectLayerSceneComponent",function(){return Ia}),i.d(t,"GlowLayer",function(){return La}),i.d(t,"HighlightLayer",function(){return Ba}),i.d(t,"Layer",function(){return za}),i.d(t,"LayerSceneComponent",function(){return Ua}),i.d(t,"LensFlare",function(){return Ga}),i.d(t,"LensFlareSystem",function(){return Xa}),i.d(t,"LensFlareSystemSceneComponent",function(){return Ha}),i.d(t,"Light",function(){return kr.a}),i.d(t,"ShadowLight",function(){return zr}),i.d(t,"DirectionalLight",function(){return Gr}),i.d(t,"HemisphericLight",function(){return Wi.a}),i.d(t,"PointLight",function(){return us}),i.d(t,"SpotLight",function(){return Wr}),i.d(t,"ShadowGenerator",function(){return qa}),i.d(t,"CascadedShadowGenerator",function(){return cs}),i.d(t,"ShadowGeneratorSceneComponent",function(){return ls}),i.d(t,"DefaultLoadingScreen",function(){return hs}),i.d(t,"SceneLoaderProgressEvent",function(){return fr}),i.d(t,"SceneLoaderAnimationGroupLoadingMode",function(){return Zn}),i.d(t,"SceneLoader",function(){return pr}),i.d(t,"SceneLoaderFlags",function(){return dr.a}),i.d(t,"_BabylonLoaderRegistered",function(){return!0}),i.d(t,"BabylonFileLoaderConfiguration",function(){return Os}),i.d(t,"ColorCurves",function(){return Ns.a}),i.d(t,"EffectFallbacks",function(){return ho.a}),i.d(t,"Effect",function(){return ai.a}),i.d(t,"FresnelParameters",function(){return Fs}),i.d(t,"ImageProcessingConfigurationDefines",function(){return Yi.b}),i.d(t,"ImageProcessingConfiguration",function(){return Yi.a}),i.d(t,"Material",function(){return Ca.a}),i.d(t,"MaterialDefines",function(){return no.a}),i.d(t,"MaterialHelper",function(){return io.a}),i.d(t,"MultiMaterial",function(){return fs.a}),i.d(t,"PBRMaterial",function(){return zo}),i.d(t,"PushMaterial",function(){return ro.a}),i.d(t,"ShaderMaterial",function(){return ks.a}),i.d(t,"StandardMaterialDefines",function(){return Ki.b}),i.d(t,"StandardMaterial",function(){return Ki.a}),i.d(t,"BaseTexture",function(){return jn.a}),i.d(t,"CubeTexture",function(){return to}),i.d(t,"DynamicTexture",function(){return qi}),i.d(t,"EquiRectangularCubeTexture",function(){return Gs}),i.d(t,"HDRCubeTexture",function(){return ms}),i.d(t,"InternalTextureSource",function(){return tt.b}),i.d(t,"InternalTexture",function(){return tt.a}),i.d(t,"MirrorTexture",function(){return Jr}),i.d(t,"MultiRenderTarget",function(){return qs}),i.d(t,"RawTexture",function(){return rt}),i.d(t,"RenderTargetTexture",function(){return Fi}),i.d(t,"Texture",function(){return et.a}),i.d(t,"UniformBuffer",function(){return wi.a}),i.d(t,"MaterialFlags",function(){return oo.a}),i.d(t,"EffectRenderer",function(){return Ll}),i.d(t,"EffectWrapper",function(){return Nl}),i.d(t,"BackgroundMaterial",function(){return po}),i.d(t,"PBRMaterialDefines",function(){return Vo}),i.d(t,"PBRBaseMaterial",function(){return ko}),i.d(t,"PBRBaseSimpleMaterial",function(){return Bs}),i.d(t,"PBRMetallicRoughnessMaterial",function(){return Us}),i.d(t,"PBRSpecularGlossinessMaterial",function(){return Vs}),i.d(t,"ColorGradingTexture",function(){return zs}),i.d(t,"RawCubeTexture",function(){return uc}),i.d(t,"RawTexture3D",function(){return hc}),i.d(t,"RawTexture2DArray",function(){return dc}),i.d(t,"RefractionTexture",function(){return fc}),i.d(t,"VideoTexture",function(){return ba}),i.d(t,"HtmlElementTexture",function(){return pc}),i.d(t,"NodeMaterialConnectionPointCompatibilityStates",function(){return cc}),i.d(t,"NodeMaterialConnectionPointDirection",function(){return lc}),i.d(t,"NodeMaterialConnectionPoint",function(){return gc}),i.d(t,"NodeMaterialBlock",function(){return yc}),i.d(t,"NodeMaterialDefines",function(){return Cc}),i.d(t,"NodeMaterial",function(){return Rc}),i.d(t,"_DDSTextureLoader",function(){return Ko}),i.d(t,"_ENVTextureLoader",function(){return Qo}),i.d(t,"_KTXTextureLoader",function(){return Jo}),i.d(t,"_TGATextureLoader",function(){return Ws}),i.d(t,"_BasisTextureLoader",function(){return Qs}),i.d(t,"CustomProceduralTexture",function(){return tc}),i.d(t,"NoiseProceduralTexture",function(){return nc}),i.d(t,"ProceduralTexture",function(){return $s}),i.d(t,"ProceduralTextureSceneComponent",function(){return Zs}),i.d(t,"TexturePacker",function(){return mc}),i.d(t,"TexturePackerFrame",function(){return _c}),i.d(t,"NodeMaterialBlockTargets",function(){return rc}),i.d(t,"NodeMaterialBlockConnectionPointTypes",function(){return oc}),i.d(t,"NodeMaterialBlockConnectionPointMode",function(){return ac}),i.d(t,"NodeMaterialSystemValues",function(){return sc}),i.d(t,"MultiplyBlock",function(){return Gc}),i.d(t,"AddBlock",function(){return jc}),i.d(t,"ScaleBlock",function(){return Wc}),i.d(t,"ClampBlock",function(){return Xc}),i.d(t,"CrossBlock",function(){return Hc}),i.d(t,"DotBlock",function(){return Yc}),i.d(t,"TransformBlock",function(){return Ec}),i.d(t,"RemapBlock",function(){return Kc}),i.d(t,"NormalizeBlock",function(){return qc}),i.d(t,"TrigonometryBlockOperations",function(){return Qc}),i.d(t,"TrigonometryBlock",function(){return Zc}),i.d(t,"ColorMergerBlock",function(){return Jc}),i.d(t,"VectorMergerBlock",function(){return $c}),i.d(t,"ColorSplitterBlock",function(){return el}),i.d(t,"VectorSplitterBlock",function(){return tl}),i.d(t,"LerpBlock",function(){return il}),i.d(t,"DivideBlock",function(){return nl}),i.d(t,"SubtractBlock",function(){return rl}),i.d(t,"StepBlock",function(){return ol}),i.d(t,"OneMinusBlock",function(){return al}),i.d(t,"ViewDirectionBlock",function(){return sl}),i.d(t,"FresnelBlock",function(){return cl}),i.d(t,"MaxBlock",function(){return ll}),i.d(t,"MinBlock",function(){return ul}),i.d(t,"DistanceBlock",function(){return hl}),i.d(t,"LengthBlock",function(){return dl}),i.d(t,"NegateBlock",function(){return fl}),i.d(t,"PowBlock",function(){return pl}),i.d(t,"RandomNumberBlock",function(){return _l}),i.d(t,"ArcTan2Block",function(){return ml}),i.d(t,"SmoothStepBlock",function(){return gl}),i.d(t,"ReciprocalBlock",function(){return vl}),i.d(t,"ReplaceColorBlock",function(){return yl}),i.d(t,"PosterizeBlock",function(){return Tl}),i.d(t,"WaveBlockKind",function(){return bl}),i.d(t,"WaveBlock",function(){return El}),i.d(t,"GradientBlockColorStep",function(){return xl}),i.d(t,"GradientBlock",function(){return Pl}),i.d(t,"NLerpBlock",function(){return Al}),i.d(t,"WorleyNoise3DBlock",function(){return Sl}),i.d(t,"SimplexPerlin3DBlock",function(){return Cl}),i.d(t,"NormalBlendBlock",function(){return Rl}),i.d(t,"Rotate2dBlock",function(){return Ol}),i.d(t,"ReflectBlock",function(){return Ml}),i.d(t,"RefractBlock",function(){return Il}),i.d(t,"DesaturateBlock",function(){return Dl}),i.d(t,"NodeMaterialOptimizer",function(){return wl}),i.d(t,"VertexOutputBlock",function(){return xc}),i.d(t,"BonesBlock",function(){return Oc}),i.d(t,"InstancesBlock",function(){return Mc}),i.d(t,"MorphTargetsBlock",function(){return Ic}),i.d(t,"LightInformationBlock",function(){return Dc}),i.d(t,"FragmentOutputBlock",function(){return Ac}),i.d(t,"ImageProcessingBlock",function(){return wc}),i.d(t,"PerturbNormalBlock",function(){return Lc}),i.d(t,"DiscardBlock",function(){return Nc}),i.d(t,"FrontFacingBlock",function(){return Fc}),i.d(t,"DerivativeBlock",function(){return Bc}),i.d(t,"FogBlock",function(){return Uc}),i.d(t,"LightBlock",function(){return Vc}),i.d(t,"TextureBlock",function(){return kc}),i.d(t,"ReflectionTextureBlock",function(){return zc}),i.d(t,"InputBlock",function(){return Sc}),i.d(t,"AnimatedInputBlockTypes",function(){return Pc}),i.d(t,"Scalar",function(){return L.a}),i.d(t,"Space",function(){return Z.b}),i.d(t,"Axis",function(){return Z.a}),i.d(t,"Color3",function(){return s.a}),i.d(t,"Color4",function(){return s.b}),i.d(t,"TmpColors",function(){return s.c}),i.d(t,"ToGammaSpace",function(){return re.b}),i.d(t,"ToLinearSpace",function(){return re.c}),i.d(t,"Epsilon",function(){return re.a}),i.d(t,"Frustum",function(){return Ui.a}),i.d(t,"Plane",function(){return mn.a}),i.d(t,"Size",function(){return U.a}),i.d(t,"Vector2",function(){return a.d}),i.d(t,"Vector3",function(){return a.e}),i.d(t,"Vector4",function(){return a.f}),i.d(t,"Quaternion",function(){return a.b}),i.d(t,"Matrix",function(){return a.a}),i.d(t,"TmpVectors",function(){return a.c}),i.d(t,"Viewport",function(){return ki.a}),i.d(t,"SphericalHarmonics",function(){return zn}),i.d(t,"SphericalPolynomial",function(){return Gn}),i.d(t,"Orientation",function(){return ee}),i.d(t,"BezierCurve",function(){return oe}),i.d(t,"Angle",function(){return ae}),i.d(t,"Arc2",function(){return se}),i.d(t,"Path2",function(){return ce}),i.d(t,"Path3D",function(){return le}),i.d(t,"Curve3",function(){return ue}),i.d(t,"PositionNormalVertex",function(){return Ta}),i.d(t,"PositionNormalTextureVertex",function(){return Ea}),i.d(t,"AbstractMesh",function(){return Ke.a}),i.d(t,"Buffer",function(){return en.a}),i.d(t,"VertexBuffer",function(){return en.b}),i.d(t,"CSG",function(){return Yl}),i.d(t,"Geometry",function(){return ds.a}),i.d(t,"GroundMesh",function(){return tn}),i.d(t,"TrailMesh",function(){return Kl}),i.d(t,"InstancedMesh",function(){return Ql.a}),i.d(t,"LinesMesh",function(){return ql.b}),i.d(t,"InstancedLinesMesh",function(){return ql.a}),i.d(t,"_CreationDataStorage",function(){return Ae.b}),i.d(t,"_InstancesBatch",function(){return Ae.c}),i.d(t,"Mesh",function(){return Ae.a}),i.d(t,"VertexData",function(){return $i.a}),i.d(t,"MeshBuilder",function(){return hu}),i.d(t,"SimplificationSettings",function(){return du}),i.d(t,"SimplificationQueue",function(){return fu}),i.d(t,"SimplificationType",function(){return lu}),i.d(t,"SimplicationQueueSceneComponent",function(){return yu}),i.d(t,"Polygon",function(){return iu}),i.d(t,"PolygonMeshBuilder",function(){return nu}),i.d(t,"BaseSubMesh",function(){return zl.a}),i.d(t,"SubMesh",function(){return zl.b}),i.d(t,"MeshLODLevel",function(){return bu.a}),i.d(t,"TransformNode",function(){return wr.a}),i.d(t,"BoxBuilder",function(){return Pr.a}),i.d(t,"SphereBuilder",function(){return Rr.a}),i.d(t,"CylinderBuilder",function(){return an.a}),i.d(t,"TorusBuilder",function(){return on}),i.d(t,"LinesBuilder",function(){return Or.a}),i.d(t,"PlaneBuilder",function(){return Lr.a}),i.d(t,"GroundBuilder",function(){return nn}),i.d(t,"DataBuffer",function(){return Fn.a}),i.d(t,"WebGLDataBuffer",function(){return Tu.a}),i.d(t,"DracoCompression",function(){return kl}),i.d(t,"TiledBoxBuilder",function(){return Jl}),i.d(t,"DiscBuilder",function(){return Zl}),i.d(t,"RibbonBuilder",function(){return As}),i.d(t,"HemisphereBuilder",function(){return jr}),i.d(t,"TorusKnotBuilder",function(){return $l}),i.d(t,"PolygonBuilder",function(){return ru}),i.d(t,"ShapeBuilder",function(){return Ss}),i.d(t,"LatheBuilder",function(){return ou}),i.d(t,"TiledPlaneBuilder",function(){return au}),i.d(t,"TubeBuilder",function(){return su}),i.d(t,"PolyhedronBuilder",function(){return Br}),i.d(t,"IcoSphereBuilder",function(){return cu}),i.d(t,"DecalBuilder",function(){return uu}),i.d(t,"MorphTarget",function(){return gs}),i.d(t,"MorphTargetManager",function(){return vs}),i.d(t,"RecastJSPlugin",function(){return Eu}),i.d(t,"RecastJSCrowd",function(){return xu}),i.d(t,"Node",function(){return B.a}),i.d(t,"Database",function(){return Au}),i.d(t,"BaseParticleSystem",function(){return Fu}),i.d(t,"GPUParticleSystem",function(){return Zu}),i.d(t,"Particle",function(){return zu}),i.d(t,"ParticleHelper",function(){return $u}),i.d(t,"ParticleSystem",function(){return Xu}),i.d(t,"_IDoNeedToBeInTheBuild",function(){return 42}),i.d(t,"ParticleSystemSet",function(){return Ju}),i.d(t,"SolidParticle",function(){return th}),i.d(t,"ModelShape",function(){return ih}),i.d(t,"DepthSortedParticle",function(){return nh}),i.d(t,"SolidParticleSystem",function(){return rh}),i.d(t,"CloudPoint",function(){return oh}),i.d(t,"PointsGroup",function(){return ah}),i.d(t,"PointColor",function(){return eh}),i.d(t,"PointsCloudSystem",function(){return sh}),i.d(t,"SubEmitterType",function(){return Pu}),i.d(t,"SubEmitter",function(){return Gu}),i.d(t,"BoxParticleEmitter",function(){return Su}),i.d(t,"ConeParticleEmitter",function(){return Cu}),i.d(t,"CylinderParticleEmitter",function(){return Ru}),i.d(t,"CylinderDirectedParticleEmitter",function(){return Ou}),i.d(t,"HemisphericParticleEmitter",function(){return Mu}),i.d(t,"PointParticleEmitter",function(){return Iu}),i.d(t,"SphereParticleEmitter",function(){return Du}),i.d(t,"SphereDirectedParticleEmitter",function(){return wu}),i.d(t,"CustomParticleEmitter",function(){return Lu}),i.d(t,"MeshParticleEmitter",function(){return Nu}),i.d(t,"PhysicsEngine",function(){return Ts}),i.d(t,"PhysicsEngineSceneComponent",function(){return uh}),i.d(t,"PhysicsHelper",function(){return hh}),i.d(t,"PhysicsRadialExplosionEventOptions",function(){return mh}),i.d(t,"PhysicsUpdraftEventOptions",function(){return gh}),i.d(t,"PhysicsVortexEventOptions",function(){return vh}),i.d(t,"PhysicsRadialImpulseFalloff",function(){return ch}),i.d(t,"PhysicsUpdraftMode",function(){return lh}),i.d(t,"PhysicsImpostor",function(){return ys.a}),i.d(t,"PhysicsJoint",function(){return bs.e}),i.d(t,"DistanceJoint",function(){return bs.a}),i.d(t,"MotorEnabledJoint",function(){return bs.d}),i.d(t,"HingeJoint",function(){return bs.c}),i.d(t,"Hinge2Joint",function(){return bs.b}),i.d(t,"CannonJSPlugin",function(){return xs}),i.d(t,"AmmoJSPlugin",function(){return Cs}),i.d(t,"OimoJSPlugin",function(){return Ps}),i.d(t,"AnaglyphPostProcess",function(){return mi}),i.d(t,"BlackAndWhitePostProcess",function(){return bh}),i.d(t,"BloomEffect",function(){return Sh}),i.d(t,"BloomMergePostProcess",function(){return Ah}),i.d(t,"BlurPostProcess",function(){return Zr}),i.d(t,"ChromaticAberrationPostProcess",function(){return Rh}),i.d(t,"CircleOfConfusionPostProcess",function(){return Mh}),i.d(t,"ColorCorrectionPostProcess",function(){return Dh}),i.d(t,"ConvolutionPostProcess",function(){return Lh}),i.d(t,"DepthOfFieldBlurPostProcess",function(){return Nh}),i.d(t,"DepthOfFieldEffectBlurLevel",function(){return Bh}),i.d(t,"DepthOfFieldEffect",function(){return kh}),i.d(t,"DepthOfFieldMergePostProcessOptions",function(){return Uh}),i.d(t,"DepthOfFieldMergePostProcess",function(){return Vh}),i.d(t,"DisplayPassPostProcess",function(){return Gh}),i.d(t,"ExtractHighlightsPostProcess",function(){return xh}),i.d(t,"FilterPostProcess",function(){return Wh}),i.d(t,"FxaaPostProcess",function(){return Yh}),i.d(t,"GrainPostProcess",function(){return Qh}),i.d(t,"HighlightsPostProcess",function(){return Zh}),i.d(t,"ImageProcessingPostProcess",function(){return Ji}),i.d(t,"MotionBlurPostProcess",function(){return nd}),i.d(t,"PassPostProcess",function(){return fi}),i.d(t,"PassCubePostProcess",function(){return pi}),i.d(t,"PostProcess",function(){return ui}),i.d(t,"PostProcessManager",function(){return Li.a}),i.d(t,"RefractionPostProcess",function(){return od}),i.d(t,"SharpenPostProcess",function(){return sd}),i.d(t,"StereoscopicInterlacePostProcessI",function(){return Ei}),i.d(t,"StereoscopicInterlacePostProcess",function(){return xi}),i.d(t,"TonemappingOperator",function(){return Ad}),i.d(t,"TonemapPostProcess",function(){return Sd}),i.d(t,"VolumetricLightScatteringPostProcess",function(){return Md}),i.d(t,"VRDistortionCorrectionPostProcess",function(){return Ii}),i.d(t,"VRMultiviewToSingleviewPostProcess",function(){return Vi}),i.d(t,"ScreenSpaceReflectionPostProcess",function(){return Td}),i.d(t,"PostProcessRenderEffect",function(){return Th}),i.d(t,"PostProcessRenderPipeline",function(){return cd}),i.d(t,"PostProcessRenderPipelineManager",function(){return ld}),i.d(t,"PostProcessRenderPipelineManagerSceneComponent",function(){return ud}),i.d(t,"DefaultRenderingPipeline",function(){return hd}),i.d(t,"LensRenderingPipeline",function(){return pd}),i.d(t,"SSAO2RenderingPipeline",function(){return gd}),i.d(t,"SSAORenderingPipeline",function(){return yd}),i.d(t,"StandardRenderingPipeline",function(){return xd}),i.d(t,"ReflectionProbe",function(){return Rs}),i.d(t,"BoundingBoxRenderer",function(){return Id}),i.d(t,"DepthRenderer",function(){return $a}),i.d(t,"DepthRendererSceneComponent",function(){return Dd}),i.d(t,"EdgesRenderer",function(){return Fd}),i.d(t,"LineEdgesRenderer",function(){return Bd}),i.d(t,"GeometryBufferRenderer",function(){return ed}),i.d(t,"GeometryBufferRendererSceneComponent",function(){return td}),i.d(t,"OutlineRenderer",function(){return kd}),i.d(t,"RenderingGroup",function(){return zd.a}),i.d(t,"RenderingGroupInfo",function(){return Ni.a}),i.d(t,"RenderingManager",function(){return Ni.b}),i.d(t,"UtilityLayerRenderer",function(){return Sr.a}),i.d(t,"Scene",function(){return K.a}),i.d(t,"SceneComponentConstants",function(){return Fe.a}),i.d(t,"Stage",function(){return Fe.b}),i.d(t,"Sprite",function(){return Gd}),i.d(t,"SpriteManager",function(){return Hd}),i.d(t,"SpriteMap",function(){return qd}),i.d(t,"SpritePackedManager",function(){return Zd}),i.d(t,"SpriteSceneComponent",function(){return jd}),i.d(t,"AlphaState",function(){return Jd.a}),i.d(t,"DepthCullingState",function(){return $d.a}),i.d(t,"StencilState",function(){return ef.a}),i.d(t,"AndOrNotEvaluator",function(){return tf.a}),i.d(t,"AssetTaskState",function(){return Qd}),i.d(t,"AbstractAssetTask",function(){return rf}),i.d(t,"AssetsProgressEvent",function(){return of}),i.d(t,"MeshAssetTask",function(){return af}),i.d(t,"TextFileAssetTask",function(){return sf}),i.d(t,"BinaryFileAssetTask",function(){return cf}),i.d(t,"ImageAssetTask",function(){return lf}),i.d(t,"TextureAssetTask",function(){return uf}),i.d(t,"CubeTextureAssetTask",function(){return hf}),i.d(t,"HDRCubeTextureAssetTask",function(){return df}),i.d(t,"EquiRectangularCubeTextureAssetTask",function(){return ff}),i.d(t,"AssetsManager",function(){return pf}),i.d(t,"BasisTranscodeConfiguration",function(){return Hs}),i.d(t,"BasisTools",function(){return Ys}),i.d(t,"DDSTools",function(){return Yo}),i.d(t,"expandToProperty",function(){return N.b}),i.d(t,"serialize",function(){return N.c}),i.d(t,"serializeAsTexture",function(){return N.m}),i.d(t,"serializeAsColor3",function(){return N.e}),i.d(t,"serializeAsFresnelParameters",function(){return N.h}),i.d(t,"serializeAsVector2",function(){return N.n}),i.d(t,"serializeAsVector3",function(){return N.o}),i.d(t,"serializeAsMeshReference",function(){return N.k}),i.d(t,"serializeAsColorCurves",function(){return N.g}),i.d(t,"serializeAsColor4",function(){return N.f}),i.d(t,"serializeAsImageProcessingConfiguration",function(){return N.i}),i.d(t,"serializeAsQuaternion",function(){return N.l}),i.d(t,"serializeAsMatrix",function(){return N.j}),i.d(t,"serializeAsCameraReference",function(){return N.d}),i.d(t,"SerializationHelper",function(){return N.a}),i.d(t,"Deferred",function(){return _f}),i.d(t,"EnvironmentTextureTools",function(){return qn}),i.d(t,"MeshExploder",function(){return mf}),i.d(t,"FilesInput",function(){return gf}),i.d(t,"KhronosTextureContainer",function(){return qo}),i.d(t,"EventState",function(){return o.a}),i.d(t,"Observer",function(){return o.d}),i.d(t,"MultiObserver",function(){return o.b}),i.d(t,"Observable",function(){return o.c}),i.d(t,"PerformanceMonitor",function(){return vf.a}),i.d(t,"RollingAverage",function(){return vf.b}),i.d(t,"PromisePolyfill",function(){return yf.a}),i.d(t,"SceneOptimization",function(){return bf}),i.d(t,"TextureOptimization",function(){return Tf}),i.d(t,"HardwareScalingOptimization",function(){return Ef}),i.d(t,"ShadowsOptimization",function(){return xf}),i.d(t,"PostProcessesOptimization",function(){return Pf}),i.d(t,"LensFlaresOptimization",function(){return Af}),i.d(t,"CustomOptimization",function(){return Sf}),i.d(t,"ParticlesOptimization",function(){return Cf}),i.d(t,"RenderTargetsOptimization",function(){return Rf}),i.d(t,"MergeMeshesOptimization",function(){return Of}),i.d(t,"SceneOptimizerOptions",function(){return Mf}),i.d(t,"SceneOptimizer",function(){return If}),i.d(t,"SceneSerializer",function(){return Nf}),i.d(t,"SmartArray",function(){return oi.a}),i.d(t,"SmartArrayNoDuplicate",function(){return oi.b}),i.d(t,"StringDictionary",function(){return It.a}),i.d(t,"Tags",function(){return Ff.a}),i.d(t,"TextureTools",function(){return Bf}),i.d(t,"TGATools",function(){return js}),i.d(t,"Tools",function(){return De.b}),i.d(t,"className",function(){return De.c}),i.d(t,"AsyncLoop",function(){return De.a}),i.d(t,"VideoRecorder",function(){return Uf}),i.d(t,"JoystickAxis",function(){return Mt}),i.d(t,"VirtualJoystick",function(){return Dt}),i.d(t,"WorkerPool",function(){return Fl}),i.d(t,"Logger",function(){return m.a}),i.d(t,"_TypeStore",function(){return c.a}),i.d(t,"FilesInputStore",function(){return hr.a}),i.d(t,"DeepCopier",function(){return O.a}),i.d(t,"PivotTools",function(){return qe.a}),i.d(t,"PrecisionDate",function(){return Q.a}),i.d(t,"ScreenshotTools",function(){return Vf}),i.d(t,"WebRequest",function(){return ec.a}),i.d(t,"InspectableType",function(){return nf}),i.d(t,"BRDFTextureTools",function(){return vo}),i.d(t,"RGBDTextureTools",function(){return go}),i.d(t,"ColorGradient",function(){return Bu}),i.d(t,"Color3Gradient",function(){return Uu}),i.d(t,"FactorGradient",function(){return Vu}),i.d(t,"GradientHelper",function(){return ku}),i.d(t,"PerfCounter",function(){return Pa.a}),i.d(t,"RetryStrategy",function(){return kf.a}),i.d(t,"CanvasGenerator",function(){return Qi.a}),i.d(t,"LoadFileError",function(){return $r.b}),i.d(t,"RequestFileError",function(){return $r.d}),i.d(t,"ReadFileError",function(){return $r.c}),i.d(t,"FileTools",function(){return $r.a}),i.d(t,"StringTools",function(){return eo.a}),i.d(t,"DataReader",function(){return zf}),i.d(t,"MinMaxReducer",function(){return ts}),i.d(t,"DepthReducer",function(){return is}),i.d(t,"CubeMapToSphericalPolynomialTools",function(){return Xn}),i.d(t,"HDRTools",function(){return _s}),i.d(t,"PanoramaToCubeMapTools",function(){return ps}),i.d(t,"WebXRCamera",function(){return $o}),i.d(t,"WebXREnterExitUIButton",function(){return pa}),i.d(t,"WebXREnterExitUIOptions",function(){return _a}),i.d(t,"WebXREnterExitUI",function(){return ma}),i.d(t,"WebXRExperienceHelper",function(){return ia}),i.d(t,"WebXRInput",function(){return ha}),i.d(t,"WebXRInputSource",function(){return ua}),i.d(t,"WebXRManagedOutputCanvasOptions",function(){return sn}),i.d(t,"WebXRManagedOutputCanvas",function(){return cn}),i.d(t,"WebXRState",function(){return rn}),i.d(t,"WebXRSessionManager",function(){return ln}),i.d(t,"WebXRDefaultExperienceOptions",function(){return va}),i.d(t,"WebXRDefaultExperience",function(){return ya}),i.d(t,"WebXRFeatureName",function(){return ea}),i.d(t,"WebXRFeaturesManager",function(){return ta}),i.d(t,"WebXRHitTestLegacy",function(){return Gf}),i.d(t,"WebXRAnchorSystem",function(){return Wf}),i.d(t,"WebXRPlaneDetector",function(){return Hf}),i.d(t,"WebXRBackgroundRemover",function(){return Yf}),i.d(t,"WebXRMotionControllerTeleportation",function(){return ga}),i.d(t,"WebXRControllerPointerSelection",function(){return fa}),i.d(t,"IWebXRControllerPhysicsOptions",function(){return Kf}),i.d(t,"WebXRControllerPhysics",function(){return Qf}),i.d(t,"WebXRAbstractMotionController",function(){return ra}),i.d(t,"WebXRControllerComponent",function(){return na}),i.d(t,"WebXRGenericTriggerMotionController",function(){return oa}),i.d(t,"WebXRMicrosoftMixedRealityController",function(){return qf}),i.d(t,"WebXRMotionControllerManager",function(){return ca}),i.d(t,"WebXROculusTouchMotionController",function(){return Jf}),i.d(t,"WebXRHTCViveMotionController",function(){return ep}),i.d(t,"WebXRProfiledMotionController",function(){return sa})},function(e,t,i){"use strict";i.d(t,"a",function(){return r});var n=i(38),r=function(){function e(){}return e.SetImmediate=function(e){n.a.IsWindowObjectExist()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)},e}()},function(e,t,i){"use strict";var n=i(36),r=function(){function e(){this.children=[]}return e.prototype.isValid=function(e){return!0},e.prototype.process=function(e,t){var i="";if(this.line){var r=this.line,o=t.processor;if(o){if(o.lineProcessor&&(r=o.lineProcessor(r,t.isFragment)),o.attributeProcessor&&n.a.StartsWith(this.line,"attribute"))r=o.attributeProcessor(this.line);else if(o.varyingProcessor&&n.a.StartsWith(this.line,"varying"))r=o.varyingProcessor(this.line,t.isFragment);else if((o.uniformProcessor||o.uniformBufferProcessor)&&n.a.StartsWith(this.line,"uniform")){/uniform (.+) (.+)/.test(this.line)?o.uniformProcessor&&(r=o.uniformProcessor(this.line,t.isFragment)):o.uniformBufferProcessor&&(r=o.uniformBufferProcessor(this.line,t.isFragment),t.lookForClosingBracketForUniformBuffer=!0)}o.endOfUniformBufferProcessor&&t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,r=o.endOfUniformBufferProcessor(this.line,t.isFragment))}i+=r+"\r\n"}return this.children.forEach(function(n){i+=n.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i},e}(),o=function(){function e(){}return Object.defineProperty(e.prototype,"currentLine",{get:function(){return this._lines[this.lineIndex]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"canRead",{get:function(){return this.lineIndex<this._lines.length-1},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lines",{set:function(e){this._lines=[];for(var t=0,i=e;t<i.length;t++){var n=i[t];if("#"!==n[0])for(var r=n.split(";"),o=0;o<r.length;o++){var a=r[o];(a=a.trim())&&this._lines.push(a+(o!==r.length-1?";":""))}else this._lines.push(n)}},enumerable:!0,configurable:!0}),e}(),a=i(1),s=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(a.d)(t,e),t.prototype.process=function(e,t){for(var i=0;i<this.children.length;i++){var n=this.children[i];if(n.isValid(e))return n.process(e,t)}return""},t}(r),c=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(a.d)(t,e),t.prototype.isValid=function(e){return this.testExpression.isTrue(e)},t}(r),l=function(){function e(){}return e.prototype.isTrue=function(e){return!0},e}(),u=function(e){function t(t,i){void 0===i&&(i=!1);var n=e.call(this)||this;return n.define=t,n.not=i,n}return Object(a.d)(t,e),t.prototype.isTrue=function(e){var t=void 0!==e[this.define];return this.not&&(t=!t),t},t}(l),h=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(a.d)(t,e),t.prototype.isTrue=function(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)},t}(l),d=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(a.d)(t,e),t.prototype.isTrue=function(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)},t}(l),f=function(e){function t(t,i,n){var r=e.call(this)||this;return r.define=t,r.operand=i,r.testValue=n,r}return Object(a.d)(t,e),t.prototype.isTrue=function(e){var t=e[this.define];void 0===t&&(t=this.define);var i=!1,n=parseInt(t),r=parseInt(this.testValue);switch(this.operand){case">":i=n>r;break;case"<":i=n<r;break;case"<=":i=n<=r;break;case">=":i=n>=r;break;case"==":i=n===r}return i},t}(l),p=i(19);i.d(t,"a",function(){return _});var _=function(){function e(){}return e.Process=function(e,t,i){var n=this;this._ProcessIncludes(e,t,function(e){var r=n._ProcessShaderConversion(e,t);i(r)})},e._ProcessPrecision=function(e,t){var i=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=i?"precision highp float;\n"+e:"precision mediump float;\n"+e:i||(e=e.replace("precision highp float","precision mediump float")),e},e._ExtractOperation=function(e){var t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new u(t[1].trim(),"!"===e[0]);for(var i="",n=0,r=0,o=["==",">=","<=","<",">"];r<o.length&&(i=o[r],!((n=e.indexOf(i))>-1));r++);if(-1===n)return new u(e);var a=e.substring(0,n).trim(),s=e.substring(n+i.length).trim();return new f(a,i,s)},e._BuildSubExpression=function(e){var t=e.indexOf("||");if(-1===t){var i=e.indexOf("&&");if(i>-1){var n=new d,r=e.substring(0,i).trim(),o=e.substring(i+2).trim();return n.leftOperand=this._BuildSubExpression(r),n.rightOperand=this._BuildSubExpression(o),n}return this._ExtractOperation(e)}var a=new h;r=e.substring(0,t).trim(),o=e.substring(t+2).trim();return a.leftOperand=this._BuildSubExpression(r),a.rightOperand=this._BuildSubExpression(o),a},e._BuildExpression=function(e,t){var i=new c,n=e.substring(0,t),r=e.substring(t).trim();return i.testExpression="#ifdef"===n?new u(r):"#ifndef"===n?new u(r,!0):this._BuildSubExpression(r),i},e._MoveCursorWithinIf=function(e,t,i){for(var n=e.currentLine;this._MoveCursor(e,i);){var o=(n=e.currentLine).substring(0,5).toLowerCase();if("#else"===o){var a=new r;return t.children.push(a),void this._MoveCursor(e,a)}if("#elif"===o){var s=this._BuildExpression(n,5);t.children.push(s),i=s}}},e._MoveCursor=function(e,t){for(;e.canRead;){e.lineIndex++;var i=e.currentLine,n=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/.exec(i);if(n&&n.length){switch(n[0]){case"#ifdef":var o=new s;t.children.push(o);var a=this._BuildExpression(i,6);o.children.push(a),this._MoveCursorWithinIf(e,o,a);break;case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":o=new s;t.children.push(o);a=this._BuildExpression(i,7);o.children.push(a),this._MoveCursorWithinIf(e,o,a);break;case"#if":o=new s,a=this._BuildExpression(i,3);t.children.push(o),o.children.push(a),this._MoveCursorWithinIf(e,o,a)}}else{var c=new r;if(c.line=i,t.children.push(c),"#"===i[0]&&"d"===i[1]){var l=i.replace(";","").split(" ");c.additionalDefineKey=l[1],3===l.length&&(c.additionalDefineValue=l[2])}}}return!1},e._EvaluatePreProcessors=function(e,t,i){var n=new r,a=new o;return a.lineIndex=-1,a.lines=e.split("\n"),this._MoveCursor(a,n),n.process(t,i)},e._PreparePreProcessors=function(e){for(var t={},i=0,n=e.defines;i<n.length;i++){var r=n[i].replace("#define","").replace(";","").trim().split(" ");t[r[0]]=r.length>1?r[1]:""}return t.GL_ES="true",t.__VERSION__=e.version,t[e.platformName]="true",t},e._ProcessShaderConversion=function(e,t){var i=this._ProcessPrecision(e,t);if(!t.processor)return i;if(-1!==i.indexOf("#version 3"))return i.replace("#version 300 es","");var n=t.defines,r=this._PreparePreProcessors(t);return t.processor.preProcessor&&(i=t.processor.preProcessor(i,n,t.isFragment)),i=this._EvaluatePreProcessors(i,r,t),t.processor.postProcessor&&(i=t.processor.postProcessor(i,n,t.isFragment)),i},e._ProcessIncludes=function(t,i,n){for(var r=this,o=/#include<(.+)>(\((.*)\))*(\[(.*)\])*/g,a=o.exec(t),s=new String(t);null!=a;){var c=a[1];if(-1!==c.indexOf("__decl__")&&(c=c.replace(/__decl__/,""),i.supportsUniformBuffers&&(c=(c=c.replace(/Vertex/,"Ubo")).replace(/Fragment/,"Ubo")),c+="Declaration"),!i.includesShadersStore[c]){var l=i.shadersRepository+"ShadersInclude/"+c+".fx";return void e._FileToolsLoadFile(l,function(e){i.includesShadersStore[c]=e,r._ProcessIncludes(s,i,n)})}var u=i.includesShadersStore[c];if(a[2])for(var h=a[3].split(","),d=0;d<h.length;d+=2){var f=new RegExp(h[d],"g"),p=h[d+1];u=u.replace(f,p)}if(a[4]){var _=a[5];if(-1!==_.indexOf("..")){var m=_.split(".."),g=parseInt(m[0]),v=parseInt(m[1]),y=u.slice(0);u="",isNaN(v)&&(v=i.indexParameters[m[1]]);for(var b=g;b<v;b++)i.supportsUniformBuffers||(y=y.replace(/light\{X\}.(\w*)/g,function(e,t){return t+"{X}"})),u+=y.replace(/\{X\}/g,b.toString())+"\n"}else i.supportsUniformBuffers||(u=u.replace(/light\{X\}.(\w*)/g,function(e,t){return t+"{X}"})),u=u.replace(/\{X\}/g,_)}s=s.replace(a[0],u),a=o.exec(t)}n(s)},e._FileToolsLoadFile=function(e,t,i,n,r,o){throw p.a.WarnImport("FileTools")},e}()},function(e,t,i){"use strict";var n="shadowsFragmentFunctions",r="#ifdef SHADOWS\n#ifndef SHADOWFLOAT\n\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\n#ifdef WEBGL2\nfloat computeShadowCSM(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nvec3 uvLayer=vec3(uv.x,uv.y,layer);\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uvLayer));\n#else\nfloat shadow=texture2D(shadowSampler,uvLayer).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\n#endif\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n#define GREATEST_LESS_THAN_ONE 0.99999994\n\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(uvDepth.z,0.,GREATEST_LESS_THAN_ONE);\nvec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);\nfloat shadow=texture(shadowSampler,uvDepthLayer);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(uvDepth.z,0.,GREATEST_LESS_THAN_ONE);\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;\nuv+=0.5;\nvec2 st=fract(uv);\nvec2 base_uv=floor(uv)-0.5;\nbase_uv*=shadowMapSizeAndInverse.y;\n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(uvDepth.z,0.,GREATEST_LESS_THAN_ONE);\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;\nuv+=0.5;\nvec2 st=fract(uv);\nvec2 base_uv=floor(uv)-0.5;\nbase_uv*=shadowMapSizeAndInverse.y;\n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;\nuv+=0.5;\nvec2 st=fract(uv);\nvec2 base_uv=floor(uv)-0.5;\nbase_uv*=shadowMapSizeAndInverse.y;\n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;\nuv+=0.5;\nvec2 st=fract(uv);\nvec2 base_uv=floor(uv)-0.5;\nbase_uv*=shadowMapSizeAndInverse.y;\n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(uvDepth.z,0.,GREATEST_LESS_THAN_ONE);\nvec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,vec3(uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);\nvec4 filterRadius=vec4(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec4 offset=vec4(poissonSamplers[i],0.);\n\noffset=vec4(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);\nshadow+=texture2D(shadowSampler,uvDepthLayer+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\nfloat computeShadowWithCSMPCSS16(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{\nreturn computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);\n}\nfloat computeShadowWithCSMPCSS32(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{\nreturn computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);\n}\nfloat computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{\nreturn computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);\n}\n#endif\n#endif\n";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="reflectionFunction",r="vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\nvec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)\n{\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y;\nreturn vec3(s,t,0);\n}\nvec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)\n{\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y;\nreturn vec3(1.0-s,t,0);\n}\nvec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{\nvec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nr=vec3(reflectionMatrix*vec4(r,0));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y;\nreturn vec3(s,t,0);\n}\nvec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix)\n{\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr=vec3(reflectionMatrix*vec4(r,0));\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n}\nvec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{\nvec3 viewDir=worldPos.xyz-eyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n}\nvec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{\nvec3 viewDir=normalize(worldPos.xyz-eyePosition);\n\nvec3 coords=reflect(viewDir,worldNormal);\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n}\nvec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition)\n{\nvec3 viewDir=normalize(worldPos.xyz-eyePosition);\n\nvec3 coords=reflect(viewDir,worldNormal);\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n}\nvec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix)\n{\nreturn vec3(reflectionMatrix*(view*worldPos));\n}\nvec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix)\n{\nreturn vec3(reflectionMatrix*vec4(positionW,0));\n}\n#ifdef REFLECTION\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nreturn computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nreturn computeFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nreturn computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nreturn computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nreturn computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_CUBIC\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nreturn computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition);\n#else\nreturn computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn computeProjectionCoords(worldPos,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn computeSkyBoxCoords(vPositionUVW,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="bumpFragmentFunctions",r="#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\nvec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale)\n{\ntextureSample=textureSample*2.0-1.0;\n#ifdef NORMALXYSCALE\ntextureSample=normalize(textureSample*vec3(scale,scale,1.0));\n#endif\nreturn normalize(cotangentFrame*textureSample);\n}\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=tangentSpaceParams.x;\nbitangent*=tangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\n#endif\n#if defined(BUMP)\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nreturn perturbNormal(cotangentFrame,texture2D(bumpSampler,uv).xyz,vBumpInfos.y);\n}\n#endif\n#if defined(BUMP) || defined(CLEARCOAT_BUMP)\nvec3 perturbNormal(mat3 cotangentFrame,vec3 color)\n{\nreturn perturbNormal(cotangentFrame,color,vBumpInfos.y);\n}\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\nreturn cotangent_frame(normal,p,uv,vTangentSpaceParams);\n}\n#endif\n#if defined(BUMP) && defined(PARALLAX)\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else\nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#elif defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW,vPositionW,vMainUV1,vec2(1.,1.));\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW);\n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif";i(8).a.IncludesShadersStore.bumpFragment=n},function(e,t,i){"use strict";var n="lightFragment",r="#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef PBR\n\n#ifdef SPOTLIGHT{X}\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(POINTLIGHT{X})\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(HEMILIGHT{X})\npreInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(DIRLIGHT{X})\npreInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#endif\npreInfo.NdotV=NdotV;\n\n#ifdef SPOTLIGHT{X}\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\npreInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);\npreInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);\npreInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\npreInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\n#elif defined(POINTLIGHT{X})\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\n#else\npreInfo.attenuation=1.0;\n#endif\n\n\n#ifdef HEMILIGHT{X}\npreInfo.roughness=roughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n\n#ifdef HEMILIGHT{X}\ninfo.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround);\n#elif defined(SS_TRANSLUCENCY)\ninfo.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,transmittance);\n#else\ninfo.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb);\n#endif\n\n#ifdef SPECULARTERM\n#ifdef ANISOTROPIC\ninfo.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicTangent,anisotropicBitangent,anisotropy,specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#else\ninfo.specular=computeSpecularLighting(preInfo,normalW,specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#endif\n\n#ifdef SHEEN\n#ifdef SHEEN_LINKWITHALBEDO\n\npreInfo.roughness=sheenIntensity;\n#endif\ninfo.sheen=computeSheenLighting(preInfo,normalW,sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n\n#ifdef CLEARCOAT\n\n#ifdef HEMILIGHT{X}\npreInfo.roughness=clearCoatRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\ninfo.clearCoat=computeClearCoatLighting(preInfo,clearCoatNormalW,clearCoatAARoughnessFactors.x,clearCoatIntensity,light{X}.vLightDiffuse.rgb);\n#ifdef CLEARCOAT_TINT\n\nabsorption=computeClearCoatLightingAbsorption(clearCoatNdotVRefract,preInfo.L,clearCoatNormalW,clearCoatColor,clearCoatThickness,clearCoatIntensity);\ninfo.diffuse*=absorption;\n#ifdef SPECULARTERM\ninfo.specular*=absorption;\n#endif\n#endif\n\ninfo.diffuse*=info.clearCoat.w;\n#ifdef SPECULARTERM\ninfo.specular*=info.clearCoat.w;\n#endif\n#ifdef SHEEN\ninfo.sheen*=info.clearCoat.w;\n#endif\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nfor (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++)\n{\n#ifdef SHADOWCSM_RIGHTHANDED{X}\ndiff{X}=viewFrustumZ{X}[i]+vPositionFromCamera{X}.z;\n#else\ndiff{X}=viewFrustumZ{X}[i]-vPositionFromCamera{X}.z;\n#endif\nif (diff{X}>=0.) {\nindex{X}=i;\nbreak;\n}\n}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nif (index{X}>=0)\n#endif\n{\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#else\nshadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#endif\n#else\nshadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}];\n#endif\n#ifndef SHADOWCSMNOBLEND{X}\nfloat frustumLength=frustumLengths{X}[index{X}];\nfloat diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};\nif (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)\n{\nindex{X}+=1;\nfloat nextShadow=0.;\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nnextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#else\nnextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#endif\n#else\nnextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\nshadow=mix(nextShadow,shadow,diffRatio);\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);\n#endif\n}\n#endif\n}\n#elif defined(SHADOWCLOSEESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor.rgb*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifndef LIGHTMAPNOSPECULAR{X}\nclearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef SHEEN\n#ifndef LIGHTMAPNOSPECULAR{X}\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#else\n#ifdef SHADOWCSMDEBUG{X}\ndiffuseBase+=info.diffuse*shadowDebug{X};\n#else\ndiffuseBase+=info.diffuse*shadow;\n#endif\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#ifdef CLEARCOAT\nclearCoatBase+=info.clearCoat.rgb*shadow;\n#endif\n#ifdef SHEEN\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#endif\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif";i(8).a.IncludesShadersStore.fogFragment=n},function(e,t,i){"use strict";var n="fogVertexDeclaration",r="#ifdef FOG\nvarying vec3 vFogDistance;\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="shadowsVertex",r="#ifdef SHADOWS\n#if defined(SHADOWCSM{X})\nvPositionFromCamera{X}=view*worldPos;\nfor (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) {\nvPositionFromLight{X}[i]=lightMatrix{X}[i]*worldPos;\nvDepthMetric{X}[i]=((vPositionFromLight{X}[i].z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n}\n#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return e.Eval=function(t,i){return"true"===(t=t.match(/\([^\(\)]*\)/g)?t.replace(/\([^\(\)]*\)/g,function(t){return t=t.slice(1,t.length-1),e._HandleParenthesisContent(t,i)}):e._HandleParenthesisContent(t,i))||"false"!==t&&e.Eval(t,i)},e._HandleParenthesisContent=function(t,i){var n;i=i||function(e){return"true"===e};var r=t.split("||");for(var o in r)if(r.hasOwnProperty(o)){var a=e._SimplifyNegation(r[o].trim()),s=a.split("&&");if(s.length>1)for(var c=0;c<s.length;++c){var l=e._SimplifyNegation(s[c].trim());if(!(n="true"!==l&&"false"!==l?"!"===l[0]?!i(l.substring(1)):i(l):"true"===l)){a="false";break}}if(n||"true"===a){n=!0;break}n="true"!==a&&"false"!==a?"!"===a[0]?!i(a.substring(1)):i(a):"true"===a}return n?"true":"false"},e._SimplifyNegation=function(e){return"!true"===(e=(e=e.replace(/^[\s!]+/,function(e){return(e=e.replace(/[\s]/g,function(){return""})).length%2?"!":""})).trim())?e="false":"!false"===e&&(e="true"),e},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return e.ExponentialBackoff=function(e,t){return void 0===e&&(e=3),void 0===t&&(t=500),function(i,n,r){return 0!==n.status||r>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,r)*t}},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,this.reset()}return Object.defineProperty(e.prototype,"isDirty",{get:function(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"zOffset",{get:function(){return this._zOffset},set:function(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cullFace",{get:function(){return this._cullFace},set:function(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cull",{get:function(){return this._cull},set:function(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"depthFunc",{get:function(){return this._depthFunc},set:function(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"depthMask",{get:function(){return this._depthMask},set:function(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"depthTest",{get:function(){return this._depthTest},set:function(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"frontFace",{get:function(){return this._frontFace},set:function(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)},enumerable:!0,configurable:!0}),e.prototype.reset=function(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1},e.prototype.apply=function(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?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,0)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r});var n=i(2),r=function(){function e(){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.reset()}return Object.defineProperty(e.prototype,"isDirty",{get:function(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stencilFunc",{get:function(){return this._stencilFunc},set:function(e){this._stencilFunc!==e&&(this._stencilFunc=e,this._isStencilFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stencilFuncRef",{get:function(){return this._stencilFuncRef},set:function(e){this._stencilFuncRef!==e&&(this._stencilFuncRef=e,this._isStencilFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stencilFuncMask",{get:function(){return this._stencilFuncMask},set:function(e){this._stencilFuncMask!==e&&(this._stencilFuncMask=e,this._isStencilFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stencilOpStencilFail",{get:function(){return this._stencilOpStencilFail},set:function(e){this._stencilOpStencilFail!==e&&(this._stencilOpStencilFail=e,this._isStencilOpDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stencilOpDepthFail",{get:function(){return this._stencilOpDepthFail},set:function(e){this._stencilOpDepthFail!==e&&(this._stencilOpDepthFail=e,this._isStencilOpDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stencilOpStencilDepthPass",{get:function(){return this._stencilOpStencilDepthPass},set:function(e){this._stencilOpStencilDepthPass!==e&&(this._stencilOpStencilDepthPass=e,this._isStencilOpDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stencilMask",{get:function(){return this._stencilMask},set:function(e){this._stencilMask!==e&&(this._stencilMask=e,this._isStencilMaskDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stencilTest",{get:function(){return this._stencilTest},set:function(e){this._stencilTest!==e&&(this._stencilTest=e,this._isStencilTestDirty=!0)},enumerable:!0,configurable:!0}),e.prototype.reset=function(){this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=e.ALWAYS,this._stencilFuncRef=1,this._stencilFuncMask=255,this._stencilOpStencilFail=e.KEEP,this._stencilOpDepthFail=e.KEEP,this._stencilOpStencilDepthPass=e.REPLACE,this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0},e.prototype.apply=function(e){this.isDirty&&(this._isStencilTestDirty&&(this.stencilTest?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.stencilMask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.stencilFunc,this.stencilFuncRef,this.stencilFuncMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.stencilOpStencilFail,this.stencilOpDepthFail,this.stencilOpStencilDepthPass),this._isStencilOpDirty=!1))},e.ALWAYS=n.a.ALWAYS,e.KEEP=n.a.KEEP,e.REPLACE=n.a.REPLACE,e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._blendFunctionParameters=new Array(4),this._blendEquationParameters=new Array(2),this._blendConstants=new Array(4),this.reset()}return Object.defineProperty(e.prototype,"isDirty",{get:function(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"alphaBlend",{get:function(){return this._alphaBlend},set:function(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)},enumerable:!0,configurable:!0}),e.prototype.setAlphaBlendConstants=function(e,t,i,n){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===n||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=n,this._isBlendConstantsDirty=!0)},e.prototype.setAlphaBlendFunctionParameters=function(e,t,i,n){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===i&&this._blendFunctionParameters[3]===n||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=n,this._isBlendFunctionParametersDirty=!0)},e.prototype.setAlphaEquationParameters=function(e,t){this._blendEquationParameters[0]===e&&this._blendEquationParameters[1]===t||(this._blendEquationParameters[0]=e,this._blendEquationParameters[1]=t,this._isBlendEquationParametersDirty=!0)},e.prototype.reset=function(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=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},e.prototype.apply=function(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?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),this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null}return Object.defineProperty(e.prototype,"isAsync",{get:function(){return this.isParallelCompiled},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isReady",{get:function(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))},enumerable:!0,configurable:!0}),e.prototype._handlesSpectorRebuildCallback=function(e){e&&this.program&&e(this.program)},e}()},function(e,t,i){"use strict";var n;i.d(t,"a",function(){return a}),function(e){e[e.Pending=0]="Pending",e[e.Fulfilled=1]="Fulfilled",e[e.Rejected=2]="Rejected"}(n||(n={}));var r=function(){this.count=0,this.target=0,this.results=[]},o=function(){function e(e){var t=this;if(this._state=n.Pending,this._children=new Array,this._rejectWasConsumed=!1,e)try{e(function(e){t._resolve(e)},function(e){t._reject(e)})}catch(e){this._reject(e)}}return Object.defineProperty(e.prototype,"_result",{get:function(){return this._resultValue},set:function(e){this._resultValue=e,this._parent&&void 0===this._parent._result&&(this._parent._result=e)},enumerable:!0,configurable:!0}),e.prototype.catch=function(e){return this.then(void 0,e)},e.prototype.then=function(t,i){var r=this,o=new e;return o._onFulfilled=t,o._onRejected=i,this._children.push(o),o._parent=this,this._state!==n.Pending&&setTimeout(function(){if(r._state===n.Fulfilled||r._rejectWasConsumed){var e=o._resolve(r._result);if(null!=e)if(void 0!==e._state){var t=e;o._children.push(t),t._parent=o,o=t}else o._result=e}else o._reject(r._reason)}),o},e.prototype._moveChildren=function(e){var t,i=this;if((t=this._children).push.apply(t,e.splice(0,e.length)),this._children.forEach(function(e){e._parent=i}),this._state===n.Fulfilled)for(var r=0,o=this._children;r<o.length;r++){o[r]._resolve(this._result)}else if(this._state===n.Rejected)for(var a=0,s=this._children;a<s.length;a++){s[a]._reject(this._reason)}},e.prototype._resolve=function(e){try{this._state=n.Fulfilled;var t=null;if(this._onFulfilled&&(t=this._onFulfilled(e)),null!=t)if(void 0!==t._state){var i=t;i._parent=this,i._moveChildren(this._children),e=i._result}else e=t;this._result=e;for(var r=0,o=this._children;r<o.length;r++){o[r]._resolve(e)}this._children.length=0,delete this._onFulfilled,delete this._onRejected}catch(e){this._reject(e,!0)}},e.prototype._reject=function(e,t){if(void 0===t&&(t=!1),this._state=n.Rejected,this._reason=e,this._onRejected&&!t)try{this._onRejected(e),this._rejectWasConsumed=!0}catch(t){e=t}for(var i=0,r=this._children;i<r.length;i++){var o=r[i];this._rejectWasConsumed?o._resolve(null):o._reject(e)}this._children.length=0,delete this._onFulfilled,delete this._onRejected},e.resolve=function(t){var i=new e;return i._resolve(t),i},e._RegisterForFulfillment=function(e,t,i){e.then(function(e){return t.results[i]=e,t.count++,t.count===t.target&&t.rootPromise._resolve(t.results),null},function(e){t.rootPromise._state!==n.Rejected&&t.rootPromise._reject(e)})},e.all=function(t){var i=new e,n=new r;if(n.target=t.length,n.rootPromise=i,t.length)for(var o=0;o<t.length;o++)e._RegisterForFulfillment(t[o],n,o);else i._resolve([]);return i},e.race=function(t){var i=new e;if(t.length)for(var n=0,r=t;n<r.length;n++){r[n].then(function(e){return i&&(i._resolve(e),i=null),null},function(e){i&&(i._reject(e),i=null)})}return i},e}(),a=function(){function e(){}return e.Apply=function(e){(void 0===e&&(e=!1),e||"undefined"==typeof Promise)&&(window.Promise=o)},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r}),i.d(t,"b",function(){return o});var n=i(52),r=function(){function e(e){void 0===e&&(e=30),this._enabled=!0,this._rollingFrameTime=new o(e)}return e.prototype.sampleFrame=function(e){if(void 0===e&&(e=n.a.Now),this._enabled){if(null!=this._lastFrameTimeMs){var t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}},Object.defineProperty(e.prototype,"averageFrameTime",{get:function(){return this._rollingFrameTime.average},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"averageFrameTimeVariance",{get:function(){return this._rollingFrameTime.variance},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"instantaneousFrameTime",{get:function(){return this._rollingFrameTime.history(0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"averageFPS",{get:function(){return 1e3/this._rollingFrameTime.average},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"instantaneousFPS",{get:function(){var e=this._rollingFrameTime.history(0);return 0===e?0:1e3/e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isSaturated",{get:function(){return this._rollingFrameTime.isSaturated()},enumerable:!0,configurable:!0}),e.prototype.enable=function(){this._enabled=!0},e.prototype.disable=function(){this._enabled=!1,this._lastFrameTimeMs=null},Object.defineProperty(e.prototype,"isEnabled",{get:function(){return this._enabled},enumerable:!0,configurable:!0}),e.prototype.reset=function(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()},e}(),o=function(){function e(e){this._samples=new Array(e),this.reset()}return e.prototype.add=function(e){var t;if(this.isSaturated()){var 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},e.prototype.history=function(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;var t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]},e.prototype.isSaturated=function(){return this._sampleCount>=this._samples.length},e.prototype.reset=function(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0},e.prototype._wrapPosition=function(e){var t=this._samples.length;return(e%t+t)%t},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r});var n=i(0),r=function(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._collider=null,this._oldPositionForCollisions=new n.e(0,0,0),this._diffPositionForCollisions=new n.e(0,0,0)}},function(e,t,i){"use strict";i.d(t,"a",function(){return a});var n=i(34),r=i(0),o=i(2),a=function(){function e(e,t,i,r,o){void 0===i&&(i=null),void 0===r&&(r=null),void 0===o&&(o=null),this.index=e,this._opaqueSubMeshes=new n.a(256),this._transparentSubMeshes=new n.a(256),this._alphaTestSubMeshes=new n.a(256),this._depthOnlySubMeshes=new n.a(256),this._particleSystems=new n.a(256),this._spriteManagers=new n.a(256),this._edgesRenderers=new n.a(16),this._scene=t,this.opaqueSortCompareFn=i,this.alphaTestSortCompareFn=r,this.transparentSortCompareFn=o}return Object.defineProperty(e.prototype,"opaqueSortCompareFn",{set:function(t){this._opaqueSortCompareFn=t,this._renderOpaque=t?this.renderOpaqueSorted:e.renderUnsorted},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"alphaTestSortCompareFn",{set:function(t){this._alphaTestSortCompareFn=t,this._renderAlphaTest=t?this.renderAlphaTestSorted:e.renderUnsorted},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transparentSortCompareFn",{set:function(t){this._transparentSortCompareFn=t||e.defaultTransparentSortCompare,this._renderTransparent=this.renderTransparentSorted},enumerable:!0,configurable:!0}),e.prototype.render=function(e,t,i,n){if(e)e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);else{var r=this._scene.getEngine();0!==this._depthOnlySubMeshes.length&&(r.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),r.setColorWrite(!0)),0!==this._opaqueSubMeshes.length&&this._renderOpaque(this._opaqueSubMeshes),0!==this._alphaTestSubMeshes.length&&this._renderAlphaTest(this._alphaTestSubMeshes);var a=r.getStencilBuffer();if(r.setStencilBuffer(!1),t&&this._renderSprites(),i&&this._renderParticles(n),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),0!==this._transparentSubMeshes.length&&(this._renderTransparent(this._transparentSubMeshes),r.setAlphaMode(o.a.ALPHA_DISABLE)),r.setStencilBuffer(!1),this._edgesRenderers.length){for(var s=0;s<this._edgesRenderers.length;s++)this._edgesRenderers.data[s].render();r.setAlphaMode(o.a.ALPHA_DISABLE)}r.setStencilBuffer(a)}},e.prototype.renderOpaqueSorted=function(t){return e.renderSorted(t,this._opaqueSortCompareFn,this._scene.activeCamera,!1)},e.prototype.renderAlphaTestSorted=function(t){return e.renderSorted(t,this._alphaTestSortCompareFn,this._scene.activeCamera,!1)},e.prototype.renderTransparentSorted=function(t){return e.renderSorted(t,this._transparentSortCompareFn,this._scene.activeCamera,!0)},e.renderSorted=function(t,i,n,a){for(var s,c=0,l=n?n.globalPosition:e._zeroVector;c<t.length;c++)(s=t.data[c])._alphaIndex=s.getMesh().alphaIndex,s._distanceToCamera=r.e.Distance(s.getBoundingInfo().boundingSphere.centerWorld,l);var u=t.data.slice(0,t.length);for(i&&u.sort(i),c=0;c<u.length;c++){if(s=u[c],a){var h=s.getMaterial();if(h&&h.needDepthPrePass){var d=h.getScene().getEngine();d.setColorWrite(!1),d.setAlphaMode(o.a.ALPHA_DISABLE),s.render(!1),d.setColorWrite(!0)}}s.render(a)}},e.renderUnsorted=function(e){for(var t=0;t<e.length;t++){e.data[t].render(!1)}},e.defaultTransparentSortCompare=function(t,i){return t._alphaIndex>i._alphaIndex?1:t._alphaIndex<i._alphaIndex?-1:e.backToFrontSortCompare(t,i)},e.backToFrontSortCompare=function(e,t){return e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0},e.frontToBackSortCompare=function(e,t){return e._distanceToCamera<t._distanceToCamera?-1:e._distanceToCamera>t._distanceToCamera?1:0},e.prototype.prepare=function(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this._spriteManagers.reset(),this._edgesRenderers.reset()},e.prototype.dispose=function(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()},e.prototype.dispatch=function(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t._edgesRenderer.isEnabled&&this._edgesRenderers.push(t._edgesRenderer))},e.prototype.dispatchSprites=function(e){this._spriteManagers.push(e)},e.prototype.dispatchParticles=function(e){this._particleSystems.push(e)},e.prototype._renderParticles=function(e){if(0!==this._particleSystems.length){var t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(var i=0;i<this._particleSystems.length;i++){var n=this._particleSystems.data[i];if(0!==(t&&t.layerMask&n.layerMask)){var r=n.emitter;r.position&&e&&-1===e.indexOf(r)||this._scene._activeParticles.addCount(n.render(),!1)}}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}},e.prototype._renderSprites=function(){if(this._scene.spritesEnabled&&0!==this._spriteManagers.length){var e=this._scene.activeCamera;this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);for(var t=0;t<this._spriteManagers.length;t++){var i=this._spriteManagers.data[t];0!==(e&&e.layerMask&i.layerMask)&&i.render()}this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)}},e._zeroVector=r.e.Zero(),e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(e,t){this.distance=e,this.mesh=t}},function(e,t,i){"use strict";i.d(t,"a",function(){return h});var n=i(1),r=i(0),o=i(7),a=i(27),s=i(5),c=i(33),l=i(43),u=i(4);s.a._instancedMeshFactory=function(e,t){var i=new h(e,t);if(t.instancedBuffers)for(var n in i.instancedBuffers={},t.instancedBuffers)i.instancedBuffers[n]=t.instancedBuffers[n];return i};var h=function(e){function t(t,i){var n=e.call(this,t,i.getScene())||this;n._indexInSourceMeshInstanceArray=-1,i.addInstance(n),n._sourceMesh=i,n._unIndexed=i._unIndexed,n.position.copyFrom(i.position),n.rotation.copyFrom(i.rotation),n.scaling.copyFrom(i.scaling),i.rotationQuaternion&&(n.rotationQuaternion=i.rotationQuaternion.clone()),n.animations=i.animations;for(var r=0,o=i.getAnimationRanges();r<o.length;r++){var a=o[r];null!=a&&n.createAnimationRange(a.name,a.from,a.to)}return n.infiniteDistance=i.infiniteDistance,n.setPivotMatrix(i.getPivotMatrix()),n.refreshBoundingInfo(),n._syncSubMeshes(),n}return Object(n.d)(t,e),t.prototype.getClassName=function(){return"InstancedMesh"},Object.defineProperty(t.prototype,"lightSources",{get:function(){return this._sourceMesh._lightSources},enumerable:!0,configurable:!0}),t.prototype._resyncLightSources=function(){},t.prototype._resyncLightSource=function(e){},t.prototype._removeLightSource=function(e,t){},Object.defineProperty(t.prototype,"receiveShadows",{get:function(){return this._sourceMesh.receiveShadows},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"material",{get:function(){return this._sourceMesh.material},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visibility",{get:function(){return this._sourceMesh.visibility},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skeleton",{get:function(){return this._sourceMesh.skeleton},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderingGroupId",{get:function(){return this._sourceMesh.renderingGroupId},set:function(e){this._sourceMesh&&e!==this._sourceMesh.renderingGroupId&&o.a.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")},enumerable:!0,configurable:!0}),t.prototype.getTotalVertices=function(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0},t.prototype.getTotalIndices=function(){return this._sourceMesh.getTotalIndices()},Object.defineProperty(t.prototype,"sourceMesh",{get:function(){return this._sourceMesh},enumerable:!0,configurable:!0}),t.prototype.isReady=function(e){return void 0===e&&(e=!1),this._sourceMesh.isReady(e,!0)},t.prototype.getVerticesData=function(e,t){return this._sourceMesh.getVerticesData(e,t)},t.prototype.setVerticesData=function(e,t,i,n){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,n),this.sourceMesh},t.prototype.updateVerticesData=function(e,t,i,n){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,n),this.sourceMesh},t.prototype.setIndices=function(e,t){return void 0===t&&(t=null),this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh},t.prototype.isVerticesDataPresent=function(e){return this._sourceMesh.isVerticesDataPresent(e)},t.prototype.getIndices=function(){return this._sourceMesh.getIndices()},Object.defineProperty(t.prototype,"_positions",{get:function(){return this._sourceMesh._positions},enumerable:!0,configurable:!0}),t.prototype.refreshBoundingInfo=function(e){if(void 0===e&&(e=!1),this._boundingInfo&&this._boundingInfo.isLocked)return this;var t=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e),t),this},t.prototype._preActivate=function(){return this._currentLOD&&this._currentLOD._preActivate(),this},t.prototype._activate=function(e,t){if(this._sourceMesh.subMeshes||o.a.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},t.prototype._postActivate=function(){this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)},t.prototype.getWorldMatrix=function(){if(this._currentLOD&&this._currentLOD.billboardMode!==l.a.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){var t=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,r.c.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),r.c.Matrix[0].copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(r.c.Vector3[7]),this._currentLOD._masterMesh=t,r.c.Matrix[0]}return e.prototype.getWorldMatrix.call(this)},Object.defineProperty(t.prototype,"isAnInstance",{get:function(){return!0},enumerable:!0,configurable:!0}),t.prototype.getLOD=function(e){if(!e)return this;var t=this.getBoundingInfo();return this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere),this._currentLOD===this.sourceMesh?this.sourceMesh:this._currentLOD},t.prototype._preActivateForIntermediateRendering=function(e){return this.sourceMesh._preActivateForIntermediateRendering(e)},t.prototype._syncSubMeshes=function(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(var e=0;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh);return this},t.prototype._generatePointsArray=function(){return this._sourceMesh._generatePointsArray()},t.prototype.clone=function(e,t,i){void 0===t&&(t=null);var n=this._sourceMesh.createInstance(e);if(c.a.DeepCopy(this,n,["name","subMeshes","uniqueId","parent"],[]),this.refreshBoundingInfo(),t&&(n.parent=t),!i)for(var r=0;r<this.getScene().meshes.length;r++){var o=this.getScene().meshes[r];o.parent===this&&o.clone(o.name,n)}return n.computeWorldMatrix(!0),n},t.prototype.dispose=function(t,i){void 0===i&&(i=!1),this._sourceMesh.removeInstance(this),e.prototype.dispose.call(this,t,i)},t}(a.a);s.a.prototype.registerInstancedBuffer=function(e,t){if(this.removeVerticesData(e),!this.instancedBuffers){this.instancedBuffers={};for(var i=0,n=this.instances;i<n.length;i++){n[i].instancedBuffers={}}this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{}}}this.instancedBuffers[e]=null,this._userInstancedBuffersStorage.strides[e]=t,this._userInstancedBuffersStorage.sizes[e]=32*t,this._userInstancedBuffersStorage.data[e]=new Float32Array(this._userInstancedBuffersStorage.sizes[e]),this._userInstancedBuffersStorage.vertexBuffers[e]=new u.b(this.getEngine(),this._userInstancedBuffersStorage.data[e],e,!0,!1,t,!0),this.setVerticesBuffer(this._userInstancedBuffersStorage.vertexBuffers[e]);for(var r=0,o=this.instances;r<o.length;r++){o[r].instancedBuffers[e]=null}},s.a.prototype._processInstancedBuffers=function(e,t){var i=e.length;for(var n in this.instancedBuffers){for(var r=this._userInstancedBuffersStorage.sizes[n],o=this._userInstancedBuffersStorage.strides[n],a=(i+1)*o;r<a;)r*=2;this._userInstancedBuffersStorage.data[n].length!=r&&(this._userInstancedBuffersStorage.data[n]=new Float32Array(r),this._userInstancedBuffersStorage.sizes[n]=r,this._userInstancedBuffersStorage.vertexBuffers[n]&&(this._userInstancedBuffersStorage.vertexBuffers[n].dispose(),this._userInstancedBuffersStorage.vertexBuffers[n]=null));var s=this._userInstancedBuffersStorage.data[n],c=0;if(t)c+=o,(h=this.instancedBuffers[n]).toArray?h.toArray(s,c):h.copyToArray(s,c);for(var l=0;l<i;l++){var h;(h=e[l].instancedBuffers[n]).toArray?h.toArray(s,c):h.copyToArray(s,c),c+=o}this._userInstancedBuffersStorage.vertexBuffers[n]?this._userInstancedBuffersStorage.vertexBuffers[n].updateDirectly(s,0):(this._userInstancedBuffersStorage.vertexBuffers[n]=new u.b(this.getEngine(),this._userInstancedBuffersStorage.data[n],n,!0,!1,o,!0),this.setVerticesBuffer(this._userInstancedBuffersStorage.vertexBuffers[n]))}},s.a.prototype._disposeInstanceSpecificData=function(){for(this._instanceDataStorage.instancesBuffer&&(this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null);this.instances.length;)this.instances[0].dispose();for(var e in this.instancedBuffers)this._userInstancedBuffersStorage.vertexBuffers[e]&&this._userInstancedBuffersStorage.vertexBuffers[e].dispose();this.instancedBuffers={}}},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return e.RandomId=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return Object.defineProperty(e,"UniqueId",{get:function(){var e=this._UniqueIdCounter;return this._UniqueIdCounter++,e},enumerable:!0,configurable:!0}),e._UniqueIdCounter=0,e}()},function(e,t,i){"use strict";var n="lightsFragmentFunctions",r="\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="logDepthFragment",r="#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif";i(8).a.IncludesShadersStore.bumpVertex=n},function(e,t,i){"use strict";var n="#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif";i(8).a.IncludesShadersStore.fogVertex=n},function(e,t,i){"use strict";var n="logDepthVertex",r="#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t){var i;i=function(){return this}();try{i=i||new Function("return this")()}catch(e){"object"==typeof window&&(i=window)}e.exports=i},function(e,t,i){"use strict";var n="fresnelFunction",r="#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif";i(8).a.IncludesShadersStore.depthPrePass=n},function(e,t,i){"use strict";var n="bumpVertexDeclaration",r="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP)\n#if defined(TANGENT) && defined(NORMAL)\nvarying mat3 vTBN;\n#endif\n#endif\n";i(8).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n=i(8),r=(i(106),i(101),"colorPixelShader"),o="#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include<clipPlaneFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}";n.a.ShadersStore[r]=o},function(e,t,i){"use strict";var n=i(8),r=(i(74),i(108),i(77),i(78),i(75),i(102),"colorVertexShader"),o="\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n#include<clipPlaneVertexDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR == 0u) {\ngl_Position=viewProjection*worldPos;\n} else {\ngl_Position=viewProjectionR*worldPos;\n}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include<clipPlaneVertex>\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}";n.a.ShadersStore[r]=o},function(e,t,i){"use strict";(function(e){i.d(t,"b",function(){return u}),i.d(t,"a",function(){return h});var n=i(1),r=i(7),o=i(11),a=i(95),s=i(25),c=i(2),l=i(85),u=function(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4},h=function(t){function i(i){void 0===i&&(i=new u);var n=t.call(this,null)||this;o.a.Instances.push(n),void 0===i.deterministicLockstep&&(i.deterministicLockstep=!1),void 0===i.lockstepMaxSteps&&(i.lockstepMaxSteps=4),n._options=i,n._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:512,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!1,astc:null,pvrtc:null,etc1:null,etc2:null,maxAnisotropy:0,uintIndices:!1,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,textureFloat:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!1,instancedArrays:!1,canUseTimestampForTimerQuery:!1,maxMSAASamples:1,blendMinMax:!1},r.a.Log("Babylon.js v"+o.a.Version+" - Null engine");var a="undefined"!=typeof self?self:void 0!==e?e:window;return"undefined"==typeof URL&&(a.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(a.Blob=function(){}),n}return Object(n.d)(i,t),i.prototype.isDeterministicLockStep=function(){return this._options.deterministicLockstep},i.prototype.getLockstepMaxSteps=function(){return this._options.lockstepMaxSteps},i.prototype.getHardwareScalingLevel=function(){return 1},i.prototype.createVertexBuffer=function(e){var t=new l.a;return t.references=1,t},i.prototype.createIndexBuffer=function(e){var t=new l.a;return t.references=1,t},i.prototype.clear=function(e,t,i,n){void 0===n&&(n=!1)},i.prototype.getRenderWidth=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth},i.prototype.getRenderHeight=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight},i.prototype.setViewport=function(e,t,i){this._cachedViewport=e},i.prototype.createShaderProgram=function(e,t,i,n,r){return{__SPECTOR_rebuildProgram:null}},i.prototype.getUniforms=function(e,t){return[]},i.prototype.getAttributes=function(e,t){return[]},i.prototype.bindSamplers=function(e){this._currentEffect=null},i.prototype.enableEffect=function(e){this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e)},i.prototype.setState=function(e,t,i,n){void 0===t&&(t=0),void 0===n&&(n=!1)},i.prototype.setIntArray=function(e,t){},i.prototype.setIntArray2=function(e,t){},i.prototype.setIntArray3=function(e,t){},i.prototype.setIntArray4=function(e,t){},i.prototype.setFloatArray=function(e,t){},i.prototype.setFloatArray2=function(e,t){},i.prototype.setFloatArray3=function(e,t){},i.prototype.setFloatArray4=function(e,t){},i.prototype.setArray=function(e,t){},i.prototype.setArray2=function(e,t){},i.prototype.setArray3=function(e,t){},i.prototype.setArray4=function(e,t){},i.prototype.setMatrices=function(e,t){},i.prototype.setMatrix3x3=function(e,t){},i.prototype.setMatrix2x2=function(e,t){},i.prototype.setFloat=function(e,t){},i.prototype.setFloat2=function(e,t,i){},i.prototype.setFloat3=function(e,t,i,n){},i.prototype.setBool=function(e,t){},i.prototype.setFloat4=function(e,t,i,n,r){},i.prototype.setAlphaMode=function(e,t){void 0===t&&(t=!1),this._alphaMode!==e&&(this.alphaState.alphaBlend=e!==c.a.ALPHA_DISABLE,t||this.setDepthWrite(e===c.a.ALPHA_DISABLE),this._alphaMode=e)},i.prototype.bindBuffers=function(e,t,i){},i.prototype.wipeCaches=function(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this.stencilState.reset(),this.depthCullingState.reset(),this.alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)},i.prototype.draw=function(e,t,i,n){},i.prototype.drawElementsType=function(e,t,i,n){},i.prototype.drawArraysType=function(e,t,i,n){},i.prototype._createTexture=function(){return{}},i.prototype._releaseTexture=function(e){},i.prototype.createTexture=function(e,t,i,n,r,o,a,l,u,h,d,f){void 0===r&&(r=c.a.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===o&&(o=null),void 0===a&&(a=null),void 0===l&&(l=null),void 0===u&&(u=null),void 0===h&&(h=null),void 0===d&&(d=null);var p=new s.a(this,s.b.Url),_=String(e);return p.url=_,p.generateMipMaps=!t,p.samplingMode=r,p.invertY=i,p.baseWidth=this._options.textureSize,p.baseHeight=this._options.textureSize,p.width=this._options.textureSize,p.height=this._options.textureSize,h&&(p.format=h),p.isReady=!0,o&&o(),this._internalTexturesCache.push(p),p},i.prototype.createRenderTargetTexture=function(e,t){var i=new a.a;void 0!==t&&"object"==typeof t?(i.generateMipMaps=t.generateMipMaps,i.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,i.generateStencilBuffer=i.generateDepthBuffer&&t.generateStencilBuffer,i.type=void 0===t.type?c.a.TEXTURETYPE_UNSIGNED_INT:t.type,i.samplingMode=void 0===t.samplingMode?c.a.TEXTURE_TRILINEAR_SAMPLINGMODE:t.samplingMode):(i.generateMipMaps=t,i.generateDepthBuffer=!0,i.generateStencilBuffer=!1,i.type=c.a.TEXTURETYPE_UNSIGNED_INT,i.samplingMode=c.a.TEXTURE_TRILINEAR_SAMPLINGMODE);var n=new s.a(this,s.b.RenderTarget),r=e.width||e,o=e.height||e;return n._depthStencilBuffer={},n._framebuffer={},n.baseWidth=r,n.baseHeight=o,n.width=r,n.height=o,n.isReady=!0,n.samples=1,n.generateMipMaps=!!i.generateMipMaps,n.samplingMode=i.samplingMode,n.type=i.type,n._generateDepthBuffer=i.generateDepthBuffer,n._generateStencilBuffer=!!i.generateStencilBuffer,this._internalTexturesCache.push(n),n},i.prototype.updateTextureSamplingMode=function(e,t){t.samplingMode=e},i.prototype.bindFramebuffer=function(e,t,i,n,r){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=e._MSAAFramebuffer?e._MSAAFramebuffer:e._framebuffer,this._cachedViewport&&!r&&this.setViewport(this._cachedViewport,i,n)},i.prototype.unBindFramebuffer=function(e,t,i){void 0===t&&(t=!1),this._currentRenderTarget=null,i&&(e._MSAAFramebuffer&&(this._currentFramebuffer=e._framebuffer),i()),this._currentFramebuffer=null},i.prototype.createDynamicVertexBuffer=function(e){var t=new l.a;return t.references=1,t.capacity=1,t},i.prototype.updateDynamicTexture=function(e,t,i,n,r){void 0===n&&(n=!1)},i.prototype.areAllEffectsReady=function(){return!0},i.prototype.getError=function(){return 0},i.prototype._getUnpackAlignement=function(){return 1},i.prototype._unpackFlipY=function(e){},i.prototype.updateDynamicIndexBuffer=function(e,t,i){void 0===i&&(i=0)},i.prototype.updateDynamicVertexBuffer=function(e,t,i,n){},i.prototype._bindTextureDirectly=function(e,t){return this._boundTexturesCache[this._activeChannel]!==t&&(this._boundTexturesCache[this._activeChannel]=t,!0)},i.prototype._bindTexture=function(e,t){e<0||this._bindTextureDirectly(0,t)},i.prototype._deleteBuffer=function(e){},i.prototype.releaseEffects=function(){},i.prototype.displayLoadingUI=function(){},i.prototype.hideLoadingUI=function(){},i.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,n,r,o,a){void 0===o&&(o=0),void 0===a&&(a=0)},i.prototype._uploadDataToTextureDirectly=function(e,t,i,n){void 0===i&&(i=0),void 0===n&&(n=0)},i.prototype._uploadArrayBufferViewToTexture=function(e,t,i,n){void 0===i&&(i=0),void 0===n&&(n=0)},i.prototype._uploadImageToTexture=function(e,t,i,n){void 0===i&&(i=0),void 0===n&&(n=0)},i}(o.a)}).call(this,i(144))},function(e,t,i){"use strict";i.r(t),function(e){i.d(t,"Debug",function(){return l});var n=i(114),r=i(93);i.d(t,"AbstractScene",function(){return n.AbstractScene}),i.d(t,"KeepAssets",function(){return n.KeepAssets}),i.d(t,"InstantiatedEntries",function(){return n.InstantiatedEntries}),i.d(t,"AssetContainer",function(){return n.AssetContainer}),i.d(t,"Node",function(){return n.Node}),i.d(t,"Scene",function(){return n.Scene}),i.d(t,"SceneComponentConstants",function(){return n.SceneComponentConstants}),i.d(t,"Stage",function(){return n.Stage}),i.d(t,"AbstractActionManager",function(){return n.AbstractActionManager}),i.d(t,"Action",function(){return n.Action}),i.d(t,"ActionEvent",function(){return n.ActionEvent}),i.d(t,"ActionManager",function(){return n.ActionManager}),i.d(t,"Condition",function(){return n.Condition}),i.d(t,"ValueCondition",function(){return n.ValueCondition}),i.d(t,"PredicateCondition",function(){return n.PredicateCondition}),i.d(t,"StateCondition",function(){return n.StateCondition}),i.d(t,"SwitchBooleanAction",function(){return n.SwitchBooleanAction}),i.d(t,"SetStateAction",function(){return n.SetStateAction}),i.d(t,"SetValueAction",function(){return n.SetValueAction}),i.d(t,"IncrementValueAction",function(){return n.IncrementValueAction}),i.d(t,"PlayAnimationAction",function(){return n.PlayAnimationAction}),i.d(t,"StopAnimationAction",function(){return n.StopAnimationAction}),i.d(t,"DoNothingAction",function(){return n.DoNothingAction}),i.d(t,"CombineAction",function(){return n.CombineAction}),i.d(t,"ExecuteCodeAction",function(){return n.ExecuteCodeAction}),i.d(t,"SetParentAction",function(){return n.SetParentAction}),i.d(t,"PlaySoundAction",function(){return n.PlaySoundAction}),i.d(t,"StopSoundAction",function(){return n.StopSoundAction}),i.d(t,"InterpolateValueAction",function(){return n.InterpolateValueAction}),i.d(t,"Animatable",function(){return n.Animatable}),i.d(t,"_IAnimationState",function(){return n._IAnimationState}),i.d(t,"Animation",function(){return n.Animation}),i.d(t,"TargetedAnimation",function(){return n.TargetedAnimation}),i.d(t,"AnimationGroup",function(){return n.AnimationGroup}),i.d(t,"AnimationPropertiesOverride",function(){return n.AnimationPropertiesOverride}),i.d(t,"EasingFunction",function(){return n.EasingFunction}),i.d(t,"CircleEase",function(){return n.CircleEase}),i.d(t,"BackEase",function(){return n.BackEase}),i.d(t,"BounceEase",function(){return n.BounceEase}),i.d(t,"CubicEase",function(){return n.CubicEase}),i.d(t,"ElasticEase",function(){return n.ElasticEase}),i.d(t,"ExponentialEase",function(){return n.ExponentialEase}),i.d(t,"PowerEase",function(){return n.PowerEase}),i.d(t,"QuadraticEase",function(){return n.QuadraticEase}),i.d(t,"QuarticEase",function(){return n.QuarticEase}),i.d(t,"QuinticEase",function(){return n.QuinticEase}),i.d(t,"SineEase",function(){return n.SineEase}),i.d(t,"BezierCurveEase",function(){return n.BezierCurveEase}),i.d(t,"RuntimeAnimation",function(){return n.RuntimeAnimation}),i.d(t,"AnimationEvent",function(){return n.AnimationEvent}),i.d(t,"AnimationKeyInterpolation",function(){return n.AnimationKeyInterpolation}),i.d(t,"AnimationRange",function(){return n.AnimationRange}),i.d(t,"Analyser",function(){return n.Analyser}),i.d(t,"AudioEngine",function(){return n.AudioEngine}),i.d(t,"AudioSceneComponent",function(){return n.AudioSceneComponent}),i.d(t,"Sound",function(){return n.Sound}),i.d(t,"SoundTrack",function(){return n.SoundTrack}),i.d(t,"WeightedSound",function(){return n.WeightedSound}),i.d(t,"Bone",function(){return n.Bone}),i.d(t,"BoneIKController",function(){return n.BoneIKController}),i.d(t,"BoneLookController",function(){return n.BoneLookController}),i.d(t,"Skeleton",function(){return n.Skeleton}),i.d(t,"CameraInputTypes",function(){return n.CameraInputTypes}),i.d(t,"CameraInputsManager",function(){return n.CameraInputsManager}),i.d(t,"Camera",function(){return n.Camera}),i.d(t,"TargetCamera",function(){return n.TargetCamera}),i.d(t,"FreeCamera",function(){return n.FreeCamera}),i.d(t,"FreeCameraInputsManager",function(){return n.FreeCameraInputsManager}),i.d(t,"TouchCamera",function(){return n.TouchCamera}),i.d(t,"ArcRotateCamera",function(){return n.ArcRotateCamera}),i.d(t,"ArcRotateCameraInputsManager",function(){return n.ArcRotateCameraInputsManager}),i.d(t,"DeviceOrientationCamera",function(){return n.DeviceOrientationCamera}),i.d(t,"FlyCamera",function(){return n.FlyCamera}),i.d(t,"FlyCameraInputsManager",function(){return n.FlyCameraInputsManager}),i.d(t,"FollowCamera",function(){return n.FollowCamera}),i.d(t,"ArcFollowCamera",function(){return n.ArcFollowCamera}),i.d(t,"FollowCameraInputsManager",function(){return n.FollowCameraInputsManager}),i.d(t,"GamepadCamera",function(){return n.GamepadCamera}),i.d(t,"UniversalCamera",function(){return n.UniversalCamera}),i.d(t,"VirtualJoysticksCamera",function(){return n.VirtualJoysticksCamera}),i.d(t,"Collider",function(){return n.Collider}),i.d(t,"DefaultCollisionCoordinator",function(){return n.DefaultCollisionCoordinator}),i.d(t,"PickingInfo",function(){return n.PickingInfo}),i.d(t,"IntersectionInfo",function(){return n.IntersectionInfo}),i.d(t,"_MeshCollisionData",function(){return n._MeshCollisionData}),i.d(t,"BoundingBox",function(){return n.BoundingBox}),i.d(t,"BoundingInfo",function(){return n.BoundingInfo}),i.d(t,"BoundingSphere",function(){return n.BoundingSphere}),i.d(t,"Ray",function(){return n.Ray}),i.d(t,"AxesViewer",function(){return n.AxesViewer}),i.d(t,"BoneAxesViewer",function(){return n.BoneAxesViewer}),i.d(t,"DebugLayerTab",function(){return n.DebugLayerTab}),i.d(t,"DebugLayer",function(){return n.DebugLayer}),i.d(t,"PhysicsViewer",function(){return n.PhysicsViewer}),i.d(t,"RayHelper",function(){return n.RayHelper}),i.d(t,"SkeletonViewer",function(){return n.SkeletonViewer}),i.d(t,"Constants",function(){return n.Constants}),i.d(t,"ThinEngine",function(){return n.ThinEngine}),i.d(t,"Engine",function(){return n.Engine}),i.d(t,"EngineStore",function(){return n.EngineStore}),i.d(t,"NullEngineOptions",function(){return n.NullEngineOptions}),i.d(t,"NullEngine",function(){return n.NullEngine}),i.d(t,"WebGLPipelineContext",function(){return n.WebGLPipelineContext}),i.d(t,"WebGL2ShaderProcessor",function(){return n.WebGL2ShaderProcessor}),i.d(t,"NativeEngine",function(){return n.NativeEngine}),i.d(t,"KeyboardEventTypes",function(){return n.KeyboardEventTypes}),i.d(t,"KeyboardInfo",function(){return n.KeyboardInfo}),i.d(t,"KeyboardInfoPre",function(){return n.KeyboardInfoPre}),i.d(t,"PointerEventTypes",function(){return n.PointerEventTypes}),i.d(t,"PointerInfoBase",function(){return n.PointerInfoBase}),i.d(t,"PointerInfoPre",function(){return n.PointerInfoPre}),i.d(t,"PointerInfo",function(){return n.PointerInfo}),i.d(t,"ClipboardEventTypes",function(){return n.ClipboardEventTypes}),i.d(t,"ClipboardInfo",function(){return n.ClipboardInfo}),i.d(t,"StickValues",function(){return n.StickValues}),i.d(t,"Gamepad",function(){return n.Gamepad}),i.d(t,"GenericPad",function(){return n.GenericPad}),i.d(t,"GamepadManager",function(){return n.GamepadManager}),i.d(t,"GamepadSystemSceneComponent",function(){return n.GamepadSystemSceneComponent}),i.d(t,"Xbox360Button",function(){return n.Xbox360Button}),i.d(t,"Xbox360Dpad",function(){return n.Xbox360Dpad}),i.d(t,"Xbox360Pad",function(){return n.Xbox360Pad}),i.d(t,"DualShockButton",function(){return n.DualShockButton}),i.d(t,"DualShockDpad",function(){return n.DualShockDpad}),i.d(t,"DualShockPad",function(){return n.DualShockPad}),i.d(t,"AxisDragGizmo",function(){return n.AxisDragGizmo}),i.d(t,"AxisScaleGizmo",function(){return n.AxisScaleGizmo}),i.d(t,"BoundingBoxGizmo",function(){return n.BoundingBoxGizmo}),i.d(t,"Gizmo",function(){return n.Gizmo}),i.d(t,"GizmoManager",function(){return n.GizmoManager}),i.d(t,"PlaneRotationGizmo",function(){return n.PlaneRotationGizmo}),i.d(t,"PositionGizmo",function(){return n.PositionGizmo}),i.d(t,"RotationGizmo",function(){return n.RotationGizmo}),i.d(t,"ScaleGizmo",function(){return n.ScaleGizmo}),i.d(t,"LightGizmo",function(){return n.LightGizmo}),i.d(t,"PlaneDragGizmo",function(){return n.PlaneDragGizmo}),i.d(t,"EnvironmentHelper",function(){return n.EnvironmentHelper}),i.d(t,"PhotoDome",function(){return n.PhotoDome}),i.d(t,"_forceSceneHelpersToBundle",function(){return n._forceSceneHelpersToBundle}),i.d(t,"VideoDome",function(){return n.VideoDome}),i.d(t,"EngineInstrumentation",function(){return n.EngineInstrumentation}),i.d(t,"SceneInstrumentation",function(){return n.SceneInstrumentation}),i.d(t,"_TimeToken",function(){return n._TimeToken}),i.d(t,"EffectLayer",function(){return n.EffectLayer}),i.d(t,"EffectLayerSceneComponent",function(){return n.EffectLayerSceneComponent}),i.d(t,"GlowLayer",function(){return n.GlowLayer}),i.d(t,"HighlightLayer",function(){return n.HighlightLayer}),i.d(t,"Layer",function(){return n.Layer}),i.d(t,"LayerSceneComponent",function(){return n.LayerSceneComponent}),i.d(t,"LensFlare",function(){return n.LensFlare}),i.d(t,"LensFlareSystem",function(){return n.LensFlareSystem}),i.d(t,"LensFlareSystemSceneComponent",function(){return n.LensFlareSystemSceneComponent}),i.d(t,"Light",function(){return n.Light}),i.d(t,"ShadowLight",function(){return n.ShadowLight}),i.d(t,"DirectionalLight",function(){return n.DirectionalLight}),i.d(t,"HemisphericLight",function(){return n.HemisphericLight}),i.d(t,"PointLight",function(){return n.PointLight}),i.d(t,"SpotLight",function(){return n.SpotLight}),i.d(t,"DefaultLoadingScreen",function(){return n.DefaultLoadingScreen}),i.d(t,"SceneLoaderProgressEvent",function(){return n.SceneLoaderProgressEvent}),i.d(t,"SceneLoaderAnimationGroupLoadingMode",function(){return n.SceneLoaderAnimationGroupLoadingMode}),i.d(t,"SceneLoader",function(){return n.SceneLoader}),i.d(t,"SceneLoaderFlags",function(){return n.SceneLoaderFlags}),i.d(t,"ColorCurves",function(){return n.ColorCurves}),i.d(t,"EffectFallbacks",function(){return n.EffectFallbacks}),i.d(t,"Effect",function(){return n.Effect}),i.d(t,"FresnelParameters",function(){return n.FresnelParameters}),i.d(t,"ImageProcessingConfigurationDefines",function(){return n.ImageProcessingConfigurationDefines}),i.d(t,"ImageProcessingConfiguration",function(){return n.ImageProcessingConfiguration}),i.d(t,"Material",function(){return n.Material}),i.d(t,"MaterialDefines",function(){return n.MaterialDefines}),i.d(t,"MaterialHelper",function(){return n.MaterialHelper}),i.d(t,"MultiMaterial",function(){return n.MultiMaterial}),i.d(t,"PBRMaterial",function(){return n.PBRMaterial}),i.d(t,"PushMaterial",function(){return n.PushMaterial}),i.d(t,"ShaderMaterial",function(){return n.ShaderMaterial}),i.d(t,"StandardMaterialDefines",function(){return n.StandardMaterialDefines}),i.d(t,"StandardMaterial",function(){return n.StandardMaterial}),i.d(t,"BaseTexture",function(){return n.BaseTexture}),i.d(t,"CubeTexture",function(){return n.CubeTexture}),i.d(t,"DynamicTexture",function(){return n.DynamicTexture}),i.d(t,"EquiRectangularCubeTexture",function(){return n.EquiRectangularCubeTexture}),i.d(t,"HDRCubeTexture",function(){return n.HDRCubeTexture}),i.d(t,"InternalTextureSource",function(){return n.InternalTextureSource}),i.d(t,"InternalTexture",function(){return n.InternalTexture}),i.d(t,"MirrorTexture",function(){return n.MirrorTexture}),i.d(t,"MultiRenderTarget",function(){return n.MultiRenderTarget}),i.d(t,"RawTexture",function(){return n.RawTexture}),i.d(t,"RenderTargetTexture",function(){return n.RenderTargetTexture}),i.d(t,"Texture",function(){return n.Texture}),i.d(t,"UniformBuffer",function(){return n.UniformBuffer}),i.d(t,"MaterialFlags",function(){return n.MaterialFlags}),i.d(t,"EffectRenderer",function(){return n.EffectRenderer}),i.d(t,"EffectWrapper",function(){return n.EffectWrapper}),i.d(t,"Scalar",function(){return n.Scalar}),i.d(t,"Space",function(){return n.Space}),i.d(t,"Axis",function(){return n.Axis}),i.d(t,"Color3",function(){return n.Color3}),i.d(t,"Color4",function(){return n.Color4}),i.d(t,"TmpColors",function(){return n.TmpColors}),i.d(t,"ToGammaSpace",function(){return n.ToGammaSpace}),i.d(t,"ToLinearSpace",function(){return n.ToLinearSpace}),i.d(t,"Epsilon",function(){return n.Epsilon}),i.d(t,"Frustum",function(){return n.Frustum}),i.d(t,"Plane",function(){return n.Plane}),i.d(t,"Size",function(){return n.Size}),i.d(t,"Vector2",function(){return n.Vector2}),i.d(t,"Vector3",function(){return n.Vector3}),i.d(t,"Vector4",function(){return n.Vector4}),i.d(t,"Quaternion",function(){return n.Quaternion}),i.d(t,"Matrix",function(){return n.Matrix}),i.d(t,"TmpVectors",function(){return n.TmpVectors}),i.d(t,"Viewport",function(){return n.Viewport}),i.d(t,"SphericalHarmonics",function(){return n.SphericalHarmonics}),i.d(t,"SphericalPolynomial",function(){return n.SphericalPolynomial}),i.d(t,"AbstractMesh",function(){return n.AbstractMesh}),i.d(t,"Buffer",function(){return n.Buffer}),i.d(t,"VertexBuffer",function(){return n.VertexBuffer}),i.d(t,"CSG",function(){return n.CSG}),i.d(t,"Geometry",function(){return n.Geometry}),i.d(t,"GroundMesh",function(){return n.GroundMesh}),i.d(t,"TrailMesh",function(){return n.TrailMesh}),i.d(t,"InstancedMesh",function(){return n.InstancedMesh}),i.d(t,"LinesMesh",function(){return n.LinesMesh}),i.d(t,"InstancedLinesMesh",function(){return n.InstancedLinesMesh}),i.d(t,"_CreationDataStorage",function(){return n._CreationDataStorage}),i.d(t,"_InstancesBatch",function(){return n._InstancesBatch}),i.d(t,"Mesh",function(){return n.Mesh}),i.d(t,"VertexData",function(){return n.VertexData}),i.d(t,"MeshBuilder",function(){return n.MeshBuilder}),i.d(t,"SimplificationSettings",function(){return n.SimplificationSettings}),i.d(t,"SimplificationQueue",function(){return n.SimplificationQueue}),i.d(t,"SimplificationType",function(){return n.SimplificationType}),i.d(t,"SimplicationQueueSceneComponent",function(){return n.SimplicationQueueSceneComponent}),i.d(t,"Polygon",function(){return n.Polygon}),i.d(t,"PolygonMeshBuilder",function(){return n.PolygonMeshBuilder}),i.d(t,"BaseSubMesh",function(){return n.BaseSubMesh}),i.d(t,"SubMesh",function(){return n.SubMesh}),i.d(t,"MeshLODLevel",function(){return n.MeshLODLevel}),i.d(t,"TransformNode",function(){return n.TransformNode}),i.d(t,"BoxBuilder",function(){return n.BoxBuilder}),i.d(t,"SphereBuilder",function(){return n.SphereBuilder}),i.d(t,"CylinderBuilder",function(){return n.CylinderBuilder}),i.d(t,"TorusBuilder",function(){return n.TorusBuilder}),i.d(t,"LinesBuilder",function(){return n.LinesBuilder}),i.d(t,"PlaneBuilder",function(){return n.PlaneBuilder}),i.d(t,"GroundBuilder",function(){return n.GroundBuilder}),i.d(t,"DataBuffer",function(){return n.DataBuffer}),i.d(t,"WebGLDataBuffer",function(){return n.WebGLDataBuffer}),i.d(t,"MorphTarget",function(){return n.MorphTarget}),i.d(t,"MorphTargetManager",function(){return n.MorphTargetManager}),i.d(t,"Database",function(){return n.Database}),i.d(t,"BaseParticleSystem",function(){return n.BaseParticleSystem}),i.d(t,"GPUParticleSystem",function(){return n.GPUParticleSystem}),i.d(t,"Particle",function(){return n.Particle}),i.d(t,"ParticleHelper",function(){return n.ParticleHelper}),i.d(t,"ParticleSystem",function(){return n.ParticleSystem}),i.d(t,"_IDoNeedToBeInTheBuild",function(){return n._IDoNeedToBeInTheBuild}),i.d(t,"ParticleSystemSet",function(){return n.ParticleSystemSet}),i.d(t,"SolidParticle",function(){return n.SolidParticle}),i.d(t,"ModelShape",function(){return n.ModelShape}),i.d(t,"DepthSortedParticle",function(){return n.DepthSortedParticle}),i.d(t,"SolidParticleSystem",function(){return n.SolidParticleSystem}),i.d(t,"CloudPoint",function(){return n.CloudPoint}),i.d(t,"PointsGroup",function(){return n.PointsGroup}),i.d(t,"PointColor",function(){return n.PointColor}),i.d(t,"PointsCloudSystem",function(){return n.PointsCloudSystem}),i.d(t,"SubEmitterType",function(){return n.SubEmitterType}),i.d(t,"SubEmitter",function(){return n.SubEmitter}),i.d(t,"PhysicsEngine",function(){return n.PhysicsEngine}),i.d(t,"PhysicsEngineSceneComponent",function(){return n.PhysicsEngineSceneComponent}),i.d(t,"PhysicsHelper",function(){return n.PhysicsHelper}),i.d(t,"PhysicsRadialExplosionEventOptions",function(){return n.PhysicsRadialExplosionEventOptions}),i.d(t,"PhysicsUpdraftEventOptions",function(){return n.PhysicsUpdraftEventOptions}),i.d(t,"PhysicsVortexEventOptions",function(){return n.PhysicsVortexEventOptions}),i.d(t,"PhysicsRadialImpulseFalloff",function(){return n.PhysicsRadialImpulseFalloff}),i.d(t,"PhysicsUpdraftMode",function(){return n.PhysicsUpdraftMode}),i.d(t,"PhysicsImpostor",function(){return n.PhysicsImpostor}),i.d(t,"PhysicsJoint",function(){return n.PhysicsJoint}),i.d(t,"DistanceJoint",function(){return n.DistanceJoint}),i.d(t,"MotorEnabledJoint",function(){return n.MotorEnabledJoint}),i.d(t,"HingeJoint",function(){return n.HingeJoint}),i.d(t,"Hinge2Joint",function(){return n.Hinge2Joint}),i.d(t,"AnaglyphPostProcess",function(){return n.AnaglyphPostProcess}),i.d(t,"BlackAndWhitePostProcess",function(){return n.BlackAndWhitePostProcess}),i.d(t,"BloomEffect",function(){return n.BloomEffect}),i.d(t,"BloomMergePostProcess",function(){return n.BloomMergePostProcess}),i.d(t,"BlurPostProcess",function(){return n.BlurPostProcess}),i.d(t,"ChromaticAberrationPostProcess",function(){return n.ChromaticAberrationPostProcess}),i.d(t,"CircleOfConfusionPostProcess",function(){return n.CircleOfConfusionPostProcess}),i.d(t,"ColorCorrectionPostProcess",function(){return n.ColorCorrectionPostProcess}),i.d(t,"ConvolutionPostProcess",function(){return n.ConvolutionPostProcess}),i.d(t,"DepthOfFieldBlurPostProcess",function(){return n.DepthOfFieldBlurPostProcess}),i.d(t,"DepthOfFieldEffectBlurLevel",function(){return n.DepthOfFieldEffectBlurLevel}),i.d(t,"DepthOfFieldEffect",function(){return n.DepthOfFieldEffect}),i.d(t,"DepthOfFieldMergePostProcessOptions",function(){return n.DepthOfFieldMergePostProcessOptions}),i.d(t,"DepthOfFieldMergePostProcess",function(){return n.DepthOfFieldMergePostProcess}),i.d(t,"DisplayPassPostProcess",function(){return n.DisplayPassPostProcess}),i.d(t,"ExtractHighlightsPostProcess",function(){return n.ExtractHighlightsPostProcess}),i.d(t,"FilterPostProcess",function(){return n.FilterPostProcess}),i.d(t,"FxaaPostProcess",function(){return n.FxaaPostProcess}),i.d(t,"GrainPostProcess",function(){return n.GrainPostProcess}),i.d(t,"HighlightsPostProcess",function(){return n.HighlightsPostProcess}),i.d(t,"ImageProcessingPostProcess",function(){return n.ImageProcessingPostProcess}),i.d(t,"MotionBlurPostProcess",function(){return n.MotionBlurPostProcess}),i.d(t,"PassPostProcess",function(){return n.PassPostProcess}),i.d(t,"PassCubePostProcess",function(){return n.PassCubePostProcess}),i.d(t,"PostProcess",function(){return n.PostProcess}),i.d(t,"PostProcessManager",function(){return n.PostProcessManager}),i.d(t,"RefractionPostProcess",function(){return n.RefractionPostProcess}),i.d(t,"SharpenPostProcess",function(){return n.SharpenPostProcess}),i.d(t,"StereoscopicInterlacePostProcessI",function(){return n.StereoscopicInterlacePostProcessI}),i.d(t,"StereoscopicInterlacePostProcess",function(){return n.StereoscopicInterlacePostProcess}),i.d(t,"TonemappingOperator",function(){return n.TonemappingOperator}),i.d(t,"TonemapPostProcess",function(){return n.TonemapPostProcess}),i.d(t,"VolumetricLightScatteringPostProcess",function(){return n.VolumetricLightScatteringPostProcess}),i.d(t,"VRDistortionCorrectionPostProcess",function(){return n.VRDistortionCorrectionPostProcess}),i.d(t,"VRMultiviewToSingleviewPostProcess",function(){return n.VRMultiviewToSingleviewPostProcess}),i.d(t,"ScreenSpaceReflectionPostProcess",function(){return n.ScreenSpaceReflectionPostProcess}),i.d(t,"ReflectionProbe",function(){return n.ReflectionProbe}),i.d(t,"BoundingBoxRenderer",function(){return n.BoundingBoxRenderer}),i.d(t,"DepthRenderer",function(){return n.DepthRenderer}),i.d(t,"DepthRendererSceneComponent",function(){return n.DepthRendererSceneComponent}),i.d(t,"EdgesRenderer",function(){return n.EdgesRenderer}),i.d(t,"LineEdgesRenderer",function(){return n.LineEdgesRenderer}),i.d(t,"GeometryBufferRenderer",function(){return n.GeometryBufferRenderer}),i.d(t,"GeometryBufferRendererSceneComponent",function(){return n.GeometryBufferRendererSceneComponent}),i.d(t,"OutlineRenderer",function(){return n.OutlineRenderer}),i.d(t,"RenderingGroup",function(){return n.RenderingGroup}),i.d(t,"RenderingGroupInfo",function(){return n.RenderingGroupInfo}),i.d(t,"RenderingManager",function(){return n.RenderingManager}),i.d(t,"UtilityLayerRenderer",function(){return n.UtilityLayerRenderer}),i.d(t,"Sprite",function(){return n.Sprite}),i.d(t,"SpriteManager",function(){return n.SpriteManager}),i.d(t,"SpriteMap",function(){return n.SpriteMap}),i.d(t,"SpritePackedManager",function(){return n.SpritePackedManager}),i.d(t,"SpriteSceneComponent",function(){return n.SpriteSceneComponent}),i.d(t,"AlphaState",function(){return n.AlphaState}),i.d(t,"DepthCullingState",function(){return n.DepthCullingState}),i.d(t,"StencilState",function(){return n.StencilState}),i.d(t,"AndOrNotEvaluator",function(){return n.AndOrNotEvaluator}),i.d(t,"AssetTaskState",function(){return n.AssetTaskState}),i.d(t,"AbstractAssetTask",function(){return n.AbstractAssetTask}),i.d(t,"AssetsProgressEvent",function(){return n.AssetsProgressEvent}),i.d(t,"MeshAssetTask",function(){return n.MeshAssetTask}),i.d(t,"TextFileAssetTask",function(){return n.TextFileAssetTask}),i.d(t,"BinaryFileAssetTask",function(){return n.BinaryFileAssetTask}),i.d(t,"ImageAssetTask",function(){return n.ImageAssetTask}),i.d(t,"TextureAssetTask",function(){return n.TextureAssetTask}),i.d(t,"CubeTextureAssetTask",function(){return n.CubeTextureAssetTask}),i.d(t,"HDRCubeTextureAssetTask",function(){return n.HDRCubeTextureAssetTask}),i.d(t,"EquiRectangularCubeTextureAssetTask",function(){return n.EquiRectangularCubeTextureAssetTask}),i.d(t,"AssetsManager",function(){return n.AssetsManager}),i.d(t,"BasisTranscodeConfiguration",function(){return n.BasisTranscodeConfiguration}),i.d(t,"BasisTools",function(){return n.BasisTools}),i.d(t,"DDSTools",function(){return n.DDSTools}),i.d(t,"expandToProperty",function(){return n.expandToProperty}),i.d(t,"serialize",function(){return n.serialize}),i.d(t,"serializeAsTexture",function(){return n.serializeAsTexture}),i.d(t,"serializeAsColor3",function(){return n.serializeAsColor3}),i.d(t,"serializeAsFresnelParameters",function(){return n.serializeAsFresnelParameters}),i.d(t,"serializeAsVector2",function(){return n.serializeAsVector2}),i.d(t,"serializeAsVector3",function(){return n.serializeAsVector3}),i.d(t,"serializeAsMeshReference",function(){return n.serializeAsMeshReference}),i.d(t,"serializeAsColorCurves",function(){return n.serializeAsColorCurves}),i.d(t,"serializeAsColor4",function(){return n.serializeAsColor4}),i.d(t,"serializeAsImageProcessingConfiguration",function(){return n.serializeAsImageProcessingConfiguration}),i.d(t,"serializeAsQuaternion",function(){return n.serializeAsQuaternion}),i.d(t,"serializeAsMatrix",function(){return n.serializeAsMatrix}),i.d(t,"serializeAsCameraReference",function(){return n.serializeAsCameraReference}),i.d(t,"SerializationHelper",function(){return n.SerializationHelper}),i.d(t,"Deferred",function(){return n.Deferred}),i.d(t,"EnvironmentTextureTools",function(){return n.EnvironmentTextureTools}),i.d(t,"MeshExploder",function(){return n.MeshExploder}),i.d(t,"FilesInput",function(){return n.FilesInput}),i.d(t,"KhronosTextureContainer",function(){return n.KhronosTextureContainer}),i.d(t,"EventState",function(){return n.EventState}),i.d(t,"Observer",function(){return n.Observer}),i.d(t,"MultiObserver",function(){return n.MultiObserver}),i.d(t,"Observable",function(){return n.Observable}),i.d(t,"PerformanceMonitor",function(){return n.PerformanceMonitor}),i.d(t,"RollingAverage",function(){return n.RollingAverage}),i.d(t,"PromisePolyfill",function(){return n.PromisePolyfill}),i.d(t,"SceneOptimization",function(){return n.SceneOptimization}),i.d(t,"TextureOptimization",function(){return n.TextureOptimization}),i.d(t,"HardwareScalingOptimization",function(){return n.HardwareScalingOptimization}),i.d(t,"ShadowsOptimization",function(){return n.ShadowsOptimization}),i.d(t,"PostProcessesOptimization",function(){return n.PostProcessesOptimization}),i.d(t,"LensFlaresOptimization",function(){return n.LensFlaresOptimization}),i.d(t,"CustomOptimization",function(){return n.CustomOptimization}),i.d(t,"ParticlesOptimization",function(){return n.ParticlesOptimization}),i.d(t,"RenderTargetsOptimization",function(){return n.RenderTargetsOptimization}),i.d(t,"MergeMeshesOptimization",function(){return n.MergeMeshesOptimization}),i.d(t,"SceneOptimizerOptions",function(){return n.SceneOptimizerOptions}),i.d(t,"SceneOptimizer",function(){return n.SceneOptimizer}),i.d(t,"SceneSerializer",function(){return n.SceneSerializer}),i.d(t,"SmartArray",function(){return n.SmartArray}),i.d(t,"SmartArrayNoDuplicate",function(){return n.SmartArrayNoDuplicate}),i.d(t,"StringDictionary",function(){return n.StringDictionary}),i.d(t,"Tags",function(){return n.Tags}),i.d(t,"TextureTools",function(){return n.TextureTools}),i.d(t,"TGATools",function(){return n.TGATools}),i.d(t,"Tools",function(){return n.Tools}),i.d(t,"className",function(){return n.className}),i.d(t,"AsyncLoop",function(){return n.AsyncLoop}),i.d(t,"VideoRecorder",function(){return n.VideoRecorder}),i.d(t,"JoystickAxis",function(){return n.JoystickAxis}),i.d(t,"VirtualJoystick",function(){return n.VirtualJoystick}),i.d(t,"WorkerPool",function(){return n.WorkerPool}),i.d(t,"Logger",function(){return n.Logger}),i.d(t,"_TypeStore",function(){return n._TypeStore}),i.d(t,"FilesInputStore",function(){return n.FilesInputStore}),i.d(t,"DeepCopier",function(){return n.DeepCopier}),i.d(t,"PivotTools",function(){return n.PivotTools}),i.d(t,"PrecisionDate",function(){return n.PrecisionDate}),i.d(t,"ScreenshotTools",function(){return n.ScreenshotTools}),i.d(t,"WebRequest",function(){return n.WebRequest}),i.d(t,"InspectableType",function(){return n.InspectableType}),i.d(t,"BRDFTextureTools",function(){return n.BRDFTextureTools}),i.d(t,"RGBDTextureTools",function(){return n.RGBDTextureTools}),i.d(t,"ColorGradient",function(){return n.ColorGradient}),i.d(t,"Color3Gradient",function(){return n.Color3Gradient}),i.d(t,"FactorGradient",function(){return n.FactorGradient}),i.d(t,"GradientHelper",function(){return n.GradientHelper}),i.d(t,"PerfCounter",function(){return n.PerfCounter}),i.d(t,"RetryStrategy",function(){return n.RetryStrategy}),i.d(t,"CanvasGenerator",function(){return n.CanvasGenerator}),i.d(t,"LoadFileError",function(){return n.LoadFileError}),i.d(t,"RequestFileError",function(){return n.RequestFileError}),i.d(t,"ReadFileError",function(){return n.ReadFileError}),i.d(t,"FileTools",function(){return n.FileTools}),i.d(t,"StringTools",function(){return n.StringTools}),i.d(t,"DataReader",function(){return n.DataReader}),i.d(t,"MinMaxReducer",function(){return n.MinMaxReducer}),i.d(t,"DepthReducer",function(){return n.DepthReducer}),i.d(t,"WebXRCamera",function(){return n.WebXRCamera}),i.d(t,"WebXREnterExitUIButton",function(){return n.WebXREnterExitUIButton}),i.d(t,"WebXREnterExitUIOptions",function(){return n.WebXREnterExitUIOptions}),i.d(t,"WebXREnterExitUI",function(){return n.WebXREnterExitUI}),i.d(t,"WebXRExperienceHelper",function(){return n.WebXRExperienceHelper}),i.d(t,"WebXRInput",function(){return n.WebXRInput}),i.d(t,"WebXRInputSource",function(){return n.WebXRInputSource}),i.d(t,"WebXRManagedOutputCanvasOptions",function(){return n.WebXRManagedOutputCanvasOptions}),i.d(t,"WebXRManagedOutputCanvas",function(){return n.WebXRManagedOutputCanvas}),i.d(t,"WebXRState",function(){return n.WebXRState}),i.d(t,"WebXRSessionManager",function(){return n.WebXRSessionManager}),i.d(t,"WebXRDefaultExperienceOptions",function(){return n.WebXRDefaultExperienceOptions}),i.d(t,"WebXRDefaultExperience",function(){return n.WebXRDefaultExperience}),i.d(t,"WebXRFeatureName",function(){return n.WebXRFeatureName}),i.d(t,"WebXRFeaturesManager",function(){return n.WebXRFeaturesManager}),i.d(t,"AutoRotationBehavior",function(){return n.AutoRotationBehavior}),i.d(t,"BouncingBehavior",function(){return n.BouncingBehavior}),i.d(t,"FramingBehavior",function(){return n.FramingBehavior}),i.d(t,"AttachToBoxBehavior",function(){return n.AttachToBoxBehavior}),i.d(t,"FadeInOutBehavior",function(){return n.FadeInOutBehavior}),i.d(t,"MultiPointerScaleBehavior",function(){return n.MultiPointerScaleBehavior}),i.d(t,"PointerDragBehavior",function(){return n.PointerDragBehavior}),i.d(t,"SixDofDragBehavior",function(){return n.SixDofDragBehavior}),i.d(t,"ArcRotateCameraGamepadInput",function(){return n.ArcRotateCameraGamepadInput}),i.d(t,"ArcRotateCameraKeyboardMoveInput",function(){return n.ArcRotateCameraKeyboardMoveInput}),i.d(t,"ArcRotateCameraMouseWheelInput",function(){return n.ArcRotateCameraMouseWheelInput}),i.d(t,"ArcRotateCameraPointersInput",function(){return n.ArcRotateCameraPointersInput}),i.d(t,"ArcRotateCameraVRDeviceOrientationInput",function(){return n.ArcRotateCameraVRDeviceOrientationInput}),i.d(t,"FlyCameraKeyboardInput",function(){return n.FlyCameraKeyboardInput}),i.d(t,"FlyCameraMouseInput",function(){return n.FlyCameraMouseInput}),i.d(t,"FollowCameraKeyboardMoveInput",function(){return n.FollowCameraKeyboardMoveInput}),i.d(t,"FollowCameraMouseWheelInput",function(){return n.FollowCameraMouseWheelInput}),i.d(t,"FollowCameraPointersInput",function(){return n.FollowCameraPointersInput}),i.d(t,"FreeCameraDeviceOrientationInput",function(){return n.FreeCameraDeviceOrientationInput}),i.d(t,"FreeCameraGamepadInput",function(){return n.FreeCameraGamepadInput}),i.d(t,"FreeCameraKeyboardMoveInput",function(){return n.FreeCameraKeyboardMoveInput}),i.d(t,"FreeCameraMouseInput",function(){return n.FreeCameraMouseInput}),i.d(t,"FreeCameraTouchInput",function(){return n.FreeCameraTouchInput}),i.d(t,"FreeCameraVirtualJoystickInput",function(){return n.FreeCameraVirtualJoystickInput}),i.d(t,"AnaglyphArcRotateCamera",function(){return n.AnaglyphArcRotateCamera}),i.d(t,"AnaglyphFreeCamera",function(){return n.AnaglyphFreeCamera}),i.d(t,"AnaglyphGamepadCamera",function(){return n.AnaglyphGamepadCamera}),i.d(t,"AnaglyphUniversalCamera",function(){return n.AnaglyphUniversalCamera}),i.d(t,"StereoscopicArcRotateCamera",function(){return n.StereoscopicArcRotateCamera}),i.d(t,"StereoscopicFreeCamera",function(){return n.StereoscopicFreeCamera}),i.d(t,"StereoscopicGamepadCamera",function(){return n.StereoscopicGamepadCamera}),i.d(t,"StereoscopicUniversalCamera",function(){return n.StereoscopicUniversalCamera}),i.d(t,"VRCameraMetrics",function(){return n.VRCameraMetrics}),i.d(t,"VRDeviceOrientationArcRotateCamera",function(){return n.VRDeviceOrientationArcRotateCamera}),i.d(t,"VRDeviceOrientationFreeCamera",function(){return n.VRDeviceOrientationFreeCamera}),i.d(t,"VRDeviceOrientationGamepadCamera",function(){return n.VRDeviceOrientationGamepadCamera}),i.d(t,"OnAfterEnteringVRObservableEvent",function(){return n.OnAfterEnteringVRObservableEvent}),i.d(t,"VRExperienceHelper",function(){return n.VRExperienceHelper}),i.d(t,"WebVRFreeCamera",function(){return n.WebVRFreeCamera}),i.d(t,"Octree",function(){return n.Octree}),i.d(t,"OctreeBlock",function(){return n.OctreeBlock}),i.d(t,"OctreeSceneComponent",function(){return n.OctreeSceneComponent}),i.d(t,"_OcclusionDataStorage",function(){return n._OcclusionDataStorage}),i.d(t,"_forceTransformFeedbackToBundle",function(){return n._forceTransformFeedbackToBundle}),i.d(t,"EngineView",function(){return n.EngineView}),i.d(t,"DaydreamController",function(){return n.DaydreamController}),i.d(t,"GearVRController",function(){return n.GearVRController}),i.d(t,"GenericController",function(){return n.GenericController}),i.d(t,"OculusTouchController",function(){return n.OculusTouchController}),i.d(t,"PoseEnabledControllerType",function(){return n.PoseEnabledControllerType}),i.d(t,"PoseEnabledControllerHelper",function(){return n.PoseEnabledControllerHelper}),i.d(t,"PoseEnabledController",function(){return n.PoseEnabledController}),i.d(t,"ViveController",function(){return n.ViveController}),i.d(t,"WebVRController",function(){return n.WebVRController}),i.d(t,"WindowsMotionController",function(){return n.WindowsMotionController}),i.d(t,"XRWindowsMotionController",function(){return n.XRWindowsMotionController}),i.d(t,"ShadowGenerator",function(){return n.ShadowGenerator}),i.d(t,"CascadedShadowGenerator",function(){return n.CascadedShadowGenerator}),i.d(t,"ShadowGeneratorSceneComponent",function(){return n.ShadowGeneratorSceneComponent}),i.d(t,"_BabylonLoaderRegistered",function(){return n._BabylonLoaderRegistered}),i.d(t,"BabylonFileLoaderConfiguration",function(){return n.BabylonFileLoaderConfiguration}),i.d(t,"BackgroundMaterial",function(){return n.BackgroundMaterial}),i.d(t,"PBRMaterialDefines",function(){return n.PBRMaterialDefines}),i.d(t,"PBRBaseMaterial",function(){return n.PBRBaseMaterial}),i.d(t,"PBRBaseSimpleMaterial",function(){return n.PBRBaseSimpleMaterial}),i.d(t,"PBRMetallicRoughnessMaterial",function(){return n.PBRMetallicRoughnessMaterial}),i.d(t,"PBRSpecularGlossinessMaterial",function(){return n.PBRSpecularGlossinessMaterial}),i.d(t,"ColorGradingTexture",function(){return n.ColorGradingTexture}),i.d(t,"RawCubeTexture",function(){return n.RawCubeTexture}),i.d(t,"RawTexture3D",function(){return n.RawTexture3D}),i.d(t,"RawTexture2DArray",function(){return n.RawTexture2DArray}),i.d(t,"RefractionTexture",function(){return n.RefractionTexture}),i.d(t,"VideoTexture",function(){return n.VideoTexture}),i.d(t,"HtmlElementTexture",function(){return n.HtmlElementTexture}),i.d(t,"NodeMaterialConnectionPointCompatibilityStates",function(){return n.NodeMaterialConnectionPointCompatibilityStates}),i.d(t,"NodeMaterialConnectionPointDirection",function(){return n.NodeMaterialConnectionPointDirection}),i.d(t,"NodeMaterialConnectionPoint",function(){return n.NodeMaterialConnectionPoint}),i.d(t,"NodeMaterialBlock",function(){return n.NodeMaterialBlock}),i.d(t,"NodeMaterialDefines",function(){return n.NodeMaterialDefines}),i.d(t,"NodeMaterial",function(){return n.NodeMaterial}),i.d(t,"Orientation",function(){return n.Orientation}),i.d(t,"BezierCurve",function(){return n.BezierCurve}),i.d(t,"Angle",function(){return n.Angle}),i.d(t,"Arc2",function(){return n.Arc2}),i.d(t,"Path2",function(){return n.Path2}),i.d(t,"Path3D",function(){return n.Path3D}),i.d(t,"Curve3",function(){return n.Curve3}),i.d(t,"PositionNormalVertex",function(){return n.PositionNormalVertex}),i.d(t,"PositionNormalTextureVertex",function(){return n.PositionNormalTextureVertex}),i.d(t,"DracoCompression",function(){return n.DracoCompression}),i.d(t,"TiledBoxBuilder",function(){return n.TiledBoxBuilder}),i.d(t,"DiscBuilder",function(){return n.DiscBuilder}),i.d(t,"RibbonBuilder",function(){return n.RibbonBuilder}),i.d(t,"HemisphereBuilder",function(){return n.HemisphereBuilder}),i.d(t,"TorusKnotBuilder",function(){return n.TorusKnotBuilder}),i.d(t,"PolygonBuilder",function(){return n.PolygonBuilder}),i.d(t,"ShapeBuilder",function(){return n.ShapeBuilder}),i.d(t,"LatheBuilder",function(){return n.LatheBuilder}),i.d(t,"TiledPlaneBuilder",function(){return n.TiledPlaneBuilder}),i.d(t,"TubeBuilder",function(){return n.TubeBuilder}),i.d(t,"PolyhedronBuilder",function(){return n.PolyhedronBuilder}),i.d(t,"IcoSphereBuilder",function(){return n.IcoSphereBuilder}),i.d(t,"DecalBuilder",function(){return n.DecalBuilder}),i.d(t,"RecastJSPlugin",function(){return n.RecastJSPlugin}),i.d(t,"RecastJSCrowd",function(){return n.RecastJSCrowd}),i.d(t,"BoxParticleEmitter",function(){return n.BoxParticleEmitter}),i.d(t,"ConeParticleEmitter",function(){return n.ConeParticleEmitter}),i.d(t,"CylinderParticleEmitter",function(){return n.CylinderParticleEmitter}),i.d(t,"CylinderDirectedParticleEmitter",function(){return n.CylinderDirectedParticleEmitter}),i.d(t,"HemisphericParticleEmitter",function(){return n.HemisphericParticleEmitter}),i.d(t,"PointParticleEmitter",function(){return n.PointParticleEmitter}),i.d(t,"SphereParticleEmitter",function(){return n.SphereParticleEmitter}),i.d(t,"SphereDirectedParticleEmitter",function(){return n.SphereDirectedParticleEmitter}),i.d(t,"CustomParticleEmitter",function(){return n.CustomParticleEmitter}),i.d(t,"MeshParticleEmitter",function(){return n.MeshParticleEmitter}),i.d(t,"CannonJSPlugin",function(){return n.CannonJSPlugin}),i.d(t,"AmmoJSPlugin",function(){return n.AmmoJSPlugin}),i.d(t,"OimoJSPlugin",function(){return n.OimoJSPlugin}),i.d(t,"PostProcessRenderEffect",function(){return n.PostProcessRenderEffect}),i.d(t,"PostProcessRenderPipeline",function(){return n.PostProcessRenderPipeline}),i.d(t,"PostProcessRenderPipelineManager",function(){return n.PostProcessRenderPipelineManager}),i.d(t,"PostProcessRenderPipelineManagerSceneComponent",function(){return n.PostProcessRenderPipelineManagerSceneComponent}),i.d(t,"CubeMapToSphericalPolynomialTools",function(){return n.CubeMapToSphericalPolynomialTools}),i.d(t,"HDRTools",function(){return n.HDRTools}),i.d(t,"PanoramaToCubeMapTools",function(){return n.PanoramaToCubeMapTools}),i.d(t,"WebXRHitTestLegacy",function(){return n.WebXRHitTestLegacy}),i.d(t,"WebXRAnchorSystem",function(){return n.WebXRAnchorSystem}),i.d(t,"WebXRPlaneDetector",function(){return n.WebXRPlaneDetector}),i.d(t,"WebXRBackgroundRemover",function(){return n.WebXRBackgroundRemover}),i.d(t,"WebXRMotionControllerTeleportation",function(){return n.WebXRMotionControllerTeleportation}),i.d(t,"WebXRControllerPointerSelection",function(){return n.WebXRControllerPointerSelection}),i.d(t,"IWebXRControllerPhysicsOptions",function(){return n.IWebXRControllerPhysicsOptions}),i.d(t,"WebXRControllerPhysics",function(){return n.WebXRControllerPhysics}),i.d(t,"WebXRAbstractMotionController",function(){return n.WebXRAbstractMotionController}),i.d(t,"WebXRControllerComponent",function(){return n.WebXRControllerComponent}),i.d(t,"WebXRGenericTriggerMotionController",function(){return n.WebXRGenericTriggerMotionController}),i.d(t,"WebXRMicrosoftMixedRealityController",function(){return n.WebXRMicrosoftMixedRealityController}),i.d(t,"WebXRMotionControllerManager",function(){return n.WebXRMotionControllerManager}),i.d(t,"WebXROculusTouchMotionController",function(){return n.WebXROculusTouchMotionController}),i.d(t,"WebXRHTCViveMotionController",function(){return n.WebXRHTCViveMotionController}),i.d(t,"WebXRProfiledMotionController",function(){return n.WebXRProfiledMotionController}),i.d(t,"_DDSTextureLoader",function(){return n._DDSTextureLoader}),i.d(t,"_ENVTextureLoader",function(){return n._ENVTextureLoader}),i.d(t,"_KTXTextureLoader",function(){return n._KTXTextureLoader}),i.d(t,"_TGATextureLoader",function(){return n._TGATextureLoader}),i.d(t,"_BasisTextureLoader",function(){return n._BasisTextureLoader}),i.d(t,"CustomProceduralTexture",function(){return n.CustomProceduralTexture}),i.d(t,"NoiseProceduralTexture",function(){return n.NoiseProceduralTexture}),i.d(t,"ProceduralTexture",function(){return n.ProceduralTexture}),i.d(t,"ProceduralTextureSceneComponent",function(){return n.ProceduralTextureSceneComponent}),i.d(t,"TexturePacker",function(){return n.TexturePacker}),i.d(t,"TexturePackerFrame",function(){return n.TexturePackerFrame}),i.d(t,"NodeMaterialBlockTargets",function(){return n.NodeMaterialBlockTargets}),i.d(t,"NodeMaterialBlockConnectionPointTypes",function(){return n.NodeMaterialBlockConnectionPointTypes}),i.d(t,"NodeMaterialBlockConnectionPointMode",function(){return n.NodeMaterialBlockConnectionPointMode}),i.d(t,"NodeMaterialSystemValues",function(){return n.NodeMaterialSystemValues}),i.d(t,"MultiplyBlock",function(){return n.MultiplyBlock}),i.d(t,"AddBlock",function(){return n.AddBlock}),i.d(t,"ScaleBlock",function(){return n.ScaleBlock}),i.d(t,"ClampBlock",function(){return n.ClampBlock}),i.d(t,"CrossBlock",function(){return n.CrossBlock}),i.d(t,"DotBlock",function(){return n.DotBlock}),i.d(t,"TransformBlock",function(){return n.TransformBlock}),i.d(t,"RemapBlock",function(){return n.RemapBlock}),i.d(t,"NormalizeBlock",function(){return n.NormalizeBlock}),i.d(t,"TrigonometryBlockOperations",function(){return n.TrigonometryBlockOperations}),i.d(t,"TrigonometryBlock",function(){return n.TrigonometryBlock}),i.d(t,"ColorMergerBlock",function(){return n.ColorMergerBlock}),i.d(t,"VectorMergerBlock",function(){return n.VectorMergerBlock}),i.d(t,"ColorSplitterBlock",function(){return n.ColorSplitterBlock}),i.d(t,"VectorSplitterBlock",function(){return n.VectorSplitterBlock}),i.d(t,"LerpBlock",function(){return n.LerpBlock}),i.d(t,"DivideBlock",function(){return n.DivideBlock}),i.d(t,"SubtractBlock",function(){return n.SubtractBlock}),i.d(t,"StepBlock",function(){return n.StepBlock}),i.d(t,"OneMinusBlock",function(){return n.OneMinusBlock}),i.d(t,"ViewDirectionBlock",function(){return n.ViewDirectionBlock}),i.d(t,"FresnelBlock",function(){return n.FresnelBlock}),i.d(t,"MaxBlock",function(){return n.MaxBlock}),i.d(t,"MinBlock",function(){return n.MinBlock}),i.d(t,"DistanceBlock",function(){return n.DistanceBlock}),i.d(t,"LengthBlock",function(){return n.LengthBlock}),i.d(t,"NegateBlock",function(){return n.NegateBlock}),i.d(t,"PowBlock",function(){return n.PowBlock}),i.d(t,"RandomNumberBlock",function(){return n.RandomNumberBlock}),i.d(t,"ArcTan2Block",function(){return n.ArcTan2Block}),i.d(t,"SmoothStepBlock",function(){return n.SmoothStepBlock}),i.d(t,"ReciprocalBlock",function(){return n.ReciprocalBlock}),i.d(t,"ReplaceColorBlock",function(){return n.ReplaceColorBlock}),i.d(t,"PosterizeBlock",function(){return n.PosterizeBlock}),i.d(t,"WaveBlockKind",function(){return n.WaveBlockKind}),i.d(t,"WaveBlock",function(){return n.WaveBlock}),i.d(t,"GradientBlockColorStep",function(){return n.GradientBlockColorStep}),i.d(t,"GradientBlock",function(){return n.GradientBlock}),i.d(t,"NLerpBlock",function(){return n.NLerpBlock}),i.d(t,"WorleyNoise3DBlock",function(){return n.WorleyNoise3DBlock}),i.d(t,"SimplexPerlin3DBlock",function(){return n.SimplexPerlin3DBlock}),i.d(t,"NormalBlendBlock",function(){return n.NormalBlendBlock}),i.d(t,"Rotate2dBlock",function(){return n.Rotate2dBlock}),i.d(t,"ReflectBlock",function(){return n.ReflectBlock}),i.d(t,"RefractBlock",function(){return n.RefractBlock}),i.d(t,"DesaturateBlock",function(){return n.DesaturateBlock}),i.d(t,"NodeMaterialOptimizer",function(){return n.NodeMaterialOptimizer}),i.d(t,"DefaultRenderingPipeline",function(){return n.DefaultRenderingPipeline}),i.d(t,"LensRenderingPipeline",function(){return n.LensRenderingPipeline}),i.d(t,"SSAO2RenderingPipeline",function(){return n.SSAO2RenderingPipeline}),i.d(t,"SSAORenderingPipeline",function(){return n.SSAORenderingPipeline}),i.d(t,"StandardRenderingPipeline",function(){return n.StandardRenderingPipeline}),i.d(t,"VertexOutputBlock",function(){return n.VertexOutputBlock}),i.d(t,"BonesBlock",function(){return n.BonesBlock}),i.d(t,"InstancesBlock",function(){return n.InstancesBlock}),i.d(t,"MorphTargetsBlock",function(){return n.MorphTargetsBlock}),i.d(t,"LightInformationBlock",function(){return n.LightInformationBlock}),i.d(t,"FragmentOutputBlock",function(){return n.FragmentOutputBlock}),i.d(t,"ImageProcessingBlock",function(){return n.ImageProcessingBlock}),i.d(t,"PerturbNormalBlock",function(){return n.PerturbNormalBlock}),i.d(t,"DiscardBlock",function(){return n.DiscardBlock}),i.d(t,"FrontFacingBlock",function(){return n.FrontFacingBlock}),i.d(t,"DerivativeBlock",function(){return n.DerivativeBlock}),i.d(t,"FogBlock",function(){return n.FogBlock}),i.d(t,"LightBlock",function(){return n.LightBlock}),i.d(t,"TextureBlock",function(){return n.TextureBlock}),i.d(t,"ReflectionTextureBlock",function(){return n.ReflectionTextureBlock}),i.d(t,"InputBlock",function(){return n.InputBlock}),i.d(t,"AnimatedInputBlockTypes",function(){return n.AnimatedInputBlockTypes});var o=void 0!==e?e:"undefined"!=typeof window?window:void 0;if(void 0!==o){o.BABYLON=a,o.BABYLON=o.BABYLON||{};var a=o.BABYLON;a.Debug=a.Debug||{};var s=[];for(var c in r)a.Debug[c]=r[c],s.push(c);for(var c in n)a[c]=n[c]}var l={AxesViewer:r.AxesViewer,BoneAxesViewer:r.BoneAxesViewer,PhysicsViewer:r.PhysicsViewer,SkeletonViewer:r.SkeletonViewer}}.call(this,i(144))}])});

/***/ }),
/* 3 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "d", function() { return /* binding */ FRONTSIDE; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ BACKSIDE; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ DOUBLESIDE; });
__webpack_require__.d(__webpack_exports__, "g", function() { return /* binding */ PERSPECTIVE_CAMERA; });
__webpack_require__.d(__webpack_exports__, "f", function() { return /* binding */ ORTHOGRAPHIC_CAMERA; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* binding */ FOGMODE_LINEAR; });
__webpack_require__.d(__webpack_exports__, "h", function() { return /* binding */ WORLDSPACE; });
__webpack_require__.d(__webpack_exports__, "e", function() { return /* binding */ LOCALSPACE; });
__webpack_require__.d(__webpack_exports__, "i", function() { return /* binding */ setupBabylonMods; });

// UNUSED EXPORTS: FOGMODE_NONE, FOGMODE_EXP, FOGMODE_EXP2, BONESPACE

// EXTERNAL MODULE: ./src/main.js
var main = __webpack_require__(1);

// EXTERNAL MODULE: ./src/util.js
var util = __webpack_require__(0);

// CONCATENATED MODULE: ./src/shaders.js

function hackShaders(){
	hackShaderAlphaCutoff('shadowMapPixelShader');
	hackShaderAlphaCutoff('depthPixelShader');
	hackDefaultShader();
}

function hackShaderAlphaCutoff(shader){
	hackShaderReplace(shader,
		'if (texture2D(diffuseSampler,vUV).a<0.4)',
		`if (texture2D(diffuseSampler,vUV).a<${mv3d.ALPHA_CUTOFF})`,
	);
}
function hackShaderReplace(shader,find,replace){
	BABYLON.Effect.ShadersStore[shader]=BABYLON.Effect.ShadersStore[shader].replace(find,replace);
}
function hackShaderInsert(shader,find,insert){
	hackShaderReplace(shader,find,`${find}\n${insert}\n`);
}

function hackDefaultShader(){
	// When no diffuse texture, use diffuseColor as baseColor
	hackShaderReplace('defaultPixelShader',
	'vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;',
	`#ifdef DIFFUSE
	vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
	#else
	vec3 finalDiffuse=clamp(diffuseBase+emissiveColor+vAmbientColor,0.0,1.0)*diffuseColor.rgb;
	#endif
	`);
	// When emissive color higher than one, use illumination.
	hackShaderReplace('defaultPixelShader',
		'vec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);',
		`vec3 mv3d_extra_emissiveColor = max(emissiveColor-1.,0.);
		vec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+mv3d_extra_emissiveColor+refractionColor,0.0,1.0),alpha);`,
	);
}

// EXTERNAL MODULE: ./node_modules/babylonjs/babylon.js
var babylon = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/babylonjs-loaders/babylonjs.loaders.min.js
var babylonjs_loaders_min = __webpack_require__(5);

// CONCATENATED MODULE: ./src/mod_babylon.js







const {
	FRONTSIDE,BACKSIDE,DOUBLESIDE,
} = babylon["Mesh"];

const {
	PERSPECTIVE_CAMERA,
	ORTHOGRAPHIC_CAMERA,
} = babylon["Camera"];

const{
	FOGMODE_NONE,
	FOGMODE_EXP,
	FOGMODE_EXP2,
	FOGMODE_LINEAR,
} = babylon["Scene"];

const {
	WORLD:WORLDSPACE,
    LOCAL:LOCALSPACE,
	BONE:BONESPACE,
} = babylon["Space"];

babylon["Texture"].prototype.crop=function(x=0,y=0,w=0,h=0){
	const { width, height } = this.getBaseSize();
	if(!w)w=width-x;
	if(!h)h=height-y;
	if(main["a" /* default */].EDGE_FIX){ x+=main["a" /* default */].EDGE_FIX;y+=main["a" /* default */].EDGE_FIX;w-=main["a" /* default */].EDGE_FIX*2;h-=main["a" /* default */].EDGE_FIX*2; }
	this.uScale=w/width;
	this.vScale=h/height;
	this.uOffset=x/width;
	this.vOffset=1-y/height-this.vScale;
}

const _mixin_xyz = {
	x:{
		get(){ return this.position?this.position.x:undefined; },
		set(v){ if(this.position){ this.position.x=v; } },
	},
	y:{
		get(){ return this.position?-this.position.z:undefined; },
		set(v){ if(this.position){ this.position.z=-v; } },
	},
	z:{
		get(){ return this.position?this.position.y:undefined; },
		set(v){ if(this.position){ this.position.y=v; } },
	},
};
const _mixin_angles = {
	pitch:{
		get(){ return this.rotation?-Object(util["radtodeg"])(this.rotation.x):undefined; },
		set(v){ if(this.rotation){ this.rotation.x=-Object(util["degtorad"])(v); } },
	},
	yaw:{
		get(){ return this.rotation?-Object(util["radtodeg"])(this.rotation.y):undefined; },
		set(v){  if(this.rotation){ this.rotation.y=-Object(util["degtorad"])(v); } },
	},
	roll:{
		get(){ return this.rotation?-Object(util["radtodeg"])(this.rotation.z):undefined; },
		set(v){  if(this.rotation){ this.rotation.z=-Object(util["degtorad"])(v); } },
	},
}
Object.defineProperties(babylon["Node"].prototype,_mixin_xyz);
Object.defineProperties(babylon["Node"].prototype,_mixin_angles);
Object.defineProperties(babylon["Sprite"].prototype,_mixin_xyz);

// mesh sorting

Object.defineProperty(babylon["Mesh"].prototype,'order',{
	get(){ return this._order; },
	set(v){ this._order=v; this._scene.sortMeshes(); }
});
const meshSorter=(m1,m2)=>(m1._order|0)-(m2._order|0);
babylon["Scene"].prototype.sortMeshes=function(){
	this.meshes.sort(meshSorter);
}
const _addMesh = babylon["Scene"].prototype.addMesh;
babylon["Scene"].prototype.addMesh=function(mesh){
	_addMesh.apply(this,arguments);
	if(typeof mesh._order==='number'){
		this.sortMeshes();
	}
}
const _removeMesh = babylon["Scene"].prototype.removeMesh;
babylon["Scene"].prototype.removeMesh=function(mesh){
	_removeMesh.apply(this,arguments);
	this.sortMeshes();
}

// color
babylon["Color3"].prototype.toNumber=babylon["Color4"].prototype.toNumber=function(){return this.r*255<<16|this.g*255<<8|this.b*255;}

// hack babylon
function setupBabylonMods(){
	hackShaders();
};

babylon["StandardMaterial"].prototype._shouldTurnAlphaTestOn=function(mesh){
	return this.needAlphaTesting();
};



/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(26);
__webpack_require__(15);
module.exports = __webpack_require__(16);


/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {

!function(e,t){ true?module.exports=t(__webpack_require__(2)):undefined}("undefined"!=typeof self?self:"undefined"!=typeof global?global:this,function(e){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=19)}([function(t,n){t.exports=e},function(e,t,n){"use strict";n.d(t,"a",function(){return a}),n.d(t,"b",function(){return i});var r=n(0),o=n(2),a=function(){function e(){}return e.Get=function(e,t,n){if(!t||null==n||!t[n])throw new Error(e+": Failed to find index ("+n+")");return t[n]},e.Assign=function(e){if(e)for(var t=0;t<e.length;t++)e[t].index=t},e}(),i=function(){function e(e){this._completePromises=new Array,this._forAssetContainer=!1,this._babylonLights=[],this._disposed=!1,this._state=null,this._extensions=new Array,this._defaultBabylonMaterialData={},this._requests=new Array,this._parent=e}return e.RegisterExtension=function(t,n){e.UnregisterExtension(t)&&r.Logger.Warn("Extension with the name '"+t+"' already exists"),e._RegisteredExtensions[t]={factory:n}},e.UnregisterExtension=function(t){return!!e._RegisteredExtensions[t]&&(delete e._RegisteredExtensions[t],!0)},Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"gltf",{get:function(){return this._gltf},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bin",{get:function(){return this._bin},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){return this._parent},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"babylonScene",{get:function(){return this._babylonScene},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rootBabylonMesh",{get:function(){return this._rootBabylonMesh},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){if(!this._disposed){this._disposed=!0;for(var e=0,t=this._requests;e<t.length;e++){t[e].abort()}for(var n in this._requests.length=0,this._completePromises.length=0,this._extensions){var r=this._extensions[n];r.dispose&&r.dispose(),delete this._extensions[n]}delete this._gltf,delete this._babylonScene,delete this._rootBabylonMesh,delete this._progressCallback,this._parent._clear()}},e.prototype.importMeshAsync=function(e,t,n,r,o,a,i){var s=this;return Promise.resolve().then(function(){s._babylonScene=t,s._rootUrl=o,s._fileName=i||"scene",s._progressCallback=a,s._forAssetContainer=n,s._loadData(r);var l=null;if(e){var u={};if(s._gltf.nodes)for(var c=0,f=s._gltf.nodes;c<f.length;c++){var d=f[c];d.name&&(u[d.name]=d.index)}l=(e instanceof Array?e:[e]).map(function(e){var t=u[e];if(void 0===t)throw new Error("Failed to find node '"+e+"'");return t})}return s._loadAsync(l,function(){return{meshes:s._getMeshes(),particleSystems:[],skeletons:s._getSkeletons(),animationGroups:s._getAnimationGroups(),lights:s._babylonLights,transformNodes:s._getTransformNodes()}})})},e.prototype.loadAsync=function(e,t,n,r,o){var a=this;return Promise.resolve().then(function(){return a._babylonScene=e,a._rootUrl=n,a._fileName=o||"scene",a._progressCallback=r,a._loadData(t),a._loadAsync(null,function(){})})},e.prototype._loadAsync=function(e,t){var n=this;return Promise.resolve().then(function(){n._uniqueRootUrl=-1===n._rootUrl.indexOf("file:")&&n._fileName?n._rootUrl:""+n._rootUrl+Date.now()+"/",n._loadExtensions(),n._checkExtensions();var i=o.GLTFLoaderState[o.GLTFLoaderState.LOADING]+" => "+o.GLTFLoaderState[o.GLTFLoaderState.READY],s=o.GLTFLoaderState[o.GLTFLoaderState.LOADING]+" => "+o.GLTFLoaderState[o.GLTFLoaderState.COMPLETE];n._parent._startPerformanceCounter(i),n._parent._startPerformanceCounter(s),n._setState(o.GLTFLoaderState.LOADING),n._extensionsOnLoading();var l=new Array,u=n._babylonScene.blockMaterialDirtyMechanism;if(n._babylonScene.blockMaterialDirtyMechanism=!0,e)l.push(n.loadSceneAsync("/nodes",{nodes:e,index:-1}));else if(null!=n._gltf.scene||n._gltf.scenes&&n._gltf.scenes[0]){var c=a.Get("/scene",n._gltf.scenes,n._gltf.scene||0);l.push(n.loadSceneAsync("/scenes/"+c.index,c))}n._babylonScene.blockMaterialDirtyMechanism=u,n._parent.compileMaterials&&l.push(n._compileMaterialsAsync()),n._parent.compileShadowGenerators&&l.push(n._compileShadowGeneratorsAsync());var f=Promise.all(l).then(function(){return n._rootBabylonMesh&&n._rootBabylonMesh.setEnabled(!0),n._setState(o.GLTFLoaderState.READY),n._extensionsOnReady(),n._startAnimations(),t()});return f.then(function(){n._parent._endPerformanceCounter(i),r.Tools.SetImmediate(function(){n._disposed||Promise.all(n._completePromises).then(function(){n._parent._endPerformanceCounter(s),n._setState(o.GLTFLoaderState.COMPLETE),n._parent.onCompleteObservable.notifyObservers(void 0),n._parent.onCompleteObservable.clear(),n.dispose()},function(e){n._parent.onErrorObservable.notifyObservers(e),n._parent.onErrorObservable.clear(),n.dispose()})})}),f},function(e){throw n._disposed||(n._parent.onErrorObservable.notifyObservers(e),n._parent.onErrorObservable.clear(),n.dispose()),e})},e.prototype._loadData=function(e){if(this._gltf=e.json,this._setupData(),e.bin){var t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){var n=t[0];(n.byteLength<e.bin.byteLength-3||n.byteLength>e.bin.byteLength)&&r.Logger.Warn("Binary buffer length ("+n.byteLength+") from JSON does not match chunk length ("+e.bin.byteLength+")"),this._bin=e.bin}else r.Logger.Warn("Unexpected BIN chunk")}},e.prototype._setupData=function(){if(a.Assign(this._gltf.accessors),a.Assign(this._gltf.animations),a.Assign(this._gltf.buffers),a.Assign(this._gltf.bufferViews),a.Assign(this._gltf.cameras),a.Assign(this._gltf.images),a.Assign(this._gltf.materials),a.Assign(this._gltf.meshes),a.Assign(this._gltf.nodes),a.Assign(this._gltf.samplers),a.Assign(this._gltf.scenes),a.Assign(this._gltf.skins),a.Assign(this._gltf.textures),this._gltf.nodes){for(var e={},t=0,n=this._gltf.nodes;t<n.length;t++){if((u=n[t]).children)for(var r=0,o=u.children;r<o.length;r++){e[o[r]]=u.index}}for(var i=this._createRootNode(),s=0,l=this._gltf.nodes;s<l.length;s++){var u,c=e[(u=l[s]).index];u.parent=void 0===c?i:this._gltf.nodes[c]}}},e.prototype._loadExtensions=function(){for(var t in e._RegisteredExtensions){var n=e._RegisteredExtensions[t].factory(this);n.name!==t&&r.Logger.Warn("The name of the glTF loader extension instance does not match the registered name: "+n.name+" !== "+t),this._extensions.push(n),this._parent.onExtensionLoadedObservable.notifyObservers(n)}this._extensions.sort(function(e,t){return(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE)}),this._parent.onExtensionLoadedObservable.clear()},e.prototype._checkExtensions=function(){if(this._gltf.extensionsRequired)for(var e=function(e){if(!t._extensions.some(function(t){return t.name===e&&t.enabled}))throw new Error("Require extension "+e+" is not available")},t=this,n=0,r=this._gltf.extensionsRequired;n<r.length;n++){e(r[n])}},e.prototype._setState=function(e){this._state=e,this.log(o.GLTFLoaderState[this._state])},e.prototype._createRootNode=function(){this._babylonScene._blockEntityCollection=this._forAssetContainer,this._rootBabylonMesh=new r.Mesh("__root__",this._babylonScene),this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);var t={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case o.GLTFLoaderCoordinateSystemMode.AUTO:this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],e._LoadTransform(t,this._rootBabylonMesh));break;case o.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw new Error("Invalid coordinate system mode ("+this._parent.coordinateSystemMode+")")}return this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh),t},e.prototype.loadSceneAsync=function(e,t){var n=this,r=this._extensionsLoadSceneAsync(e,t);if(r)return r;var o=new Array;if(this.logOpen(e+" "+(t.name||"")),t.nodes)for(var i=0,s=t.nodes;i<s.length;i++){var l=s[i],u=a.Get(e+"/nodes/"+l,this._gltf.nodes,l);o.push(this.loadNodeAsync("/nodes/"+u.index,u,function(e){e.parent=n._rootBabylonMesh}))}if(this._gltf.nodes)for(var c=0,f=this._gltf.nodes;c<f.length;c++){if((u=f[c])._babylonTransformNode&&u._babylonBones)for(var d=0,h=u._babylonBones;d<h.length;d++){h[d].linkTransformNode(u._babylonTransformNode)}}return o.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(o).then(function(){})},e.prototype._forEachPrimitive=function(e,t){if(e._primitiveBabylonMeshes)for(var n=0,r=e._primitiveBabylonMeshes;n<r.length;n++){t(r[n])}},e.prototype._getMeshes=function(){var e=new Array;e.push(this._rootBabylonMesh);var t=this._gltf.nodes;if(t)for(var n=0,r=t;n<r.length;n++){var o=r[n];this._forEachPrimitive(o,function(t){e.push(t)})}return e},e.prototype._getTransformNodes=function(){var e=new Array,t=this._gltf.nodes;if(t)for(var n=0,r=t;n<r.length;n++){var o=r[n];o._babylonTransformNode&&"TransformNode"===o._babylonTransformNode.getClassName()&&e.push(o._babylonTransformNode)}return e},e.prototype._getSkeletons=function(){var e=new Array,t=this._gltf.skins;if(t)for(var n=0,r=t;n<r.length;n++){var o=r[n];o._data&&e.push(o._data.babylonSkeleton)}return e},e.prototype._getAnimationGroups=function(){var e=new Array,t=this._gltf.animations;if(t)for(var n=0,r=t;n<r.length;n++){var o=r[n];o._babylonAnimationGroup&&e.push(o._babylonAnimationGroup)}return e},e.prototype._startAnimations=function(){switch(this._parent.animationStartMode){case o.GLTFLoaderAnimationStartMode.NONE:break;case o.GLTFLoaderAnimationStartMode.FIRST:0!==(e=this._getAnimationGroups()).length&&e[0].start(!0);break;case o.GLTFLoaderAnimationStartMode.ALL:for(var e,t=0,n=e=this._getAnimationGroups();t<n.length;t++){n[t].start(!0)}break;default:return void r.Logger.Error("Invalid animation start mode ("+this._parent.animationStartMode+")")}},e.prototype.loadNodeAsync=function(t,n,o){var i=this;void 0===o&&(o=function(){});var s=this._extensionsLoadNodeAsync(t,n,o);if(s)return s;if(n._babylonTransformNode)throw new Error(t+": Invalid recursive node hierarchy");var l=new Array;this.logOpen(t+" "+(n.name||""));var u=function(r){if(e.AddPointerMetadata(r,t),e._LoadTransform(n,r),null!=n.camera){var s=a.Get(t+"/camera",i._gltf.cameras,n.camera);l.push(i.loadCameraAsync("/cameras/"+s.index,s,function(e){e.parent=r}))}if(n.children)for(var u=0,c=n.children;u<c.length;u++){var f=c[u],d=a.Get(t+"/children/"+f,i._gltf.nodes,f);l.push(i.loadNodeAsync("/nodes/"+d.index,d,function(e){e.parent=r}))}o(r)};if(null==n.mesh){var c=n.name||"node"+n.index;this._babylonScene._blockEntityCollection=this._forAssetContainer,n._babylonTransformNode=new r.TransformNode(c,this._babylonScene),this._babylonScene._blockEntityCollection=!1,u(n._babylonTransformNode)}else{var f=a.Get(t+"/mesh",this._gltf.meshes,n.mesh);l.push(this._loadMeshAsync("/meshes/"+f.index,n,f,u))}return this.logClose(),Promise.all(l).then(function(){return i._forEachPrimitive(n,function(e){e.refreshBoundingInfo(!0)}),n._babylonTransformNode})},e.prototype._loadMeshAsync=function(e,t,n,o){var i=n.primitives;if(!i||!i.length)throw new Error(e+": Primitives are missing");null==i[0].index&&a.Assign(i);var s=new Array;this.logOpen(e+" "+(n.name||""));var l=t.name||"node"+t.index;if(1===i.length){var u=n.primitives[0];s.push(this._loadMeshPrimitiveAsync(e+"/primitives/"+u.index,l,t,n,u,function(e){t._babylonTransformNode=e,t._primitiveBabylonMeshes=[e]}))}else{t._babylonTransformNode=new r.TransformNode(l,this._babylonScene),t._primitiveBabylonMeshes=[];for(var c=0,f=i;c<f.length;c++){u=f[c];s.push(this._loadMeshPrimitiveAsync(e+"/primitives/"+u.index,l+"_primitive"+u.index,t,n,u,function(e){e.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(e)}))}}if(null!=t.skin){var d=a.Get(e+"/skin",this._gltf.skins,t.skin);s.push(this._loadSkinAsync("/skins/"+d.index,t,d))}return o(t._babylonTransformNode),this.logClose(),Promise.all(s).then(function(){return t._babylonTransformNode})},e.prototype._loadMeshPrimitiveAsync=function(t,n,o,i,s,l){var u=this,c=this._extensionsLoadMeshPrimitiveAsync(t,n,o,i,s,l);if(c)return c;this.logOpen(""+t);var f,d,h=this._parent.createInstances&&null==o.skin&&!i.primitives[0].targets;if(h&&s._instanceData)f=s._instanceData.babylonSourceMesh.createInstance(n),d=s._instanceData.promise;else{var p=new Array;this._babylonScene._blockEntityCollection=this._forAssetContainer;var m=new r.Mesh(n,this._babylonScene);this._babylonScene._blockEntityCollection=!1,m.overrideMaterialSideOrientation=this._babylonScene.useRightHandedSystem?r.Material.CounterClockWiseSideOrientation:r.Material.ClockWiseSideOrientation,this._createMorphTargets(t,o,i,s,m),p.push(this._loadVertexDataAsync(t,s,m).then(function(e){return u._loadMorphTargetsAsync(t,s,m,e).then(function(){e.applyToMesh(m)})}));var _=e._GetDrawMode(t,s.mode);if(null==s.material){var y=this._defaultBabylonMaterialData[_];y||(y=this._createDefaultMaterial("__GLTFLoader._default",_),this._parent.onMaterialLoadedObservable.notifyObservers(y),this._defaultBabylonMaterialData[_]=y),m.material=y}else{var b=a.Get(t+"/material",this._gltf.materials,s.material);p.push(this._loadMaterialAsync("/materials/"+b.index,b,m,_,function(e){m.material=e}))}d=Promise.all(p),h&&(s._instanceData={babylonSourceMesh:m,promise:d}),f=m}return e.AddPointerMetadata(f,t),this._parent.onMeshLoadedObservable.notifyObservers(f),l(f),this.logClose(),d.then(function(){return f})},e.prototype._loadVertexDataAsync=function(e,t,n){var o=this,i=this._extensionsLoadVertexDataAsync(e,t,n);if(i)return i;var s=t.attributes;if(!s)throw new Error(e+": Attributes are missing");var l=new Array,u=new r.Geometry(n.name,this._babylonScene);if(null==t.indices)n.isUnIndexed=!0;else{var c=a.Get(e+"/indices",this._gltf.accessors,t.indices);l.push(this._loadIndicesAccessorAsync("/accessors/"+c.index,c).then(function(e){u.setIndices(e)}))}var f=function(t,i,c){if(null!=s[t]){n._delayInfo=n._delayInfo||[],-1===n._delayInfo.indexOf(i)&&n._delayInfo.push(i);var f=a.Get(e+"/attributes/"+t,o._gltf.accessors,s[t]);l.push(o._loadVertexAccessorAsync("/accessors/"+f.index,f,i).then(function(e){u.setVerticesBuffer(e,f.count)})),i==r.VertexBuffer.MatricesIndicesExtraKind&&(n.numBoneInfluencers=8),c&&c(f)}};return f("POSITION",r.VertexBuffer.PositionKind),f("NORMAL",r.VertexBuffer.NormalKind),f("TANGENT",r.VertexBuffer.TangentKind),f("TEXCOORD_0",r.VertexBuffer.UVKind),f("TEXCOORD_1",r.VertexBuffer.UV2Kind),f("JOINTS_0",r.VertexBuffer.MatricesIndicesKind),f("WEIGHTS_0",r.VertexBuffer.MatricesWeightsKind),f("JOINTS_1",r.VertexBuffer.MatricesIndicesExtraKind),f("WEIGHTS_1",r.VertexBuffer.MatricesWeightsExtraKind),f("COLOR_0",r.VertexBuffer.ColorKind,function(e){"VEC4"===e.type&&(n.hasVertexAlpha=!0)}),Promise.all(l).then(function(){return u})},e.prototype._createMorphTargets=function(e,t,n,o,a){if(o.targets){if(null==t._numMorphTargets)t._numMorphTargets=o.targets.length;else if(o.targets.length!==t._numMorphTargets)throw new Error(e+": Primitives do not have the same number of targets");var i=n.extras?n.extras.targetNames:null;a.morphTargetManager=new r.MorphTargetManager(a.getScene());for(var s=0;s<o.targets.length;s++){var l=t.weights?t.weights[s]:n.weights?n.weights[s]:0,u=i?i[s]:"morphTarget"+s;a.morphTargetManager.addTarget(new r.MorphTarget(u,l,a.getScene()))}}},e.prototype._loadMorphTargetsAsync=function(e,t,n,r){if(!t.targets)return Promise.resolve();for(var o=new Array,a=n.morphTargetManager,i=0;i<a.numTargets;i++){var s=a.getTarget(i);o.push(this._loadMorphTargetVertexDataAsync(e+"/targets/"+i,r,t.targets[i],s))}return Promise.all(o).then(function(){})},e.prototype._loadMorphTargetVertexDataAsync=function(e,t,n,o){var i=this,s=new Array,l=function(r,o,l){if(null!=n[r]){var u=t.getVertexBuffer(o);if(u){var c=a.Get(e+"/"+r,i._gltf.accessors,n[r]);s.push(i._loadFloatAccessorAsync("/accessors/"+c.index,c).then(function(e){l(u,e)}))}}};return l("POSITION",r.VertexBuffer.PositionKind,function(e,t){var n=new Float32Array(t.length);e.forEach(t.length,function(e,r){n[r]=t[r]+e}),o.setPositions(n)}),l("NORMAL",r.VertexBuffer.NormalKind,function(e,t){var n=new Float32Array(t.length);e.forEach(n.length,function(e,r){n[r]=t[r]+e}),o.setNormals(n)}),l("TANGENT",r.VertexBuffer.TangentKind,function(e,t){var n=new Float32Array(t.length/3*4),r=0;e.forEach(t.length/3*4,function(e,o){(o+1)%4!=0&&(n[r]=t[r]+e,r++)}),o.setTangents(n)}),Promise.all(s).then(function(){})},e._LoadTransform=function(e,t){if(null==e.skin){var n=r.Vector3.Zero(),o=r.Quaternion.Identity(),a=r.Vector3.One();if(e.matrix)r.Matrix.FromArray(e.matrix).decompose(a,o,n);else e.translation&&(n=r.Vector3.FromArray(e.translation)),e.rotation&&(o=r.Quaternion.FromArray(e.rotation)),e.scale&&(a=r.Vector3.FromArray(e.scale));t.position=n,t.rotationQuaternion=o,t.scaling=a}},e.prototype._loadSkinAsync=function(e,t,n){var o=this,a=this._extensionsLoadSkinAsync(e,t,n);if(a)return a;var i=function(e){o._forEachPrimitive(t,function(t){t.skeleton=e})};if(n._data)return i(n._data.babylonSkeleton),n._data.promise;var s="skeleton"+n.index;this._babylonScene._blockEntityCollection=this._forAssetContainer;var l=new r.Skeleton(n.name||s,s,this._babylonScene);this._babylonScene._blockEntityCollection=!1,l.overrideMesh=this._rootBabylonMesh,this._loadBones(e,n,l),i(l);var u=this._loadSkinInverseBindMatricesDataAsync(e,n).then(function(e){o._updateBoneMatrices(l,e)});return n._data={babylonSkeleton:l,promise:u},u},e.prototype._loadBones=function(e,t,n){for(var r={},o=0,i=t.joints;o<i.length;o++){var s=i[o],l=a.Get(e+"/joints/"+s,this._gltf.nodes,s);this._loadBone(l,t,n,r)}},e.prototype._loadBone=function(e,t,n,o){var a=o[e.index];if(a)return a;var i=null;e.parent&&e.parent._babylonTransformNode!==this._rootBabylonMesh&&(i=this._loadBone(e.parent,t,n,o));var s=t.joints.indexOf(e.index);return a=new r.Bone(e.name||"joint"+e.index,n,i,this._getNodeMatrix(e),null,null,s),o[e.index]=a,e._babylonBones=e._babylonBones||[],e._babylonBones.push(a),a},e.prototype._loadSkinInverseBindMatricesDataAsync=function(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);var n=a.Get(e+"/inverseBindMatrices",this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync("/accessors/"+n.index,n)},e.prototype._updateBoneMatrices=function(e,t){for(var n=0,o=e.bones;n<o.length;n++){var a=o[n],i=r.Matrix.Identity(),s=a._index;t&&-1!==s&&(r.Matrix.FromArrayToRef(t,16*s,i),i.invertToRef(i));var l=a.getParent();l&&i.multiplyToRef(l.getInvertedAbsoluteTransform(),i),a.updateMatrix(i,!1,!1),a._updateDifferenceMatrix(void 0,!1)}},e.prototype._getNodeMatrix=function(e){return e.matrix?r.Matrix.FromArray(e.matrix):r.Matrix.Compose(e.scale?r.Vector3.FromArray(e.scale):r.Vector3.One(),e.rotation?r.Quaternion.FromArray(e.rotation):r.Quaternion.Identity(),e.translation?r.Vector3.FromArray(e.translation):r.Vector3.Zero())},e.prototype.loadCameraAsync=function(t,n,o){void 0===o&&(o=function(){});var a=this._extensionsLoadCameraAsync(t,n,o);if(a)return a;var i=new Array;this.logOpen(t+" "+(n.name||"")),this._babylonScene._blockEntityCollection=this._forAssetContainer;var s=new r.FreeCamera(n.name||"camera"+n.index,r.Vector3.Zero(),this._babylonScene,!1);switch(this._babylonScene._blockEntityCollection=!1,s.rotation=new r.Vector3(0,Math.PI,0),n.type){case"perspective":var l=n.perspective;if(!l)throw new Error(t+": Camera perspective properties are missing");s.fov=l.yfov,s.minZ=l.znear,s.maxZ=l.zfar||Number.MAX_VALUE;break;case"orthographic":if(!n.orthographic)throw new Error(t+": Camera orthographic properties are missing");s.mode=r.Camera.ORTHOGRAPHIC_CAMERA,s.orthoLeft=-n.orthographic.xmag,s.orthoRight=n.orthographic.xmag,s.orthoBottom=-n.orthographic.ymag,s.orthoTop=n.orthographic.ymag,s.minZ=n.orthographic.znear,s.maxZ=n.orthographic.zfar;break;default:throw new Error(t+": Invalid camera type ("+n.type+")")}return e.AddPointerMetadata(s,t),this._parent.onCameraLoadedObservable.notifyObservers(s),o(s),Promise.all(i).then(function(){return s})},e.prototype._loadAnimationsAsync=function(){var e=this._gltf.animations;if(!e)return Promise.resolve();for(var t=new Array,n=0;n<e.length;n++){var r=e[n];t.push(this.loadAnimationAsync("/animations/"+r.index,r))}return Promise.all(t).then(function(){})},e.prototype.loadAnimationAsync=function(e,t){var n=this._extensionsLoadAnimationAsync(e,t);if(n)return n;this._babylonScene._blockEntityCollection=this._forAssetContainer;var o=new r.AnimationGroup(t.name||"animation"+t.index,this._babylonScene);this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=o;var i=new Array;a.Assign(t.channels),a.Assign(t.samplers);for(var s=0,l=t.channels;s<l.length;s++){var u=l[s];i.push(this._loadAnimationChannelAsync(e+"/channels/"+u.index,e,t,u,o))}return Promise.all(i).then(function(){return o.normalize(0),o})},e.prototype._loadAnimationChannelAsync=function(e,t,n,o,i,s){var l=this;if(void 0===s&&(s=null),null==o.target.node)return Promise.resolve();var u=a.Get(e+"/target/node",this._gltf.nodes,o.target.node);if("weights"===o.target.path&&!u._numMorphTargets||"weights"!==o.target.path&&!u._babylonTransformNode)return Promise.resolve();var c=a.Get(e+"/sampler",n.samplers,o.sampler);return this._loadAnimationSamplerAsync(t+"/samplers/"+o.sampler,c).then(function(t){var n,a;switch(o.target.path){case"translation":n="position",a=r.Animation.ANIMATIONTYPE_VECTOR3;break;case"rotation":n="rotationQuaternion",a=r.Animation.ANIMATIONTYPE_QUATERNION;break;case"scale":n="scaling",a=r.Animation.ANIMATIONTYPE_VECTOR3;break;case"weights":n="influence",a=r.Animation.ANIMATIONTYPE_FLOAT;break;default:throw new Error(e+"/target/path: Invalid value ("+o.target.path+")")}var c,f,d=0;switch(n){case"position":c=function(){var e=r.Vector3.FromArray(t.output,d);return d+=3,e};break;case"rotationQuaternion":c=function(){var e=r.Quaternion.FromArray(t.output,d);return d+=4,e};break;case"scaling":c=function(){var e=r.Vector3.FromArray(t.output,d);return d+=3,e};break;case"influence":c=function(){for(var e=new Array(u._numMorphTargets),n=0;n<u._numMorphTargets;n++)e[n]=t.output[d++];return e}}switch(t.interpolation){case"STEP":f=function(e){return{frame:t.input[e],value:c(),interpolation:r.AnimationKeyInterpolation.STEP}};break;case"LINEAR":f=function(e){return{frame:t.input[e],value:c()}};break;case"CUBICSPLINE":f=function(e){return{frame:t.input[e],inTangent:c(),value:c(),outTangent:c()}}}for(var h=new Array(t.input.length),p=0;p<t.input.length;p++)h[p]=f(p);if("influence"===n)for(var m=function(e){var t=i.name+"_channel"+i.targetedAnimations.length,o=new r.Animation(t,n,1,a);o.setKeys(h.map(function(t){return{frame:t.frame,inTangent:t.inTangent?t.inTangent[e]:void 0,value:t.value[e],outTangent:t.outTangent?t.outTangent[e]:void 0}})),l._forEachPrimitive(u,function(t){var n=t.morphTargetManager.getTarget(e),r=o.clone();n.animations.push(r),i.addTargetedAnimation(r,n)})},_=0;_<u._numMorphTargets;_++)m(_);else{var y=i.name+"_channel"+i.targetedAnimations.length,b=new r.Animation(y,n,1,a);b.setKeys(h),null!=s&&null!=s.animations?(s.animations.push(b),i.addTargetedAnimation(b,s)):(u._babylonTransformNode.animations.push(b),i.addTargetedAnimation(b,u._babylonTransformNode))}})},e.prototype._loadAnimationSamplerAsync=function(e,t){if(t._data)return t._data;var n=t.interpolation||"LINEAR";switch(n){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(e+"/interpolation: Invalid value ("+t.interpolation+")")}var r=a.Get(e+"/input",this._gltf.accessors,t.input),o=a.Get(e+"/output",this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync("/accessors/"+r.index,r),this._loadFloatAccessorAsync("/accessors/"+o.index,o)]).then(function(e){var t=e[0],r=e[1];return{input:t,interpolation:n,output:r}}),t._data},e.prototype._loadBufferAsync=function(e,t,n,r){var o=this._extensionsLoadBufferAsync(e,t,n,r);if(o)return o;if(!t._data)if(t.uri)t._data=this.loadUriAsync(e+"/uri",t,t.uri);else{if(!this._bin)throw new Error(e+": Uri is missing or the binary glTF is missing its binary chunk");t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then(function(t){try{return new Uint8Array(t.buffer,t.byteOffset+n,r)}catch(t){throw new Error(e+": "+t.message)}})},e.prototype.loadBufferViewAsync=function(e,t){var n=this._extensionsLoadBufferViewAsync(e,t);if(n)return n;if(t._data)return t._data;var r=a.Get(e+"/buffer",this._gltf.buffers,t.buffer);return t._data=this._loadBufferAsync("/buffers/"+r.index,r,t.byteOffset||0,t.byteLength),t._data},e.prototype._loadAccessorAsync=function(t,n,o){var i=this;if(n._data)return n._data;var s=e._GetNumComponents(t,n.type),l=s*r.VertexBuffer.GetTypeByteLength(n.componentType),u=s*n.count;if(null==n.bufferView)n._data=Promise.resolve(new o(u));else{var c=a.Get(t+"/bufferView",this._gltf.bufferViews,n.bufferView);n._data=this.loadBufferViewAsync("/bufferViews/"+c.index,c).then(function(a){if(5126!==n.componentType||n.normalized){var i=new o(u);return r.VertexBuffer.ForEach(a,n.byteOffset||0,c.byteStride||l,s,n.componentType,i.length,n.normalized||!1,function(e,t){i[t]=e}),i}return e._GetTypedArray(t,n.componentType,a,n.byteOffset,u)})}if(n.sparse){var f=n.sparse;n._data=n._data.then(function(u){var c=u,d=a.Get(t+"/sparse/indices/bufferView",i._gltf.bufferViews,f.indices.bufferView),h=a.Get(t+"/sparse/values/bufferView",i._gltf.bufferViews,f.values.bufferView);return Promise.all([i.loadBufferViewAsync("/bufferViews/"+d.index,d),i.loadBufferViewAsync("/bufferViews/"+h.index,h)]).then(function(a){var i,u=a[0],d=a[1],h=e._GetTypedArray(t+"/sparse/indices",f.indices.componentType,u,f.indices.byteOffset,f.count),p=s*f.count;if(5126!==n.componentType||n.normalized){var m=e._GetTypedArray(t+"/sparse/values",n.componentType,d,f.values.byteOffset,p);i=new o(p),r.VertexBuffer.ForEach(m,0,l,s,n.componentType,i.length,n.normalized||!1,function(e,t){i[t]=e})}else i=e._GetTypedArray(t+"/sparse/values",n.componentType,d,f.values.byteOffset,p);for(var _=0,y=0;y<h.length;y++)for(var b=h[y]*s,v=0;v<s;v++)c[b++]=i[_++];return c})})}return n._data},e.prototype._loadFloatAccessorAsync=function(e,t){return this._loadAccessorAsync(e,t,Float32Array)},e.prototype._loadIndicesAccessorAsync=function(t,n){if("SCALAR"!==n.type)throw new Error(t+"/type: Invalid value "+n.type);if(5121!==n.componentType&&5123!==n.componentType&&5125!==n.componentType)throw new Error(t+"/componentType: Invalid value "+n.componentType);if(n._data)return n._data;if(n.sparse){var r=e._GetTypedArrayConstructor(t+"/componentType",n.componentType);n._data=this._loadAccessorAsync(t,n,r)}else{var o=a.Get(t+"/bufferView",this._gltf.bufferViews,n.bufferView);n._data=this.loadBufferViewAsync("/bufferViews/"+o.index,o).then(function(r){return e._GetTypedArray(t,n.componentType,r,n.byteOffset,n.count)})}return n._data},e.prototype._loadVertexBufferViewAsync=function(e,t){var n=this;return e._babylonBuffer?e._babylonBuffer:(e._babylonBuffer=this.loadBufferViewAsync("/bufferViews/"+e.index,e).then(function(e){return new r.Buffer(n._babylonScene.getEngine(),e,!1)}),e._babylonBuffer)},e.prototype._loadVertexAccessorAsync=function(t,n,o){var i=this;if(n._babylonVertexBuffer)return n._babylonVertexBuffer;if(n.sparse)n._babylonVertexBuffer=this._loadFloatAccessorAsync("/accessors/"+n.index,n).then(function(e){return new r.VertexBuffer(i._babylonScene.getEngine(),e,o,!1)});else if(n.byteOffset&&n.byteOffset%r.VertexBuffer.GetTypeByteLength(n.componentType)!=0)r.Logger.Warn("Accessor byte offset is not a multiple of component type byte length"),n._babylonVertexBuffer=this._loadFloatAccessorAsync("/accessors/"+n.index,n).then(function(e){return new r.VertexBuffer(i._babylonScene.getEngine(),e,o,!1)});else if(o===r.VertexBuffer.MatricesIndicesKind||o===r.VertexBuffer.MatricesIndicesExtraKind)n._babylonVertexBuffer=this._loadFloatAccessorAsync("/accessors/"+n.index,n).then(function(e){return new r.VertexBuffer(i._babylonScene.getEngine(),e,o,!1)});else{var s=a.Get(t+"/bufferView",this._gltf.bufferViews,n.bufferView);n._babylonVertexBuffer=this._loadVertexBufferViewAsync(s,o).then(function(a){var l=e._GetNumComponents(t,n.type);return new r.VertexBuffer(i._babylonScene.getEngine(),a,o,!1,!1,s.byteStride,!1,n.byteOffset,l,n.componentType,n.normalized,!0)})}return n._babylonVertexBuffer},e.prototype._loadMaterialMetallicRoughnessPropertiesAsync=function(e,t,n){if(!(n instanceof r.PBRMaterial))throw new Error(e+": Material type not supported");var o=new Array;return t&&(t.baseColorFactor?(n.albedoColor=r.Color3.FromArray(t.baseColorFactor),n.alpha=t.baseColorFactor[3]):n.albedoColor=r.Color3.White(),n.metallic=null==t.metallicFactor?1:t.metallicFactor,n.roughness=null==t.roughnessFactor?1:t.roughnessFactor,t.baseColorTexture&&o.push(this.loadTextureInfoAsync(e+"/baseColorTexture",t.baseColorTexture,function(e){e.name=n.name+" (Base Color)",n.albedoTexture=e})),t.metallicRoughnessTexture&&(o.push(this.loadTextureInfoAsync(e+"/metallicRoughnessTexture",t.metallicRoughnessTexture,function(e){e.name=n.name+" (Metallic Roughness)",n.metallicTexture=e})),n.useMetallnessFromMetallicTextureBlue=!0,n.useRoughnessFromMetallicTextureGreen=!0,n.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(o).then(function(){})},e.prototype._loadMaterialAsync=function(t,n,r,o,a){void 0===a&&(a=function(){});var i=this._extensionsLoadMaterialAsync(t,n,r,o,a);if(i)return i;n._data=n._data||{};var s=n._data[o];if(!s){this.logOpen(t+" "+(n.name||""));var l=this.createMaterial(t,n,o);s={babylonMaterial:l,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(t,n,l)},n._data[o]=s,e.AddPointerMetadata(l,t),this._parent.onMaterialLoadedObservable.notifyObservers(l),this.logClose()}return s.babylonMeshes.push(r),r.onDisposeObservable.addOnce(function(){var e=s.babylonMeshes.indexOf(r);-1!==e&&s.babylonMeshes.splice(e,1)}),a(s.babylonMaterial),s.promise.then(function(){return s.babylonMaterial})},e.prototype._createDefaultMaterial=function(e,t){this._babylonScene._blockEntityCollection=this._forAssetContainer;var n=new r.PBRMaterial(e,this._babylonScene);return this._babylonScene._blockEntityCollection=!1,n.fillMode=t,n.enableSpecularAntiAliasing=!0,n.useRadianceOverAlpha=!this._parent.transparencyAsCoverage,n.useSpecularOverAlpha=!this._parent.transparencyAsCoverage,n.transparencyMode=r.PBRMaterial.PBRMATERIAL_OPAQUE,n.metallic=1,n.roughness=1,n},e.prototype.createMaterial=function(e,t,n){var r=this._extensionsCreateMaterial(e,t,n);if(r)return r;var o=t.name||"material"+t.index;return this._createDefaultMaterial(o,n)},e.prototype.loadMaterialPropertiesAsync=function(e,t,n){var r=this._extensionsLoadMaterialPropertiesAsync(e,t,n);if(r)return r;var o=new Array;return o.push(this.loadMaterialBasePropertiesAsync(e,t,n)),t.pbrMetallicRoughness&&o.push(this._loadMaterialMetallicRoughnessPropertiesAsync(e+"/pbrMetallicRoughness",t.pbrMetallicRoughness,n)),this.loadMaterialAlphaProperties(e,t,n),Promise.all(o).then(function(){})},e.prototype.loadMaterialBasePropertiesAsync=function(e,t,n){if(!(n instanceof r.PBRMaterial))throw new Error(e+": Material type not supported");var o=new Array;return n.emissiveColor=t.emissiveFactor?r.Color3.FromArray(t.emissiveFactor):new r.Color3(0,0,0),t.doubleSided&&(n.backFaceCulling=!1,n.twoSidedLighting=!0),t.normalTexture&&(o.push(this.loadTextureInfoAsync(e+"/normalTexture",t.normalTexture,function(e){e.name=n.name+" (Normal)",n.bumpTexture=e})),n.invertNormalMapX=!this._babylonScene.useRightHandedSystem,n.invertNormalMapY=this._babylonScene.useRightHandedSystem,null!=t.normalTexture.scale&&(n.bumpTexture.level=t.normalTexture.scale),n.forceIrradianceInFragment=!0),t.occlusionTexture&&(o.push(this.loadTextureInfoAsync(e+"/occlusionTexture",t.occlusionTexture,function(e){e.name=n.name+" (Occlusion)",n.ambientTexture=e})),n.useAmbientInGrayScale=!0,null!=t.occlusionTexture.strength&&(n.ambientTextureStrength=t.occlusionTexture.strength)),t.emissiveTexture&&o.push(this.loadTextureInfoAsync(e+"/emissiveTexture",t.emissiveTexture,function(e){e.name=n.name+" (Emissive)",n.emissiveTexture=e})),Promise.all(o).then(function(){})},e.prototype.loadMaterialAlphaProperties=function(e,t,n){if(!(n instanceof r.PBRMaterial))throw new Error(e+": Material type not supported");switch(t.alphaMode||"OPAQUE"){case"OPAQUE":n.transparencyMode=r.PBRMaterial.PBRMATERIAL_OPAQUE;break;case"MASK":n.transparencyMode=r.PBRMaterial.PBRMATERIAL_ALPHATEST,n.alphaCutOff=null==t.alphaCutoff?.5:t.alphaCutoff,n.albedoTexture&&(n.albedoTexture.hasAlpha=!0);break;case"BLEND":n.transparencyMode=r.PBRMaterial.PBRMATERIAL_ALPHABLEND,n.albedoTexture&&(n.albedoTexture.hasAlpha=!0,n.useAlphaFromAlbedoTexture=!0);break;default:throw new Error(e+"/alphaMode: Invalid value ("+t.alphaMode+")")}},e.prototype.loadTextureInfoAsync=function(t,n,r){var o=this;void 0===r&&(r=function(){});var i=this._extensionsLoadTextureInfoAsync(t,n,r);if(i)return i;if(this.logOpen(""+t),n.texCoord>=2)throw new Error(t+"/texCoord: Invalid value ("+n.texCoord+")");var s=a.Get(t+"/index",this._gltf.textures,n.index),l=this._loadTextureAsync("/textures/"+n.index,s,function(a){a.coordinatesIndex=n.texCoord||0,e.AddPointerMetadata(a,t),o._parent.onTextureLoadedObservable.notifyObservers(a),r(a)});return this.logClose(),l},e.prototype._loadTextureAsync=function(t,n,r){void 0===r&&(r=function(){});var o=this._extensionsLoadTextureAsync(t,n,r);if(o)return o;this.logOpen(t+" "+(n.name||""));var i=null==n.sampler?e.DefaultSampler:a.Get(t+"/sampler",this._gltf.samplers,n.sampler),s=a.Get(t+"/source",this._gltf.images,n.source),l=this._createTextureAsync(t,i,s,r);return this.logClose(),l},e.prototype._createTextureAsync=function(e,t,n,o){var a=this;void 0===o&&(o=function(){});var i=this._loadSampler("/samplers/"+t.index,t),s=new Array,l=new r.Deferred;this._babylonScene._blockEntityCollection=this._forAssetContainer;var u=new r.Texture(null,this._babylonScene,i.noMipMaps,!1,i.samplingMode,function(){a._disposed||l.resolve()},function(t,n){a._disposed||l.reject(new Error(e+": "+(n&&n.message?n.message:t||"Failed to load texture")))},void 0,void 0,void 0,n.mimeType);return this._babylonScene._blockEntityCollection=!1,s.push(l.promise),s.push(this.loadImageAsync("/images/"+n.index,n).then(function(e){var t=n.uri||a._fileName+"#image"+n.index,r="data:"+a._uniqueRootUrl+t;u.updateURL(r,e)})),u.wrapU=i.wrapU,u.wrapV=i.wrapV,o(u),Promise.all(s).then(function(){return u})},e.prototype._loadSampler=function(t,n){return n._data||(n._data={noMipMaps:9728===n.minFilter||9729===n.minFilter,samplingMode:e._GetTextureSamplingMode(t,n),wrapU:e._GetTextureWrapMode(t+"/wrapS",n.wrapS),wrapV:e._GetTextureWrapMode(t+"/wrapT",n.wrapT)}),n._data},e.prototype.loadImageAsync=function(e,t){if(!t._data){if(this.logOpen(e+" "+(t.name||"")),t.uri)t._data=this.loadUriAsync(e+"/uri",t,t.uri);else{var n=a.Get(e+"/bufferView",this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync("/bufferViews/"+n.index,n)}this.logClose()}return t._data},e.prototype.loadUriAsync=function(t,n,a){var i=this,s=this._extensionsLoadUriAsync(t,n,a);if(s)return s;if(!e._ValidateUri(a))throw new Error(t+": '"+a+"' is invalid");if(r.Tools.IsBase64(a)){var l=new Uint8Array(r.Tools.DecodeBase64(a));return this.log("Decoded "+a.substr(0,64)+"... ("+l.length+" bytes)"),Promise.resolve(l)}return this.log("Loading "+a),this._parent.preprocessUrlAsync(this._rootUrl+a).then(function(e){return new Promise(function(n,s){if(!i._disposed){var l=r.Tools.LoadFile(e,function(e){if(!i._disposed){var t=new Uint8Array(e);i.log("Loaded "+a+" ("+t.length+" bytes)"),n(t)}},function(e){if(!i._disposed&&(l&&(l._lengthComputable=e.lengthComputable,l._loaded=e.loaded,l._total=e.total),i._state===o.GLTFLoaderState.LOADING))try{i._onProgress()}catch(e){s(e)}},i._babylonScene.offlineProvider,!0,function(e,n){i._disposed||s(new r.LoadFileError(t+": Failed to load '"+a+"'"+(e?": "+e.status+" "+e.statusText:""),e))});i._requests.push(l)}})})},e.prototype._onProgress=function(){if(this._progressCallback){for(var e=!0,t=0,n=0,o=0,a=this._requests;o<a.length;o++){var i=a[o];if(void 0===i._lengthComputable||void 0===i._loaded||void 0===i._total)return;e=e&&i._lengthComputable,t+=i._loaded,n+=i._total}this._progressCallback(new r.SceneLoaderProgressEvent(e,t,e?n:0))}},e.AddPointerMetadata=function(e,t){var n=e.metadata=e.metadata||{},r=n.gltf=n.gltf||{};(r.pointers=r.pointers||[]).push(t)},e._GetTextureWrapMode=function(e,t){switch(t=null==t?10497:t){case 33071:return r.Texture.CLAMP_ADDRESSMODE;case 33648:return r.Texture.MIRROR_ADDRESSMODE;case 10497:return r.Texture.WRAP_ADDRESSMODE;default:return r.Logger.Warn(e+": Invalid value ("+t+")"),r.Texture.WRAP_ADDRESSMODE}},e._GetTextureSamplingMode=function(e,t){var n=null==t.magFilter?9729:t.magFilter,o=null==t.minFilter?9987:t.minFilter;if(9729===n)switch(o){case 9728:return r.Texture.LINEAR_NEAREST;case 9729:return r.Texture.LINEAR_LINEAR;case 9984:return r.Texture.LINEAR_NEAREST_MIPNEAREST;case 9985:return r.Texture.LINEAR_LINEAR_MIPNEAREST;case 9986:return r.Texture.LINEAR_NEAREST_MIPLINEAR;case 9987:return r.Texture.LINEAR_LINEAR_MIPLINEAR;default:return r.Logger.Warn(e+"/minFilter: Invalid value ("+o+")"),r.Texture.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==n&&r.Logger.Warn(e+"/magFilter: Invalid value ("+n+")"),o){case 9728:return r.Texture.NEAREST_NEAREST;case 9729:return r.Texture.NEAREST_LINEAR;case 9984:return r.Texture.NEAREST_NEAREST_MIPNEAREST;case 9985:return r.Texture.NEAREST_LINEAR_MIPNEAREST;case 9986:return r.Texture.NEAREST_NEAREST_MIPLINEAR;case 9987:return r.Texture.NEAREST_LINEAR_MIPLINEAR;default:return r.Logger.Warn(e+"/minFilter: Invalid value ("+o+")"),r.Texture.NEAREST_NEAREST_MIPNEAREST}},e._GetTypedArrayConstructor=function(e,t){switch(t){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(e+": Invalid component type "+t)}},e._GetTypedArray=function(t,n,r,o,a){var i=r.buffer;o=r.byteOffset+(o||0);var s=e._GetTypedArrayConstructor(t+"/componentType",n);try{return new s(i,o,a)}catch(e){throw new Error(t+": "+e)}},e._GetNumComponents=function(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(e+": Invalid type ("+t+")")},e._ValidateUri=function(e){return r.Tools.IsBase64(e)||-1===e.indexOf("..")},e._GetDrawMode=function(e,t){switch(null==t&&(t=4),t){case 0:return r.Material.PointListDrawMode;case 1:return r.Material.LineListDrawMode;case 2:return r.Material.LineLoopDrawMode;case 3:return r.Material.LineStripDrawMode;case 4:return r.Material.TriangleFillMode;case 5:return r.Material.TriangleStripDrawMode;case 6:return r.Material.TriangleFanDrawMode}throw new Error(e+": Invalid mesh primitive mode ("+t+")")},e.prototype._compileMaterialsAsync=function(){var e=this;this._parent._startPerformanceCounter("Compile materials");var t=new Array;if(this._gltf.materials)for(var n=0,r=this._gltf.materials;n<r.length;n++){var o=r[n];if(o._data)for(var a in o._data)for(var i=o._data[a],s=0,l=i.babylonMeshes;s<l.length;s++){var u=l[s];u.computeWorldMatrix(!0);var c=i.babylonMaterial;t.push(c.forceCompilationAsync(u)),t.push(c.forceCompilationAsync(u,{useInstances:!0})),this._parent.useClipPlane&&(t.push(c.forceCompilationAsync(u,{clipPlane:!0})),t.push(c.forceCompilationAsync(u,{clipPlane:!0,useInstances:!0})))}}return Promise.all(t).then(function(){e._parent._endPerformanceCounter("Compile materials")})},e.prototype._compileShadowGeneratorsAsync=function(){var e=this;this._parent._startPerformanceCounter("Compile shadow generators");for(var t=new Array,n=0,r=this._babylonScene.lights;n<r.length;n++){var o=r[n].getShadowGenerator();o&&t.push(o.forceCompilationAsync())}return Promise.all(t).then(function(){e._parent._endPerformanceCounter("Compile shadow generators")})},e.prototype._forEachExtensions=function(e){for(var t=0,n=this._extensions;t<n.length;t++){var r=n[t];r.enabled&&e(r)}},e.prototype._applyExtensions=function(e,t,n){for(var r=0,o=this._extensions;r<o.length;r++){var a=o[r];if(a.enabled){var i=a.name+"."+t,s=e;s._activeLoaderExtensionFunctions=s._activeLoaderExtensionFunctions||{};var l=s._activeLoaderExtensionFunctions;if(!l[i]){l[i]=!0;try{var u=n(a);if(u)return u}finally{delete l[i]}}}}return null},e.prototype._extensionsOnLoading=function(){this._forEachExtensions(function(e){return e.onLoading&&e.onLoading()})},e.prototype._extensionsOnReady=function(){this._forEachExtensions(function(e){return e.onReady&&e.onReady()})},e.prototype._extensionsLoadSceneAsync=function(e,t){return this._applyExtensions(t,"loadScene",function(n){return n.loadSceneAsync&&n.loadSceneAsync(e,t)})},e.prototype._extensionsLoadNodeAsync=function(e,t,n){return this._applyExtensions(t,"loadNode",function(r){return r.loadNodeAsync&&r.loadNodeAsync(e,t,n)})},e.prototype._extensionsLoadCameraAsync=function(e,t,n){return this._applyExtensions(t,"loadCamera",function(r){return r.loadCameraAsync&&r.loadCameraAsync(e,t,n)})},e.prototype._extensionsLoadVertexDataAsync=function(e,t,n){return this._applyExtensions(t,"loadVertexData",function(r){return r._loadVertexDataAsync&&r._loadVertexDataAsync(e,t,n)})},e.prototype._extensionsLoadMeshPrimitiveAsync=function(e,t,n,r,o,a){return this._applyExtensions(o,"loadMeshPrimitive",function(i){return i._loadMeshPrimitiveAsync&&i._loadMeshPrimitiveAsync(e,t,n,r,o,a)})},e.prototype._extensionsLoadMaterialAsync=function(e,t,n,r,o){return this._applyExtensions(t,"loadMaterial",function(a){return a._loadMaterialAsync&&a._loadMaterialAsync(e,t,n,r,o)})},e.prototype._extensionsCreateMaterial=function(e,t,n){return this._applyExtensions(t,"createMaterial",function(r){return r.createMaterial&&r.createMaterial(e,t,n)})},e.prototype._extensionsLoadMaterialPropertiesAsync=function(e,t,n){return this._applyExtensions(t,"loadMaterialProperties",function(r){return r.loadMaterialPropertiesAsync&&r.loadMaterialPropertiesAsync(e,t,n)})},e.prototype._extensionsLoadTextureInfoAsync=function(e,t,n){return this._applyExtensions(t,"loadTextureInfo",function(r){return r.loadTextureInfoAsync&&r.loadTextureInfoAsync(e,t,n)})},e.prototype._extensionsLoadTextureAsync=function(e,t,n){return this._applyExtensions(t,"loadTexture",function(r){return r._loadTextureAsync&&r._loadTextureAsync(e,t,n)})},e.prototype._extensionsLoadAnimationAsync=function(e,t){return this._applyExtensions(t,"loadAnimation",function(n){return n.loadAnimationAsync&&n.loadAnimationAsync(e,t)})},e.prototype._extensionsLoadSkinAsync=function(e,t,n){return this._applyExtensions(n,"loadSkin",function(r){return r._loadSkinAsync&&r._loadSkinAsync(e,t,n)})},e.prototype._extensionsLoadUriAsync=function(e,t,n){return this._applyExtensions(t,"loadUri",function(r){return r._loadUriAsync&&r._loadUriAsync(e,t,n)})},e.prototype._extensionsLoadBufferViewAsync=function(e,t){return this._applyExtensions(t,"loadBufferView",function(n){return n.loadBufferViewAsync&&n.loadBufferViewAsync(e,t)})},e.prototype._extensionsLoadBufferAsync=function(e,t,n,r){return this._applyExtensions(t,"loadBuffer",function(o){return o.loadBufferAsync&&o.loadBufferAsync(e,t,n,r)})},e.LoadExtensionAsync=function(e,t,n,r){if(!t.extensions)return null;var o=t.extensions[n];return o?r(e+"/extensions/"+n,o):null},e.LoadExtraAsync=function(e,t,n,r){if(!t.extras)return null;var o=t.extras[n];return o?r(e+"/extras/"+n,o):null},e.prototype.isExtensionUsed=function(e){return!!this._gltf.extensionsUsed&&-1!==this._gltf.extensionsUsed.indexOf(e)},e.prototype.logOpen=function(e){this._parent._logOpen(e)},e.prototype.logClose=function(){this._parent._logClose()},e.prototype.log=function(e){this._parent._log(e)},e.prototype.startPerformanceCounter=function(e){this._parent._startPerformanceCounter(e)},e.prototype.endPerformanceCounter=function(e){this._parent._endPerformanceCounter(e)},e._RegisteredExtensions={},e.DefaultSampler={index:-1},e}();o.GLTFFileLoader._CreateGLTF2Loader=function(e){return new i(e)}},function(e,t,n){"use strict";n.r(t),n.d(t,"GLTFLoaderCoordinateSystemMode",function(){return r}),n.d(t,"GLTFLoaderAnimationStartMode",function(){return o}),n.d(t,"GLTFLoaderState",function(){return a}),n.d(t,"GLTFFileLoader",function(){return l});var r,o,a,i=n(0),s=n(3);!function(e){e[e.AUTO=0]="AUTO",e[e.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"}(r||(r={})),function(e){e[e.NONE=0]="NONE",e[e.FIRST=1]="FIRST",e[e.ALL=2]="ALL"}(o||(o={})),function(e){e[e.LOADING=0]="LOADING",e[e.READY=1]="READY",e[e.COMPLETE=2]="COMPLETE"}(a||(a={}));var l=function(){function e(){this.onParsedObservable=new i.Observable,this.coordinateSystemMode=r.AUTO,this.animationStartMode=o.FIRST,this.compileMaterials=!1,this.useClipPlane=!1,this.compileShadowGenerators=!1,this.transparencyAsCoverage=!1,this.useRangeRequests=!1,this.createInstances=!0,this.preprocessUrlAsync=function(e){return Promise.resolve(e)},this.onMeshLoadedObservable=new i.Observable,this.onTextureLoadedObservable=new i.Observable,this.onMaterialLoadedObservable=new i.Observable,this.onCameraLoadedObservable=new i.Observable,this.onCompleteObservable=new i.Observable,this.onErrorObservable=new i.Observable,this.onDisposeObservable=new i.Observable,this.onExtensionLoadedObservable=new i.Observable,this.validate=!1,this.onValidatedObservable=new i.Observable,this._loader=null,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled}return Object.defineProperty(e.prototype,"onParsed",{set:function(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),this._onParsedObserver=this.onParsedObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onMeshLoaded",{set:function(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onTextureLoaded",{set:function(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onMaterialLoaded",{set:function(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onCameraLoaded",{set:function(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onComplete",{set:function(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onError",{set:function(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onExtensionLoaded",{set:function(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"loggingEnabled",{get:function(){return this._loggingEnabled},set:function(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"capturePerformanceCounters",{get:function(){return this._capturePerformanceCounters},set:function(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onValidated",{set:function(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this._loader&&(this._loader.dispose(),this._loader=null),this._clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()},e.prototype._clear=function(){this.preprocessUrlAsync=function(e){return Promise.resolve(e)},this.onMeshLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear()},e.prototype.requestFile=function(e,t,n,r,o,a){var s=this;if(o){if(this.useRangeRequests){this.validate&&i.Logger.Warn("glTF validation is not supported when range requests are enabled");var l=new Array,u={abort:function(){return l.forEach(function(e){return e.abort()})},onCompleteObservable:new i.Observable},c={readAsync:function(n,o){return new Promise(function(a,i){l.push(e._requestFile(t,function(e,t){var n=t.getResponseHeader("Content-Range");n&&(c.byteLength=Number(n.split("/")[1])),a(new Uint8Array(e))},r,!0,!0,function(e){i(e)},function(e){e.setRequestHeader("Range","bytes="+n+"-"+(n+o-1))}))})},byteLength:0};return this._unpackBinaryAsync(new i.DataReader(c)).then(function(e){u.onCompleteObservable.notifyObservers(u),n(e)},a),u}return e._requestFile(t,function(e,t){var r=e;s._unpackBinaryAsync(new i.DataReader({readAsync:function(e,t){return Promise.resolve(new Uint8Array(r,e,t))},byteLength:r.byteLength})).then(function(e){n(e,t)},a)},r,!0,!0,a)}return e._requestFile(t,function(r,o){s._validate(e,r,i.Tools.GetFolderPath(t),i.Tools.GetFilename(t)),n({json:s._parseJson(r)},o)},r,!0,!1,a)},e.prototype.readFile=function(e,t,n,r,o,a){var s=this;return e._readFile(t,function(r){if(s._validate(e,r,"file:",t.name),o){var l=r;s._unpackBinaryAsync(new i.DataReader({readAsync:function(e,t){return Promise.resolve(new Uint8Array(l,e,t))},byteLength:l.byteLength})).then(n,a)}else n({json:s._parseJson(r)})},r,o,a)},e.prototype.importMeshAsync=function(e,t,n,r,o,a){var i=this;return Promise.resolve().then(function(){return i.onParsedObservable.notifyObservers(n),i.onParsedObservable.clear(),i._log("Loading "+(a||"")),i._loader=i._getLoader(n),i._loader.importMeshAsync(e,t,!1,n,r,o,a)})},e.prototype.loadAsync=function(e,t,n,r,o){var a=this;return Promise.resolve().then(function(){return a.onParsedObservable.notifyObservers(t),a.onParsedObservable.clear(),a._log("Loading "+(o||"")),a._loader=a._getLoader(t),a._loader.loadAsync(e,t,n,r,o)})},e.prototype.loadAssetContainerAsync=function(e,t,n,r,o){var a=this;return Promise.resolve().then(function(){a.onParsedObservable.notifyObservers(t),a.onParsedObservable.clear(),a._log("Loading "+(o||"")),a._loader=a._getLoader(t);var s=[];a.onMaterialLoadedObservable.add(function(e){s.push(e)});var l=[];return a.onTextureLoadedObservable.add(function(e){l.push(e)}),a._loader.importMeshAsync(null,e,!0,t,n,r,o).then(function(t){var n=new i.AssetContainer(e);return Array.prototype.push.apply(n.meshes,t.meshes),Array.prototype.push.apply(n.particleSystems,t.particleSystems),Array.prototype.push.apply(n.skeletons,t.skeletons),Array.prototype.push.apply(n.animationGroups,t.animationGroups),Array.prototype.push.apply(n.materials,s),Array.prototype.push.apply(n.textures,l),Array.prototype.push.apply(n.lights,t.lights),Array.prototype.push.apply(n.transformNodes,t.transformNodes),n})})},e.prototype.canDirectLoad=function(e){return-1!==e.indexOf("asset")&&-1!==e.indexOf("version")},e.prototype.directLoad=function(e,t){return this._validate(e,t),{json:this._parseJson(t)}},e.prototype.createPlugin=function(){return new e},Object.defineProperty(e.prototype,"loaderState",{get:function(){return this._loader?this._loader.state:null},enumerable:!0,configurable:!0}),e.prototype.whenCompleteAsync=function(){var e=this;return new Promise(function(t,n){e.onCompleteObservable.addOnce(function(){t()}),e.onErrorObservable.addOnce(function(e){n(e)})})},e.prototype._validate=function(e,t,n,r){var o=this;void 0===n&&(n=""),void 0===r&&(r=""),this.validate&&(this._startPerformanceCounter("Validate JSON"),s.GLTFValidation.ValidateAsync(t,n,r,function(t){return o.preprocessUrlAsync(n+t).then(function(t){return e._loadFileAsync(t,void 0,!0,!0)})}).then(function(e){o._endPerformanceCounter("Validate JSON"),o.onValidatedObservable.notifyObservers(e),o.onValidatedObservable.clear()},function(e){o._endPerformanceCounter("Validate JSON"),i.Tools.Warn("Failed to validate: "+e.message),o.onValidatedObservable.clear()}))},e.prototype._getLoader=function(t){var n=t.json.asset||{};this._log("Asset version: "+n.version),n.minVersion&&this._log("Asset minimum version: "+n.minVersion),n.generator&&this._log("Asset generator: "+n.generator);var r=e._parseVersion(n.version);if(!r)throw new Error("Invalid version: "+n.version);if(void 0!==n.minVersion){var o=e._parseVersion(n.minVersion);if(!o)throw new Error("Invalid minimum version: "+n.minVersion);if(e._compareVersion(o,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+n.minVersion)}var a={1:e._CreateGLTF1Loader,2:e._CreateGLTF2Loader}[r.major];if(!a)throw new Error("Unsupported version: "+n.version);return a(this)},e.prototype._parseJson=function(e){this._startPerformanceCounter("Parse JSON"),this._log("JSON length: "+e.length);var t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t},e.prototype._unpackBinaryAsync=function(e){var t=this;return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then(function(){var n=e.readUint32();if(1179937895!==n)throw new Error("Unexpected magic: "+n);var r=e.readUint32();t.loggingEnabled&&t._log("Binary version: "+r);var o,a=e.readUint32();if(0!=e.buffer.byteLength&&a!==e.buffer.byteLength)throw new Error("Length in header does not match actual data length: "+a+" != "+e.buffer.byteLength);switch(r){case 1:o=t._unpackBinaryV1Async(e,a);break;case 2:o=t._unpackBinaryV2Async(e,a);break;default:throw new Error("Unsupported version: "+r)}return t._endPerformanceCounter("Unpack Binary"),o})},e.prototype._unpackBinaryV1Async=function(e,t){var n=e.readUint32(),r=e.readUint32();if(0!==r)throw new Error("Unexpected content format: "+r);var o=t-e.byteOffset,a={json:this._parseJson(e.readString(n)),bin:null};if(0!==o){var i=e.byteOffset;a.bin={readAsync:function(t,n){return e.buffer.readAsync(i+t,n)},byteLength:o}}return Promise.resolve(a)},e.prototype._unpackBinaryV2Async=function(e,t){var n=this,r=1313821514,o=5130562,a=e.readUint32();if(e.readUint32()!==r)throw new Error("First chunk format is not JSON");return e.byteOffset+a===t?e.loadAsync(a).then(function(){return{json:n._parseJson(e.readString(a)),bin:null}}):e.loadAsync(a+8).then(function(){var i={json:n._parseJson(e.readString(a)),bin:null},s=function(){var n=e.readUint32();switch(e.readUint32()){case r:throw new Error("Unexpected JSON chunk");case o:var a=e.byteOffset;i.bin={readAsync:function(t,n){return e.buffer.readAsync(a+t,n)},byteLength:n},e.skipBytes(n);break;default:e.skipBytes(n)}return e.byteOffset!==t?e.loadAsync(8).then(s):Promise.resolve(i)};return s()})},e._parseVersion=function(e){if("1.0"===e||"1.0.1"===e)return{major:1,minor:0};var t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null},e._compareVersion=function(e,t){return e.major>t.major?1:e.major<t.major?-1:e.minor>t.minor?1:e.minor<t.minor?-1:0},e.prototype._logOpen=function(e){this._log(e),this._logIndentLevel++},e.prototype._logClose=function(){--this._logIndentLevel},e.prototype._logEnabled=function(t){var n=e._logSpaces.substr(0,2*this._logIndentLevel);i.Logger.Log(""+n+t)},e.prototype._logDisabled=function(e){},e.prototype._startPerformanceCounterEnabled=function(e){i.Tools.StartPerformanceCounter(e)},e.prototype._startPerformanceCounterDisabled=function(e){},e.prototype._endPerformanceCounterEnabled=function(e){i.Tools.EndPerformanceCounter(e)},e.prototype._endPerformanceCounterDisabled=function(e){},e.IncrementalLoading=!0,e.HomogeneousCoordinates=!1,e._logSpaces="                                ",e}();i.SceneLoader&&i.SceneLoader.RegisterPlugin(new l)},function(e,t,n){"use strict";n.r(t),n.d(t,"GLTFValidation",function(){return a});var r=n(0);function o(e,t,n,r){var o={externalResourceFunction:function(e){return r(e).then(function(e){return new Uint8Array(e)})}};return n&&(o.uri="file:"===t?n:t+n),e instanceof ArrayBuffer?GLTFValidator.validateBytes(new Uint8Array(e),o):GLTFValidator.validateString(e,o)}var a=function(){function e(){}return e.ValidateAsync=function(e,t,n,a){var i=this;return"function"==typeof Worker?new Promise(function(s,l){var u=o+"("+function(){var e=[];onmessage=function(t){var n=t.data;switch(n.id){case"init":importScripts(n.url);break;case"validate":o(n.data,n.rootUrl,n.fileName,function(t){return new Promise(function(n,r){var o=e.length;e.push({resolve:n,reject:r}),postMessage({id:"getExternalResource",index:o,uri:t})})}).then(function(e){postMessage({id:"validate.resolve",value:e})},function(e){postMessage({id:"validate.reject",reason:e})});break;case"getExternalResource.resolve":e[n.index].resolve(n.value);break;case"getExternalResource.reject":e[n.index].reject(n.reason)}}}+")()",c=URL.createObjectURL(new Blob([u],{type:"application/javascript"})),f=new Worker(c),d=function(e){f.removeEventListener("error",d),f.removeEventListener("message",h),l(e)},h=function(e){var t=e.data;switch(t.id){case"getExternalResource":a(t.uri).then(function(e){f.postMessage({id:"getExternalResource.resolve",index:t.index,value:e},[e])},function(e){f.postMessage({id:"getExternalResource.reject",index:t.index,reason:e})});break;case"validate.resolve":f.removeEventListener("error",d),f.removeEventListener("message",h),s(t.value);break;case"validate.reject":f.removeEventListener("error",d),f.removeEventListener("message",h),l(t.reason)}};f.addEventListener("error",d),f.addEventListener("message",h),f.postMessage({id:"init",url:r.Tools.GetAbsoluteUrl(i.Configuration.url)}),f.postMessage({id:"validate",data:e,rootUrl:t,fileName:n})}):(this._LoadScriptPromise||(this._LoadScriptPromise=r.Tools.LoadScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then(function(){return o(e,t,n,a)}))},e.Configuration={url:"https://preview.babylonjs.com/gltf_validator.js"},e}()},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){"use strict";n.r(t);var r=n(0),o=n(1),a="EXT_lights_image_based",i=function(){function e(e){this.name=a,this._loader=e,this.enabled=this._loader.isExtensionUsed(a)}return e.prototype.dispose=function(){delete this._loader,delete this._lights},e.prototype.onLoading=function(){var e=this._loader.gltf.extensions;if(e&&e[this.name]){var t=e[this.name];this._lights=t.lights}},e.prototype.loadSceneAsync=function(e,t){var n=this;return o.b.LoadExtensionAsync(e,t,this.name,function(r,a){var i=new Array;i.push(n._loader.loadSceneAsync(e,t)),n._loader.logOpen(""+r);var s=o.a.Get(r+"/light",n._lights,a.light);return i.push(n._loadLightAsync("#/extensions/"+n.name+"/lights/"+a.light,s).then(function(e){n._loader.babylonScene.environmentTexture=e})),n._loader.logClose(),Promise.all(i).then(function(){})})},e.prototype._loadLightAsync=function(e,t){var n=this;if(!t._loaded){var a=new Array;this._loader.logOpen(""+e);for(var i=new Array(t.specularImages.length),s=function(n){var r=t.specularImages[n];i[n]=new Array(r.length);for(var s=function(t){var s=e+"/specularImages/"+n+"/"+t;l._loader.logOpen(""+s);var u=r[t],c=o.a.Get(s,l._loader.gltf.images,u);a.push(l._loader.loadImageAsync("#/images/"+u,c).then(function(e){i[n][t]=e})),l._loader.logClose()},u=0;u<r.length;u++)s(u)},l=this,u=0;u<t.specularImages.length;u++)s(u);this._loader.logClose(),t._loaded=Promise.all(a).then(function(){var e=new r.RawCubeTexture(n._loader.babylonScene,null,t.specularImageSize);if(t._babylonTexture=e,null!=t.intensity&&(e.level=t.intensity),t.rotation){var o=r.Quaternion.FromArray(t.rotation);n._loader.babylonScene.useRightHandedSystem||(o=r.Quaternion.Inverse(o)),r.Matrix.FromQuaternionToRef(o,e.getReflectionTextureMatrix())}var a=r.SphericalHarmonics.FromArray(t.irradianceCoefficients);a.scaleInPlace(t.intensity),a.convertIrradianceToLambertianRadiance();var s=r.SphericalPolynomial.FromHarmonics(a),l=(i.length-1)/r.Scalar.Log2(t.specularImageSize);return e.updateRGBDAsync(i,s,l)})}return t._loaded.then(function(){return t._babylonTexture})},e}();o.b.RegisterExtension(a,function(e){return new i(e)});var s="KHR_draco_mesh_compression",l=function(){function e(e){this.name=s,this._loader=e,this.enabled=r.DracoCompression.DecoderAvailable&&this._loader.isExtensionUsed(s)}return e.prototype.dispose=function(){delete this.dracoCompression,delete this._loader},e.prototype._loadVertexDataAsync=function(e,t,n){var a=this;return o.b.LoadExtensionAsync(e,t,this.name,function(i,s){if(null!=t.mode){if(5!==t.mode&&4!==t.mode)throw new Error(e+": Unsupported mode "+t.mode);if(5===t.mode)throw new Error(e+": Mode "+t.mode+" is not currently supported")}var l={},u=function(e,t){var r=s.attributes[e];null!=r&&(n._delayInfo=n._delayInfo||[],-1===n._delayInfo.indexOf(t)&&n._delayInfo.push(t),l[t]=r)};u("POSITION",r.VertexBuffer.PositionKind),u("NORMAL",r.VertexBuffer.NormalKind),u("TANGENT",r.VertexBuffer.TangentKind),u("TEXCOORD_0",r.VertexBuffer.UVKind),u("TEXCOORD_1",r.VertexBuffer.UV2Kind),u("JOINTS_0",r.VertexBuffer.MatricesIndicesKind),u("WEIGHTS_0",r.VertexBuffer.MatricesWeightsKind),u("COLOR_0",r.VertexBuffer.ColorKind);var c=o.a.Get(i,a._loader.gltf.bufferViews,s.bufferView);return c._dracoBabylonGeometry||(c._dracoBabylonGeometry=a._loader.loadBufferViewAsync("#/bufferViews/"+c.index,c).then(function(t){return(a.dracoCompression||r.DracoCompression.Default).decodeMeshAsync(t,l).then(function(e){var t=new r.Geometry(n.name,a._loader.babylonScene);return e.applyToGeometry(t),t}).catch(function(t){throw new Error(e+": "+t.message)})})),c._dracoBabylonGeometry})},e}();o.b.RegisterExtension(s,function(e){return new l(e)});var u,c="KHR_lights_punctual";!function(e){e.DIRECTIONAL="directional",e.POINT="point",e.SPOT="spot"}(u||(u={}));var f=function(){function e(e){this.name=c,this._loader=e,this.enabled=this._loader.isExtensionUsed(c)}return e.prototype.dispose=function(){delete this._loader,delete this._lights},e.prototype.onLoading=function(){var e=this._loader.gltf.extensions;if(e&&e[this.name]){var t=e[this.name];this._lights=t.lights}},e.prototype.loadNodeAsync=function(e,t,n){var a=this;return o.b.LoadExtensionAsync(e,t,this.name,function(i,s){return a._loader.loadNodeAsync(e,t,function(e){var t,l=o.a.Get(i,a._lights,s.light),c=l.name||e.name;switch(a._loader.babylonScene._blockEntityCollection=a._loader._forAssetContainer,l.type){case u.DIRECTIONAL:t=new r.DirectionalLight(c,r.Vector3.Backward(),a._loader.babylonScene);break;case u.POINT:t=new r.PointLight(c,r.Vector3.Zero(),a._loader.babylonScene);break;case u.SPOT:var f=new r.SpotLight(c,r.Vector3.Zero(),r.Vector3.Backward(),0,1,a._loader.babylonScene);f.angle=2*(l.spot&&l.spot.outerConeAngle||Math.PI/4),f.innerAngle=2*(l.spot&&l.spot.innerConeAngle||0),t=f;break;default:throw a._loader.babylonScene._blockEntityCollection=!1,new Error(i+": Invalid light type ("+l.type+")")}a._loader.babylonScene._blockEntityCollection=!1,t.falloffType=r.Light.FALLOFF_GLTF,t.diffuse=l.color?r.Color3.FromArray(l.color):r.Color3.White(),t.intensity=null==l.intensity?1:l.intensity,t.range=null==l.range?Number.MAX_VALUE:l.range,t.parent=e,a._loader._babylonLights.push(t),o.b.AddPointerMetadata(t,i),n(e)})})},e}();o.b.RegisterExtension(c,function(e){return new f(e)});var d="KHR_materials_pbrSpecularGlossiness",h=function(){function e(e){this.name=d,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(d)}return e.prototype.dispose=function(){delete this._loader},e.prototype.loadMaterialPropertiesAsync=function(e,t,n){var r=this;return o.b.LoadExtensionAsync(e,t,this.name,function(o,a){var i=new Array;return i.push(r._loader.loadMaterialBasePropertiesAsync(e,t,n)),i.push(r._loadSpecularGlossinessPropertiesAsync(o,t,a,n)),r._loader.loadMaterialAlphaProperties(e,t,n),Promise.all(i).then(function(){})})},e.prototype._loadSpecularGlossinessPropertiesAsync=function(e,t,n,o){if(!(o instanceof r.PBRMaterial))throw new Error(e+": Material type not supported");var a=new Array;return o.metallic=null,o.roughness=null,n.diffuseFactor?(o.albedoColor=r.Color3.FromArray(n.diffuseFactor),o.alpha=n.diffuseFactor[3]):o.albedoColor=r.Color3.White(),o.reflectivityColor=n.specularFactor?r.Color3.FromArray(n.specularFactor):r.Color3.White(),o.microSurface=null==n.glossinessFactor?1:n.glossinessFactor,n.diffuseTexture&&a.push(this._loader.loadTextureInfoAsync(e+"/diffuseTexture",n.diffuseTexture,function(e){e.name=o.name+" (Diffuse)",o.albedoTexture=e})),n.specularGlossinessTexture&&(a.push(this._loader.loadTextureInfoAsync(e+"/specularGlossinessTexture",n.specularGlossinessTexture,function(e){e.name=o.name+" (Specular Glossiness)",o.reflectivityTexture=e})),o.reflectivityTexture.hasAlpha=!0,o.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(a).then(function(){})},e}();o.b.RegisterExtension(d,function(e){return new h(e)});var p="KHR_materials_unlit",m=function(){function e(e){this.name=p,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(p)}return e.prototype.dispose=function(){delete this._loader},e.prototype.loadMaterialPropertiesAsync=function(e,t,n){var r=this;return o.b.LoadExtensionAsync(e,t,this.name,function(){return r._loadUnlitPropertiesAsync(e,t,n)})},e.prototype._loadUnlitPropertiesAsync=function(e,t,n){if(!(n instanceof r.PBRMaterial))throw new Error(e+": Material type not supported");var o=new Array;n.unlit=!0;var a=t.pbrMetallicRoughness;return a&&(a.baseColorFactor?(n.albedoColor=r.Color3.FromArray(a.baseColorFactor),n.alpha=a.baseColorFactor[3]):n.albedoColor=r.Color3.White(),a.baseColorTexture&&o.push(this._loader.loadTextureInfoAsync(e+"/baseColorTexture",a.baseColorTexture,function(e){e.name=n.name+" (Base Color)",n.albedoTexture=e}))),t.doubleSided&&(n.backFaceCulling=!1,n.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,n),Promise.all(o).then(function(){})},e}();o.b.RegisterExtension(p,function(e){return new m(e)});var _="KHR_materials_clearcoat",y=function(){function e(e){this.name=_,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(_)}return e.prototype.dispose=function(){delete this._loader},e.prototype.loadMaterialPropertiesAsync=function(e,t,n){var r=this;return o.b.LoadExtensionAsync(e,t,this.name,function(o,a){var i=new Array;return i.push(r._loader.loadMaterialPropertiesAsync(e,t,n)),i.push(r._loadClearCoatPropertiesAsync(o,a,n)),Promise.all(i).then(function(){})})},e.prototype._loadClearCoatPropertiesAsync=function(e,t,n){if(!(n instanceof r.PBRMaterial))throw new Error(e+": Material type not supported");var o=new Array;return n.clearCoat.isEnabled=!0,null!=t.clearcoatFactor?n.clearCoat.intensity=t.clearcoatFactor:n.clearCoat.intensity=0,t.clearcoatTexture&&o.push(this._loader.loadTextureInfoAsync(e+"/clearcoatTexture",t.clearcoatTexture,function(e){e.name=n.name+" (ClearCoat Intensity)",n.clearCoat.texture=e})),null!=t.clearcoatRoughnessFactor?n.clearCoat.roughness=t.clearcoatRoughnessFactor:n.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&o.push(this._loader.loadTextureInfoAsync(e+"/clearcoatRoughnessTexture",t.clearcoatRoughnessTexture,function(e){e.name=n.name+" (ClearCoat Roughness)",n.clearCoat.texture=e})),t.clearcoatNormalTexture&&(o.push(this._loader.loadTextureInfoAsync(e+"/clearcoatNormalTexture",t.clearcoatNormalTexture,function(e){e.name=n.name+" (ClearCoat Normal)",n.clearCoat.bumpTexture=e})),n.invertNormalMapX=!n.getScene().useRightHandedSystem,n.invertNormalMapY=n.getScene().useRightHandedSystem,null!=t.clearcoatNormalTexture.scale&&(n.clearCoat.bumpTexture.level=t.clearcoatNormalTexture.scale)),Promise.all(o).then(function(){})},e}();o.b.RegisterExtension(_,function(e){return new y(e)});var b="KHR_materials_sheen",v=function(){function e(e){this.name=b,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(b)}return e.prototype.dispose=function(){delete this._loader},e.prototype.loadMaterialPropertiesAsync=function(e,t,n){var r=this;return o.b.LoadExtensionAsync(e,t,this.name,function(o,a){var i=new Array;return i.push(r._loader.loadMaterialPropertiesAsync(e,t,n)),i.push(r._loadSheenPropertiesAsync(o,a,n)),Promise.all(i).then(function(){})})},e.prototype._loadSheenPropertiesAsync=function(e,t,n){if(!(n instanceof r.PBRMaterial))throw new Error(e+": Material type not supported");var o=new Array;return n.sheen.isEnabled=!0,null!=t.intensityFactor?n.sheen.intensity=t.intensityFactor:n.sheen.intensity=0,null!=t.colorFactor&&(n.sheen.color=r.Color3.FromArray(t.colorFactor)),t.colorIntensityTexture&&o.push(this._loader.loadTextureInfoAsync(e+"/sheenTexture",t.colorIntensityTexture,function(e){e.name=n.name+" (Sheen Intensity)",n.sheen.texture=e})),Promise.all(o).then(function(){})},e}();o.b.RegisterExtension(b,function(e){return new v(e)});var A="KHR_materials_specular",g=function(){function e(e){this.name=A,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(A)}return e.prototype.dispose=function(){delete this._loader},e.prototype.loadMaterialPropertiesAsync=function(e,t,n){var r=this;return o.b.LoadExtensionAsync(e,t,this.name,function(o,a){var i=new Array;return i.push(r._loader.loadMaterialPropertiesAsync(e,t,n)),i.push(r._loadSpecularPropertiesAsync(o,a,n)),Promise.all(i).then(function(){})})},e.prototype._loadSpecularPropertiesAsync=function(e,t,n){if(!(n instanceof r.PBRMaterial))throw new Error(e+": Material type not supported");return void 0!==t.specularFactor&&(n.metallicF0Factor=t.specularFactor),t.specularTexture&&(n.useMetallicF0FactorFromMetallicTexture=!0),Promise.resolve()},e}();o.b.RegisterExtension(A,function(e){return new g(e)});var T="KHR_mesh_quantization",x=function(){function e(e){this.name=T,this.enabled=e.isExtensionUsed(T)}return e.prototype.dispose=function(){},e}();o.b.RegisterExtension(T,function(e){return new x(e)});var E="KHR_texture_basisu",L=function(){function e(e){this.name=E,this._loader=e,this.enabled=e.isExtensionUsed(E)}return e.prototype.dispose=function(){delete this._loader},e.prototype._loadTextureAsync=function(e,t,n){var r=this;return o.b.LoadExtensionAsync(e,t,this.name,function(a,i){var s=null==t.sampler?o.b.DefaultSampler:o.a.Get(e+"/sampler",r._loader.gltf.samplers,t.sampler),l=o.a.Get(a+"/source",r._loader.gltf.images,i.source);return r._loader._createTextureAsync(e,s,l,function(e){e.gammaSpace=!1,n(e)})})},e}();o.b.RegisterExtension(E,function(e){return new L(e)});var O="KHR_texture_transform",M=function(){function e(e){this.name=O,this._loader=e,this.enabled=this._loader.isExtensionUsed(O)}return e.prototype.dispose=function(){delete this._loader},e.prototype.loadTextureInfoAsync=function(e,t,n){var a=this;return o.b.LoadExtensionAsync(e,t,this.name,function(o,i){return a._loader.loadTextureInfoAsync(e,t,function(e){if(!(e instanceof r.Texture))throw new Error(o+": Texture type not supported");i.offset&&(e.uOffset=i.offset[0],e.vOffset=i.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,i.rotation&&(e.wAng=-i.rotation),i.scale&&(e.uScale=i.scale[0],e.vScale=i.scale[1]),null!=i.texCoord&&(e.coordinatesIndex=i.texCoord),n(e)})})},e}();o.b.RegisterExtension(O,function(e){return new M(e)});var S="MSFT_audio_emitter",w=function(){function e(e){this.name=S,this._loader=e,this.enabled=this._loader.isExtensionUsed(S)}return e.prototype.dispose=function(){delete this._loader,delete this._clips,delete this._emitters},e.prototype.onLoading=function(){var e=this._loader.gltf.extensions;if(e&&e[this.name]){var t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,o.a.Assign(this._clips),o.a.Assign(this._emitters)}},e.prototype.loadSceneAsync=function(e,t){var n=this;return o.b.LoadExtensionAsync(e,t,this.name,function(r,a){var i=new Array;i.push(n._loader.loadSceneAsync(e,t));for(var s=0,l=a.emitters;s<l.length;s++){var u=l[s],c=o.a.Get(r+"/emitters",n._emitters,u);if(null!=c.refDistance||null!=c.maxDistance||null!=c.rolloffFactor||null!=c.distanceModel||null!=c.innerAngle||null!=c.outerAngle)throw new Error(r+": Direction or Distance properties are not allowed on emitters attached to a scene");i.push(n._loadEmitterAsync(r+"/emitters/"+c.index,c))}return Promise.all(i).then(function(){})})},e.prototype.loadNodeAsync=function(e,t,n){var a=this;return o.b.LoadExtensionAsync(e,t,this.name,function(e,i){var s=new Array;return a._loader.loadNodeAsync(e,t,function(t){for(var l=function(n){var i=o.a.Get(e+"/emitters",a._emitters,n);s.push(a._loadEmitterAsync(e+"/emitters/"+i.index,i).then(function(){for(var e=0,n=i._babylonSounds;e<n.length;e++){var o=n[e];o.attachToMesh(t),null==i.innerAngle&&null==i.outerAngle||(o.setLocalDirectionToMesh(r.Vector3.Forward()),o.setDirectionalCone(2*r.Tools.ToDegrees(null==i.innerAngle?Math.PI:i.innerAngle),2*r.Tools.ToDegrees(null==i.outerAngle?Math.PI:i.outerAngle),0))}}))},u=0,c=i.emitters;u<c.length;u++){l(c[u])}n(t)}).then(function(e){return Promise.all(s).then(function(){return e})})})},e.prototype.loadAnimationAsync=function(e,t){var n=this;return o.b.LoadExtensionAsync(e,t,this.name,function(r,a){return n._loader.loadAnimationAsync(e,t).then(function(i){var s=new Array;o.a.Assign(a.events);for(var l=0,u=a.events;l<u.length;l++){var c=u[l];s.push(n._loadAnimationEventAsync(r+"/events/"+c.index,e,t,c,i))}return Promise.all(s).then(function(){return i})})})},e.prototype._loadClipAsync=function(e,t){if(t._objectURL)return t._objectURL;var n;if(t.uri)n=this._loader.loadUriAsync(e,t,t.uri);else{var r=o.a.Get(e+"/bufferView",this._loader.gltf.bufferViews,t.bufferView);n=this._loader.loadBufferViewAsync("#/bufferViews/"+r.index,r)}return t._objectURL=n.then(function(e){return URL.createObjectURL(new Blob([e],{type:t.mimeType}))}),t._objectURL},e.prototype._loadEmitterAsync=function(e,t){var n=this;if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){for(var a=new Array,i=t.name||"emitter"+t.index,s={loop:!1,autoplay:!1,volume:null==t.volume?1:t.volume},l=function(e){var l="#/extensions/"+u.name+"/clips",c=o.a.Get(l,u._clips,t.clips[e].clip);a.push(u._loadClipAsync(l+"/"+t.clips[e].clip,c).then(function(o){var a=t._babylonSounds[e]=new r.Sound(i,o,n._loader.babylonScene,null,s);a.refDistance=t.refDistance||1,a.maxDistance=t.maxDistance||256,a.rolloffFactor=t.rolloffFactor||1,a.distanceModel=t.distanceModel||"exponential",a._positionInEmitterSpace=!0}))},u=this,c=0;c<t.clips.length;c++)l(c);var f=Promise.all(a).then(function(){var e=t.clips.map(function(e){return e.weight||1}),n=new r.WeightedSound(t.loop||!1,t._babylonSounds,e);t.innerAngle&&(n.directionalConeInnerAngle=2*r.Tools.ToDegrees(t.innerAngle)),t.outerAngle&&(n.directionalConeOuterAngle=2*r.Tools.ToDegrees(t.outerAngle)),t.volume&&(n.volume=t.volume),t._babylonData.sound=n});t._babylonData={loaded:f}}return t._babylonData.loaded},e.prototype._getEventAction=function(e,t,n,r,o){switch(n){case"play":return function(e){var n=(o||0)+(e-r);t.play(n)};case"stop":return function(e){t.stop()};case"pause":return function(e){t.pause()};default:throw new Error(e+": Unsupported action "+n)}},e.prototype._loadAnimationEventAsync=function(e,t,n,a,i){var s=this;if(0==i.targetedAnimations.length)return Promise.resolve();var l=i.targetedAnimations[0],u=a.emitter,c=o.a.Get("#/extensions/"+this.name+"/emitters",this._emitters,u);return this._loadEmitterAsync(e,c).then(function(){var t=c._babylonData.sound;if(t){var n=new r.AnimationEvent(a.time,s._getEventAction(e,t,a.action,a.time,a.startOffset));l.animation.addEvent(n),i.onAnimationGroupEndObservable.add(function(){t.stop()}),i.onAnimationGroupPauseObservable.add(function(){t.pause()})}})},e}();o.b.RegisterExtension(S,function(e){return new w(e)});var C="MSFT_lod",N=function(){function e(e){this.name=C,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new r.Observable,this.onMaterialLODsLoadedObservable=new r.Observable,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._indexLOD=null,this._bufferLODs=new Array,this._loader=e,this.enabled=this._loader.isExtensionUsed(C)}return e.prototype.dispose=function(){delete this._loader,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._indexLOD=null,this._bufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()},e.prototype.onReady=function(){for(var e=this,t=function(t){var r=Promise.all(n._nodePromiseLODs[t]).then(function(){0!==t&&e._loader.endPerformanceCounter("Node LOD "+t),e._loader.log("Loaded node LOD "+t),e.onNodeLODsLoadedObservable.notifyObservers(t),t!==e._nodePromiseLODs.length-1&&(e._loader.startPerformanceCounter("Node LOD "+(t+1)),e._nodeSignalLODs[t]&&e._nodeSignalLODs[t].resolve())});n._loader._completePromises.push(r)},n=this,r=0;r<this._nodePromiseLODs.length;r++)t(r);var o=function(t){var n=Promise.all(a._materialPromiseLODs[t]).then(function(){0!==t&&e._loader.endPerformanceCounter("Material LOD "+t),e._loader.log("Loaded material LOD "+t),e.onMaterialLODsLoadedObservable.notifyObservers(t),t!==e._materialPromiseLODs.length-1&&(e._loader.startPerformanceCounter("Material LOD "+(t+1)),e._materialSignalLODs[t]&&e._materialSignalLODs[t].resolve())});a._loader._completePromises.push(n)},a=this;for(r=0;r<this._materialPromiseLODs.length;r++)o(r);for(r=1;r<this._bufferLODs.length;r++)this._loadBufferLOD(r)},e.prototype.loadSceneAsync=function(e,t){var n=this._loader.loadSceneAsync(e,t);return 0!==this._bufferLODs.length&&this._loadBufferLOD(0),n},e.prototype.loadNodeAsync=function(e,t,n){var a=this;return o.b.LoadExtensionAsync(e,t,this.name,function(e,n){var o,i=a._getLODs(e,t,a._loader.gltf.nodes,n.ids);a._loader.logOpen(""+e);for(var s=function(e){var t=i[e];a._indexLOD=e,0!==e&&(a._nodeIndexLOD=e,a._nodeSignalLODs[e]=a._nodeSignalLODs[e]||new r.Deferred);var n=a._loader.loadNodeAsync("#/nodes/"+t.index,t,function(e){e.setEnabled(!1)}).then(function(t){if(0!==e){var n=i[e-1];n._babylonTransformNode&&(a._disposeTransformNode(n._babylonTransformNode),delete n._babylonTransformNode)}return t.setEnabled(!0),t});0===e?o=n:a._nodeIndexLOD=null,a._indexLOD=null,a._nodePromiseLODs[e]=a._nodePromiseLODs[e]||[],a._nodePromiseLODs[e].push(n)},l=0;l<i.length;l++)s(l);return a._loader.logClose(),o})},e.prototype._loadMaterialAsync=function(e,t,n,r,a){var i=this;return this._indexLOD?null:o.b.LoadExtensionAsync(e,t,this.name,function(e,o){var s,l=i._getLODs(e,t,i._loader.gltf.materials,o.ids);i._loader.logOpen(""+e);for(var u=function(e){var t=l[e];i._indexLOD=e,0!==e&&(i._materialIndexLOD=e);var o=i._loader._loadMaterialAsync("#/materials/"+t.index,t,n,r,function(t){0===e&&a(t)}).then(function(t){if(0!==e){a(t);var n=l[e-1]._data;n[r]&&(i._disposeMaterials([n[r].babylonMaterial]),delete n[r])}return t});0===e?s=o:i._materialIndexLOD=null,i._indexLOD=null,i._materialPromiseLODs[e]=i._materialPromiseLODs[e]||[],i._materialPromiseLODs[e].push(o)},c=0;c<l.length;c++)u(c);return i._loader.logClose(),s})},e.prototype._loadUriAsync=function(e,t,n){var o=this;if(null!==this._materialIndexLOD){this._loader.log("deferred");var a=this._materialIndexLOD-1;return this._materialSignalLODs[a]=this._materialSignalLODs[a]||new r.Deferred,this._materialSignalLODs[a].promise.then(function(){return o._loader.loadUriAsync(e,t,n)})}if(null!==this._nodeIndexLOD){this._loader.log("deferred");a=this._nodeIndexLOD-1;return this._nodeSignalLODs[a]=this._nodeSignalLODs[a]||new r.Deferred,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then(function(){return o._loader.loadUriAsync(e,t,n)})}return null},e.prototype.loadBufferAsync=function(e,t,n,o){if(this._loader.parent.useRangeRequests&&!t.uri){if(!this._loader.bin)throw new Error(e+": Uri is missing or the binary glTF is missing its binary chunk");var a=this._indexLOD||0,i=n,s=i+o-1,l=this._bufferLODs[a];return l?(l.start=Math.min(l.start,i),l.end=Math.max(l.end,s)):(l={start:i,end:s,loaded:new r.Deferred},this._bufferLODs[a]=l),l.loaded.promise.then(function(e){return new Uint8Array(e.buffer,e.byteOffset+n-l.start,o)})}return null},e.prototype._loadBufferLOD=function(e){var t=this._bufferLODs[e];this._loader.bin.readAsync(t.start,t.end-t.start+1).then(function(e){t.loaded.resolve(e)},function(e){t.loaded.reject(e)})},e.prototype._getLODs=function(e,t,n,r){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");for(var a=new Array,i=r.length-1;i>=0;i--)if(a.push(o.a.Get(e+"/ids/"+r[i],n,r[i])),a.length===this.maxLODsToLoad)return a;return a.push(t),a},e.prototype._disposeTransformNode=function(e){var t=this,n=new Array,r=e.material;r&&n.push(r);for(var o=0,a=e.getChildMeshes();o<a.length;o++){var i=a[o];i.material&&n.push(i.material)}e.dispose();var s=n.filter(function(e){return t._loader.babylonScene.meshes.every(function(t){return t.material!=e})});this._disposeMaterials(s)},e.prototype._disposeMaterials=function(e){for(var t={},n=0,r=e;n<r.length;n++){for(var o=0,a=(c=r[n]).getActiveTextures();o<a.length;o++){var i=a[o];t[i.uniqueId]=i}c.dispose()}for(var s in t)for(var l=0,u=this._loader.babylonScene.materials;l<u.length;l++){var c;(c=u[l]).hasTexture(t[s])&&delete t[s]}for(var s in t)t[s].dispose()},e}();o.b.RegisterExtension(C,function(e){return new N(e)});var P="MSFT_minecraftMesh",R=function(){function e(e){this.name=P,this._loader=e,this.enabled=this._loader.isExtensionUsed(P)}return e.prototype.dispose=function(){delete this._loader},e.prototype.loadMaterialPropertiesAsync=function(e,t,n){var a=this;return o.b.LoadExtraAsync(e,t,this.name,function(o,i){if(i){if(!(n instanceof r.PBRMaterial))throw new Error(o+": Material type not supported");var s=a._loader.loadMaterialPropertiesAsync(e,t,n);return n.needAlphaBlending()&&(n.forceDepthWrite=!0,n.separateCullingPass=!0),n.backFaceCulling=n.forceDepthWrite,n.twoSidedLighting=!0,s}return null})},e}();o.b.RegisterExtension(P,function(e){return new R(e)});var I="MSFT_sRGBFactors",F=function(){function e(e){this.name=I,this._loader=e,this.enabled=this._loader.isExtensionUsed(I)}return e.prototype.dispose=function(){delete this._loader},e.prototype.loadMaterialPropertiesAsync=function(e,t,n){var a=this;return o.b.LoadExtraAsync(e,t,this.name,function(o,i){if(i){if(!(n instanceof r.PBRMaterial))throw new Error(o+": Material type not supported");var s=a._loader.loadMaterialPropertiesAsync(e,t,n);return n.albedoTexture||n.albedoColor.toLinearSpaceToRef(n.albedoColor),n.reflectivityTexture||n.reflectivityColor.toLinearSpaceToRef(n.reflectivityColor),s}return null})},e}();o.b.RegisterExtension(I,function(e){return new F(e)});var V="ExtrasAsMetadata",B=function(){function e(e){this.name=V,this.enabled=!0,this._loader=e}return e.prototype._assignExtras=function(e,t){if(t.extras&&Object.keys(t.extras).length>0){var n=e.metadata=e.metadata||{};(n.gltf=n.gltf||{}).extras=t.extras}},e.prototype.dispose=function(){delete this._loader},e.prototype.loadNodeAsync=function(e,t,n){var r=this;return this._loader.loadNodeAsync(e,t,function(e){r._assignExtras(e,t),n(e)})},e.prototype.loadCameraAsync=function(e,t,n){var r=this;return this._loader.loadCameraAsync(e,t,function(e){r._assignExtras(e,t),n(e)})},e.prototype.createMaterial=function(e,t,n){var r=this._loader.createMaterial(e,t,n);return this._assignExtras(r,t),r},e}();o.b.RegisterExtension(V,function(e){return new B(e)}),n.d(t,"EXT_lights_image_based",function(){return i}),n.d(t,"KHR_draco_mesh_compression",function(){return l}),n.d(t,"KHR_lights",function(){return f}),n.d(t,"KHR_materials_pbrSpecularGlossiness",function(){return h}),n.d(t,"KHR_materials_unlit",function(){return m}),n.d(t,"KHR_materials_clearcoat",function(){return y}),n.d(t,"KHR_materials_sheen",function(){return v}),n.d(t,"KHR_materials_specular",function(){return g}),n.d(t,"KHR_mesh_quantization",function(){return x}),n.d(t,"KHR_texture_basisu",function(){return L}),n.d(t,"KHR_texture_transform",function(){return M}),n.d(t,"MSFT_audio_emitter",function(){return w}),n.d(t,"MSFT_lod",function(){return N}),n.d(t,"MSFT_minecraftMesh",function(){return R}),n.d(t,"MSFT_sRGBFactors",function(){return F}),n.d(t,"ExtrasAsMetadata",function(){return B})},function(e,t,n){"use strict";n.r(t);var r=n(1);n.d(t,"ArrayItem",function(){return r.a}),n.d(t,"GLTFLoader",function(){return r.b});var o=n(5);n.d(t,"EXT_lights_image_based",function(){return o.EXT_lights_image_based}),n.d(t,"KHR_draco_mesh_compression",function(){return o.KHR_draco_mesh_compression}),n.d(t,"KHR_lights",function(){return o.KHR_lights}),n.d(t,"KHR_materials_pbrSpecularGlossiness",function(){return o.KHR_materials_pbrSpecularGlossiness}),n.d(t,"KHR_materials_unlit",function(){return o.KHR_materials_unlit}),n.d(t,"KHR_materials_clearcoat",function(){return o.KHR_materials_clearcoat}),n.d(t,"KHR_materials_sheen",function(){return o.KHR_materials_sheen}),n.d(t,"KHR_materials_specular",function(){return o.KHR_materials_specular}),n.d(t,"KHR_mesh_quantization",function(){return o.KHR_mesh_quantization}),n.d(t,"KHR_texture_basisu",function(){return o.KHR_texture_basisu}),n.d(t,"KHR_texture_transform",function(){return o.KHR_texture_transform}),n.d(t,"MSFT_audio_emitter",function(){return o.MSFT_audio_emitter}),n.d(t,"MSFT_lod",function(){return o.MSFT_lod}),n.d(t,"MSFT_minecraftMesh",function(){return o.MSFT_minecraftMesh}),n.d(t,"MSFT_sRGBFactors",function(){return o.MSFT_sRGBFactors}),n.d(t,"ExtrasAsMetadata",function(){return o.ExtrasAsMetadata})},function(e,t,n){"use strict";n.r(t);
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
var r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function o(e,t){function n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var a,i,s,l,u,c,f,d;!function(e){e[e.BYTE=5120]="BYTE",e[e.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",e[e.SHORT=5122]="SHORT",e[e.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",e[e.FLOAT=5126]="FLOAT"}(a||(a={})),function(e){e[e.FRAGMENT=35632]="FRAGMENT",e[e.VERTEX=35633]="VERTEX"}(i||(i={})),function(e){e[e.BYTE=5120]="BYTE",e[e.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",e[e.SHORT=5122]="SHORT",e[e.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",e[e.INT=5124]="INT",e[e.UNSIGNED_INT=5125]="UNSIGNED_INT",e[e.FLOAT=5126]="FLOAT",e[e.FLOAT_VEC2=35664]="FLOAT_VEC2",e[e.FLOAT_VEC3=35665]="FLOAT_VEC3",e[e.FLOAT_VEC4=35666]="FLOAT_VEC4",e[e.INT_VEC2=35667]="INT_VEC2",e[e.INT_VEC3=35668]="INT_VEC3",e[e.INT_VEC4=35669]="INT_VEC4",e[e.BOOL=35670]="BOOL",e[e.BOOL_VEC2=35671]="BOOL_VEC2",e[e.BOOL_VEC3=35672]="BOOL_VEC3",e[e.BOOL_VEC4=35673]="BOOL_VEC4",e[e.FLOAT_MAT2=35674]="FLOAT_MAT2",e[e.FLOAT_MAT3=35675]="FLOAT_MAT3",e[e.FLOAT_MAT4=35676]="FLOAT_MAT4",e[e.SAMPLER_2D=35678]="SAMPLER_2D"}(s||(s={})),function(e){e[e.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",e[e.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",e[e.REPEAT=10497]="REPEAT"}(l||(l={})),function(e){e[e.NEAREST=9728]="NEAREST",e[e.LINEAR=9728]="LINEAR",e[e.NEAREST_MIPMAP_NEAREST=9984]="NEAREST_MIPMAP_NEAREST",e[e.LINEAR_MIPMAP_NEAREST=9985]="LINEAR_MIPMAP_NEAREST",e[e.NEAREST_MIPMAP_LINEAR=9986]="NEAREST_MIPMAP_LINEAR",e[e.LINEAR_MIPMAP_LINEAR=9987]="LINEAR_MIPMAP_LINEAR"}(u||(u={})),function(e){e[e.ALPHA=6406]="ALPHA",e[e.RGB=6407]="RGB",e[e.RGBA=6408]="RGBA",e[e.LUMINANCE=6409]="LUMINANCE",e[e.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA"}(c||(c={})),function(e){e[e.FRONT=1028]="FRONT",e[e.BACK=1029]="BACK",e[e.FRONT_AND_BACK=1032]="FRONT_AND_BACK"}(f||(f={})),function(e){e[e.ZERO=0]="ZERO",e[e.ONE=1]="ONE",e[e.SRC_COLOR=768]="SRC_COLOR",e[e.ONE_MINUS_SRC_COLOR=769]="ONE_MINUS_SRC_COLOR",e[e.DST_COLOR=774]="DST_COLOR",e[e.ONE_MINUS_DST_COLOR=775]="ONE_MINUS_DST_COLOR",e[e.SRC_ALPHA=770]="SRC_ALPHA",e[e.ONE_MINUS_SRC_ALPHA=771]="ONE_MINUS_SRC_ALPHA",e[e.DST_ALPHA=772]="DST_ALPHA",e[e.ONE_MINUS_DST_ALPHA=773]="ONE_MINUS_DST_ALPHA",e[e.CONSTANT_COLOR=32769]="CONSTANT_COLOR",e[e.ONE_MINUS_CONSTANT_COLOR=32770]="ONE_MINUS_CONSTANT_COLOR",e[e.CONSTANT_ALPHA=32771]="CONSTANT_ALPHA",e[e.ONE_MINUS_CONSTANT_ALPHA=32772]="ONE_MINUS_CONSTANT_ALPHA",e[e.SRC_ALPHA_SATURATE=776]="SRC_ALPHA_SATURATE"}(d||(d={}));var h,p=n(0),m=function(){function e(){}return e.SetMatrix=function(e,t,n,r,o){var a=null;if("MODEL"===n.semantic?a=t.getWorldMatrix():"PROJECTION"===n.semantic?a=e.getProjectionMatrix():"VIEW"===n.semantic?a=e.getViewMatrix():"MODELVIEWINVERSETRANSPOSE"===n.semantic?a=p.Matrix.Transpose(t.getWorldMatrix().multiply(e.getViewMatrix()).invert()):"MODELVIEW"===n.semantic?a=t.getWorldMatrix().multiply(e.getViewMatrix()):"MODELVIEWPROJECTION"===n.semantic?a=t.getWorldMatrix().multiply(e.getTransformMatrix()):"MODELINVERSE"===n.semantic?a=t.getWorldMatrix().invert():"VIEWINVERSE"===n.semantic?a=e.getViewMatrix().invert():"PROJECTIONINVERSE"===n.semantic?a=e.getProjectionMatrix().invert():"MODELVIEWINVERSE"===n.semantic?a=t.getWorldMatrix().multiply(e.getViewMatrix()).invert():"MODELVIEWPROJECTIONINVERSE"===n.semantic?a=t.getWorldMatrix().multiply(e.getTransformMatrix()).invert():"MODELINVERSETRANSPOSE"===n.semantic&&(a=p.Matrix.Transpose(t.getWorldMatrix().invert())),a)switch(n.type){case s.FLOAT_MAT2:o.setMatrix2x2(r,p.Matrix.GetAsMatrix2x2(a));break;case s.FLOAT_MAT3:o.setMatrix3x3(r,p.Matrix.GetAsMatrix3x3(a));break;case s.FLOAT_MAT4:o.setMatrix(r,a)}},e.SetUniform=function(e,t,n,r){switch(r){case s.FLOAT:return e.setFloat(t,n),!0;case s.FLOAT_VEC2:return e.setVector2(t,p.Vector2.FromArray(n)),!0;case s.FLOAT_VEC3:return e.setVector3(t,p.Vector3.FromArray(n)),!0;case s.FLOAT_VEC4:return e.setVector4(t,p.Vector4.FromArray(n)),!0;default:return!1}},e.GetWrapMode=function(e){switch(e){case l.CLAMP_TO_EDGE:return p.Texture.CLAMP_ADDRESSMODE;case l.MIRRORED_REPEAT:return p.Texture.MIRROR_ADDRESSMODE;case l.REPEAT:default:return p.Texture.WRAP_ADDRESSMODE}},e.GetByteStrideFromType=function(e){switch(e.type){case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return 1}},e.GetTextureFilterMode=function(e){switch(e){case u.LINEAR:case u.LINEAR_MIPMAP_NEAREST:case u.LINEAR_MIPMAP_LINEAR:return p.Texture.TRILINEAR_SAMPLINGMODE;case u.NEAREST:case u.NEAREST_MIPMAP_NEAREST:return p.Texture.NEAREST_SAMPLINGMODE;default:return p.Texture.BILINEAR_SAMPLINGMODE}},e.GetBufferFromBufferView=function(e,t,n,r,o){n=t.byteOffset+n;var i=e.loadedBufferViews[t.buffer];if(n+r>i.byteLength)throw new Error("Buffer access is out of range");var s=i.buffer;switch(n+=i.byteOffset,o){case a.BYTE:return new Int8Array(s,n,r);case a.UNSIGNED_BYTE:return new Uint8Array(s,n,r);case a.SHORT:return new Int16Array(s,n,r);case a.UNSIGNED_SHORT:return new Uint16Array(s,n,r);default:return new Float32Array(s,n,r)}},e.GetBufferFromAccessor=function(t,n){var r=t.bufferViews[n.bufferView],o=n.count*e.GetByteStrideFromType(n);return e.GetBufferFromBufferView(t,r,n.byteOffset,o,n.componentType)},e.DecodeBufferToText=function(e){for(var t="",n=e.byteLength,r=0;r<n;++r)t+=String.fromCharCode(e[r]);return t},e.GetDefaultMaterial=function(t){if(!e._DefaultMaterial){p.Effect.ShadersStore.GLTFDefaultMaterialVertexShader=["precision highp float;","","uniform mat4 worldView;","uniform mat4 projection;","","attribute vec3 position;","","void main(void)","{","    gl_Position = projection * worldView * vec4(position, 1.0);","}"].join("\n"),p.Effect.ShadersStore.GLTFDefaultMaterialPixelShader=["precision highp float;","","uniform vec4 u_emission;","","void main(void)","{","    gl_FragColor = u_emission;","}"].join("\n");var n={attributes:["position"],uniforms:["worldView","projection","u_emission"],samplers:new Array,needAlphaBlending:!1};e._DefaultMaterial=new p.ShaderMaterial("GLTFDefaultMaterial",t,{vertex:"GLTFDefaultMaterial",fragment:"GLTFDefaultMaterial"},n),e._DefaultMaterial.setColor4("u_emission",new p.Color4(.5,.5,.5,1))}return e._DefaultMaterial},e._DefaultMaterial=null,e}(),_=n(2);!function(e){e[e.IDENTIFIER=1]="IDENTIFIER",e[e.UNKNOWN=2]="UNKNOWN",e[e.END_OF_INPUT=3]="END_OF_INPUT"}(h||(h={}));var y=function(){function e(e){this._pos=0,this.currentToken=h.UNKNOWN,this.currentIdentifier="",this.currentString="",this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}return e.prototype.getNextToken=function(){if(this.isEnd())return h.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=h.UNKNOWN,"_"===this.currentString||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=h.IDENTIFIER,this.currentIdentifier=this.currentString;!this.isEnd()&&(this.isLetterOrDigitPattern.test(this.currentString=this.peek())||"_"===this.currentString);)this.currentIdentifier+=this.currentString,this.forward();return this.currentToken},e.prototype.peek=function(){return this._toParse[this._pos]},e.prototype.read=function(){return this._toParse[this._pos++]},e.prototype.forward=function(){this._pos++},e.prototype.isEnd=function(){return this._pos>=this._maxPos},e}(),b=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],v=["world","view","projection","worldView","worldViewProjection","mBones"],A=["translation","rotation","scale"],g=["position","rotationQuaternion","scaling"],T=function(e,t,n){for(var r in e){var o=e[r];n[t][r]=o}},x=function(e){if(e)for(var t=0;t<e.length/2;t++)e[2*t+1]=1-e[2*t+1]},E=function(e){if("NORMAL"===e.semantic)return"normal";if("POSITION"===e.semantic)return"position";if("JOINT"===e.semantic)return"matricesIndices";if("WEIGHT"===e.semantic)return"matricesWeights";if("COLOR"===e.semantic)return"color";if(e.semantic&&-1!==e.semantic.indexOf("TEXCOORD_")){var t=Number(e.semantic.split("_")[1]);return"uv"+(0===t?"":t+1)}return null},L=function(e){var t=null;if(e.translation||e.rotation||e.scale){var n=p.Vector3.FromArray(e.scale||[1,1,1]),r=p.Quaternion.FromArray(e.rotation||[0,0,0,1]),o=p.Vector3.FromArray(e.translation||[0,0,0]);t=p.Matrix.Compose(n,r,o)}else t=p.Matrix.FromArray(e.matrix);return t},O=function(e,t,n,r){for(var o=0;o<r.bones.length;o++)if(r.bones[o].name===n)return r.bones[o];var a=e.nodes;for(var i in a){var s=a[i];if(s.jointName){var l=s.children;for(o=0;o<l.length;o++){var u=e.nodes[l[o]];if(u.jointName&&u.jointName===n){var c=L(s),f=new p.Bone(s.name||"",r,O(e,t,s.jointName,r),c);return f.id=i,f}}}}return null},M=function(e,t){for(var n=0;n<e.length;n++)for(var r=e[n],o=0;o<r.node.children.length;o++){if(r.node.children[o]===t)return r.bone}return null},S=function(e,t){var n=e.nodes,r=n[t];if(r)return{node:r,id:t};for(var o in n)if((r=n[o]).jointName===t)return{node:r,id:o};return null},w=function(e,t){for(var n=0;n<e.jointNames.length;n++)if(e.jointNames[n]===t)return!0;return!1},C=function(e,t,n,r,o){if(r||(r=new p.Skeleton(t.name||"","",e.scene)),!t.babylonSkeleton)return r;var a=[],i=[];!function(e,t,n,r){for(var o in e.nodes){var a=e.nodes[o],i=o;if(a.jointName&&!w(n,a.jointName)){var s=L(a),l=new p.Bone(a.name||"",t,null,s);l.id=i,r.push({bone:l,node:a,id:i})}}for(var u=0;u<r.length;u++)for(var c=r[u],f=c.node.children,d=0;d<f.length;d++){for(var h=null,m=0;m<r.length;m++)if(r[m].id===f[d]){h=r[m];break}h&&(h.bone._parent=c.bone,c.bone.children.push(h.bone))}}(e,r,t,a),r.bones=[];for(var s=0;s<t.jointNames.length;s++){if(A=S(e,t.jointNames[s])){var l=A.node;if(l){o=A.id;var u=e.scene.getBoneByID(o);if(u)r.bones.push(u);else{for(var c=!1,f=null,d=0;d<s;d++){var h=S(e,t.jointNames[d]);if(h){var m=h.node;if(m){var _=m.children;if(_){c=!1;for(var y=0;y<_.length;y++)if(_[y]===o){f=O(e,t,t.jointNames[d],r),c=!0;break}if(c)break}}else p.Tools.Warn("Joint named "+t.jointNames[d]+" does not exist when looking for parent")}}var b=L(l);!f&&a.length>0&&(f=M(a,o))&&-1===i.indexOf(f)&&i.push(f),new p.Bone(l.jointName||"",r,f,b).id=o}}else p.Tools.Warn("Joint named "+t.jointNames[s]+" does not exist")}}var v=r.bones;r.bones=[];for(s=0;s<t.jointNames.length;s++){var A;if(A=S(e,t.jointNames[s]))for(d=0;d<v.length;d++)if(v[d].id===A.id){r.bones.push(v[d]);break}}r.prepare();for(s=0;s<i.length;s++)r.bones.push(i[s]);return r},N=function(e,t,n,r,o){if(o||(e.scene._blockEntityCollection=e.forAssetContainer,o=new p.Mesh(t.name||"",e.scene),e.scene._blockEntityCollection=!1,o.id=r),!t.babylonNode)return o;for(var a,i=[],s=null,l=new Array,u=new Array,c=new Array,f=new Array,d=0;d<n.length;d++){var h=n[d];if(P=e.meshes[h])for(var y=0;y<P.primitives.length;y++){var b=new p.VertexData,v=P.primitives[y];v.mode;var A=v.attributes,g=null,T=null;for(var E in A)if(g=e.accessors[A[E]],T=m.GetBufferFromAccessor(e,g),"NORMAL"===E)b.normals=new Float32Array(T.length),b.normals.set(T);else if("POSITION"===E){if(_.GLTFFileLoader.HomogeneousCoordinates){b.positions=new Float32Array(T.length-T.length/4);for(var L=0;L<T.length;L+=4)b.positions[L]=T[L],b.positions[L+1]=T[L+1],b.positions[L+2]=T[L+2]}else b.positions=new Float32Array(T.length),b.positions.set(T);u.push(b.positions.length)}else if(-1!==E.indexOf("TEXCOORD_")){var O=Number(E.split("_")[1]),M=p.VertexBuffer.UVKind+(0===O?"":O+1),S=new Float32Array(T.length);S.set(T),x(S),b.set(S,M)}else"JOINT"===E?(b.matricesIndices=new Float32Array(T.length),b.matricesIndices.set(T)):"WEIGHT"===E?(b.matricesWeights=new Float32Array(T.length),b.matricesWeights.set(T)):"COLOR"===E&&(b.colors=new Float32Array(T.length),b.colors.set(T));if(g=e.accessors[v.indices])T=m.GetBufferFromAccessor(e,g),b.indices=new Int32Array(T.length),b.indices.set(T),f.push(b.indices.length);else{var w=[];for(L=0;L<b.positions.length/3;L++)w.push(L);b.indices=new Int32Array(w),f.push(b.indices.length)}s?s.merge(b):s=b;var C=e.scene.getMaterialByID(v.material);i.push(null===C?m.GetDefaultMaterial(e.scene):C),l.push(0===l.length?0:l[l.length-1]+u[u.length-2]),c.push(0===c.length?0:c[c.length-1]+f[f.length-2])}}e.scene._blockEntityCollection=e.forAssetContainer,i.length>1?(a=new p.MultiMaterial("multimat"+r,e.scene)).subMaterials=i:a=new p.StandardMaterial("multimat"+r,e.scene),1===i.length&&(a=i[0]),o.material||(o.material=a),new p.Geometry(r,e.scene,s,!1,o),o.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,o.subMeshes=[];var N=0;for(d=0;d<n.length;d++){var P;h=n[d];if(P=e.meshes[h])for(y=0;y<P.primitives.length;y++)P.primitives[y].mode,p.SubMesh.AddToMesh(N,l[N],u[N],c[N],f[N],o,o,!0),N++}return o},P=function(e,t,n,r){e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=n),e.scaling&&(e.scaling=r)},R=function(e,t,n,r){var o=null;if(e.importOnlyMeshes&&(t.skin||t.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&-1===e.importMeshesNames.indexOf(t.name||""))return null;if(t.skin){if(t.meshes){var a=e.skins[t.skin];(i=N(e,t,t.meshes,n,t.babylonNode)).skeleton=e.scene.getLastSkeletonByID(t.skin),null===i.skeleton&&(i.skeleton=C(e,a,0,a.babylonSkeleton,t.skin),a.babylonSkeleton||(a.babylonSkeleton=i.skeleton)),o=i}}else if(t.meshes){var i;o=i=N(e,t,t.mesh?[t.mesh]:t.meshes,n,t.babylonNode)}else if(!t.light||t.babylonNode||e.importOnlyMeshes){if(t.camera&&!t.babylonNode&&!e.importOnlyMeshes){var s=e.cameras[t.camera];if(s){if(e.scene._blockEntityCollection=e.forAssetContainer,"orthographic"===s.type){var l=new p.FreeCamera(t.camera,p.Vector3.Zero(),e.scene,!1);l.name=t.name||"",l.mode=p.Camera.ORTHOGRAPHIC_CAMERA,l.attachControl(e.scene.getEngine().getInputElement()),o=l}else if("perspective"===s.type){var u=s[s.type],c=new p.FreeCamera(t.camera,p.Vector3.Zero(),e.scene,!1);c.name=t.name||"",c.attachControl(e.scene.getEngine().getInputElement()),u.aspectRatio||(u.aspectRatio=e.scene.getEngine().getRenderWidth()/e.scene.getEngine().getRenderHeight()),u.znear&&u.zfar&&(c.maxZ=u.zfar,c.minZ=u.znear),o=c}e.scene._blockEntityCollection=!1}}}else{var f=e.lights[t.light];if(f)if("ambient"===f.type){var d=f[f.type],h=new p.HemisphericLight(t.light,p.Vector3.Zero(),e.scene);h.name=t.name||"",d.color&&(h.diffuse=p.Color3.FromArray(d.color)),o=h}else if("directional"===f.type){var m=f[f.type],_=new p.DirectionalLight(t.light,p.Vector3.Zero(),e.scene);_.name=t.name||"",m.color&&(_.diffuse=p.Color3.FromArray(m.color)),o=_}else if("point"===f.type){var y=f[f.type],b=new p.PointLight(t.light,p.Vector3.Zero(),e.scene);b.name=t.name||"",y.color&&(b.diffuse=p.Color3.FromArray(y.color)),o=b}else if("spot"===f.type){var v=f[f.type],A=new p.SpotLight(t.light,p.Vector3.Zero(),p.Vector3.Zero(),0,0,e.scene);A.name=t.name||"",v.color&&(A.diffuse=p.Color3.FromArray(v.color)),v.fallOfAngle&&(A.angle=v.fallOfAngle),v.fallOffExponent&&(A.exponent=v.fallOffExponent),o=A}}if(!t.jointName){if(t.babylonNode)return t.babylonNode;if(null===o){e.scene._blockEntityCollection=e.forAssetContainer;var g=new p.Mesh(t.name||"",e.scene);e.scene._blockEntityCollection=!1,t.babylonNode=g,o=g}}if(null!==o){if(t.matrix&&o instanceof p.Mesh)!function(e,t,n){if(t.matrix){var r=new p.Vector3(0,0,0),o=new p.Quaternion,a=new p.Vector3(0,0,0);p.Matrix.FromArray(t.matrix).decompose(a,o,r),P(e,r,o,a)}else t.translation&&t.rotation&&t.scale&&P(e,p.Vector3.FromArray(t.translation),p.Quaternion.FromArray(t.rotation),p.Vector3.FromArray(t.scale));e.computeWorldMatrix(!0)}(o,t);else{var T=t.translation||[0,0,0],x=t.rotation||[0,0,0,1],E=t.scale||[1,1,1];P(o,p.Vector3.FromArray(T),p.Quaternion.FromArray(x),p.Vector3.FromArray(E))}o.updateCache(!0),t.babylonNode=o}return o},I=function(e,t,n,r){void 0===r&&(r=!1);var o=e.nodes[t],a=null;if(r=!(e.importOnlyMeshes&&!r&&e.importMeshesNames)||(-1!==e.importMeshesNames.indexOf(o.name||"")||0===e.importMeshesNames.length),!o.jointName&&r&&null!==(a=R(e,o,t))&&(a.id=t,a.parent=n),o.children)for(var i=0;i<o.children.length;i++)I(e,o.children[i],a,r)},F=function(e){var t=e.currentScene;if(t)for(var n=0;n<t.nodes.length;n++)I(e,t.nodes[n],null);else for(var r in e.scenes){t=e.scenes[r];for(n=0;n<t.nodes.length;n++)I(e,t.nodes[n],null)}!function(e){for(var t in e.animations){var n=e.animations[t];if(n.channels&&n.samplers)for(var r=null,o=0;o<n.channels.length;o++){var a=n.channels[o],i=n.samplers[a.sampler];if(i){var s=null,l=null;n.parameters?(s=n.parameters[i.input],l=n.parameters[i.output]):(s=i.input,l=i.output);var u=m.GetBufferFromAccessor(e,e.accessors[s]),c=m.GetBufferFromAccessor(e,e.accessors[l]),f=a.target.id,d=e.scene.getNodeByID(f);if(null===d&&(d=e.scene.getNodeByName(f)),null!==d){var h=d instanceof p.Bone,_=a.target.path,y=A.indexOf(_);-1!==y&&(_=g[y]);var b=p.Animation.ANIMATIONTYPE_MATRIX;h||("rotationQuaternion"===_?(b=p.Animation.ANIMATIONTYPE_QUATERNION,d.rotationQuaternion=new p.Quaternion):b=p.Animation.ANIMATIONTYPE_VECTOR3);var v=null,T=[],x=0,E=!1;h&&r&&r.getKeys().length===u.length&&(v=r,E=!0),E||(e.scene._blockEntityCollection=e.forAssetContainer,v=new p.Animation(t,h?"_matrix":_,1,b,p.Animation.ANIMATIONLOOPMODE_CYCLE),e.scene._blockEntityCollection=!1);for(var L=0;L<u.length;L++){var O=null;if("rotationQuaternion"===_?(O=p.Quaternion.FromArray([c[x],c[x+1],c[x+2],c[x+3]]),x+=4):(O=p.Vector3.FromArray([c[x],c[x+1],c[x+2]]),x+=3),h){var M=d,S=p.Vector3.Zero(),w=new p.Quaternion,C=p.Vector3.Zero(),N=M.getBaseMatrix();E&&r&&(N=r.getKeys()[L].value),N.decompose(C,w,S),"position"===_?S=O:"rotationQuaternion"===_?w=O:C=O,O=p.Matrix.Compose(C,w,S)}E?r&&(r.getKeys()[L].value=O):T.push({frame:u[L],value:O})}!E&&v&&(v.setKeys(T),d.animations.push(v)),r=v,e.scene.stopAnimation(d),e.scene.beginAnimation(d,0,u[u.length-1],!0,1)}else p.Tools.Warn("Creating animation named "+t+". But cannot find node named "+f+" to attach to")}}}}(e);for(n=0;n<e.scene.skeletons.length;n++){var o=e.scene.skeletons[n];e.scene.beginAnimation(o,0,Number.MAX_VALUE,!0,1)}},V=function(e,t,n,r,o,a){return function(i){!function(e,t,n,r,o){var a=r.values||n.parameters,i=n.uniforms;for(var l in o){var u=o[l],c=u.type,f=a[i[l]];if(void 0===f&&(f=u.value),f){var d=function(e){return function(n){u.value&&e&&(t.setTexture(e,n),delete o[e])}};c===s.SAMPLER_2D?k.LoadTextureAsync(e,r.values?f:u.value,d(l),function(){return d(null)}):u.value&&m.SetUniform(t,l,r.values?f:u.value,c)&&delete o[l]}}}(e,t,n,r,o),t.onBind=function(i){!function(e,t,n,r,o,a,i){var l=a.values||o.parameters;for(var u in n){var c=n[u],f=c.type;if(f===s.FLOAT_MAT2||f===s.FLOAT_MAT3||f===s.FLOAT_MAT4)if(!c.semantic||c.source||c.node){if(c.semantic&&(c.source||c.node)){var d=t.scene.getNodeByName(c.source||c.node||"");if(null===d&&(d=t.scene.getNodeByID(c.source||c.node||"")),null===d)continue;m.SetMatrix(t.scene,d,c,u,r.getEffect())}}else m.SetMatrix(t.scene,e,c,u,r.getEffect());else{var h=l[o.uniforms[u]];if(!h)continue;if(f===s.SAMPLER_2D){var p=t.textures[a.values?h:c.value].babylonTexture;if(null==p)continue;r.getEffect().setTexture(u,p)}else m.SetUniform(r.getEffect(),u,h,f)}}i(r)}(i,e,o,t,n,r,a)}}},B=function(e,t,n){for(var r in t.uniforms){var o=t.uniforms[r],a=t.parameters[o];if(e.currentIdentifier===r&&a.semantic&&!a.source&&!a.node){var i=b.indexOf(a.semantic);if(-1!==i)return delete n[r],v[i]}}return e.currentIdentifier},D=function(e){for(var t in e.materials)k.LoadMaterialAsync(e,t,function(e){},function(){})},G=function(){function e(){}return e.CreateRuntime=function(e,t,n){var r={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:n,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],forAssetContainer:!1};return e.extensions&&T(e.extensions,"extensions",r),e.extensionsUsed&&T(e.extensionsUsed,"extensionsUsed",r),e.buffers&&function(e,t){for(var n in e){var r=e[n];t.buffers[n]=r,t.buffersCount++}}(e.buffers,r),e.bufferViews&&T(e.bufferViews,"bufferViews",r),e.accessors&&T(e.accessors,"accessors",r),e.meshes&&T(e.meshes,"meshes",r),e.lights&&T(e.lights,"lights",r),e.cameras&&T(e.cameras,"cameras",r),e.nodes&&T(e.nodes,"nodes",r),e.images&&T(e.images,"images",r),e.textures&&T(e.textures,"textures",r),e.shaders&&function(e,t){for(var n in e){var r=e[n];t.shaders[n]=r,t.shaderscount++}}(e.shaders,r),e.programs&&T(e.programs,"programs",r),e.samplers&&T(e.samplers,"samplers",r),e.techniques&&T(e.techniques,"techniques",r),e.materials&&T(e.materials,"materials",r),e.animations&&T(e.animations,"animations",r),e.skins&&T(e.skins,"skins",r),e.scenes&&(r.scenes=e.scenes),e.scene&&e.scenes&&(r.currentScene=e.scenes[e.scene]),r},e.LoadBufferAsync=function(e,t,n,r,o){var a=e.buffers[t];p.Tools.IsBase64(a.uri)?setTimeout(function(){return n(new Uint8Array(p.Tools.DecodeBase64(a.uri)))}):p.Tools.LoadFile(e.rootUrl+a.uri,function(e){return n(new Uint8Array(e))},o,void 0,!0,function(e){e&&r(e.status+" "+e.statusText)})},e.LoadTextureBufferAsync=function(e,t,n,r){var o=e.textures[t];if(o&&o.source)if(o.babylonTexture)n(null);else{var a=e.images[o.source];p.Tools.IsBase64(a.uri)?setTimeout(function(){return n(new Uint8Array(p.Tools.DecodeBase64(a.uri)))}):p.Tools.LoadFile(e.rootUrl+a.uri,function(e){return n(new Uint8Array(e))},void 0,void 0,!0,function(e){e&&r(e.status+" "+e.statusText)})}else r("")},e.CreateTextureAsync=function(e,t,n,r,o){var a=e.textures[t];if(a.babylonTexture)r(a.babylonTexture);else{var i=e.samplers[a.sampler],s=i.minFilter===u.NEAREST_MIPMAP_NEAREST||i.minFilter===u.NEAREST_MIPMAP_LINEAR||i.minFilter===u.LINEAR_MIPMAP_NEAREST||i.minFilter===u.LINEAR_MIPMAP_LINEAR,l=p.Texture.BILINEAR_SAMPLINGMODE,c=null==n?new Blob:new Blob([n]),f=URL.createObjectURL(c),d=function(){return URL.revokeObjectURL(f)},h=new p.Texture(f,e.scene,!s,!0,l,d,d);void 0!==i.wrapS&&(h.wrapU=m.GetWrapMode(i.wrapS)),void 0!==i.wrapT&&(h.wrapV=m.GetWrapMode(i.wrapT)),h.name=t,a.babylonTexture=h,r(h)}},e.LoadShaderStringAsync=function(e,t,n,r){var o=e.shaders[t];if(p.Tools.IsBase64(o.uri)){var a=atob(o.uri.split(",")[1]);n&&n(a)}else p.Tools.LoadFile(e.rootUrl+o.uri,n,void 0,void 0,!1,function(e){e&&r&&r(e.status+" "+e.statusText)})},e.LoadMaterialAsync=function(e,t,n,r){var o=e.materials[t];if(o.technique){var a=e.techniques[o.technique];if(!a){e.scene._blockEntityCollection=e.forAssetContainer;var i=new p.StandardMaterial(t,e.scene);return e.scene._blockEntityCollection=!1,i.diffuseColor=new p.Color3(.5,.5,.5),i.sideOrientation=p.Material.CounterClockWiseSideOrientation,void n(i)}var l=e.programs[a.program],u=a.states,c=p.Effect.ShadersStore[l.vertexShader+"VertexShader"],m=p.Effect.ShadersStore[l.fragmentShader+"PixelShader"],_="",A="",g=new y(c),T=new y(m),x={},L=[],O=[],M=[];for(var S in a.uniforms){var w=a.uniforms[S],C=a.parameters[w];if(x[S]=C,!C.semantic||C.node||C.source)C.type===s.SAMPLER_2D?M.push(S):L.push(S);else{var N=b.indexOf(C.semantic);-1!==N?(L.push(v[N]),delete x[S]):L.push(S)}}for(var P in a.attributes){var R=a.attributes[P];if((D=a.parameters[R]).semantic){var I=E(D);I&&O.push(I)}}for(;!g.isEnd()&&g.getNextToken();){if(g.currentToken===h.IDENTIFIER){var F=!1;for(var P in a.attributes){R=a.attributes[P];var D=a.parameters[R];if(g.currentIdentifier===P&&D.semantic){_+=E(D),F=!0;break}}F||(_+=B(g,a,x))}else _+=g.currentString}for(;!T.isEnd()&&T.getNextToken();){T.currentToken===h.IDENTIFIER?A+=B(T,a,x):A+=T.currentString}var G={vertex:l.vertexShader+t,fragment:l.fragmentShader+t},U={attributes:O,uniforms:L,samplers:M,needAlphaBlending:u&&u.enable&&-1!==u.enable.indexOf(3042)};p.Effect.ShadersStore[l.vertexShader+t+"VertexShader"]=_,p.Effect.ShadersStore[l.fragmentShader+t+"PixelShader"]=A;var k=new p.ShaderMaterial(t,e.scene,G,U);if(k.onError=function(e,t,n){return function(r,o){t.dispose(!0),n("Cannot compile program named "+e.name+". Error: "+o+". Default material will be applied")}}(l,k,r),k.onCompiled=V(e,k,a,o,x,n),k.sideOrientation=p.Material.CounterClockWiseSideOrientation,u&&u.functions){var H=u.functions;H.cullFace&&H.cullFace[0]!==f.BACK&&(k.backFaceCulling=!1);var j=H.blendFuncSeparate;j&&(j[0]===d.SRC_ALPHA&&j[1]===d.ONE_MINUS_SRC_ALPHA&&j[2]===d.ONE&&j[3]===d.ONE?k.alphaMode=p.Constants.ALPHA_COMBINE:j[0]===d.ONE&&j[1]===d.ONE&&j[2]===d.ZERO&&j[3]===d.ONE?k.alphaMode=p.Constants.ALPHA_ONEONE:j[0]===d.SRC_ALPHA&&j[1]===d.ONE&&j[2]===d.ZERO&&j[3]===d.ONE?k.alphaMode=p.Constants.ALPHA_ADD:j[0]===d.ZERO&&j[1]===d.ONE_MINUS_SRC_COLOR&&j[2]===d.ONE&&j[3]===d.ONE?k.alphaMode=p.Constants.ALPHA_SUBTRACT:j[0]===d.DST_COLOR&&j[1]===d.ZERO&&j[2]===d.ONE&&j[3]===d.ONE?k.alphaMode=p.Constants.ALPHA_MULTIPLY:j[0]===d.SRC_ALPHA&&j[1]===d.ONE_MINUS_SRC_COLOR&&j[2]===d.ONE&&j[3]===d.ONE&&(k.alphaMode=p.Constants.ALPHA_MAXIMIZED))}}else r&&r("No technique found.")},e}(),U=function(){function e(){this.state=null}return e.RegisterExtension=function(t){e.Extensions[t.name]?p.Tools.Error('Tool with the same name "'+t.name+'" already exists'):e.Extensions[t.name]=t},e.prototype.dispose=function(){},e.prototype._importMeshAsync=function(e,t,n,r,o,a,i,s){var l=this;return t.useRightHandedSystem=!0,k.LoadRuntimeAsync(t,n,r,function(t){t.forAssetContainer=o,t.importOnlyMeshes=!0,""===e?t.importMeshesNames=[]:"string"==typeof e?t.importMeshesNames=[e]:!e||e instanceof Array?(t.importMeshesNames=[],p.Tools.Warn("Argument meshesNames must be of type string or string[]")):t.importMeshesNames=[e],l._createNodes(t);var n=new Array,r=new Array;for(var s in t.nodes){var u=t.nodes[s];u.babylonNode instanceof p.AbstractMesh&&n.push(u.babylonNode)}for(var c in t.skins){var f=t.skins[c];f.babylonSkeleton instanceof p.Skeleton&&r.push(f.babylonSkeleton)}l._loadBuffersAsync(t,function(){l._loadShadersAsync(t,function(){D(t),F(t),!_.GLTFFileLoader.IncrementalLoading&&a&&a(n,r)})},i),_.GLTFFileLoader.IncrementalLoading&&a&&a(n,r)},s),!0},e.prototype.importMeshAsync=function(e,t,n,r,o,a){var i=this;return new Promise(function(s,l){i._importMeshAsync(e,t,r,o,n,function(e,t){s({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[]})},a,function(e){l(new Error(e))})})},e.prototype._loadAsync=function(e,t,n,r,o,a,i){var s=this;e.useRightHandedSystem=!0,k.LoadRuntimeAsync(e,t,n,function(e){k.LoadRuntimeExtensionsAsync(e,function(){s._createNodes(e),s._loadBuffersAsync(e,function(){s._loadShadersAsync(e,function(){D(e),F(e),_.GLTFFileLoader.IncrementalLoading||o()})}),_.GLTFFileLoader.IncrementalLoading&&o()},i)},i)},e.prototype.loadAsync=function(e,t,n,r){var o=this;return new Promise(function(a,i){o._loadAsync(e,t,n,!1,function(){a()},r,function(e){i(new Error(e))})})},e.prototype._loadShadersAsync=function(e,t){var n=!1,r=function(n,r){k.LoadShaderStringAsync(e,n,function(o){o instanceof ArrayBuffer||(e.loadedShaderCount++,o&&(p.Effect.ShadersStore[n+(r.type===i.VERTEX?"VertexShader":"PixelShader")]=o),e.loadedShaderCount===e.shaderscount&&t())},function(){p.Tools.Error("Error when loading shader program named "+n+" located at "+r.uri)})};for(var o in e.shaders){n=!0;var a=e.shaders[o];a?r.bind(this,o,a)():p.Tools.Error("No shader named: "+o)}n||t()},e.prototype._loadBuffersAsync=function(e,t,n){var r=!1,o=function(n,r){k.LoadBufferAsync(e,n,function(o){e.loadedBufferCount++,o&&(o.byteLength!=e.buffers[n].byteLength&&p.Tools.Error("Buffer named "+n+" is length "+o.byteLength+". Expected: "+r.byteLength),e.loadedBufferViews[n]=o),e.loadedBufferCount===e.buffersCount&&t()},function(){p.Tools.Error("Error when loading buffer named "+n+" located at "+r.uri)})};for(var a in e.buffers){r=!0;var i=e.buffers[a];i?o.bind(this,a,i)():p.Tools.Error("No buffer named: "+a)}r||t()},e.prototype._createNodes=function(e){var t=e.currentScene;if(t)for(var n=0;n<t.nodes.length;n++)I(e,t.nodes[n],null);else for(var r in e.scenes){t=e.scenes[r];for(n=0;n<t.nodes.length;n++)I(e,t.nodes[n],null)}},e.Extensions={},e}(),k=function(){function e(e){this._name=e}return Object.defineProperty(e.prototype,"name",{get:function(){return this._name},enumerable:!0,configurable:!0}),e.prototype.loadRuntimeAsync=function(e,t,n,r,o){return!1},e.prototype.loadRuntimeExtensionsAsync=function(e,t,n){return!1},e.prototype.loadBufferAsync=function(e,t,n,r,o){return!1},e.prototype.loadTextureBufferAsync=function(e,t,n,r){return!1},e.prototype.createTextureAsync=function(e,t,n,r,o){return!1},e.prototype.loadShaderStringAsync=function(e,t,n,r){return!1},e.prototype.loadMaterialAsync=function(e,t,n,r){return!1},e.LoadRuntimeAsync=function(t,n,r,o,a){e.ApplyExtensions(function(e){return e.loadRuntimeAsync(t,n,r,o,a)},function(){setTimeout(function(){o&&o(G.CreateRuntime(n.json,t,r))})})},e.LoadRuntimeExtensionsAsync=function(t,n,r){e.ApplyExtensions(function(e){return e.loadRuntimeExtensionsAsync(t,n,r)},function(){setTimeout(function(){n()})})},e.LoadBufferAsync=function(t,n,r,o,a){e.ApplyExtensions(function(e){return e.loadBufferAsync(t,n,r,o,a)},function(){G.LoadBufferAsync(t,n,r,o,a)})},e.LoadTextureAsync=function(t,n,r,o){e.LoadTextureBufferAsync(t,n,function(a){a&&e.CreateTextureAsync(t,n,a,r,o)},o)},e.LoadShaderStringAsync=function(t,n,r,o){e.ApplyExtensions(function(e){return e.loadShaderStringAsync(t,n,r,o)},function(){G.LoadShaderStringAsync(t,n,r,o)})},e.LoadMaterialAsync=function(t,n,r,o){e.ApplyExtensions(function(e){return e.loadMaterialAsync(t,n,r,o)},function(){G.LoadMaterialAsync(t,n,r,o)})},e.LoadTextureBufferAsync=function(t,n,r,o){e.ApplyExtensions(function(e){return e.loadTextureBufferAsync(t,n,r,o)},function(){G.LoadTextureBufferAsync(t,n,r,o)})},e.CreateTextureAsync=function(t,n,r,o,a){e.ApplyExtensions(function(e){return e.createTextureAsync(t,n,r,o,a)},function(){G.CreateTextureAsync(t,n,r,o,a)})},e.ApplyExtensions=function(e,t){for(var n in U.Extensions){if(e(U.Extensions[n]))return}t()},e}();_.GLTFFileLoader._CreateGLTF1Loader=function(){return new U};var H=function(e){function t(){return e.call(this,"KHR_binary_glTF")||this}return o(t,e),t.prototype.loadRuntimeAsync=function(e,t,n,r,o){var a=t.json.extensionsUsed;return!(!a||-1===a.indexOf(this.name)||!t.bin)&&(this._bin=t.bin,r(G.CreateRuntime(t.json,e,n)),!0)},t.prototype.loadBufferAsync=function(e,t,n,r){return-1!==e.extensionsUsed.indexOf(this.name)&&("binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(n,function(e){return r(e.message)}),!0))},t.prototype.loadTextureBufferAsync=function(e,t,n,r){var o=e.textures[t],i=e.images[o.source];if(!(i.extensions&&this.name in i.extensions))return!1;var s=i.extensions[this.name],l=e.bufferViews[s.bufferView];return n(m.GetBufferFromBufferView(e,l,0,l.byteLength,a.UNSIGNED_BYTE)),!0},t.prototype.loadShaderStringAsync=function(e,t,n,r){var o=e.shaders[t];if(!(o.extensions&&this.name in o.extensions))return!1;var i=o.extensions[this.name],s=e.bufferViews[i.bufferView],l=m.GetBufferFromBufferView(e,s,0,s.byteLength,a.UNSIGNED_BYTE);return setTimeout(function(){var e=m.DecodeBufferToText(l);n(e)}),!0},t}(k);U.RegisterExtension(new H);var j=function(e){function t(){return e.call(this,"KHR_materials_common")||this}return o(t,e),t.prototype.loadRuntimeExtensionsAsync=function(e,t,n){if(!e.extensions)return!1;var r=e.extensions[this.name];if(!r)return!1;var o=r.lights;if(o)for(var a in o){var i=o[a];switch(i.type){case"ambient":var s=new p.HemisphericLight(i.name,new p.Vector3(0,1,0),e.scene),l=i.ambient;l&&(s.diffuse=p.Color3.FromArray(l.color||[1,1,1]));break;case"point":var u=new p.PointLight(i.name,new p.Vector3(10,10,10),e.scene),c=i.point;c&&(u.diffuse=p.Color3.FromArray(c.color||[1,1,1]));break;case"directional":var f=new p.DirectionalLight(i.name,new p.Vector3(0,-1,0),e.scene),d=i.directional;d&&(f.diffuse=p.Color3.FromArray(d.color||[1,1,1]));break;case"spot":var h=i.spot;if(h)new p.SpotLight(i.name,new p.Vector3(0,10,0),new p.Vector3(0,-1,0),h.fallOffAngle||Math.PI,h.fallOffExponent||0,e.scene).diffuse=p.Color3.FromArray(h.color||[1,1,1]);break;default:p.Tools.Warn('GLTF Material Common extension: light type "'+i.type+"” not supported")}}return!1},t.prototype.loadMaterialAsync=function(e,t,n,r){var o=e.materials[t];if(!o||!o.extensions)return!1;var a=o.extensions[this.name];if(!a)return!1;var i=new p.StandardMaterial(t,e.scene);return i.sideOrientation=p.Material.CounterClockWiseSideOrientation,"CONSTANT"===a.technique&&(i.disableLighting=!0),i.backFaceCulling=void 0!==a.doubleSided&&!a.doubleSided,i.alpha=void 0===a.values.transparency?1:a.values.transparency,i.specularPower=void 0===a.values.shininess?0:a.values.shininess,"string"==typeof a.values.ambient?this._loadTexture(e,a.values.ambient,i,"ambientTexture",r):i.ambientColor=p.Color3.FromArray(a.values.ambient||[0,0,0]),"string"==typeof a.values.diffuse?this._loadTexture(e,a.values.diffuse,i,"diffuseTexture",r):i.diffuseColor=p.Color3.FromArray(a.values.diffuse||[0,0,0]),"string"==typeof a.values.emission?this._loadTexture(e,a.values.emission,i,"emissiveTexture",r):i.emissiveColor=p.Color3.FromArray(a.values.emission||[0,0,0]),"string"==typeof a.values.specular?this._loadTexture(e,a.values.specular,i,"specularTexture",r):i.specularColor=p.Color3.FromArray(a.values.specular||[0,0,0]),!0},t.prototype._loadTexture=function(e,t,n,r,o){G.LoadTextureBufferAsync(e,t,function(a){G.CreateTextureAsync(e,t,a,function(e){return n[r]=e},o)},o)},t}(k);U.RegisterExtension(new j),n.d(t,"GLTFBinaryExtension",function(){return H}),n.d(t,"GLTFLoaderBase",function(){return G}),n.d(t,"GLTFLoader",function(){return U}),n.d(t,"GLTFLoaderExtension",function(){return k}),n.d(t,"EComponentType",function(){return a}),n.d(t,"EShaderType",function(){return i}),n.d(t,"EParameterType",function(){return s}),n.d(t,"ETextureWrapMode",function(){return l}),n.d(t,"ETextureFilterType",function(){return u}),n.d(t,"ETextureFormat",function(){return c}),n.d(t,"ECullingType",function(){return f}),n.d(t,"EBlendingFunction",function(){return d}),n.d(t,"GLTFUtils",function(){return m}),n.d(t,"GLTFMaterialsCommonExtension",function(){return j})},function(e,t,n){"use strict";n.r(t);var r=n(0),o=function(){function e(){this.materials=[]}return e.prototype.parseMTL=function(t,n,o,a){if(!(n instanceof ArrayBuffer)){for(var i,s=n.split("\n"),l=/\s+/,u=null,c=0;c<s.length;c++){var f=s[c].trim();if(0!==f.length&&"#"!==f.charAt(0)){var d=f.indexOf(" "),h=d>=0?f.substring(0,d):f;h=h.toLowerCase();var p=d>=0?f.substring(d+1).trim():"";"newmtl"===h?(u&&this.materials.push(u),t._blockEntityCollection=a,u=new r.StandardMaterial(p,t),t._blockEntityCollection=!1):"kd"===h&&u?(i=p.split(l,3).map(parseFloat),u.diffuseColor=r.Color3.FromArray(i)):"ka"===h&&u?(i=p.split(l,3).map(parseFloat),u.ambientColor=r.Color3.FromArray(i)):"ks"===h&&u?(i=p.split(l,3).map(parseFloat),u.specularColor=r.Color3.FromArray(i)):"ke"===h&&u?(i=p.split(l,3).map(parseFloat),u.emissiveColor=r.Color3.FromArray(i)):"ns"===h&&u?u.specularPower=parseFloat(p):"d"===h&&u?u.alpha=parseFloat(p):"map_ka"===h&&u?u.ambientTexture=e._getTexture(o,p,t):"map_kd"===h&&u?u.diffuseTexture=e._getTexture(o,p,t):"map_ks"===h&&u?u.specularTexture=e._getTexture(o,p,t):"map_ns"===h||("map_bump"===h&&u?u.bumpTexture=e._getTexture(o,p,t):"map_d"===h&&u&&(u.opacityTexture=e._getTexture(o,p,t)))}}u&&this.materials.push(u)}},e._getTexture=function(t,n,o){if(!n)return null;var a=t;if("file:"===t){var i=n.lastIndexOf("\\");-1===i&&(i=n.lastIndexOf("/")),a+=i>-1?n.substr(i+1):n}else a+=n;return new r.Texture(a,o,!1,e.INVERT_TEXTURE_Y)},e.INVERT_TEXTURE_Y=!0,e}(),a=function(){function e(t){this.name="obj",this.extensions=".obj",this.obj=/^o/,this.group=/^g/,this.mtllib=/^mtllib /,this.usemtl=/^usemtl /,this.smooth=/^s /,this.vertexPattern=/v( +[\d|\.|\+|\-|e|E]+){3,7}/,this.normalPattern=/vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,this.uvPattern=/vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,this.facePattern1=/f\s+(([\d]{1,}[\s]?){3,})+/,this.facePattern2=/f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,this.facePattern3=/f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,this.facePattern4=/f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,this.facePattern5=/f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,this._forAssetContainer=!1,this._meshLoadOptions=t||e.currentMeshLoadOptions}return Object.defineProperty(e,"INVERT_TEXTURE_Y",{get:function(){return o.INVERT_TEXTURE_Y},set:function(e){o.INVERT_TEXTURE_Y=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"currentMeshLoadOptions",{get:function(){return{ComputeNormals:e.COMPUTE_NORMALS,ImportVertexColors:e.IMPORT_VERTEX_COLORS,InvertY:e.INVERT_Y,InvertTextureY:e.INVERT_TEXTURE_Y,UVScaling:e.UV_SCALING,MaterialLoadingFailsSilently:e.MATERIAL_LOADING_FAILS_SILENTLY,OptimizeWithUV:e.OPTIMIZE_WITH_UV,SkipMaterials:e.SKIP_MATERIALS}},enumerable:!0,configurable:!0}),e.prototype._loadMTL=function(e,t,n,o){var a=r.Tools.BaseUrl+t+e;r.Tools.LoadFile(a,n,void 0,void 0,!1,function(e,t){o(a,t)})},e.prototype.createPlugin=function(){return new e(e.currentMeshLoadOptions)},e.prototype.canDirectLoad=function(e){return!1},e.prototype.importMeshAsync=function(e,t,n,r,o,a){return this._parseSolid(e,t,n,r).then(function(e){return{meshes:e,particleSystems:[],skeletons:[],animationGroups:[]}})},e.prototype.loadAsync=function(e,t,n,r,o){return this.importMeshAsync(null,e,t,n,r).then(function(){})},e.prototype.loadAssetContainerAsync=function(e,t,n,o,a){var i=this;return this._forAssetContainer=!0,this.importMeshAsync(null,e,t,n).then(function(t){var n=new r.AssetContainer(e);return t.meshes.forEach(function(e){return n.meshes.push(e)}),t.meshes.forEach(function(e){var t=e.material;t&&(-1==n.materials.indexOf(t)&&(n.materials.push(t),t.getActiveTextures().forEach(function(e){-1==n.textures.indexOf(e)&&n.textures.push(e)})))}),i._forAssetContainer=!1,n}).catch(function(e){throw i._forAssetContainer=!1,e})},e.prototype._parseSolid=function(t,n,a,i){for(var s,l=this,u=[],c=[],f=[],d=[],h=[],p=[],m=[],_=[],y=[],b=[],v=[],A=0,g=!1,T=[],x=[],E=[],L=[],O=[],M="",S="",w=new o,C=1,N=!0,P=new r.Color4(.5,.5,.5,1),R=function(e,t,n,r,o,a,i){var s;-1===(s=l._meshLoadOptions.OptimizeWithUV?function(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});var n=e[t[0]].normals.indexOf(t[1]);return 1!=n&&t[2]===e[t[0]].uv[n]?e[t[0]].idx[n]:-1}(v,[e,n,t]):function(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});var n=e[t[0]].normals.indexOf(t[1]);return-1===n?-1:e[t[0]].idx[n]}(v,[e,n]))?(p.push(m.length),m.push(r),_.push(o),b.push(a),void 0!==i&&y.push(i),v[e].normals.push(n),v[e].idx.push(A++),l._meshLoadOptions.OptimizeWithUV&&v[e].uv.push(t)):p.push(s)},I=function(){for(var e=0;e<m.length;e++)T.push(m[e].x,m[e].y,m[e].z),E.push(b[e].x,b[e].y,b[e].z),L.push(_[e].x,_[e].y);!0===l._meshLoadOptions.ImportVertexColors&&x.push(y[e].r,y[e].g,y[e].b,y[e].a),m=[],b=[],_=[],y=[],v=[],A=0},F=function(e,t){for(var n=t;n<e.length-1;n++)O.push(e[0],e[n],e[n+1])},V=function(e,t){F(e,t);for(var n=0;n<O.length;n++){var o=parseInt(O[n])-1;R(o,0,0,u[o],r.Vector2.Zero(),r.Vector3.Up(),!0===l._meshLoadOptions.ImportVertexColors?d[o]:void 0)}O=[]},B=function(e,t){F(e,t);for(var n=0;n<O.length;n++){var o=O[n].split("/"),a=parseInt(o[0])-1,i=parseInt(o[1])-1;R(a,i,0,u[a],f[i],r.Vector3.Up(),!0===l._meshLoadOptions.ImportVertexColors?d[a]:void 0)}O=[]},D=function(e,t){F(e,t);for(var n=0;n<O.length;n++){var r=O[n].split("/"),o=parseInt(r[0])-1,a=parseInt(r[1])-1,i=parseInt(r[2])-1;R(o,a,i,u[o],f[a],c[i])}O=[]},G=function(e,t){F(e,t);for(var n=0;n<O.length;n++){var o=O[n].split("//"),a=parseInt(o[0])-1,i=parseInt(o[1])-1;R(a,1,i,u[a],r.Vector2.Zero(),c[i],!0===l._meshLoadOptions.ImportVertexColors?d[a]:void 0)}O=[]},U=function(e,t){F(e,t);for(var n=0;n<O.length;n++){var r=O[n].split("/"),o=u.length+parseInt(r[0]),a=f.length+parseInt(r[1]),i=c.length+parseInt(r[2]);R(o,a,i,u[o],f[a],c[i],!0===l._meshLoadOptions.ImportVertexColors?d[o]:void 0)}O=[]},k=function(){h.length>0&&(s=h[h.length-1],I(),p.reverse(),s.indices=p.slice(),s.positions=T.slice(),s.normals=E.slice(),s.uvs=L.slice(),!0===l._meshLoadOptions.ImportVertexColors&&(s.colors=x.slice()),p=[],T=[],x=[],E=[],L=[])},H=a.split("\n"),j=0;j<H.length;j++){var K,W=H[j].trim().replace(/\s\s/g," ");if(0!==W.length&&"#"!==W.charAt(0))if(this.vertexPattern.test(W))K=W.match(/[^ ]+/g),u.push(new r.Vector3(parseFloat(K[1]),parseFloat(K[2]),parseFloat(K[3]))),!0===this._meshLoadOptions.ImportVertexColors&&(K.length>=7?d.push(new r.Color4(parseFloat(K[4]),parseFloat(K[5]),parseFloat(K[6]),7===K.length||void 0===K[7]?1:parseFloat(K[7]))):d.push(P));else if(null!==(K=this.normalPattern.exec(W)))c.push(new r.Vector3(parseFloat(K[1]),parseFloat(K[2]),parseFloat(K[3])));else if(null!==(K=this.uvPattern.exec(W)))f.push(new r.Vector2(parseFloat(K[1])*e.UV_SCALING.x,parseFloat(K[2])*e.UV_SCALING.y));else if(null!==(K=this.facePattern3.exec(W)))D(K[1].trim().split(" "),1);else if(null!==(K=this.facePattern4.exec(W)))G(K[1].trim().split(" "),1);else if(null!==(K=this.facePattern5.exec(W)))U(K[1].trim().split(" "),1);else if(null!==(K=this.facePattern2.exec(W)))B(K[1].trim().split(" "),1);else if(null!==(K=this.facePattern1.exec(W)))V(K[1].trim().split(" "),1);else if(this.group.test(W)||this.obj.test(W)){var Y={name:W.substring(2).trim(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,colors:void 0,materialName:""};k(),h.push(Y),g=!0,N=!0,C=1}else if(this.usemtl.test(W)){if(M=W.substring(7).trim(),!N||!g){k();Y={name:"mesh_mm"+C.toString(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,colors:void 0,materialName:M};C++,h.push(Y),g=!0}g&&N&&(h[h.length-1].materialName=M,N=!1)}else this.mtllib.test(W)?S=W.substring(7).trim():this.smooth.test(W)||console.log("Unhandled expression at line : "+W)}g&&(s=h[h.length-1],p.reverse(),I(),s.indices=p,s.positions=T,s.normals=E,s.uvs=L,!0===this._meshLoadOptions.ImportVertexColors&&(s.colors=x)),g||(p.reverse(),I(),h.push({name:r.Geometry.RandomId(),indices:p,positions:T,colors:x,normals:E,uvs:L,materialName:M}));for(var J=[],q=new Array,Z=0;Z<h.length;Z++){if(t&&h[Z].name)if(t instanceof Array){if(-1===t.indexOf(h[Z].name))continue}else if(h[Z].name!==t)continue;s=h[Z],n._blockEntityCollection=this._forAssetContainer;var Q=new r.Mesh(h[Z].name,n);n._blockEntityCollection=!1,q.push(h[Z].materialName);var X=new r.VertexData;if(X.uvs=s.uvs,X.indices=s.indices,X.positions=s.positions,!0===this._meshLoadOptions.ComputeNormals){var z=new Array;r.VertexData.ComputeNormals(s.positions,s.indices,z),X.normals=z}else X.normals=s.normals;!0===this._meshLoadOptions.ImportVertexColors&&(X.colors=s.colors),X.applyToMesh(Q),this._meshLoadOptions.InvertY&&(Q.scaling.y*=-1),J.push(Q)}var $=[];return""!==S&&!1===this._meshLoadOptions.SkipMaterials&&$.push(new Promise(function(e,t){l._loadMTL(S,i,function(o){try{w.parseMTL(n,o,i,l._forAssetContainer);for(var a=0;a<w.materials.length;a++){for(var s,u=0,c=[];(s=q.indexOf(w.materials[a].name,u))>-1;)c.push(s),u=s+1;if(-1===s&&0===c.length)w.materials[a].dispose();else for(var f=0;f<c.length;f++)J[c[f]].material=w.materials[a]}e()}catch(n){r.Tools.Warn("Error processing MTL file: '"+S+"'"),l._meshLoadOptions.MaterialLoadingFailsSilently?e():t(n)}},function(n,o){r.Tools.Warn("Error downloading MTL file: '"+S+"'"),l._meshLoadOptions.MaterialLoadingFailsSilently?e():t(o)})})),Promise.all($).then(function(){return J})},e.OPTIMIZE_WITH_UV=!0,e.INVERT_Y=!1,e.IMPORT_VERTEX_COLORS=!1,e.COMPUTE_NORMALS=!1,e.UV_SCALING=new r.Vector2(1,1),e.SKIP_MATERIALS=!1,e.MATERIAL_LOADING_FAILS_SILENTLY=!0,e}();r.SceneLoader&&r.SceneLoader.RegisterPlugin(new a),n.d(t,"MTLFileLoader",function(){return o}),n.d(t,"OBJFileLoader",function(){return a})},function(e,t,n){"use strict";n.r(t);var r=n(0),o=function(){function e(){this.solidPattern=/solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g,this.facetsPattern=/facet([\s\S]*?)endfacet/g,this.normalPattern=/normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g,this.vertexPattern=/vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g,this.name="stl",this.extensions={".stl":{isBinary:!0}}}return e.prototype.importMesh=function(e,t,n,o,a,i,s){var l;if("string"!=typeof n){if(this._isBinary(n)){var u=new r.Mesh("stlmesh",t);return this._parseBinary(u,n),a&&a.push(u),!0}for(var c=new Uint8Array(n),f="",d=0;d<n.byteLength;d++)f+=String.fromCharCode(c[d]);n=f}for(;l=this.solidPattern.exec(n);){var h=l[1];if(h!=l[3])return r.Tools.Error("Error in STL, solid name != endsolid name"),!1;if(e&&h)if(e instanceof Array){if(!e.indexOf(h))continue}else if(h!==e)continue;h=h||"stlmesh";u=new r.Mesh(h,t);this._parseASCII(u,l[2]),a&&a.push(u)}return!0},e.prototype.load=function(e,t,n){return this.importMesh(null,e,t,n,null,null,null)},e.prototype.loadAssetContainer=function(e,t,n,o){var a=new r.AssetContainer(e);return e._blockEntityCollection=!0,this.importMesh(null,e,t,n,a.meshes,null,null),e._blockEntityCollection=!1,a},e.prototype._isBinary=function(e){var t;if(50,84+50*(t=new DataView(e)).getUint32(80,!0)===t.byteLength)return!0;for(var n=t.byteLength,r=0;r<n;r++)if(t.getUint8(r)>127)return!0;return!1},e.prototype._parseBinary=function(e,t){for(var n=new DataView(t),o=n.getUint32(80,!0),a=0,i=new Float32Array(3*o*3),s=new Float32Array(3*o*3),l=new Uint32Array(3*o),u=0,c=0;c<o;c++){for(var f=84+50*c,d=n.getFloat32(f,!0),h=n.getFloat32(f+4,!0),p=n.getFloat32(f+8,!0),m=1;m<=3;m++){var _=f+12*m;i[a]=n.getFloat32(_,!0),i[a+2]=n.getFloat32(_+4,!0),i[a+1]=n.getFloat32(_+8,!0),s[a]=d,s[a+2]=h,s[a+1]=p,a+=3}l[u]=u++,l[u]=u++,l[u]=u++}e.setVerticesData(r.VertexBuffer.PositionKind,i),e.setVerticesData(r.VertexBuffer.NormalKind,s),e.setIndices(l),e.computeWorldMatrix(!0)},e.prototype._parseASCII=function(e,t){for(var n,o=[],a=[],i=[],s=0;n=this.facetsPattern.exec(t);){var l=n[1],u=this.normalPattern.exec(l);if(this.normalPattern.lastIndex=0,u){for(var c,f=[Number(u[1]),Number(u[5]),Number(u[3])];c=this.vertexPattern.exec(l);)o.push(Number(c[1]),Number(c[5]),Number(c[3])),a.push(f[0],f[1],f[2]);i.push(s++,s++,s++),this.vertexPattern.lastIndex=0}}this.facetsPattern.lastIndex=0,e.setVerticesData(r.VertexBuffer.PositionKind,o),e.setVerticesData(r.VertexBuffer.NormalKind,a),e.setIndices(i),e.computeWorldMatrix(!0)},e}();r.SceneLoader&&r.SceneLoader.RegisterPlugin(new o),n.d(t,"STLFileLoader",function(){return o})},function(e,t,n){"use strict";(function(e){var r=n(2),o=n(3);n.d(t,"a",function(){return r.GLTFFileLoader}),n.d(t,"b",function(){return r.GLTFLoaderAnimationStartMode}),n.d(t,"c",function(){return r.GLTFLoaderCoordinateSystemMode}),n.d(t,"d",function(){return r.GLTFLoaderState}),n.d(t,"e",function(){return o.GLTFValidation});var a=void 0!==e?e:"undefined"!=typeof window?window:void 0;if(void 0!==a){for(var i in a.BABYLON=a.BABYLON||{},r)a.BABYLON[i]=r[i];for(var i in o)a.BABYLON[i]=o[i]}}).call(this,n(4))},function(e,t){},function(e,t,n){"use strict";(function(e){var r=n(7);n.d(t,"a",function(){return r});var o=void 0!==e?e:"undefined"!=typeof window?window:void 0;if(void 0!==o)for(var a in o.BABYLON=o.BABYLON||{},o.BABYLON.GLTF1=o.BABYLON.GLTF1||{},r)o.BABYLON.GLTF1[a]=r[a]}).call(this,n(4))},function(e,t,n){"use strict";(function(e){var r=n(5),o=n(11),a=n(6);n.d(t,"a",function(){return a});var i=void 0!==e?e:"undefined"!=typeof window?window:void 0;if(void 0!==i){i.BABYLON=i.BABYLON||{};var s=i.BABYLON;s.GLTF2=s.GLTF2||{},s.GLTF2.Loader=s.GLTF2.Loader||{},s.GLTF2.Loader.Extensions=s.GLTF2.Loader.Extensions||{};var l=[];for(var u in r)s.GLTF2.Loader.Extensions[u]=r[u],l.push(u);for(var u in o)s.GLTF2.Loader[u]=o[u],l.push(u);for(var u in a)l.indexOf(u)>-1||(s.GLTF2[u]=a[u])}}).call(this,n(4))},function(e,t,n){"use strict";n.r(t),function(e){var r=n(8);n.d(t,"MTLFileLoader",function(){return r.MTLFileLoader}),n.d(t,"OBJFileLoader",function(){return r.OBJFileLoader});var o=void 0!==e?e:"undefined"!=typeof window?window:void 0;if(void 0!==o)for(var a in r)o.BABYLON[a]=r[a]}.call(this,n(4))},function(e,t,n){"use strict";n.r(t),function(e){var r=n(9);n.d(t,"STLFileLoader",function(){return r.STLFileLoader});var o=void 0!==e?e:"undefined"!=typeof window?window:void 0;if(void 0!==o)for(var a in r)o.BABYLON[a]=r[a]}.call(this,n(4))},,,,function(e,t,n){"use strict";n.r(t);n(2),n(3),n(7),n(6),n(8),n(9);var r=n(10),o=n(12),a=n(13),i=n(14),s=n(15);n.d(t,"GLTFLoaderCoordinateSystemMode",function(){return r.c}),n.d(t,"GLTFLoaderAnimationStartMode",function(){return r.b}),n.d(t,"GLTFLoaderState",function(){return r.d}),n.d(t,"GLTFFileLoader",function(){return r.a}),n.d(t,"GLTFValidation",function(){return r.e}),n.d(t,"GLTF1",function(){return o.a}),n.d(t,"GLTF2",function(){return a.a}),n.d(t,"MTLFileLoader",function(){return i.MTLFileLoader}),n.d(t,"OBJFileLoader",function(){return i.OBJFileLoader}),n.d(t,"STLFileLoader",function(){return s.STLFileLoader})}])});

/***/ }),
/* 6 */
/***/ (function(module, exports) {

const mz3d = window.mz3d;

//setup was here	

const _graphics_updateAllElements=Graphics._updateAllElements;
Graphics._updateAllElements = function() {
	_graphics_updateAllElements.apply(this,arguments);
	if(mz3d.canvas){
		mz3d.updateCanvas();
	}
};

const _sceneMap_update=Scene_Map.prototype.update;
Scene_Map.prototype.update = function(){
	_sceneMap_update.apply(this,arguments);
	if(!mz3d.isDisabled()){
		mz3d.update();
		mz3d.render();
	}
}

const _createTilemap=Spriteset_Map.prototype.createTilemap;
Spriteset_Map.prototype.createTilemap=function(){
	_createTilemap.apply(this,arguments);
	mz3d.mapDisabled = mz3d.isDisabled();
	mz3d.pixiSprite=new PIXI.Sprite(mz3d.texture);
	mz3d.pixiSprite.scale.set(1/mz3d.RES_SCALE,1/mz3d.RES_SCALE);
	mz3d.pixiContainer=new PIXI.Container();
	mz3d.viewContainer=new PIXI.Container();
	mz3d.pixiContainer.addChild( mz3d.viewContainer );
	mz3d.viewContainer.addChild( mz3d.pixiSprite );
	mz3d.mv_baseSprite = this._baseSprite;
	if(!mz3d.mapDisabled){
		this._tilemap.visible=false;
		this._baseSprite.addChild( mz3d.pixiContainer );
	}
};

const _sprite_char_setchar = Sprite_Character.prototype.setCharacter;
Sprite_Character.prototype.setCharacter = function(character) {
	_sprite_char_setchar.apply(this,arguments);
	Object.defineProperty(character,'mv_sprite',{
		value:this,
		configurable:true,
		enumerable:false,
	});
};

// Player Transfer

const _performTransfer=Game_Player.prototype.performTransfer;
Game_Player.prototype.performTransfer = function() {
	const newmap = this._newMapId !== $gameMap.mapId();
	_performTransfer.apply(this,arguments);
	if(mz3d.is1stPerson()){
		mz3d.blendCameraYaw.setValue(mz3d.dirToYaw($gamePlayer.direction(),0));
	}
	if(!newmap){
		this.z = mz3d.getWalkHeight(this.x,this.y);
		for ( const follower of this._followers._data){
			follower.z=this.z;
		}
	}
};

// On Map Load

let tilesetLoaded = false;

const _onMapLoaded=Scene_Map.prototype.onMapLoaded;
Scene_Map.prototype.onMapLoaded=function(){
	const newmap = this._transfer && ( $gamePlayer._newMapId !== $gameMap.mapId() );
	Input.clear();
	if(newmap || mz3d.needClearMap){
		mz3d.clearMap();
		mz3d.needClearMap=false;
	}else if(mz3d.needReloadMap&&mz3d.mapLoaded){
		mz3d.reloadMap();
	}
	mz3d.needReloadMap=false;
	tilesetLoaded = false;
	if(!mz3d.mapLoaded){
		mz3d.beforeMapLoad(newmap);
		mz3d.loadMapSettings();
	}
	_onMapLoaded.apply(this,arguments);
	if(!tilesetLoaded){ mz3d.loadTilesetSettings(); }
	if(!mz3d.mapLoaded){
		if(newmap){ mz3d.applyMapSettings(); }
		mz3d.afterMapLoad(newmap);
		if(mz3d.isDisabled()){
			mz3d.mapReady=true;
			//mv3d.createCharacters();
		}else{
			mz3d.mapReady=false;
			//mv3d.mapReady=true;
			mz3d.loadMap();
		}
	}
	mz3d.updateBlenders(true);
};

// onMapLoaded > performTransfer > map setup
// hook into map setup before Qmovement's setup.
const _map_battleback_Setup = Game_Map.prototype.setupBattleback;
Game_Map.prototype.setupBattleback=function(){
	_map_battleback_Setup.apply(this,arguments);
	mz3d.loadTilesetSettings();
	tilesetLoaded = true;
};

const _onLoadSuccess = Scene_Load.prototype.onLoadSuccess;
Scene_Load.prototype.onLoadSuccess = function() {
	_onLoadSuccess.apply(this,arguments);
	mz3d.needClearMap=true;
};

const _map_isReady = Scene_Map.prototype.isReady;
Scene_Map.prototype.isReady = function() {
	let ready = _map_isReady.apply(this,arguments);
	return ready && mz3d.mapReady;
};

// Title

const _title_start=Scene_Title.prototype.start;
Scene_Title.prototype.start = function() {
	_title_start.apply(this,arguments);
	mz3d.clearMap();
	mz3d.clearCameraTarget();
};

const _initGraphics = SceneManager.initGraphics;
SceneManager.initGraphics = function() {
	_initGraphics.apply(this,arguments);
	if(mz3d.isMV && !Graphics.isWebGL()){
		throw new Error("MV3D requires WebGL");
	}
};

// force webgl
SceneManager.preferableRendererType = function() {
    if (Utils.isOptionValid('canvas')) {
        return 'canvas';
    } else if (Utils.isOptionValid('webgl')) {
        return 'webgl';
    } else {
		if(Graphics.hasWebGL()){ return 'webgl'; }
        return 'auto';
    }
};

/***/ }),
/* 7 */
/***/ (function(module, exports) {

const mv3d = window.mv3d;

mv3d.blendModes={
	[PIXI.BLEND_MODES.NORMAL]: BABYLON.Engine.ALPHA_COMBINE,
	[PIXI.BLEND_MODES.ADD]: BABYLON.Engine.ALPHA_ADD,
	[PIXI.BLEND_MODES.MULTIPLY]: BABYLON.Engine.ALPHA_MULTIPLY,
	[PIXI.BLEND_MODES.SCREEN]: BABYLON.Engine.ALPHA_SCREENMODE,
	
	NORMAL:BABYLON.Engine.ALPHA_COMBINE,
	ADD:BABYLON.Engine.ALPHA_ADD,
	MULTIPLY:BABYLON.Engine.ALPHA_MULTIPLY,
	SCREEN:BABYLON.Engine.ALPHA_SCREENMODE,
};

/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {


__webpack_require__(9);
__webpack_require__(11);

if(window.Imported&&Imported.YEP_SaveCore){
	const _onLoadSuccess = Scene_File.prototype.onLoadSuccess;
	Scene_File.prototype.onLoadSuccess=function(){
		_onLoadSuccess.apply(this,arguments);
		mv3d.needClearMap=true;
	}
}

/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {

const mv3d = window.mv3d;

mv3d['option-store']={}

mv3d.options={};

if(mv3d.OPTION_RENDER_DIST) mv3d.options['mv3d-renderDist']={
	name:mv3d.OPTION_NAME_RENDER_DIST,
	min:mv3d.OPTION_RENDER_DIST_MIN, max:mv3d.OPTION_RENDER_DIST_MAX,
	increment:5,
	wrap:false,
	apply(v){ mv3d.RENDER_DIST=v; },
	default:mv3d.RENDER_DIST,
};

if(mv3d.OPTION_FOV) mv3d.options['mv3d-fov']={
	name:mv3d.OPTION_NAME_FOV,
	min:mv3d.OPTION_FOV_MIN, max:mv3d.OPTION_FOV_MAX,
	increment:5,
	apply(v){ mv3d.FOV=v; },
	default:mv3d.FOV,
};

if(mv3d.OPTION_MIPMAP) mv3d.options['mv3d-mipmap']={
	name:mv3d.OPTION_NAME_MIPMAP,
	type:'bool',
	apply(v){ mv3d.MIPMAP=v; mv3d.needReloadMap=true; },
	default:mv3d.MIPMAP,
};

mv3d.invertY=false;
if(mv3d.OPTION_INVERTY) mv3d.options['mv3d-inverty']={
	name: mv3d.OPTION_NAME_INVERTY,
	type:'bool',
	apply(v){ mv3d.invertY=v; },
	default: false,
};

mv3d.lookSensitivity=1.0;
if(mv3d.OPTION_LOOKSENSITIVITY) mv3d.options['mv3d-looksensitivity']={
	name: mv3d.OPTION_NAME_LOOKSENSITIVITY,
	min:10, max:400,
	increment:10,
	wrap:false,
	apply(v){ mv3d.lookSensitivity=v/100; },
	default:100,
};

if(mv3d.ENABLE_3D_OPTIONS){
	__webpack_require__(10);
}

/***/ }),
/* 10 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
const mv3d = window.mv3d;



const _option_command_list = Window_Options.prototype.makeCommandList;
Window_Options.prototype.makeCommandList = function() {
	_option_command_list.apply(this,arguments);
	if(mv3d.ENABLE_3D_OPTIONS===mv3d.enumOptionModes.SUBMENU && Object.keys(mv3d.options).length){
		this.addCommand("3D Options", 'mv3d-options');
	}else if(mv3d.ENABLE_3D_OPTIONS===mv3d.enumOptionModes.ENABLE){
		for (const key in mv3d.options){
			this.addCommand(mv3d.options[key].name,key);
		}
	}
};

const _option_status_text = Window_Options.prototype.statusText;
Window_Options.prototype.statusText = function(index) {
	const symbol = this.commandSymbol(index);
	const value = this.getConfigValue(symbol);
	if(symbol==='mv3d-options'){ return ''; }
	return _option_status_text.apply(this,arguments);
};

Object.defineProperty(ConfigManager, 'mv3d-options', {
	get(){ return undefined; },
	set(v){ SceneManager.push(Scene_3D_Options); },
	configurable: true,
	enumerable:false,
});

const _config_makeData=ConfigManager.makeData;
ConfigManager.makeData = function() {
	const config = _config_makeData.apply(this,arguments);
	Object.assign(config,mv3d['option-store']);
	return config;
};
const _config_applyData=ConfigManager.applyData;
ConfigManager.applyData = function(config) {
	_config_applyData.apply(this,arguments);
	for(const key in mv3d.options){
		if(key in config){
			mv3d['option-store'][key]=config[key];
			mv3d.options[key].apply(config[key]);
		}
	}
	mv3d.updateParameters();
};



class Scene_3D_Options extends Scene_Options{
	createOptionsWindow(){
		this._optionsWindow = new Window_3D_Options();
		this._optionsWindow.setHandler('cancel', this.popScene.bind(this));
		this.addWindow(this._optionsWindow);
	}
	terminate(){
		super.terminate();
		mv3d.updateParameters();
	}
}

class Window_3D_Options extends Window_Options{
	makeCommandList(){
		for (const key in mv3d.options){
			this.addCommand(mv3d.options[key].name,key);
		}
	}
}

if(mv3d.ENABLE_3D_OPTIONS===1) Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Scene_Options.prototype,'terminate',o=>function(){
	o.apply(this,arguments);
	mv3d.updateParameters();
},true);

Window_Options.prototype._is_mv3d_option=function(symbol){
	return symbol in mv3d.options;
}

Window_Options.prototype._mv3d_cursor=function(wrap,direction){
	const index = this.index();
	const symbol = this.commandSymbol(index);
	let value = this.getConfigValue(symbol);
	const option = mv3d.options[symbol];
	if(!option) { return; }
	if(option.type==='bool'){
		this.changeValue(symbol, direction>0);
	}else{
		const min = option.min||0;
		const max = option.values?option.values.length-1:option.max||1;
		value += (option.increment||1)*direction;
		if(wrap&&option.wrap||wrap==='ok'){
			if(value>max){ value = min; }
			if(value<min){ value = max; }
		}else{
			value = value.clamp(min,max);
		}
		this.changeValue(symbol, value);
	}
}


Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Window_Options.prototype,'statusText',o=>function(index){
    const symbol = this.commandSymbol(index);
    if(!this._is_mv3d_option(symbol)){ return o.apply(this,arguments); }
    const value = this.getConfigValue(symbol);
    const option = mv3d.options[symbol];
    if(option.type==='bool'){
        return this.booleanStatusText(value);
    }else if(option.values){
        return option.values[value];
    }
    return String(value);
},true);

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Window_Options.prototype,'setConfigValue',o=>function(symbol, value){
    if(!this._is_mv3d_option(symbol)){ return o.apply(this,arguments); }
    mv3d['option-store'][symbol]=value;
    const option = mv3d.options[symbol];
    if(option.apply){ option.apply(value); }
},true);

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Window_Options.prototype,'getConfigValue',o=>function(symbol){
    if(!this._is_mv3d_option(symbol)){ return o.apply(this,arguments); }
    const option = mv3d.options[symbol];
    let value = mv3d['option-store'][symbol];
    if(value==null){ value=option.default||option.min||0; }
    return value;
},true);

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Window_Options.prototype,'cursorLeft',o=>function(wrap){
    const symbol = this.commandSymbol(this.index());
    if(this._is_mv3d_option(symbol)){
        return this._mv3d_cursor(wrap,-1);
    }else{
        return o.apply(this,arguments);
    }
},true);

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Window_Options.prototype,'cursorRight',o=>function(wrap){
    const symbol = this.commandSymbol(this.index());
    if(this._is_mv3d_option(symbol)){
        return this._mv3d_cursor(wrap,1);
    }else{
        return o.apply(this,arguments);
    }
},true);

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Window_Options.prototype,'processOk',o=>function(){
    const index = this.index();
    const symbol = this.commandSymbol(index);
    if(!this._is_mv3d_option(symbol)){
        return o.apply(this,arguments);
    }
    let value = this.getConfigValue(symbol);
    const option = mv3d.options[symbol];
    if(option.type==='bool'){
        this.changeValue(symbol, !value);
    }else{
        this._mv3d_cursor('ok',1);
    }
},true);


/***/ }),
/* 11 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
const mv3d = window.mv3d;


Object.assign(mv3d,{
	vehicleObstructed(vehicle,...args){
		return vehicleObstructed.apply(vehicle,args);
	},
	tileCollision(char,x,y,useStairThresh=false,useTargetZ=false){
		if(!(char instanceof mv3d.Character)){if(!char.mv3d_sprite){return false;}char=char.mv3d_sprite;}
		const z = typeof useTargetZ==='number'? useTargetZ
		:useTargetZ?char.getTargetElevation(x,y):char.z;
		const cc = char.getCollisionHeight(z);
		const tcs = this.getCollisionHeights(x,y);
		if(useStairThresh==2){ cc.z1+=mv3d.STAIR_THRESH; cc.z2+=mv3d.STAIR_THRESH; }
		for (const tc of tcs){
			if(cc.z1<tc.z2&&cc.z2>tc.z1){
				if(useStairThresh==1&&mv3d.STAIR_THRESH){ return this.tileCollision(char,x,y,2,useTargetZ); }
				return true;
			}
		}
		return false;
	},
	charCollision(char1,char2,useStairThresh=false,useTargetZ1=false,useTargetZ2=useTargetZ1,triggerMode=false){
		if(!(char1 instanceof mv3d.Character)){if(!char1.mv3d_sprite){return false;}char1=char1.mv3d_sprite;}
		if(!(char2 instanceof mv3d.Character)){if(!char2.mv3d_sprite){return false;}char2=char2.mv3d_sprite;}
		if(!triggerMode&&(!char1.char._mv3d_hasCollide()||!char2.char._mv3d_hasCollide())){ return false; } 
		const c1z = typeof useTargetZ1==='number'? useTargetZ1 : useTargetZ1?char1.getTargetElevation(char2.x,char2.y):char1.z;
		const c2z = typeof useTargetZ2==='number'? useTargetZ2 : useTargetZ2?char2.targetElevation:char2.z;
		const cc1 = char1.getCollisionHeight(c1z);
		const cc2 = triggerMode ? char2.getTriggerHeight(c2z) : char2.getCollisionHeight(c2z);
		if(useStairThresh==2){ cc1.z1+=mv3d.STAIR_THRESH; cc1.z2+=mv3d.STAIR_THRESH; }
		if(!triggerMode&&cc1.z1<cc2.z2&&cc1.z2>cc2.z1 || triggerMode&&cc1.z1<=cc2.z2&&cc1.z2>=cc2.z1){
			if(useStairThresh==1&&mv3d.STAIR_THRESH){ return this.charCollision(char1,char2,2,useTargetZ1,useTargetZ2); }
			return true;
		}
		return false;
	},
	getPlatformFloatForCharacter(char,x,y,opts={}){
		if(!(char instanceof mv3d.Character)){if(!char.mv3d_sprite){return 0;}char=char.mv3d_sprite;}
		let z = mv3d.getPlatformForCharacter(char,x,y,opts).z2;
		if(char.hasFloat){
			const cHeight = char.getCHeight();
			z += mv3d.getFloatHeight(x,y,char.z+Math.max(cHeight,mv3d.STAIR_THRESH),mv3d.STAIR_THRESH>=cHeight);
		}
		return z;
	},
	getPlatformForCharacter(char,x,y,opts={}){
		if(!(char instanceof mv3d.Character)){if(!char.mv3d_sprite){return false;}char=char.mv3d_sprite;}
		const cHeight = char.getCHeight();
		const useStairThresh = mv3d.STAIR_THRESH>=cHeight;
		Object.assign(opts,{char:char,gte:useStairThresh});
		return this.getPlatformAtLocation(x,y,char.z+Math.max(cHeight,mv3d.STAIR_THRESH),opts);
	},
	getPlatformAtLocation(x,y,z,opts={}){
		const char = opts.char;
		const cs = this.getCollisionHeights(x,y,opts);
		cs.push(...mv3d.getEventsAt(x,y)
			.filter(event=>{
				if(!(event.mv3d_sprite&&event._mv3d_isPlatform()&&event._mv3d_hasCollide()&&event.mv3d_sprite.visible)){ return false; }
				if(char){
					if(char.char===event || event.isMoving()){ return false; }
					let pc=event.mv3d_sprite;
					while(pc=pc.platformChar){
						if(pc===char||pc===event.mv3d_sprite){ return false; }
					}
				}
				return true;
			})
			.map(event=>event.mv3d_sprite.getCollisionHeight())
		);
		let closest = cs[0];
		for (const c of cs){
			if(c.z2>closest.z2 && (opts.gte?c.z2<=z:c.z2<z) ){
				closest=c;
			}
		}
		return closest;
	},

	getEventsAt(x,y){
		return $gameMap.eventsXyNt(Math.round(x),Math.round(y));
	},

	isRampAt(x,y,z){
		const tileData = this.getTileData(x,y);
		let height = 0;
		for (let l=0;l<4;++l){
			height += this.getTileFringe(x,y,l);
			height += this.getTileHeight(x,y,l);
			const conf = this.getTileConfig(tileData[l],x,y,l);
			if(conf.shape!==this.enumShapes.SLOPE){ continue; }
			const slopeHeight = conf.slopeHeight||1;
			if(z>=height-slopeHeight && z<=height){
				return { id:tileData[l], x,y,l,conf, z1:height-slopeHeight, z2:height };
			}
		}
		return false;
	},

	getRampData(x,y,l,conf=null){
		const tileId = mv3d.getTileId(x,y,l);
		if(!conf){ conf = this.getTileConfig(tileId,x,y,l); }
		if(conf.shape!==this.enumShapes.SLOPE){ return false; }
		const height = mv3d.getStackHeight(x,y,l);
		const slopeHeight = conf.slopeHeight||1;
		return { id:tileId, x,y,l,conf, z1:height-slopeHeight, z2:height };
	},

	canPassRamp(d,slope,opts={}){
		if(d===5||d<=0||d>=10){ return true; }
		const {dir:sd} = mv3d.getSlopeDirection(slope.x,slope.y,slope.l,true);
		const x2 = $gameMap.roundXWithDirection(slope.x,d);
		const y2 = $gameMap.roundYWithDirection(slope.y,d);
		const slope2 = this.isRampAt(x2,y2,sd===d?slope.z1:sd===10-d?slope.z2:(slope.z1+slope.z2)/2);
		if(slope2){
			const  {dir:sd2} = mv3d.getSlopeDirection(x2,y2,slope2.l,true);
			if(sd!==d&&sd!==10-d){
				if(sd===sd2&&slope.z1===slope2.z1&&slope.z2===slope2.z2){ return true; }
				return false;
			}
			return sd===sd2 && (sd===d?(slope.z1===slope2.z2):(slope.z2===slope2.z1));
		}
		if(sd!==d&&sd!==10-d){ return false; }
		const dh = this.getPlatformAtLocation(x2,y2, (opts.z!=null?opts.z:sd===d?slope.z1:slope.z2)+mv3d.STAIR_THRESH ).z2;
		return Math.abs(dh-(sd===d?slope.z1:slope.z2))<=mv3d.STAIR_THRESH;
	}
});

Game_CharacterBase.prototype._mv3d_isFlying=function(){
	if(!this.mv3d_sprite){ return false;}
	return this.mv3d_sprite.blendElevation.currentValue()>0||this.mv3d_sprite.hasConfig('zlock')||!this.mv3d_sprite.getConfig('gravity',mv3d.GRAVITY);
};
Game_Vehicle.prototype._mv3d_isFlying=function(){
	return this.isAirship()||Game_CharacterBase.prototype._mv3d_isFlying.apply(this,arguments);
};
Game_Player.prototype._mv3d_isFlying=function(){
	if(this.isInVehicle()&&this.vehicle().isAirship()){ return true; }
	return Game_CharacterBase.prototype._mv3d_isFlying.apply(this,arguments);
};

Game_CharacterBase.prototype._mv3d_isPlatform=function(){
	return this.mv3d_sprite&&this.mv3d_sprite.getConfig('platform',mv3d.WALK_ON_EVENTS);
};

Game_CharacterBase.prototype._mv3d_hasCollide=function(){
	const sprite = this.mv3d_sprite;
	if(!sprite || sprite.getConfig('collide')===false){ return false; }
	return this._mv3d_isPlatform() || Boolean(sprite.getCHeight());
};

if(window.Imported&&Imported.QMovement){
	__webpack_require__(12);
}else if(PluginManager._scripts.includes("AltimitMovement")&&Game_CharacterBase.prototype.moveVector){
	__webpack_require__(13);
}else{
	__webpack_require__(14);
}

// jump
const _charBase_jump = Game_CharacterBase.prototype.jump;
Game_CharacterBase.prototype.jump = function(xPlus, yPlus) {
	if (mv3d.isDisabled()){ return _charBase_jump.apply(this,arguments); }
	this.mv3d_jumpHeightStart = this.z!=null?this.z:mv3d.getWalkHeight(this.x,this.y);
	this.mv3d_jumpHeightEnd = mv3d.getWalkHeight(this.x+xPlus,this.y+yPlus);
	_charBase_jump.apply(this,arguments);
};

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Map.prototype,'allTiles',o=>function(x,y){
	return this.layeredTiles(x, y);
});

/***/ }),
/* 12 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);

const mv3d = window.mv3d;

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(ColliderManager,'update',o=>function(){
	this.hide();
});

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(ColliderManager.container,'update',o=>function(){
	if(this.visible){ o.apply(this,arguments); }
},true);

let _tileColliders={};
mv3d.getQTileColliders=()=>_tileColliders;

function mv3d_makeTileCollider(x,y,zcollider,extra){
	const tc=new Box_Collider($gameMap.tileWidth(),$gameMap.tileHeight());
	tc.x=x*$gameMap.tileWidth();
	tc.y=y*$gameMap.tileHeight();
	tc.mv3d_collider=zcollider;
	tc.mv3d_collider_type=extra;
	return tc;
}

const infiniteHeightCollider={z1:-Infinity,z2:Infinity};

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Map.prototype,'setupMapColliders',o=>function(){
	this._tileCounter = 0;
	_tileColliders={};
	for (let x = 0; x < this.width(); x++)
	for (let y = 0; y < this.height(); y++) {
		const px = x * this.tileWidth(), py = y * this.tileHeight();
		const flags = this.tilesetFlags();
		const tiles = mv3d.getTileData(x, y);
		const zColliders = mv3d.getCollisionHeights(x,y,{layers:true,slopeMin:true});
		const tileCollider_list = _tileColliders[[x,y]]=[];
		for (let i=0; i<zColliders.length; ++i) {
			tileCollider_list[i]=mv3d_makeTileCollider(x,y,zColliders[i],'mv3d');
		}
		_tileColliders[[x,y,'x']]=mv3d_makeTileCollider(x,y,infiniteHeightCollider,'mv3d_x');
		for (let l = 0; l < tiles.length; ++l) {
			const flag = flags[tiles[l]];
			const passage = mv3d.getTilePassage(tiles[l],x,y,l);
			if(passage===mv3d.enumPassage.THROUGH){ continue; }
			const conf = mv3d.getTileConfig(x,y,l);
			if(conf.shape===mv3d.enumShapes.SLOPE){
				const rampData = mv3d.getRampData(x,y,l,conf);
				let dcol=0;
				if(!mv3d.canPassRamp(2,rampData)){ dcol|=0b0001; }
				if(!mv3d.canPassRamp(4,rampData)){ dcol|=0b0010; }
				if(!mv3d.canPassRamp(6,rampData)){ dcol|=0b0100; }
				if(!mv3d.canPassRamp(8,rampData)){ dcol|=0b1000; }
				dcol+=1536;
				const slopeZ2 = mv3d.getStackHeight(x,y,l);
				const slopeZ1 = slopeZ2-(conf.slopeHeight||1);
				//const data = Array.from(QMovement.tileBoxes[flag]);
				let data = QMovement.tileBoxes[dcol];
				const key = [x,y,l,'slope'].toString();
				_tileColliders[key]=[];
				if(data){
					if(data[0].constructor!==Array){ data=[data]; }
					for(const box of data){
						const c = new Box_Collider(box[0]||0,box[1]||0,box[2],box[3]);
						c.slopeZ1=slopeZ1; c.slopeZ2=slopeZ2;
						c.moveTo(px,py);
						c.mv3d_collider=infiniteHeightCollider;
						_tileColliders[key].push(c);
					}
				}
			}
			let mv3d_collider;
			if(zColliders.layers[l]){
				mv3d_collider=zColliders.layers[l];
				mv3d_collider.passage=passage;
				mv3d_collider.l=l;
			}
			let data = this.getMapCollider(x, y, flag);
			if (!data){ continue; }
			data=Array.from(data);
			if (data[0].constructor === Array) {
				for (var j = 0; j < data.length; j++) {
					data[j].mv3d_collider=mv3d_collider;
					data[j].isRegionCollider=true;
					this.makeTileCollider(x, y, flag, data[j], j);
				}
			} else {
				data.mv3d_collider=mv3d_collider;
				data.isQCollider=true;
				this.makeTileCollider(x, y, flag, data, 0);
			}
		}
	}
},true);

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Map.prototype,'makeTileCollider',o=>function(x,y,flag,boxData,index){
	const collider = o.apply(this,arguments);
	if(boxData.mv3d_collider){
		if(boxData.isRegionCollider){
			collider.mv3d_collider = infiniteHeightCollider;
		}else if(boxData.isQCollider){
			collider.mv3d_collider = {z1:-Infinity,z2:Infinity};
			if(boxData.mv3d_collider){
				collider.mv3d_collider.l = boxData.mv3d_collider.l;
			}
			/*
			collider.mv3d_collider = {
				z1: boxData.mv3d_collider.z2,
				z2: boxData.mv3d_collider.z2 + mv3d.STAIR_THRESH + 0.01,
			};
			*/
		}else{
			collider.mv3d_collider = boxData.mv3d_collider;
		}
	}
	return collider;
},true);

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_CharacterBase.prototype,'collider',o=>function collider(){
	const collider = o.apply(this,arguments);
	if(!this.mv3d_sprite){ return collider; }
	if(!collider.mv3d_collider){
		Object.defineProperty(collider,'mv3d_collider',{
			configurable:true,enumerable:false, value: this.mv3d_sprite.getCollider(),
		});
		Object.defineProperty(collider,'mv3d_triggerCollider',{
			configurable:true,enumerable:false, value: this.mv3d_sprite.getTriggerCollider(),
		});
	}
	return collider;
});

function QzCollidersOverlap(c1,c2){
	if(!c1.mv3d_collider||!c2.mv3d_collider){ return true; }
	c1=c1.mv3d_collider; c2=c2.mv3d_collider;
	return zCollidersOverlap(c1,c2);
}
function zCollidersOverlap(c1,c2){
	if(c1.z1<c2.z2&&c1.z2>c2.z1 && c1.z1+mv3d.STAIR_THRESH<c2.z2&&c1.z2+mv3d.STAIR_THRESH>c2.z1){
		return true;
	}
	return false;
}

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(ColliderManager,'getCollidersNear',o=>function getCollidersNear(collider, only, debug){
	// Q colliders
	let isBreak=false;
	const near = o.call(this,collider,c=>{
		if(QzCollidersOverlap(collider,c)===false){ return false; }
		if(collider.mv3d_collider){
			const cx = Math.round(c.x/QMovement.tileSize);
			const cy = Math.round(c.y/QMovement.tileSize);
			if(collider.mv3d_collider.char){
				// if we're standing on a character, ignore Q colliders.
				//const platform = collider.mv3d_collider.char.getPlatform();
				const platform = collider.mv3d_collider.char.getPlatform(cx,cy);
				if(platform.char){ return false; }
			}
			if(c.mv3d_collider){
				// ignore Q colliders not on current layer
				const tileLayers = mv3d.getTileLayers(cx,cy,collider.mv3d_collider.z1+mv3d.STAIR_THRESH);
				if(!tileLayers.includes(c.mv3d_collider.l)){ return false; }
			}
		}
		if(only){
			const value = only(c);
			if(value==='break'){isBreak=true;}
			return value;
		}
		return true;
	},debug);
	if(isBreak){ return near; }
	const x1 = (collider.x+collider._offset.x-1)/QMovement.tileSize;
	const y1 = (collider.y+collider._offset.y-1)/QMovement.tileSize;
	const x2 = (collider.x+collider._offset.x+collider.width+1)/QMovement.tileSize;
	const y2 = (collider.y+collider._offset.y+collider.height+1)/QMovement.tileSize;
	if (collider.mv3d_collider)
	for (let tx = Math.floor(x1); tx < Math.ceil(x2); ++tx)
	for (let ty = Math.floor(y1); ty < Math.ceil(y2); ++ty){
		const colliderList=_tileColliders[[tx,ty]];
		const xCollider = _tileColliders[[tx,ty,'x']];
		let slopeColliders = null;
		let isWall=false;
		const tileLayers = mv3d.getTileLayers(tx,ty,collider.mv3d_collider.z1+mv3d.STAIR_THRESH);
		for(const l of tileLayers){
			if( mv3d.getTilePassage(tx,ty,l)===mv3d.enumPassage.WALL ){ isWall=true; }
			const slopeKey = [tx,ty,l,'slope'].toString();
			if(slopeKey in _tileColliders){ slopeColliders = _tileColliders[slopeKey]; }
		}
		let shouldCollide=false;
		if(xCollider&&collider.mv3d_collider.char){
			const char = collider.mv3d_collider.char;
			const opts = {slopeMin:true};
			const platform = char.getPlatform(tx,ty,opts);
			opts.platform=platform;
			// collide if falling
			if(char.falling&&!char.char._mv3d_isFlying()){ shouldCollide=true; }
			// x passage
			else if(isWall && !platform.char){
				shouldCollide=true;
			}
			// collide slopes
			else if (slopeColliders && !char.platform.char && !platform.char){
				for (const c of slopeColliders){
					if(mv3d.WALK_OFF_EDGE && char.z>c.slopeZ1){ continue; }
					let value=true;
					if(only){ value = only(c); }
					if(value!==false){
						near.push(c);
						if(value==='break'){ return near; }
						continue;
					}
				}
			}
			// collide ledges
			else if(!mv3d.WALK_OFF_EDGE && !char.char._mv3d_isFlying() && (!char.platform||!char.platform.isSlope)
			&& Object(_util__WEBPACK_IMPORTED_MODULE_0__["unround"])(Math.abs(char.getPlatformFloat(tx,ty,opts)-char.targetElevation))>mv3d.STAIR_THRESH){
				shouldCollide=true;
			}
			
			if(shouldCollide){
				let value=true;
				if(only){ value = only(xCollider); }
				if(value!==false){
					near.push(xCollider);
					if(value==='break'){ return near; }
					continue;
				}
			}
		}
		// collide with wall
		if(colliderList) for(let i = 0; i<colliderList.length; ++i){
			if(QzCollidersOverlap(collider,colliderList[i])){
				if(only){
					const value = only(colliderList[i]);
					if(value!==false){ near.push(colliderList[i]); }
					if(value==='break'){ return near; }
				}else{
					near.push(colliderList[i]);
				}
			}
		}
	}
	return near;
});

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(ColliderManager,'getCharactersNear',o=>function(collider, only){
	return o.call(this,collider,char=>{
		const sprite = char.mv3d_sprite; if(!sprite){ return true; }
		const c1 = collider.mv3d_collider;
		const c2 = $gameTemp._mv3d_Q_getCharactersTriggerHeight?sprite.getTriggerHeight():sprite.getCollisionHeight();
		if(!c1||!c2){ return true; }
		if(zCollidersOverlap(c1,c2)===false){ return false; }
		if(only){ return only(char); }
		return true;
	});
});

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Player.prototype,'startMapEvent',o=>function(x,y,triggers,normal){
	$gameTemp._mv3d_Q_getCharactersTriggerHeight=true;
	o.apply(this,arguments);
	$gameTemp._mv3d_Q_getCharactersTriggerHeight=false;
});

mv3d.Character.prototype.getPlatform=function(x=this.char._realX,y=this.char._realY,opts={}){
	const px = (x-0.5)*QMovement.tileSize;
	const py = (y-0.5)*QMovement.tileSize;
	const collider = this.char.collider();

	const x1 = (px+collider._offset.x+1)/QMovement.tileSize;
	const y1 = (py+collider._offset.y+1)/QMovement.tileSize;
	const x2 = (px+collider._offset.x+collider.width-1)/QMovement.tileSize;
	const y2 = (py+collider._offset.y+collider.height-1)/QMovement.tileSize;
	
	const platform = [
		//mv3d.getPlatformForCharacter(this,x,y),
		mv3d.getPlatformForCharacter(this,x1,y1,opts),
		mv3d.getPlatformForCharacter(this,x2,y1,opts),
		mv3d.getPlatformForCharacter(this,x2,y2,opts),
		mv3d.getPlatformForCharacter(this,x1,y2,opts),
	].reduce((a,b)=>a.z2>=b.z2?a:b);
	return platform;
};

mv3d.getEventsAt=function(x,y){
	let events;
	try{
		events = ColliderManager._characterGrid[Math.round(x)][Math.round(y)];
	}catch(err){
		return [];
	}
	if(!events){ return []; }
	return events.filter(event=>{
		if(!(event instanceof Game_Event) || event.isThrough()){ return false; }
		return true;
	});
};

mv3d.setDestination=function(x,y){
	$gameTemp.setPixelDestination(Math.round(x*$gameMap.tileWidth()), Math.round(y*$gameMap.tileHeight()));
};

const _clearMouseMove = Game_Player.prototype.clearMouseMove;
Game_Player.prototype.clearMouseMove=function(){
	_clearMouseMove.apply(this,arguments);
	if(this._pathfind){
		this.clearPathfind();
	}
}


const _QdiagMap={
	1: [4, 2], 3: [6, 2],
	7: [4, 8], 9: [6, 8]
};
const _QMoveVH=o=>function(dir) {
	if($gameMap.offGrid()){
		this.mv3d_QMoveRadian(dir);
		return;
	}
	dir=mv3d.transformDirection(dir);
	if(dir%2){
		const diag = _QdiagMap[dir];
		this.moveDiagonally(diag[0], diag[1]);
	}else{
		this.moveStraight(dir);
	}
	
};
Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Player.prototype,'moveInputHorizontal',_QMoveVH);
Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Player.prototype,'moveInputVertical',_QMoveVH);
Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Player.prototype,'moveInputDiagonal',_QMoveVH);

Game_Player.prototype.mv3d_QMoveRadian=function(dir,dist=this.moveTiles()){
	this.moveRadian(-Object(_util__WEBPACK_IMPORTED_MODULE_0__["degtorad"])(mv3d.blendCameraYaw.currentValue()+90+mv3d.dirToYaw(dir)),dist);
	//this.mv3d_setDirection(mv3d.transformDirection(dir));
};

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Character.prototype,'moveRadian',o=>function(radian, dist){
	o.apply(this,arguments);
	const d = mv3d.yawToDir(Object(_util__WEBPACK_IMPORTED_MODULE_0__["radtodeg"])(-radian)-90,true);
	this.mv3d_setDirection(d);
});

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Character.prototype,'moveDiagonally',o=>function(h,v){
	o.apply(this,arguments);
	const d = Object(_util__WEBPACK_IMPORTED_MODULE_0__["hvtodir"])(h,v);
	this.mv3d_setDirection(d);
});

if(Game_Follower.prototype.updateMoveList)
Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Follower.prototype,'updateMoveList',o=>function(){
	const move = this._moveList[0];
	o.apply(this,arguments);
	if(!move){ return; }
	this.mv3d_setDirection(move[3]);
});

/***/ }),
/* 13 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
const mv3d = window.mv3d;


Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Player.prototype,'moveByInput',o=>function(){
	$gameTemp._mv3d_altimit_moveByInput=true;
	o.apply(this,arguments);
	$gameTemp._mv3d_altimit_moveByInput=false;
});

mv3d.getInputDirection=function(){
	let dir = mv3d.DIR8MOVE ? Input.dir8 : Input.dir4;
	return dir;
};

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Player.prototype,'moveVector',o=>function(vx,vy){
	if($gameTemp._mv3d_altimit_moveByInput && !this._touchTarget){
		const _vx=vx,_vy=vy;
		const yaw = Object(_util__WEBPACK_IMPORTED_MODULE_0__["degtorad"])(mv3d.blendCameraYaw.currentValue());
		vx=Object(_util__WEBPACK_IMPORTED_MODULE_0__["cos"])(yaw)*_vx + Object(_util__WEBPACK_IMPORTED_MODULE_0__["sin"])(yaw)*_vy;
		vy=-Object(_util__WEBPACK_IMPORTED_MODULE_0__["sin"])(yaw)*_vx + Object(_util__WEBPACK_IMPORTED_MODULE_0__["cos"])(yaw)*_vy;
		//console.log(_vx,_vy,vx,vy);
	}
	if(this.mv3d_sprite && this.mv3d_sprite.platform && this.mv3d_sprite.platform.isSlope){
		if(Math.abs(vx)>Math.abs(vy)){ 
			vx=Math.round(this._x)-this._x+Math.sign(vx);
			vy=Math.round(this._y)-this._y;
		}else{
			vx=Math.round(this._x)-this._x;
			vy=Math.round(this._y)-this._y+Math.sign(vy);
		}
		if($gamePlayer._touchTarget){
			$gamePlayer._touchTarget.x=Math.round($gamePlayer._touchTarget.x);
			$gamePlayer._touchTarget.y=Math.round($gamePlayer._touchTarget.y);
		}
	}
	
	o.call(this,vx,vy);
});

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_CharacterBase.prototype,'setDirectionVector',o=>function(vx,vy){
	this.mv3d_setDirection(mv3d.yawToDir(Object(_util__WEBPACK_IMPORTED_MODULE_0__["pointtodeg"])(vx,vy),true));
});

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_CharacterBase.prototype,'moveVectorMap',o=>function(owner, collider, bboxTests, move, vx, vy){
	o.apply(this,arguments);
	const sprite = owner.mv3d_sprite;
	if(!sprite){ return; }

	const x = Math.floor(owner.x+collider.x);
	const y = Math.floor(owner.y+collider.y);
	const x1=Math.floor(owner.x+move.x+collider.aabbox.left), x2=Math.ceil(owner.x+move.x+collider.aabbox.right);
	const y1=Math.floor(owner.y+move.y+collider.aabbox.top), y2=Math.ceil(owner.y+move.y+collider.aabbox.bottom);
	
	//const d = Input._makeNumpadDirection(Math.sign(move.x),Math.sign(move.y));
	//const d = this.direction();

	for (let tx = x1; tx < x2; ++tx)
	for (let ty = y1; ty < y2; ++ty){
		const d = Input._makeNumpadDirection(Math.sign(tx-x),Math.sign(ty-y));
		//if(tx===x&&ty===y){continue;}
		let slope;
		let realign = false;
		if(slope=mv3d.isRampAt(tx,ty,sprite.z)){
			if(mv3d.canPassRamp(10-d,slope,{z:sprite.z})){ continue; }
		}
		const tx2 = $gameMap.roundXWithDirection(tx, 10-d);
		const ty2 = $gameMap.roundYWithDirection(ty, 10-d);
		if(slope=mv3d.isRampAt(tx2,ty2,sprite.z)){
			if(mv3d.canPassRamp(d,slope)){ continue; }
		}

		let collided = false;
		if(this._mv3d_isFlying()){
			if(!mv3d.allowGlide&&mv3d.tileCollision(this,tx,ty,true,true)||mv3d.tileCollision(this,tx,ty,true,false)){ collided=true; }
		}else{
			if(sprite.falling){ collided=true; }
			else if(mv3d.tileCollision(this,tx,ty,true,true)){ collided=true; }
			else if(!mv3d.WALK_OFF_EDGE){
				const platformz = mv3d.getPlatformFloatForCharacter(this,tx,ty);
				if(Object(_util__WEBPACK_IMPORTED_MODULE_0__["unround"])(Math.abs(platformz-sprite.targetElevation))>mv3d.STAIR_THRESH){
					collided=true;
				}
			}
		}
		if(collided){
			if(tx!==x){ move.x=0; }
			if(ty!==y){ move.y=0; }
		}
	}
});

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_CharacterBase.prototype,'moveVectorCharacters',o=>function(owner, collider, characters, loopMap, move){
	const spr1=this.mv3d_sprite; if(!spr1){ return o.apply(this,arguments); }
	const zcol1=spr1.getCollisionHeight();
	characters=characters.filter(character=>{
		const spr2 = character.mv3d_sprite; if(!spr2){ return true; }
		const zcol2=spr2.getCollisionHeight();
		return zcol1.z1<zcol2.z2&&zcol1.z2>zcol2.z1;
	});
	return o.call(this,owner,collider,characters,loopMap,move);
});

mv3d.Character.prototype.getPlatform=function(x=this.char._realX,y=this.char._realY,opts={}){
	const collider = this.char.collider();
	if(collider.type===0){
		x+=collider.x-0.5; y+=collider.y-0.5;
		const r = collider.radius*0.95;
		
		const platform = [
			mv3d.getPlatformForCharacter(this,x,y),
			mv3d.getPlatformForCharacter(this,x,y-r,opts),
			mv3d.getPlatformForCharacter(this,x-r,y,opts),
			mv3d.getPlatformForCharacter(this,x,y+r,opts),
			mv3d.getPlatformForCharacter(this,x+r,y,opts),
		]
		const diagPlatforms = [
			-Infinity,
			mv3d.getPlatformForCharacter(this,x-r*Math.SQRT1_2,y-r*Math.SQRT1_2,opts),
			mv3d.getPlatformForCharacter(this,x-r*Math.SQRT1_2,y+r*Math.SQRT1_2,opts),
			mv3d.getPlatformForCharacter(this,x+r*Math.SQRT1_2,y+r*Math.SQRT1_2,opts),
			mv3d.getPlatformForCharacter(this,x+r*Math.SQRT1_2,y-r*Math.SQRT1_2,opts),
		].filter(c=>c.z2<=this.z);
		return platform.concat(diagPlatforms).reduce((a,b)=>a.z2>=b.z2?a:b);
	}else{
		x-=0.5; y-=0.5;
		const b = {
			l:collider.aabbox.left*0.99,
			r:collider.aabbox.right*0.99,
			t:collider.aabbox.top*0.99,
			b:collider.aabbox.bottom*0.99,
		};
		const platform = [
			mv3d.getPlatformForCharacter(this,x,y),
			mv3d.getPlatformForCharacter(this,x+b.l,y+b.t,opts),
			mv3d.getPlatformForCharacter(this,x+b.l,y+b.b,opts),
			mv3d.getPlatformForCharacter(this,x+b.r,y+b.t,opts),
			mv3d.getPlatformForCharacter(this,x+b.r,y+b.b,opts),
		].reduce((a,b)=>a.z2>=b.z2?a:b);
		return platform;
	}
};

mv3d.getEventsAt=function(x,y){
	x=Math.round(x); y=Math.round(y);
	return $gameMap.events().filter( character=>{
		if(character.isThrough()){ return false; }
		const {x:cx,y:cy}=character;
		const {left,right,top,bottom}=character.collider().aabbox;
		return cx+left<x+1 && cx+right>x && cy+top<y+1 && cy+bottom>y;
	  } );
};

// give followers through if they fall behind
/*
const _FOLLOWER_THROUGH_THRESH=3;
override(Game_Follower.prototype,'isThrough',o=>function(){
	const precedingCharacter = (this._memberIndex > 1 ? $gamePlayer._followers._data[this._memberIndex - 2] : $gamePlayer);
	if(Math.abs(precedingCharacter.x-this.x)+Math.abs(precedingCharacter.y-this.y)>_FOLLOWER_THROUGH_THRESH){ return true; }
	return o.apply(this,arguments);
});
*/

function zCollidersOverlap(s1,s2){
	s1=s1.getCollisionHeight(); s2=s2.getCollisionHeight();
	if(s1.z1===s1.z2||s2.z1===s2.z2){ return s1.z1<=s2.z2&&s1.z2>=s2.z1 }
	return s1.z1<s2.z2&&s1.z2>s2.z1;
}

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Map.prototype,'events',o=>function(){
	const events = o.apply(this,arguments);
	if(!$gameTemp._mv3d_altimit_eventsHeightFilter){ return events; }
	delete $gameTemp._mv3d_altimit_eventsHeightFilter;
	const player=$gamePlayer.mv3d_sprite;
	if(!player){ return events; }
	return events.filter(e=>{
		const sprite = e.mv3d_sprite;
		if(!sprite){ return true; }
		return zCollidersOverlap(sprite,player);
	});
});

Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Event.prototype,'checkEventTriggerTouch',o=>function(){
	const sprite = this.mv3d_sprite, player=$gamePlayer.mv3d_sprite;
	if(sprite&&player){
		if(!zCollidersOverlap(sprite,player)){ return false; }
	}
	return o.apply(this,arguments);
});

const _eventsHeightFilter=o=>function(){
	$gameTemp._mv3d_altimit_eventsHeightFilter=true;
	return o.apply(this,arguments);
};
Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Player.prototype,'checkEventTriggerHere',_eventsHeightFilter);
Object(_util__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Player.prototype,'checkEventTriggerThere',_eventsHeightFilter);

/***/ }),
/* 14 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
const mv3d = window.mv3d;


const _characterBase_canPass = Game_CharacterBase.prototype.canPass
Game_CharacterBase.prototype.canPass = function(x, y, d) {

	if(!_characterBase_canPass.apply(this,arguments)){
		return false;
	}
	if (mv3d.isDisabled()||this.isDebugThrough()||this.isThrough()){return true; }

	return true;
};

function charCollidesWithChars(char1,charlist,x,y){
	return charlist.some(char2=>{
		const isPlatform = char2._mv3d_isPlatform();
		if(mv3d.WALK_OFF_EDGE&&!isPlatform){
			const platformHeight = mv3d.getPlatformForCharacter(char1,x,y).z2;
			if(mv3d.charCollision(char1,char2,false,platformHeight)){ return true; }
		}
		return mv3d.charCollision(char1,char2,isPlatform,true);
	});
}

const _isCollidedWithEvents=o=>function(x,y){
	return charCollidesWithChars(this,$gameMap.eventsXyNt(x,y),x,y);
};

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_CharacterBase.prototype,'isCollidedWithEvents',_isCollidedWithEvents);

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Event.prototype,'isCollidedWithEvents',_isCollidedWithEvents);

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Event.prototype,'isCollidedWithPlayerCharacters',o=>function(x,y){
	if($gamePlayer.isThrough()){ return false; }
	const chars = [$gamePlayer,...$gamePlayer.followers()._data.filter(f=>f.isVisible()&&f.mv3d_sprite&&f.mv3d_sprite.visible)]
	.filter(char=>char.pos(x,y));
	return charCollidesWithChars(this,chars,x,y);
});

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_CharacterBase.prototype,'isCollidedWithVehicles',o=>function(x,y){
	const boat=$gameMap.boat(), ship=$gameMap.ship();
	return boat.posNt(x,y)&&mv3d.charCollision(this,boat,boat._mv3d_isPlatform(),true) || ship.posNt(x,y)&&mv3d.charCollision(this,ship,ship._mv3d_isPlatform(),true);
});

const _isMapPassable=o=>function(x,y,d){
	const sprite = this.mv3d_sprite;
	if(!sprite){ return o.apply(this,arguments); }

	$gameTemp._mv3d_collision_char = sprite;
	let collided = !o.apply(this,arguments);
	delete $gameTemp._mv3d_collision_char;
	if(collided){ return false; }


	let slope;
	if(slope=mv3d.isRampAt(x,y,sprite.z)){
		if(mv3d.canPassRamp(d,slope)){ return true; }
	}

	var x2 = $gameMap.roundXWithDirection(x, d);
	var y2 = $gameMap.roundYWithDirection(y, d);
	
	if(slope=mv3d.isRampAt(x2,y2,sprite.z)){
		if(mv3d.canPassRamp(10-d,slope,{z:sprite.z})){ return true; }
	}
	
	if(this._mv3d_isFlying()){
		if(!mv3d.allowGlide&&mv3d.tileCollision(this,x2,y2,true,sprite.targetElevation)||mv3d.tileCollision(this,x2,y2,true,false)){ return false; }
	}else{
		if(mv3d.tileCollision(this,x2,y2,true,false)){ return false; }
		
		if(sprite.falling){ return false; }
		if(!mv3d.WALK_OFF_EDGE){
			const platformz = mv3d.getPlatformFloatForCharacter(this,x2,y2);
			if(Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["unround"])(Math.abs(platformz-sprite.targetElevation))>mv3d.STAIR_THRESH){
				return false; 
			}
		}
	}
	return true;
};

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_CharacterBase.prototype,'isMapPassable',_isMapPassable);

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Vehicle.prototype,'isMapPassable',_isMapPassable);

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Player.prototype,'startMapEvent',o=>function(x,y,triggers,normal){
	if ($gameMap.isEventRunning()) { return; }
	$gameMap.eventsXy(x,y)
	.filter(event=>mv3d.charCollision(this,event,false,false,false,true))
	.forEach(event=>{
		if (event.isTriggerIn(triggers) && event.isNormalPriority() === normal) {
			event.start();
		}
	});
});

const _checkPassage = Game_Map.prototype.checkPassage;
Game_Map.prototype.checkPassage = function(x, y, bit) {
	if(!('_mv3d_collision_char' in $gameTemp)){
		return _checkPassage.apply(this,arguments);
	}
	const char = $gameTemp._mv3d_collision_char;
	const cHeight = char.getCHeight();
	const z = char.z+Math.max(cHeight,mv3d.STAIR_THRESH);
	const platform = mv3d.getPlatformForCharacter(char,x,y);
	if(platform.char){ return true; }
	var flags = this.tilesetFlags();
	//var tiles = this.allTiles(x, y);
	const layers = mv3d.getTileLayers(x,y,z,mv3d.STAIR_THRESH>=cHeight);
	const tiles = mv3d.getTileData(x,y);
	for (var i = layers.length-1; i>=0; --i) {
		const l=layers[i];
		if(bit&0x0f){
			const conf = mv3d.getTileConfig(x,y,l);
			if('pass' in conf){
				//const passage = mv3d.getTilePassage(x,y,l);
				if(conf.pass===mv3d.enumPassage.THROUGH){ continue; }
				if(conf.pass===mv3d.enumPassage.FLOOR){ return true; }
				if(conf.pass===mv3d.enumPassage.WALL){ return false; }
			}
		}
		const flag = flags[tiles[l]];
		if ((flag & 0x10) !== 0)  // [*] No effect on passage
			continue;
		if ((flag & bit) === 0)   // [o] Passable
			return true;
		if ((flag & bit) === bit) // [x] Impassable
			return false;
	}
    return false;
};

const _dir8Condition=()=> !mv3d.isDisabled() || mv3d.DIR8MOVE&&mv3d.DIR8_2D;

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Player.prototype,'moveStraight',o=>function(d){
	if(!mv3d.DIR8MOVE){ return o.apply(this,arguments); }
	switch(d){
		case 1: this.moveDiagonally(4, 2); break;
		case 3: this.moveDiagonally(6, 2); break;
		case 7: this.moveDiagonally(4, 8); break;
		case 9: this.moveDiagonally(6, 8); break;
		default: o.apply(this,arguments);
	}
	
},_dir8Condition);

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Character.prototype,'moveDiagonally',o=>function(h,v){
	o.apply(this,arguments);

	let adjustDirection=false;

	if(this.isMovementSucceeded()){
		adjustDirection=true;
	}else if(mv3d.DIR8SMART && !this.isDebugThrough()){
		this.moveStraight(h);
		if(!this.isMovementSucceeded()){
			this.moveStraight(v);
			if(!this.isMovementSucceeded()){
				adjustDirection=true;
			}
		}
	}else{ adjustDirection=true; }

	if(adjustDirection){
		const d = Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["hvtodir"])(h,v);
		this.mv3d_setDirection(d);
	}

},_dir8Condition);

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_CharacterBase.prototype,'canPassDiagonally',o=>function(x,y,horz,vert){
	if(this.isDebugThrough()){ return true; }
    const x2 = $gameMap.roundXWithDirection(x, horz);
	const y2 = $gameMap.roundYWithDirection(y, vert);
	if(mv3d.tileCollision(this,x,y2,true,false)||mv3d.tileCollision(this,x2,y,true,false)){
		return false;
	}
	return o.apply(this,arguments);
});

const _dontSnapRealXY=o=>function(){
	const realX=this._realX, realY=this._realY;
	o.apply(this,arguments);
	if(Math.abs(realX-this._realX)>2||Math.abs(realY-this._realY)>2){ return;}
	this._realX=realX; this._realY=realY;
};
Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Follower.prototype,'moveDiagonally',_dontSnapRealXY,_dir8Condition);
Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Follower.prototype,'moveStraight',_dontSnapRealXY,_dir8Condition);

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_CharacterBase.prototype,'distancePerFrame',o=>function(){
	const dist = o.apply(this,arguments);
	if(this._mv3d_direction%2){
		return dist * Math.SQRT1_2;
	}
	return dist;
},_dir8Condition);

// triggering

Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Player.prototype,'checkEventTriggerThere',o=>function(triggers){
	if (!this.canStartLocalEvents()) { return; }
	const dir = this.mv3d_direction();
	if(dir%2===0){ return o.apply(this,arguments); }
	const horz = Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["dirtoh"])(dir),vert = Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["dirtov"])(dir);
	const x2 = $gameMap.roundXWithDirection(this.x, horz);
	const y2 = $gameMap.roundYWithDirection(this.y, vert);
	this.startMapEvent(x2, y2, triggers, true);
	if(!$gameMap.isAnyEventStarting()){
		return o.apply(this,arguments);
	}
},_dir8Condition);


// VEHICLES

const _airship_land_ok = Game_Map.prototype.isAirshipLandOk;
Game_Map.prototype.isAirshipLandOk = function(x, y) {
	if (mv3d.isDisabled()){ return _airship_land_ok.apply(this,arguments); }
	if(mv3d.AIRSHIP_SETTINGS.bushLanding){
		return this.checkPassage(x, y, 0x0f);
	}else{
		return _airship_land_ok.apply(this,arguments);
	}

};

const _player_updateVehicleGetOn = Game_Player.prototype.updateVehicleGetOn;
Game_Player.prototype.updateVehicleGetOn = function() {
	if (mv3d.isDisabled()){ return _player_updateVehicleGetOn.apply(this,arguments); }
	const vehicle = this.vehicle();
	//const speed = mv3d.loadData(`${vehicle._type}_speed`,vehicle._moveSpeed);
	//vehicle.setMoveSpeed(speed);
	_player_updateVehicleGetOn.apply(this,arguments);
	this.setThrough(false);
};

// get on off vehicle

const _getOnVehicle = Game_Player.prototype.getOnVehicle;
Game_Player.prototype.getOnVehicle = function(){
	if(mv3d.isDisabled()){ return _getOnVehicle.apply(this,arguments); }
	var d = this.direction();
	var x1 = Math.round(this.x);
    var y1 = Math.round(this.y);
    var x2 = $gameMap.roundXWithDirection(x1,d);
	var y2 = $gameMap.roundYWithDirection(y1,d);
	
	if($gameMap.airship().pos(x1,y1) && mv3d.charCollision(this,$gameMap.airship(),false,false,false,true)){
		this._vehicleType = 'airship';
	}else if($gameMap.ship().pos(x2,y2) && mv3d.charCollision(this,$gameMap.ship())) {
		this._vehicleType = 'ship';
	}else if($gameMap.boat().pos(x2,y2) && mv3d.charCollision(this,$gameMap.boat())) {
		this._vehicleType = 'boat';
	}
	if (this.isInVehicle()) {
		this._vehicleGettingOn = true;
		if (!this.isInAirship()) {
			this.forceMoveForward();
		}
		this.gatherFollowers();
	}
	return this._vehicleGettingOn;
};


Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["override"])(Game_Vehicle.prototype,'isLandOk',o=>function(x,y,d){
	$gameTemp._mv3d_collision_char = $gamePlayer.mv3d_sprite;
	let landOk = o.apply(this,arguments);
	delete $gameTemp._mv3d_collision_char;
	if (this.isAirship()) { return landOk; }
	var x2 = $gameMap.roundXWithDirection(x, d);
	var y2 = $gameMap.roundYWithDirection(y, d);
	const platform = mv3d.getPlatformForCharacter($gamePlayer,x2,y2);
	if(platform.char){ landOk=true; }
	const diff = Math.abs(platform.z2-this.z);
	return landOk && diff<Math.max($gamePlayer.mv3d_sprite.getCHeight(),this.mv3d_sprite.getCHeight());
});

/***/ }),
/* 15 */
/***/ (function(module, exports) {

const mv3d = window.mv3d;

mv3d.isMV=true;
mv3d.isMZ=false;
mz3d.MV3D_FOLDER="img/MV3D";

//Tilemap.prototype._mv3d_addTile = Tilemap.prototype._drawTile;

const _renderWebGL = ShaderTilemap.prototype.renderWebGL;
ShaderTilemap.prototype.renderWebGL = function(renderer) {
	if(mv3d.mapDisabled){ _renderWebGL.apply(this,arguments); }
};

const _graphics_createCanvas=Graphics._createCanvas;
Graphics._createCanvas = function() {
	mv3d.setup();
	mv3d.updateCanvas();
	_graphics_createCanvas.apply(this,arguments);
};

Object.assign(mv3d,{

	async getTextureUrl(url){
		const bitmap = ImageManager.loadNormalBitmap(encodeURI(url));
		if(Decrypter.hasEncryptedImages){
			await mv3d.waitBitmapLoaded(bitmap);
			return bitmap.canvas.toDataURL();
		}else{
			return bitmap._image.src;
		}
	},

});

/***/ }),
/* 16 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _parameters_premium_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _parameters_premium_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_parameters_premium_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _mod_babylon_premium_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(18);
/* harmony import */ var _mod_babylon_premium_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_mod_babylon_premium_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _views_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(19);
/* harmony import */ var _views_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_views_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _feature_dynamicShadows_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(20);
/* harmony import */ var _feature_dynamicShadows_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_feature_dynamicShadows_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _feature_ambientOcclusion_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(21);
/* harmony import */ var _feature_ambientOcclusion_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_feature_ambientOcclusion_js__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _feature_alphaFog_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(22);
/* harmony import */ var _feature_alphaFog_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_feature_alphaFog_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _feature_glow_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(23);
/* harmony import */ var _feature_glow_js__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_feature_glow_js__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _feature_skybox_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(24);
/* harmony import */ var _feature_skybox_js__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_feature_skybox_js__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _model_import_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(25);
/* harmony import */ var _model_import_js__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_model_import_js__WEBPACK_IMPORTED_MODULE_8__);

//import './data.js';




//features







const mz3d = window.mz3d;
mz3d.isPremium=true;

/***/ }),
/* 17 */
/***/ (function(module, exports) {

const mv3d = window.mv3d;
const {booleanString} = mv3d.util;

const parameters = PluginManager.parameters(mv3d.pluginName);

function parameter(name,dfault,type){
	return name in parameters ? (type?type(parameters[name]):parameters[name]) : dfault;
}


Object.assign(mv3d,{
	DYNAMIC_SHADOWS:booleanString(parameters.dynShadowEnabled),
	DEFAULT_SHADOW_QUALITY: Math.max(0,['OFF','LOW','MEDIUM','HIGH']
		.indexOf(parameters.defShadowQuality.toUpperCase())),
	SOFT_SHADOWS:booleanString(parameters.softShadows),
	//BACK_SHADOWS:booleanString(parameters.backShadows),
	DYNAMIC_SHADOW_RES:1024,

	OPTION_NAME_DYNAMIC_SHADOWS: parameter('shadowQualityOptionName',"Shadow Quality",String),

	ABNORMAL:booleanString(parameters.abnormal),
	DYNAMIC_NORMALS:booleanString(parameters.dynamicNormals),

	ALPHA_FOG: Number(parameters.alphaFog),
	AMBIENT_OCCLUSION: booleanString(parameters.ambientOcclusion),

	GLOW: Number(mv3d.util.booleanNumber(parameters.glow)),
	GLOW_RADIUS: Number(parameters.glowRadius),

});


/***/ }),
/* 18 */
/***/ (function(module, exports) {

const mv3d = window.mv3d;
const {MaterialHelper} = BABYLON;

mv3d.getDepthMap=function(camera=mv3d.camera){
	const depthRenderer = camera.getScene().enableDepthRenderer(camera);
	const depthMap = depthRenderer.getDepthMap();
	if (depthMap.mv3d_modded){ return depthMap; }
	depthRenderer._mv3d_modDepthRenderer();
	depthMap.mv3d_modded=true;
	return depthMap;
}

BABYLON.DepthRenderer.prototype._mv3d_modDepthRenderer=function(){
    const _oldCustomRenderFunction = this._depthMap.customRenderFunction;
    this._depthMap.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes)=>{
        _oldCustomRenderFunction(opaqueSubMeshes, alphaTestSubMeshes, [], depthOnlySubMeshes);
        _oldCustomRenderFunction([], transparentSubMeshes, [], []);
    }
    this._depthMap.getCustomRenderList = ()=>{
        return this._camera.getActiveMeshes().data;
    }
    this._depthMap.mv3d_modded=true;
}

const _renderSubMeshForShadowMap = BABYLON.ShadowGenerator.prototype._renderSubMeshForShadowMap
BABYLON.ShadowGenerator.prototype._renderSubMeshForShadowMap=function(subMesh){
    const material = subMesh.getMaterial();
    if(!material||material.mv3d_noShadow){ return; }
    _renderSubMeshForShadowMap.apply(this,arguments);
}

/***/ }),
/* 19 */
/***/ (function(module, exports) {

const mv3d = window.mv3d;

class View{
	constructor(canvas,camera){
		let options;
		if(!(canvas instanceof HTMLCanvasElement)){
			options=canvas;
			if(!camera){camera=options.camera;}
			canvas=options.canvas;
			if(!canvas){ canvas = document.createElement('canvas'); }
			if(!canvas.width){
				canvas.width=options.width||Graphics.width;
			}
			if(!canvas.height){
				canvas.height=options.height||Graphics.height;
			}
		}else{
			options={};
		}
		this.canvas=canvas;
		this.camera=camera;
		this.view=mv3d.engine.registerView(canvas,camera);
		this.texture=PIXI.Texture.from(canvas);
		this.texture.baseTexture.scaleMode=PIXI.SCALE_MODES.NEAREST;
		this.sprite=new PIXI.Sprite(this.texture);
		this.sprite.destroy=()=>{};
		this.index=options.index||0;
		View.list.push(this);
		View.sort();
		this.enabled=true;
		this.needsRender=null;
	}
	updateSize(){
		this.canvas.width=mv3d.canvas.width;
		this.canvas.height=mv3d.canvas.height;
		this.sprite.scale.copy(mv3d.pixiSprite.scale);
	}
	disable(){
		this.enabled=false;
		this.sprite.visible=false;
	}
	enable(){
		this.enabled=true;
		this.sprite.visible=true;
	}
	static sort(){
		View.list
		.sort(View._sortAbs)
		.sort(View._sortNeg);
	}
	static _sortFunction(v1,v2){ return Math.abs(v2)-Math.abs(v1); }
};
View._sortAbs=(v1,v2)=>Math.abs(v2.index)-Math.abs(v1.index);
View._sortNeg=(v1,v2)=>(v1,v2)=>v1.index<0&&v2.index>=0?-1:0;
View.list=[];
mv3d.View = View;

const _createTilemap=Spriteset_Map.prototype.createTilemap;
Spriteset_Map.prototype.createTilemap=function(){
	mv3d.callFeatures('createViews');
	_createTilemap.apply(this,arguments);
	const container = mv3d.viewContainer;
	const index = container.children.indexOf(mv3d.pixiSprite);
	for(view of View.list){
		container.addChildAt( view.sprite, view.index<0?index:index+1 );
	}
};

mv3d.renderViews=function(){
	if(!View.list.length){ return; }
	const width = mv3d.canvas.width;
	const height = mv3d.canvas.height;
	const activeCamera=mv3d.scene.activeCamera;
	for (const view of View.list){
		if(!view.enabled){ continue; }
		if(view.needsRender!=null){
			if(!view.needsRender){ continue; }
			view.needsRender=false;
		}
		const canvas = view.canvas;
		const context = canvas.getContext("2d");
		if(!context){ continue; }
		view.updateSize();
		const camera = view.camera||activeCamera;
		mv3d.scene.activeCamera=camera;
		mv3d.canvas.width=canvas.width;
		mv3d.canvas.height=canvas.height;

		mv3d.scene.render();
		context.clearRect(0,0,canvas.width,canvas.height);
		context.drawImage(mv3d.canvas,0,0);
		view.texture.update();
	}
	mv3d.canvas.width=width;
	mv3d.canvas.height=height;
	mv3d.scene.activeCamera=activeCamera;
}

const _render = mv3d.render;
mv3d.render=function(){
	mv3d.renderViews();
	_render.apply(this,arguments);
}

/***/ }),
/* 20 */
/***/ (function(module, exports) {

const mv3d = window.mv3d;
const { util, Feature, Blender, ColorBlender } = mv3d;
const { makeColor } = util;
const {
	TransformNode, DirectionalLight, ShadowGenerator, Vector3, Mesh
} = window.BABYLON

new Feature('dynamicShadows',{
	resizeShadowMap(size){
		mv3d.shadowGenerator._mapSize=size;
		mv3d.shadowGenerator.recreateShadowMap();
	},
	setup(){
		mv3d.sunNode = new TransformNode("sunNode",mv3d.scene);
		mv3d.sunlight = new DirectionalLight('sunlight', new Vector3(0,-1,0), mv3d.scene);
		mv3d.sunlight.renderPriority=10;
		mv3d.sunlight.parent=mv3d.sunNode;
		mv3d.sunlight.specular.set(0,0,0);
		mv3d.shadowGenerator = new ShadowGenerator(mv3d.DYNAMIC_SHADOW_RES,mv3d.sunlight);
		mv3d.shadowGenerator.transparencyShadow=true;
		//mv3d.shadowGenerator.forceBackFacesOnly=mv3d.BACK_SHADOWS;
		//mv3d.shadowGenerator.useCloseExponentialShadowMap=true;
		mv3d.shadowGenerator.usePercentageCloserFiltering=mv3d.SOFT_SHADOWS;
		//mv3d.shadowGenerator.usePoissonSampling=true;

		mv3d.blendSunYaw=new Blender('sunYaw',45);
		mv3d.blendSunYaw.cycle=360;
		mv3d.blendSunPitch=new Blender('sunPitch',45);
		mv3d.blendSunPitch.cycle=360;
		mv3d.blendSunColor=new ColorBlender('sunColor',0xffffff);
		applyShadowSettings();
	},
	update(){
		mv3d.sunNode.position.copyFrom(mv3d.cameraStick.position);
	},
	blend(reorient){
		if(reorient|mv3d.blendSunYaw.update()|mv3d.blendSunPitch.update()
		|mv3d.blendSunColor.update()){
			mv3d.sunNode.yaw=mv3d.blendSunYaw.currentValue();
			mv3d.sunNode.pitch=mv3d.blendSunPitch.currentValue();
			mv3d.sunlight.diffuse.set(...mv3d.blendSunColor.currentComponents());
			this.updateEnabled();
		}
	},
	updateEnabled(){
		if(mv3d.blendSunColor.currentValue()){
			if(!mv3d.sunlight.isEnabled()){ mv3d.sunlight.setEnabled(true); }
		}else{
			if(mv3d.sunlight.isEnabled()){ mv3d.sunlight.setEnabled(false); }
		}
	},
	clearMap(){
		mv3d.shadowGenerator.getShadowMap().renderList.splice(0,Infinity);
	},
	createCellMesh(mesh){
		mesh.receiveShadows=true;
		//mv3d.shadowGenerator.getShadowMap().renderList.push(mesh);
		mv3d.shadowGenerator.addShadowCaster(mesh);
	},
	destroyCellMesh(mesh){
		mv3d.shadowGenerator.removeShadowCaster(mesh);
	},
	createCharMesh(mesh){
		const index = mv3d.shadowGenerator.getShadowMap().renderList.indexOf(mesh);
		if(index===-1){
			mesh.receiveShadows=true;
			mv3d.shadowGenerator.addShadowCaster(mesh);
		}
	},
	destroyCharMesh(mesh){
		mv3d.shadowGenerator.removeShadowCaster(mesh);
	},
	updateParameters(){
		applyShadowSettings();
		this.updateEnabled();
	},
	applyMapSettings(mapconf){
		if('sunColor' in mapconf){
			mv3d.blendSunColor.setValue(mapconf.sunColor,0);
		}
		if('sunYaw' in mapconf){
			mv3d.blendSunYaw.setValue(mapconf.sunYaw,0);
		}
		if('sunPitch' in mapconf){
			mv3d.blendSunPitch.setValue(mapconf.sunPitch,0);
		}
		this.updateEnabled();
	},
},()=>mv3d.DYNAMIC_SHADOWS);

let shadowQuality = mv3d.DEFAULT_SHADOW_QUALITY;

if(mv3d.DYNAMIC_SHADOWS) mv3d.options['mv3d-dynShadow']={
	name: mv3d.OPTION_NAME_DYNAMIC_SHADOWS,
	values: ['OFF','LOW','MEDIUM','HIGH'],
	default: mv3d.DEFAULT_SHADOW_QUALITY,
	apply(v){
		shadowQuality=v;
	}
};

function applyShadowSettings(){
	mv3d.shadowGenerator.frustumEdgeFalloff=0;
	mv3d.sunlight.shadowFrustumSize=mv3d.RENDER_DIST*2;
	mv3d.sunlight.shadowMinZ=-mv3d.RENDER_DIST;
	mv3d.sunlight.shadowMaxZ=mv3d.RENDER_DIST;
	if(shadowQuality){
		mv3d.sunlight.shadowEnabled=true;
		const res = Math.min(4096,mv3d.RENDER_DIST*24*shadowQuality);
		mv3d.callFeature('dynamicShadows','resizeShadowMap',res);
		//mv3d.shadowGenerator.bias=6/res;
		mv3d.shadowGenerator.bias=10/res;
		//mv3d.shadowGenerator.normalBias=mv3d.shadowGenerator.bias*10;
		mv3d.shadowGenerator.normalBias=0;
	}else{
		mv3d.sunlight.shadowEnabled=false;
	}
}

if(mv3d.DYNAMIC_SHADOWS)Object.assign(mv3d.PluginCommand.prototype,{
	sun(...a){
		var time=this._TIME(a[2]);
		switch(a[0].toLowerCase()){
			case 'color': this._sunColor (a[1],time); return;
			case 'yaw'  : this._sunYaw   (a[1],time); return;
			case 'pitch': this._sunPitch (a[1],time); return;
			case 'angle':
				time=this._TIME(a[3]);
				this._sunYaw(a[1],time);
				this._sunPitch(a[2],time);
				return;
			//case 'intensity': this._lightIntensity(a[1],time); return;
		}
		time=this._TIME(a[3]);
		this._sunColor(a[0],time);
		this._sunYaw(a[1],time);
		this._sunPitch(a[2],time);
	},
	_sunColor(color,time=1){ mv3d.blendSunColor.setValue(makeColor(color).toNumber(),time); },
	_sunYaw(deg,time=1){ this._RELATIVE_BLEND(mv3d.blendSunYaw,deg,time); },
	_sunPitch(deg,time=1){ this._RELATIVE_BLEND(mv3d.blendSunPitch,deg,time); },
});

if(mv3d.DYNAMIC_SHADOWS)Object.assign(mv3d.mapConfigurationFunctions,{
	sun:new mv3d.ConfigurationFunction('color[dir]yaw,pitch',function(conf,params){
		const {color,yaw,pitch}=params;
		if(color){ conf.sunColor=makeColor(color).toNumber(); }
		if(yaw){ conf.sunYaw=Number(yaw); }
		if(pitch){ conf.sunPitch=Number(pitch) }
	}),
});

const shadowCasterList=[];
Object.defineProperty(Mesh.prototype,'mv3d_castShadows',{
	get(){ return this._mv3d_castShadows; },
	set(v){
		this._mv3d_castShadows=v;
		const index = shadowCasterList.indexOf(this);
		if(v){
			if(index<0){
				shadowCasterList.push(this);
			}
		}else{
			if(index>=0){
				shadowCasterList.splice(index,1);
			}
		}
		
	}
});
Object.defineProperty(mv3d.MeshGroup.prototype,'mv3d_castShadows',{
	get(){ return this._mv3d_castShadows; },
	set(v){
		this._mv3d_castShadows=v;
		for(const mesh of this.meshes){
			mesh.mv3d_castShadows=v;
		}
	}
});


/***/ }),
/* 21 */
/***/ (function(module, exports) {

const mv3d = window.mv3d;
const Feature = mv3d.Feature;
const {
	Vector2, PostProcess
} = window.BABYLON

new Feature('ambientOcclusion',{
	setup(){
		const ssao = new BABYLON.SSAORenderingPipeline('ssao',mv3d.scene,{
			ssaoRatio: 0.5,
			combineRatio:1.0,
		});
		ssao.fallOff = 0.000001;
		ssao.area = 1;
		ssao.radius = 0.03;
		ssao.totalStrength = 1.0;
		ssao.base = 0.5;
		mv3d.scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline('ssao',mv3d.camera);
		mv3d.ssao=ssao;
		mv3d.getDepthMap(mv3d.camera).resize(Graphics);
	},
},()=>mv3d.AMBIENT_OCCLUSION);

/*
if(mv3d.AMBIENT_OCCLUSION) mv3d.options['mv3d-ambientOcclusion']={
	name: "Ambient Occlusion",
	type:'bool',
	default: false,
	apply(v){ }
};
*/

/***/ }),
/* 22 */
/***/ (function(module, exports) {

const mv3d = window.mv3d;
const Feature = mv3d.Feature;
const {
	Vector2, PostProcess
} = window.BABYLON

new Feature('alphaFog',{
	setup(){
		this.alphaFog = new AlphaFogPostProcess('alphaFog',mv3d.camera);
	},
	updateCameraMode(){
		const index = mv3d.camera._postProcesses.indexOf(this.alphaFog);
		if(mv3d.hasAlphaFog){
			if(index<0){ mv3d.camera._postProcesses.push(this.alphaFog); }
		}else{
			if(index>=0){ mv3d.camera._postProcesses.splice(index,1); }
		}
	},
});
const feature = mv3d.features.alphaFog.methods;

Object.defineProperties(mv3d,{
	hasAlphaFog:{
		get(){return Boolean(mv3d.cameraMode!=='ORTHOGRAPHIC'&& mv3d.ALPHA_FOG); }
	},
	alphaFog:{
		get(){return this.ALPHA_FOG; },
		set(v){ this.ALPHA_FOG=v; feature.updateCameraMode(); mv3d.updateClearColor(); mv3d.updateBlenders(true); },
	}
});

class AlphaFogPostProcess extends PostProcess{
	constructor(name,camera){
		super(name,"alphaFog",['alphaFog'],['depthMap'],1,camera);
		this.depthMap=mv3d.getDepthMap(camera);
		this.depthMap.resize({width:Graphics.width,height:Graphics.height});

        this.onApplyObservable.add(effect=>{
            effect.setTexture("depthMap", this.depthMap);
            effect.setFloat("alphaFog", mv3d.ALPHA_FOG);
        });

	}
}
BABYLON.Effect.ShadersStore.alphaFogPixelShader=`
varying vec2 vUV;
uniform sampler2D textureSampler;
uniform sampler2D depthMap;
uniform float alphaFog;
void main(void) {
	gl_FragColor=texture2D(textureSampler,vUV).rgba;
	gl_FragColor.a *= min(1.0,(1.0-texture2D(depthMap,vUV).r)/alphaFog);
	gl_FragColor.rgb*=gl_FragColor.a;
	//gl_FragColor=texture2D(depthMap,vUV).rgba;
}
`;

/***/ }),
/* 23 */
/***/ (function(module, exports) {

const mv3d = window.mv3d;
const Feature = mv3d.Feature;
const {
	Color4
} = window.BABYLON

new Feature('glowLayer',{
	setup(){
		mv3d.glowLayer = new BABYLON.GlowLayer('glow',mv3d.scene,{
			mainTextureRatio: 0.5,
			blurKernelSize: mv3d.GLOW_RADIUS,
		});
		mv3d.glowLayer.intensity=mv3d.GLOW;
		mv3d.glowLayer.customEmissiveColorSelector=getGlowColor;
	},
},()=>mv3d.GLOW);

function getGlowColor(mesh, subMesh, material, result) {
	const glow = material.mv3d_glowColor;
	if(!glow){
		result.copyFrom(new BABYLON.Color4(0,0,0,0));
		return result;
	}
	result.copyFrom(material.mv3d_glowColor);
	result.r*=glow.a; result.g*=glow.a; result.b*=glow.a; result.a=glow.a;
	return result;
}

/***/ }),
/* 24 */
/***/ (function(module, exports) {

const mv3d = window.mv3d;
const {
	Feature, ConfigurationFunction, util
} = mv3d;
const {
	file,booleanString
} = util;
const {
	MeshBuilder, StandardMaterial, CubeTexture, Color3, Vector3, Quaternion,
	FreeCamera, RenderTargetTexture, TransformNode
} = window.BABYLON
const SKYBOX_MODE = BABYLON.Texture.SKYBOX_MODE;

Object.defineProperties(mv3d,{
	hasSkybox:{
		get(){return Boolean(getSkyboxData()); }
	}
});

new Feature('skybox',{
	createViews(){
		if(!mv3d.skyboxView){
			mv3d.skyboxCamera = new FreeCamera("skyboxCamera",new Vector3(0,0,0),this.scene);
			mv3d.skyboxCamera.minZ=0.1;
			mv3d.skyboxCamera.maxZ=2;
			mv3d.skyboxCamera.z=-1000;
			mv3d.skyboxView = new mv3d.View({camera:mv3d.skyboxCamera,index:-1});
			mv3d.skyboxView.disable();
		}
		this.createSkybox();
	},
	createSkybox(){
		if(!mv3d.hasSkybox||mv3d.skybox){ return; }

		mv3d.skybox = MeshBuilder.CreateBox("skybox",{size:1},mv3d.scene);
		mv3d.skybox.setEnabled(false);
		mv3d.skybox.isPickable=false;
		mv3d.skybox.material = new StandardMaterial("skybox",mv3d.scene);
		mv3d.skybox.material.backFaceCulling=false;
		mv3d.skybox.material.diffuseColor=Color3.Black();
		mv3d.skybox.material.specularColor=Color3.Black();
		mv3d.skybox.material.fogEnabled=false;
		mv3d.skybox.renderingGroupId=mv3d.enumRenderGroups.BACK;
		mv3d.skyboxNode = new TransformNode('skyboxNode',mv3d.scene);
		mv3d.skybox.parent=mv3d.skyboxNode;
		mv3d.skyboxNode.parent=mv3d.skyboxCamera;
		mv3d.skyboxMatrix=mv3d.skybox._localMatrix.clone();
		this.updateParameters();
	},
	updateParameters(){
		if(!mv3d.skybox){ return; }
		mv3d.skyboxCamera.fov=mv3d.camera.fov;
	},
	update(){
		if(!mv3d.skybox||!mv3d.skybox._isEnabled){ return; }
		mv3d.skyboxNode.rotation.copyFrom(
			Quaternion.Inverse(mv3d.cameraNode.rotation.toQuaternion()).toEulerAngles()
		);
		if(mv3d.hasAlphaFog||mv3d.cameraMode==="ORTHOGRAPHIC"){
			mv3d.skyboxNode.parent=mv3d.skyboxCamera;
			if(!mv3d.skyboxCamera.rotation.equals(mv3d.cameraNode.rotation)
			||!mv3d.skyboxMatrix.equals(mv3d.skybox._localMatrix)){
				mv3d.skyboxMatrix.copyFrom(mv3d.skybox._localMatrix);
				mv3d.skyboxCamera.rotation.copyFrom(mv3d.cameraNode.rotation);
				mv3d.skyboxView.needsRender=true;
			}
			if(!mv3d.skyboxView.enabled){ mv3d.skyboxView.enable(); }
		}else{
			mv3d.skyboxNode.parent=mv3d.camera;
			if(mv3d.skyboxView.enabled){ mv3d.skyboxView.disable(); }
		}
	},
	blend(reorient){
		if(!mv3d.skybox){ return; }
		if(mv3d.blendResolutionScale.updated){
			mv3d.skyboxView.needsRender=true;
		}
	},
	beforeMapLoad(newmap){
		if(newmap){
			mv3d.clearData('skybox');
		}
	},
	async afterMapLoad(newmap){
		if(!mv3d.skybox){ return; }
		const skyboxData = getSkyboxData();
		if(!skyboxData){
			mv3d.skyboxView.disable();
			mv3d.skybox.setEnabled(false);
			return;
		}
		const files=[];
		for(let i=0; i<skyboxData.length; ++i){
			files[i]=await mv3d.getTextureUrl(skyboxData[i]);
		}
		if(skyboxData !== getSkyboxData()){ return;}
		const reflectionTexture =
			CubeTexture.CreateFromImages(files, mv3d.scene, true);
		reflectionTexture.coordinatesMode=SKYBOX_MODE;

		await mv3d.waitTextureLoaded(reflectionTexture);

		if(skyboxData !== getSkyboxData()){
			reflectionTexture.dispose();
			return;
		}
		reflectionTexture.updateSamplingMode(1);
		if(mv3d.skybox.material.reflectionTexture){
			mv3d.skybox.material.reflectionTexture.dispose();
		}
		mv3d.skybox.material.reflectionTexture=reflectionTexture;
		mv3d.skybox.rotation.set(0,0,0);
		mv3d.skyboxView.enable();
		mv3d.skyboxView.needsRender=true;
		mv3d.skybox.setEnabled(true);
	}
});
const feature = mv3d.features.skybox.methods;

const skyboxFolder = 'img/parallaxes';

mv3d.mapConfigurationFunctions.skybox=new ConfigurationFunction(
'default,top,bottom,north,west,south,east',function(conf,params){
	const {
		bottom=params.default||params.top   ||params.north||params.south||params.east||params.west,
		   top=params.default||params.bottom||params.north||params.south||params.east||params.west,
		 north=params.default||params.south ||params.east ||params.west ||params.top ||params.bottom,
		 south=params.default||params.north ||params.east ||params.west ||params.top ||params.bottom,
		  east=params.default||params.west  ||params.north||params.south||params.top ||params.bottom,
		  west=params.default||params.east  ||params.north||params.south||params.top ||params.bottom,
	}=params;
	conf.skybox=[east,top,north,west,bottom,south]
	.map(u=>file(skyboxFolder,u));
});

function getSkyboxData(){
	return mv3d.loadData('skybox',mv3d.getMapConfig('skybox',null));
}

function decodeSkybox(){
	if(!getSkyboxData()){ return {}; }
	const [east,top,north,west,bottom,south]=getSkyboxData();
	return {east,top,north,west,bottom,south};
}

Object.assign(mv3d.PluginCommand.prototype,{
	skybox(...a){
		if(!booleanString(a[0].toLowerCase())){
			delete mv3d.mapConfigurations.skybox;
			mv3d.clearData('skybox');
			feature.afterMapLoad();
			return;
		}
		const settings=decodeSkybox();
		let dfault=null;
		for(let i=0;i<a.length;++i){
			const side = a[i].toLowerCase();
			switch(side){
				case'north':case'south':case'east':case'west':case'top':case'bottom':
					if(a[i+1]!=null)settings[side]=a[i+1];++i; break;
				case 'default':
					if(a[i+1]!=null)dfault=a[i+1];++i; break;
				default:
					if(!dfault){dfault=a[i];}
			}
		}
		if(dfault){ settings.default = dfault; }
		let params=[];
		for(const side in settings){
			params.push(`${side}:${settings[side]}`)
		}
		params=params.join(',');
		const conf = {};
		mv3d.mapConfigurationFunctions.skybox.run(conf,params);
		mv3d.mapConfigurations.skybox=conf.skybox;
		mv3d.saveData('skybox',conf.skybox);
		feature.createSkybox();
		feature.afterMapLoad();
	},
});

/***/ }),
/* 25 */
/***/ (function(module, exports) {

const mv3d = window.mv3d;
const { util, ConfigurationFunction } = mv3d;
const { assign, file, foldername, filename } = util;
const { SceneLoader, Mesh } = BABYLON;

const configurationFunctions = {
	model:new ConfigurationFunction('filename',function(config,params){
		config.model = file("./models/",params.filename);
		config.shape = mv3d.enumShapes.MODEL;
	}),
};

assign(mv3d.tilesetConfigurationFunctions,configurationFunctions);
assign(mv3d.eventConfigurationFunctions,configurationFunctions);

mv3d.tilesetConfigurationFunctions.scale = mv3d.eventConfigurationFunctions.scale;


mv3d.importModel=(url,merge=true)=>new Promise((resolve,reject)=>{
	SceneLoader.LoadAssetContainer(foldername(url), filename(url), mv3d.scene, container=>{
		const meshes = container.meshes;
		const materials = container.materials;
		for (const mat of materials){
			mat.ambientColor.set(1,1,1);
			const texture = mat.diffuseTexture;
			if(texture) mv3d.waitTextureLoaded(texture).then(texture=>{
				texture.updateSamplingMode(1);
			});
		}
		let totalVertices = 0;
		for (const mesh of meshes){
			totalVertices += mesh.getTotalVertices();
			if(!merge){
				mesh.renderingGroupId=mv3d.enumRenderGroups.MAIN;
			}
		}
		if(merge){
			const importedMesh = Mesh.MergeMeshes(meshes,true,totalVertices>64000,undefined,false,true);;
			importedMesh.renderingGroupId=mv3d.enumRenderGroups.MAIN;
			importedMesh.mv3d_materials=materials;
			resolve(importedMesh);
		}else{
			const group = new MeshGroup();
			container.addAllToScene();
			group.addMesh(...meshes);
			group.mv3d_materials = materials;
			resolve(group);
		}
	});
});

/***/ }),
/* 26 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXTERNAL MODULE: ./src/main.js
var main = __webpack_require__(1);

// EXTERNAL MODULE: ./src/mod_babylon.js + 1 modules
var mod_babylon = __webpack_require__(3);

// EXTERNAL MODULE: ./src/mod_mv.js
var mod_mv = __webpack_require__(6);

// EXTERNAL MODULE: ./src/util.js
var util = __webpack_require__(0);

// CONCATENATED MODULE: ./src/attributes.js
const attributes_mz3d = window.mz3d;

attributes_mz3d.attributes={};

class Attribute{
	constructor(name,dfault,reader){
		this.name=name.toLowerCase();
		this.reader = reader?reader:v=>v;
		this.default=this.reader(dfault);
		this.descriptor={
			get:()=>this.get(),
			set:v=>this.set(this.reader(v)),
		};
		Object.defineProperty(attributes_mz3d.attributes,this.name,this.descriptor);
	}
	get(){
		const storage = Attribute.getStorageLocation();
		if(!storage || !(this.name in storage)){ return this.default; }
		return storage[this.name];
	}
	set(v){
		const storage = Attribute.getStorageLocation();
		if (!storage){console.warn(`MV3D: Couldn't get Attribute storage location.`); return;}
		storage[this.name]=v;
	}
	static getStorageLocation(){
		if(!$gameVariables){ return null; }
		if(!$gameVariables.mv3d_attributes){ $gameVariables.mv3d_attributes = {}; }
		return $gameVariables.mv3d_attributes;
	}
}
attributes_mz3d.Attribute = Attribute;
// CONCATENATED MODULE: ./src/parameters.js
const parameters_mz3d = window.mz3d;




const pluginNames = ['mz3d','mv3d','mv3d-babylon'];
parameters_mz3d.pluginName = PluginManager._scripts.filter(v=>pluginNames.includes(v))[0]||'mz3d';

const parameters = PluginManager.parameters(parameters_mz3d.pluginName);
/* harmony default export */ var src_parameters = (parameters);

function parameter(name,dfault,type){
	return name in parameters ? (type?type(parameters[name]):parameters[name]) : dfault;
}

Object.assign(parameters_mz3d,{
	enumOptionModes:{
		DISABLE: 0,
		ENABLE: 1,
		SUBMENU: 2,
	}
});

function tryParseString(s){
	try{
		return JSON.parse(s);
	}catch(err){
		return s;
	}
}

Object(util["assign"])(parameters_mz3d,{
	CAMERA_MODE:"PERSPECTIVE",
	ORTHOGRAPHIC_DIST:100,
	MV3D_FOLDER:"img/MV3D",
	get MZ3D_FOLDER(){ return this.MV3D_FOLDER; },

	ANIM_DELAY:Number(parameters.animDelay),
	ALPHA_CUTOFF:Math.max(0.01,parameters.alphatest),

	EDGE_FIX: Number(parameters.edgefix)*Object(util["tileSize"])()/48,
	ANTIALIASING: Object(util["booleanString"])(parameters.antialiasing),
	FOV:Number(parameters.fov),
	RES_SCALE: parameter('resScale',1,Number)||1,

	//WALL_HEIGHT:Number(parameters.wallHeight),
	//TABLE_HEIGHT:Number(parameters.tableHeight),
	//FRINGE_HEIGHT:Number(parameters.fringeHeight),
	CEILING_HEIGHT:Number(parameters.ceilingHeight),
	BASE_HEIGHT:parameter('baseHeight',0,Number),
	LAYER_DIST:Number(parameters.layerDist),

	//ENABLED_DEFAULT: booleanString(parameters.enabledDefault),
	EVENTS_UPDATE_NEAR: Object(util["booleanString"])(parameters.eventsUpdateNear),

	UNLOAD_CELLS: Object(util["booleanString"])(parameters.unloadCells),
	CELL_SIZE: Number(parameters.cellSize),
	RENDER_DIST: Number(parameters.renderDist),
	MIPMAP:Object(util["booleanString"])(parameters.mipmap),

	TILE_SETTINGS_WALL: parameter('wallTileSettings',"height(2)",JSON.parse),
	TILE_SETTINGS_TABLE: parameter('tableTileSettings',"height(0.33)",JSON.parse),
	TILE_SETTINGS_STAR: parameter('starTileSettings',"fringe(2),pass(*)",JSON.parse),
	MAP_DEFAULTS: parameter('mapDefaults',"",JSON.parse),

	get renderDist(){ return Math.min(this.RENDER_DIST, parameters_mz3d.blendFogFar.currentValue()+7.5); },

	OPTION_MIPMAP:Object(util["booleanString"])(parameters.mipmapOption),
	OPTION_NAME_MIPMAP: parameter('mipmapOptionName',"Mipmapping",String),
	OPTION_RENDER_DIST: parameter('renderDistOption',true,util["booleanString"]),
	OPTION_NAME_RENDER_DIST: parameter('renderDistOptionName',"Render Distance",String),
	OPTION_RENDER_DIST_MIN: parameter('renderDistMin',10,Number),
	OPTION_RENDER_DIST_MAX: parameter('renderDistMax',100,Number),
	OPTION_FOV: parameter('fovOption',false,util["booleanString"]),
	OPTION_NAME_FOV: parameter('fovOptionName',"FOV",String),
	OPTION_FOV_MIN: parameter('fovMin',50,Number),
	OPTION_FOV_MAX: parameter('fovMax',100,Number),
	OPTION_INVERTY: parameter('invertYOption',true,util["booleanString"]),
	OPTION_NAME_INVERTY: parameter('invertYOptionName',"Invert Y Axis", String),
	OPTION_LOOKSENSITIVITY: parameter('lookSensitivityOption',true,util["booleanString"]),
	OPTION_NAME_LOOKSENSITIVITY: parameter('lookSensitivityOptionName',"Look Sensitivity", String),

	STAIR_THRESH: Number(parameters.stairThresh),
	WALK_OFF_EDGE:Object(util["booleanString"])(parameters.walkOffEdge),
	WALK_ON_EVENTS:Object(util["booleanString"])(parameters.walkOnEvents),
	GRAVITY:Number(parameters.gravity),

	FOG_COLOR: 0,
	FOG_NEAR: 20,
	FOG_FAR: 30, 
	//AMBIENT_COLOR: makeColor(parameters.ambientColor).toNumber(),
	get AMBIENT_COLOR(){ return parameters_mz3d.featureEnabled('dynamicShadows')?0x888888:0xffffff; },

	LIGHT_LIMIT: parameter('lightLimit',8,n=>{n=Number(n);return isFinite(n)?n:8;}),
	LIGHT_HEIGHT: 0.5,
	LAMP_HEIGHT: 0.5,
	FLASHLIGHT_HEIGHT: 0.25,
	LIGHT_DECAY: 1,
	LIGHT_DIST: 3,
	LIGHT_ANGLE: 60,
	FLASHLIGHT_EXTRA_ANGLE: 10,
	FLASHLIGHT_INTENSITY_MULTIPLIER: 2,

	REGION_DATA:{},
	_REGION_DATA:{},
	_REGION_DATA_MAP:{},
	TTAG_DATA:{},

	EVENT_HEIGHT:Number(parameters.eventHeight),
	//VEHICLE_BUSH:booleanString(parameters.vehicleBush),
	BOAT_SETTINGS:JSON.parse(parameters.boatSettings),
	SHIP_SETTINGS:JSON.parse(parameters.shipSettings),
	AIRSHIP_SETTINGS:JSON.parse(parameters.airshipSettings),

	EVENT_CHAR_SETTINGS: parameter('eventCharDefaults',"",tryParseString),
	EVENT_OBJ_SETTINGS: parameter('eventObjDefaults',"",tryParseString),
	EVENT_TILE_SETTINGS: parameter('eventTileDefaults',"",tryParseString),

	allowGlide: new Attribute('allowGlide',Object(util["booleanString"])(parameters.allowGlide),util["booleanString"]),
	get ALLOW_GLIDE(){ return this.allowGlide; },

	SPRITE_OFFSET:Number(parameters.spriteOffset)/2,

	ENABLE_3D_OPTIONS:parameters_mz3d.enumOptionModes[parameters['3dMenu'].toUpperCase()],

	TEXTURE_SHADOW: parameters.shadowTexture||'shadow',
	TEXTURE_BUSHALPHA: parameters.alphaMask||'bushAlpha',
	TEXTURE_ERROR: parameters.errorTexture||'errorTexture',

	diagonalMovement: new Attribute('diagonalMovement',String(parameters.dir8Movement),function(v){
		v=String(v).toUpperCase();
		return {
			enabled:Object(util["booleanString"])(v),
			smart:v.includes('SMART'),
			'2D':!v.includes('3D'),
		}
	}),
	get DIR8MOVE(){ return this.diagonalMovement.enabled; },
	get DIR8SMART(){ return this.diagonalMovement.smart; },
	get DIR8_2D(){ return this.diagonalMovement['2D']; },

	turnIncrement: new Attribute('turnIncrement',String(parameters.turnIncrement),v=>Number(v)),
	get TURN_INCREMENT(){ return parameters_mz3d.turnIncrement; },
	WASD: Object(util["booleanString"])(parameters.WASD),

	inputCameraMouse: new Attribute('inputCameraMouse',String(parameters.inputCameraMouse),util["booleanString"]),
	inputCameraGamepad: new Attribute('inputCameraGamepad',String(parameters.inputCameraGamepad),util["booleanString"]),
	GAMEPAD_TURN_BUTTON: parameter('inputGamepadTurnButton',0,v=>{return {'U':0,'B':1,'T':2}[v[0]]||0;}),

	lockCamera: new Attribute('lockCamera',false,util["booleanString"]),
	allowPitch: new Attribute('allowPitch',Object(util["booleanString"])(parameters.keyboardPitch),util["booleanString"]),
	allowRotation: new Attribute('allowRotation',Object(util["booleanString"])(parameters.keyboardTurn),util["booleanString"]),
	KEYBOARD_STRAFE: Object(util["falseString"])(parameters.keyboardStrafe),

	get KEYBOARD_PITCH(){ return this.allowPitch; },
	get KEYBOARD_TURN(){ return this.allowRotation; },

	YAW_SPEED: Number(parameters.yawSpeed)||90,
	PITCH_SPEED: Number(parameters.pitchSpeed)||90,

	TRIGGER_INFINITE: !Object(util["booleanString"])(parameters.heightTrigger),

	BACKFACE_CULLING: parameter('backfaceCulling',true,util["booleanString"]),
	cameraCollision: new Attribute('cameraCollision',String(parameters.cameraCollision),function(v){
		if(typeof v === 'string'){
			const values=v.split(' '); v=values[0];
			const ret = {type:!Object(util["booleanString"])(v)?0:Number((v.match(/\d+/)||'1')[0])};
			for (let v of values)if(v.toUpperCase().includes("SMOOTH")){ ret.smooth=true; }
			return ret;
		}else if(typeof v == 'object'){
			return Object.assign(this.get(),v);
		}
		const ret = this.get(); ret.type=Number(v); return ret;
	}),

	DIAG_SYMBOL: parameter('diagSymbol','{d}',String),

	setupParameters(){
		this.REGION_DATA=new Proxy(this._REGION_DATA,{
			get:(target,key)=>{
				if(key in this._REGION_DATA_MAP){ return this._REGION_DATA_MAP[key]; }
				if(key in this._REGION_DATA){ return this._REGION_DATA[key]; }
			},
			set:(target,key,value)=>{
				target[key]=value;
			},
			has:(target,key)=>{
				return key in this._REGION_DATA_MAP || key in this._REGION_DATA;
			},
		});
		for (let entry of JSON.parse(parameters.regions)){
			entry=JSON.parse(entry);
			const regionData = this.readConfigurationFunctions(entry.conf,this.tilesetConfigurationFunctions)
			this._REGION_DATA[entry.regionId]=regionData;
			
		}
		for (const id in this._REGION_DATA){
			this.applyTextureConfigs(this._REGION_DATA[id],'B',0,0);
			this.collapseCeilingOffsets(this._REGION_DATA[id]);
		}
		for (let entry of JSON.parse(parameters.ttags)){
			entry=JSON.parse(entry);
			this.TTAG_DATA[entry.terrainTag]=this.readConfigurationFunctions(entry.conf,this.tilesetConfigurationFunctions);
		}
		for (const id in this.TTAG_DATA){
			this.applyTextureConfigs(this.TTAG_DATA[id],'B',0,0);
			this.collapseCeilingOffsets(this.TTAG_DATA[id]);
		}

		this.EVENT_CHAR_SETTINGS = this.readConfigurationFunctions(
			this.EVENT_CHAR_SETTINGS,
			this.eventConfigurationFunctions,
		);
		this.EVENT_OBJ_SETTINGS = this.readConfigurationFunctions(
			this.EVENT_OBJ_SETTINGS,
			this.eventConfigurationFunctions,
		);
		this.EVENT_TILE_SETTINGS = this.readConfigurationFunctions(
			this.EVENT_TILE_SETTINGS,
			this.eventConfigurationFunctions,
		);

		this.BOAT_SETTINGS.big=Object(util["booleanString"])(this.BOAT_SETTINGS.big);
		this.SHIP_SETTINGS.big=Object(util["booleanString"])(this.SHIP_SETTINGS.big);
		this.AIRSHIP_SETTINGS.height=Number(this.AIRSHIP_SETTINGS.height);
		this.AIRSHIP_SETTINGS.big=Object(util["booleanString"])(this.AIRSHIP_SETTINGS.big);
		this.AIRSHIP_SETTINGS.bushLanding=Object(util["booleanString"])(this.AIRSHIP_SETTINGS.bushLanding);

		this.BOAT_SETTINGS.conf = this.readConfigurationFunctions(
			this.BOAT_SETTINGS.conf,
			this.eventConfigurationFunctions,
		);
		this.SHIP_SETTINGS.conf = this.readConfigurationFunctions(
			this.SHIP_SETTINGS.conf,
			this.eventConfigurationFunctions,
		);
		this.AIRSHIP_SETTINGS.conf = this.readConfigurationFunctions(
			this.AIRSHIP_SETTINGS.conf,
			this.eventConfigurationFunctions,
		);

		//Texture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=0;

		this.TILE_SETTINGS_WALL = this.readConfigurationFunctions(this.TILE_SETTINGS_WALL,this.tilesetConfigurationFunctions);
		this.TILE_SETTINGS_TABLE = this.readConfigurationFunctions(this.TILE_SETTINGS_TABLE,this.tilesetConfigurationFunctions);
		this.TILE_SETTINGS_STAR = this.readConfigurationFunctions(this.TILE_SETTINGS_STAR,this.tilesetConfigurationFunctions);

		this.MAP_DEFAULTS = this.readConfigurationFunctions(this.MAP_DEFAULTS,this.mapConfigurationFunctions);
		
		Object(util["assign"])(parameters_mz3d,{
			airshipHeight: new Attribute('airshipHeight',this.AIRSHIP_SETTINGS.height,Number),
		});

	},

	updateParameters(){
		this.updateRenderDist();
		this.updateFov();
		this.callFeatures('updateParameters');
	},
	updateRenderDist(){
		if(this.camera.mode===mod_babylon["f" /* ORTHOGRAPHIC_CAMERA */]){
			this.camera.maxZ=this.renderDist;
			this.camera.minZ=-this.renderDist;
		}else{
			this.camera.maxZ=this.renderDist;
			this.camera.minZ=0.1;
		}
	},
	updateFov(){
		const dist = this.blendCameraDist.currentValue()||0.1;
		const frustrumHeight = this.getFrustrumHeight(dist,Object(util["degtorad"])(this.FOV));
		const fov = this.getFovForDist(dist,frustrumHeight/this.blendCameraZoom.currentValue());
		this.camera.fov=fov;
	},
});
// EXTERNAL MODULE: ./node_modules/babylonjs/babylon.js
var babylon = __webpack_require__(2);

// CONCATENATED MODULE: ./src/blenders.js
const mv3d = window.mv3d;




const raycastPredicate=mesh=>{
	if(!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable || mesh.character){ return false; }
	return true;
}

Object.assign(mv3d,{

	cameraTargets:[],
	getCameraTarget(){
		return this.cameraTargets[0];
	},
	setCameraTarget(char,time){
		if(!char){ this.cameraTargets.length=0; return; }
		this.cameraTargets.unshift(char);
		if(this.cameraTargets.length>2){ this.cameraTargets.length=2; }
		this.saveData('cameraTarget',this.getTargetString(char));
		this.blendCameraTransition.value=1;
		this.blendCameraTransition.setValue(0,time);
	},
	clearCameraTarget(){
		this.cameraTargets.length=0;
	},
	resetCameraTarget(){
		this.clearCameraTarget();
		this.setCameraTarget($gamePlayer,0);
	},
	rememberCameraTarget(){
		const target = this.loadData('cameraTarget');
		if(target){
			this.setCameraTarget(this.targetChar(target),0);
		}
	},

	cameraTrack:null,
	cameraTrackTime:0,
	cameraTrackMode:0,
	setCameraTrack(target,time=0,mode=3){
		if(!target){ this.cameraTrack=null; return; }
		this.cameraTrack=target;
		this.cameraTrackTime=time;
		this.cameraTrackMode=mode;
	},

	setupBlenders(){
		this.blendFogColor = new ColorBlender('fogColor',this.FOG_COLOR);
		this.blendFogNear = new Blender('fogNear',this.FOG_NEAR);
		this.blendFogFar = new Blender('fogFar',this.FOG_FAR);
		this.blendCameraRoll = new Blender('cameraRoll',0);
		this.blendCameraRoll.cycle=360;
		this.blendCameraYaw = new Blender('cameraYaw',0);
		this.blendCameraYaw.cycle=360;
		this.blendCameraPitch = new Blender('cameraPitch',60);
		this.blendCameraPitch.min=0;
		this.blendCameraPitch.max=180;
		this.blendCameraDist = new Blender('cameraDist',this.getDistForFov());
		this.blendCameraZoom = new Blender('cameraZoom',1);
		this.blendCameraDist.min=0;
		this.blendCameraHeight = new Blender('cameraHeight',0.7);
		this.blendAmbientColor = new ColorBlender('ambientColor',this.AMBIENT_COLOR);
		this.blendPanX = new Blender('panX',0);
		this.blendPanY = new Blender('panY',0);
		this.blendCameraTransition = new Blender('cameraTransition',0);
		this.blendResolutionScale = new Blender('resolutionScale',mv3d.RES_SCALE);
	},

    updateBlenders(reorient){
		this.updateCameraMode();
		// camera target & pan
		if(!this.cameraTargets.length){
			if($gamePlayer){
				this.cameraTargets[0]=$gamePlayer;
			}
		}

		// camera tracking
		if(this.cameraTrack && this.cameraTrack!==this.cameraTargets[0]){
			if(this.cameraTrackMode&1){
				const yaw = Object(util["radtodeg"])(Math.atan2(-(this.cameraTrack._realY-this.cameraStick.y),this.cameraTrack._realX-this.cameraStick.x))-90;
				if(this.blendCameraYaw.targetValue()!==yaw){ this.blendCameraYaw.setValue(yaw,this.cameraTrackTime); }
			}
			if(this.cameraTrackMode&2){
				const dist = babylon["Vector2"].Distance(new babylon["Vector2"](this.cameraTrack._realX,this.cameraTrack._realY), new babylon["Vector2"](this.cameraStick.absolutePosition.x,-this.cameraStick.absolutePosition.z));
				const zdist = this.cameraTrack.z - this.cameraStick.absolutePosition.y;
				const pitch = Object(util["radtodeg"])(Math.atan(zdist/dist)) + 90;
				if(this.blendCameraPitch.targetValue()!==pitch && isFinite(pitch)){ this.blendCameraPitch.setValue(pitch,this.cameraTrackTime); }
			}
		}

		// camera following
		if(mv3d.getCameraTarget()===$gamePlayer && $gamePlayer._vehicleGettingOn){
			mv3d.setCameraTarget($gamePlayer.vehicle(),0.5);
		}else if(mv3d.getCameraTarget()===$gamePlayer.vehicle() && $gamePlayer._vehicleGettingOff){
			mv3d.setCameraTarget($gamePlayer,0.5);
		}
		if(this.blendCameraTransition.update() && this.cameraTargets.length>=2){
			const t = this.blendCameraTransition.currentValue();
			let char1=this.cameraTargets[0];
			//if(char1===$gamePlayer&&$gamePlayer.isInVehicle()){ char1=$gamePlayer.vehicle(); }
			let char2=this.cameraTargets[1];
			//if(char2===$gamePlayer&&$gamePlayer.isInVehicle()){ char2=$gamePlayer.vehicle(); }
			if(char1.mv3d_sprite&&char2.mv3d_sprite && char1.mv3d_sprite.isEnabled()&&char2.mv3d_sprite.isEnabled()){
				const pos1 = char1.mv3d_sprite.spriteOrigin.getAbsolutePosition();
				const pos2 = char2.mv3d_sprite.spriteOrigin.getAbsolutePosition();
				this.cameraStick.position.x = pos1.x*(1-t) + pos2.x*t;
				this.cameraStick.position.y = pos1.y*(1-t) + pos2.y*t;
				this.cameraStick.position.z = pos1.z*(1-t) + pos2.z*t;
			}else{
				this.cameraStick.x = char1._realX*(1-t) + char2._realX*t;
				this.cameraStick.y = char1._realY*(1-t) + char2._realY*t;
				if(char1.mv3d_sprite){
					this.cameraStick.z=char1.mv3d_sprite.z;
				}
			}
		}else if(this.cameraTargets.length){
			let char = this.getCameraTarget();
			//if(char===$gamePlayer&&$gamePlayer.isInVehicle()){ char=$gamePlayer.vehicle(); }
			
			if(char.mv3d_sprite && char.mv3d_sprite.isEnabled()){
				this.cameraStick.position.copyFrom(char.mv3d_sprite.spriteOrigin.getAbsolutePosition());
			}else{
				this.cameraStick.x=char._realX;
				this.cameraStick.y=char._realY;
			}
			
		}
		this.blendPanX.update();
		this.blendPanY.update();
		this.cameraStick.x+=this.blendPanX.currentValue();
		this.cameraStick.y+=this.blendPanY.currentValue();

		// camera yaw, pitch, dist & height
		if(reorient|this.blendCameraPitch.update()|this.blendCameraYaw.update()|this.blendCameraRoll.update()
		|this.blendCameraDist.update()|this.blendCameraHeight.update()|this.blendCameraZoom.update()
		|$gameScreen._shake!==0
		|(mv3d.cameraCollision.type&&$gamePlayer.mv3d_positionUpdated)){
			this.cameraNode.pitch = this.blendCameraPitch.currentValue()-90;
			this.cameraNode.yaw = this.blendCameraYaw.currentValue();
			this.cameraNode.roll = this.blendCameraRoll.currentValue();
			this.cameraNode.position.set(0,0,0);
			let dist = this.blendCameraDist.currentValue();
			if(mv3d.cameraCollision.type){
				let doCollide = true;
				if(mv3d.cameraCollision.type>1){
					this.cameraNode.translate(util["ZAxis"],-dist,mod_babylon["e" /* LOCALSPACE */]);
					const gpos = mv3d.globalPosition(this.cameraNode);
					this.cameraNode.position.set(0,0,0);
					const z = mv3d.getWalkHeight(gpos.x,-gpos.z);
					if(gpos.y>z){doCollide=false;}
					//if(Date.now()%10===0)console.log(gpos,z);
				}
				if(doCollide){
					const raycastOrigin = new babylon["Vector3"]().copyFrom(this.cameraStick.position);
					raycastOrigin.y+=this.blendCameraHeight.currentValue()+0.1;
					const ray = new babylon["Ray"](raycastOrigin, babylon["Vector3"].TransformCoordinates(mv3d.camera.getTarget().negate(),mv3d.getRotationMatrix(mv3d.camera)),dist);
					const intersections = mv3d.scene.multiPickWithRay(ray,raycastPredicate);
					for (const intersection of intersections){
						if(!intersection.hit){ continue; }
						let material = intersection.pickedMesh.material; if(!material){ continue; }
						if(material.subMaterials){
							material = material.subMaterials[intersection.pickedMesh.subMeshes[intersection.subMeshId].materialIndex];
						}
						if(material.mv3d_through){ continue; }
						dist=intersection.distance;
						break;
					}
				}
			}
			if(this.cameraCollision.smooth){
				if(this.camera.dist==null){this.camera.dist=dist;}
				this.camera.dist=this.camera.dist+(dist-this.camera.dist)/2;
				dist=this.camera.dist;
			}
			this.cameraNode.translate(util["ZAxis"],-dist,mod_babylon["e" /* LOCALSPACE */]);
			if(this.camera.mode===mod_babylon["f" /* ORTHOGRAPHIC_CAMERA */]){
				const fieldSize = this.getFieldSize();
				this.camera.orthoLeft=-fieldSize.width/2;
				this.camera.orthoRight=fieldSize.width/2;
				this.camera.orthoTop=fieldSize.height/2;
				this.camera.orthoBottom=-fieldSize.height/2;
			}else{
				if(this.cameraNode.z<0){ this.cameraNode.z=0; }
			}
			this.cameraNode.z += this.blendCameraHeight.currentValue();
			this.cameraNode.translate(util["XAxis"],-$gameScreen._shake/48,mod_babylon["e" /* LOCALSPACE */]);
			this.updateDirection();
			this.updateFov();

			if(mv3d.DYNAMIC_NORMALS && (reorient||this.blendCameraPitch.updated||(this.blendSunColor&&this.blendSunColor.updated)) ){
				this.updateDynamicNormals();
			}
		}

		//fog
		if(reorient|this.blendFogColor.update()|this.blendFogNear.update()|this.blendFogFar.update()){
			if(mv3d.hasAlphaFog){
				this.scene.fogStart=this.blendFogNear.currentValue();
				this.scene.fogEnd=this.blendFogFar.currentValue();
			}else{
				this.scene.fogStart=Math.min(mv3d.RENDER_DIST-1,this.blendFogNear.currentValue());
				this.scene.fogEnd=Math.min(mv3d.RENDER_DIST,this.blendFogFar.currentValue());
			}
			this.scene.fogColor.copyFromFloats(
				this.blendFogColor.r.currentValue()/255,
				this.blendFogColor.g.currentValue()/255,
				this.blendFogColor.b.currentValue()/255,
			);
			mv3d.updateClearColor();
			mv3d.updateRenderDist();
		}

		//light
		if(reorient|this.blendAmbientColor.update()){
			this.scene.ambientColor.copyFromFloats(
				this.blendAmbientColor.r.currentValue()/255,
				this.blendAmbientColor.g.currentValue()/255,
				this.blendAmbientColor.b.currentValue()/255,
			);
		}

		// res scale
		if(reorient|this.blendResolutionScale.update()){
			const resScale=Object(util["minmax"])(0,1,this.blendResolutionScale.currentValue());
			mv3d.RES_SCALE=resScale;
			if(resScale<1){
				mv3d.pixiSprite.scale.set(
					1/((Graphics.width*resScale-1)/Graphics.width),
					1/((Graphics.height*resScale-1)/Graphics.height));
			}else{
				mv3d.pixiSprite.scale.set(1,1);
			}
			mv3d.updateCanvas();
		}

		this.callFeatures('blend',reorient);
	},

	updateClearColor(){
		if($gameMap.parallaxName()||mv3d.hasSkybox){
			if(mv3d.hasAlphaFog){
				mv3d.scene.clearColor.set(...mv3d.blendFogColor.currentComponents(),0);
			}else{
				mv3d.scene.clearColor.set(0,0,0,0);
			}
		}else{
			mv3d.scene.clearColor.set(...mv3d.blendFogColor.currentComponents(),1);
		}
	},

});

const _changeParallax = Game_Map.prototype.changeParallax;
Game_Map.prototype.changeParallax = function() {
	_changeParallax.apply(this,arguments);
	mv3d.updateClearColor();
};


class Blender{
	constructor(key,dfault,track=true){
		this.key=key;
		this.dfault=mv3d.loadData(key,dfault);
		this.value=dfault;
		this.speed=1;
		this.max=Infinity;
		this.min=-Infinity;
		this.cycle=false;
		if(track){
			Blender.list.push(this);
		}
	}
	setValue(target,time=0,normalize=true){
		target = Math.min(this.max,Math.max(this.min,target));
		let diff = target - this.value;
		if(this.cycle){
			while( target>this.cycle ){ target-=this.cycle; }
			while( target<-this.cycle ){ target+=this.cycle; }
			this.value=target - diff;
		}
		this.saveValue(this.key,target);
		if(!time){ this.instantChanged=true; this.value=target; }
		if(normalize&&this.cycle){
			while ( Math.abs(diff)>this.cycle/2 ){
				this.value += Math.sign(diff)*this.cycle;
				diff = target - this.value;
			}
		}
		this.speed = Math.abs(diff)/(60*time);
	}
	currentValue(){ return this.value; }
	targetValue(){ return this.loadValue(this.key); }
	defaultValue(){ return this.dfault; }
	update(){
		const target = this.targetValue();
		if(this.value===target){ 
			if(this.instantChanged){
				this.updated=true;
				delete this.instantChanged;
				return true;
			}else{
				this.updated=false;
				return false;
			}
		}
		const diff = target - this.value;
		if(isNaN(this.speed)){ this.speed=Infinity; }
		if(this.speed > Math.abs(diff)){
			this.value=target;
		}else{
			this.value+=this.speed*Math.sign(diff);
		}
		this.updated=true;
		return true;
	}
	storageLocation(){
		if(!$gameVariables){
			console.warn(`MV3D: Couldn't get Blend storage location.`);
			return {};
		}
		if(!$gameVariables.mv3d){ $gameVariables.mv3d = {}; }
		return $gameVariables.mv3d;
	}
	loadValue(key){
		const storage = this.storageLocation();
		if(!(key in storage)){ return this.dfault; }
		return storage[key];
	}
	saveValue(key,value){
		const storage = this.storageLocation();
		storage[key]=value;
	}
	static reset(){
		for (const blender of Blender.list){
			blender.speed=Infinity;
		}
	}
}
Blender.list = [];

class ColorBlender{
	constructor(key,dfault,track=true){
		this.dfault=dfault;
		this.r=new Blender(`${key}_r`,dfault>>16,track);
		this.g=new Blender(`${key}_g`,dfault>>8&0xff,track);
		this.b=new Blender(`${key}_b`,dfault&0xff,track);
	}
	get updated(){
		return this.r.updated||this.g.updated||this.b.updated;
	}
	setValue(color,time){
		this.r.setValue(color>>16,time);
		this.g.setValue(color>>8&0xff,time);
		this.b.setValue(color&0xff,time);
	}
	averageCurrentValue(){
		return (this.r.value+this.g.value+this.b.value)/3|0;
	}
	averageTargetValue(){
		return (this.r.targetValue()+this.g.targetValue()+this.b.targetValue())/3|0;
	}
	currentValue(){
		return this.r.value<<16|this.g.value<<8|this.b.value;
	}
	targetValue(){
		return this.r.targetValue()<<16|this.g.targetValue()<<8|this.b.targetValue();
	}
	defaultValue(){ return this.dfault; }
	update(){
		let ret=0;
		ret|=this.r.update();
		ret|=this.g.update();
		ret|=this.b.update();
		return Boolean(ret);
	}
	get storageLocation(){ return this.r.storageLocation; }
	set storageLocation(v){
		this.r.storageLocation=v;
		this.g.storageLocation=v;
		this.b.storageLocation=v;
	}
	currentComponents(){
		return [this.r.currentValue()/255,this.g.currentValue()/255,this.b.currentValue()/255];
	}
	targetComponents(){
		return [this.r.targetValue()/255,this.g.targetValue()/255,this.b.targetValue()/255];
	}
}

mv3d.Blender=Blender;
mv3d.ColorBlender=ColorBlender;
// EXTERNAL MODULE: ./src/blendModes.js
var blendModes = __webpack_require__(7);

// CONCATENATED MODULE: ./src/input.js
const input_mv3d = window.mv3d;


input_mv3d._gamepadStick={
	x:0,
	y:0,
};


input_mv3d._touchState={
	lastX:0,
	lastY:0,
	isTouching:false,
};

Object(util["override"])(Input, '_pollGamepads',o=>function(gamepad){
	input_mv3d._gamepadStick.x=0;
	input_mv3d._gamepadStick.y=0;
	o.apply(this,arguments);
},true);

Object(util["override"])(Input, '_updateGamepadState',o=>function(gamepad){
	o.apply(this,arguments);
	const threshold = 0.1;
	const max = 1 - threshold;
	const axes = gamepad.axes;
	if (Math.abs(axes[2]) > threshold) {
		input_mv3d._gamepadStick.x -= ( axes[2] - Math.sign(axes[2])*threshold ) / max;
    }
    if (Math.abs(axes[3]) > threshold) {
        input_mv3d._gamepadStick.y -= ( axes[3] - Math.sign(axes[2])*threshold ) / max;
    }
});

Object.assign(input_mv3d,{
	updateInput(){
		input_mv3d.updateInputCamera();
	},

	updateInputCamera(){
		if(this.isDisabled()||this.lockCamera||!$gamePlayer.canMove()){ return; }
		const is1stPerson = this.is1stPerson();
		const allowRotation = this.allowRotation || is1stPerson;
		const allowPitch = this.allowPitch;
		if( allowRotation ){
			const leftKey=input_mv3d.getTurnKey('left'), rightKey=input_mv3d.getTurnKey('right');
			if(input_mv3d.TURN_INCREMENT>1){
				const turning = this.blendCameraYaw.currentValue()!==this.blendCameraYaw.targetValue();
				const yawSpeed = input_mv3d.TURN_INCREMENT / input_mv3d.YAW_SPEED;
				if(Input.isTriggered(leftKey)||Input.isPressed(leftKey)&&!turning){
					this.blendCameraYaw.setValue(this.blendCameraYaw.targetValue()+input_mv3d.TURN_INCREMENT,yawSpeed,false);
				}else if(Input.isTriggered(rightKey)||Input.isPressed(rightKey)&&!turning){
					this.blendCameraYaw.setValue(this.blendCameraYaw.targetValue()-input_mv3d.TURN_INCREMENT,yawSpeed,false);
				}
			}else{
				const increment = input_mv3d.YAW_SPEED / 60;
				if(Input.isPressed(leftKey)&&Input.isPressed(rightKey)){
					// do nothing
				}else if(Input.isPressed(leftKey)){
					this.blendCameraYaw.setValue(this.blendCameraYaw.targetValue()+increment,0.1);
				}else if(Input.isPressed(rightKey)){
					this.blendCameraYaw.setValue(this.blendCameraYaw.targetValue()-increment,0.1);
				}
			}
		}
		if( allowPitch ){
			const increment = input_mv3d.PITCH_SPEED / 60;
			if(Input.isPressed('pageup')&&Input.isPressed('pagedown')){
				// do nothing
			}else if(Input.isPressed('pageup')){
				this.blendCameraPitch.setValue(Math.min(179,this.blendCameraPitch.targetValue()+increment),0.1);
			}else if(Input.isPressed('pagedown')){
				this.blendCameraPitch.setValue(Math.max(1,this.blendCameraPitch.targetValue()-increment),0.1);
			}
		}

		if(input_mv3d.inputCameraGamepad){
			if(input_mv3d._gamepadStick.x && allowRotation){
				const increment = input_mv3d.YAW_SPEED / 60 * input_mv3d.lookSensitivity;
				this.blendCameraYaw.setValue(this.blendCameraYaw.targetValue()+input_mv3d._gamepadStick.x*increment,0.1);
			}
			if(input_mv3d._gamepadStick.y && allowPitch){
				const increment = input_mv3d.PITCH_SPEED / 60 * input_mv3d.lookSensitivity;
				this.blendCameraPitch.setValue(this.blendCameraPitch.targetValue()+input_mv3d._gamepadStick.y*increment*(input_mv3d.invertY*-2+1),0.1);
			}
		}

		if(input_mv3d.inputCameraMouse){
			input_mv3d._touchState.isTapped = !TouchInput._screenPressed && input_mv3d._touchState.touchCount>0 && input_mv3d._touchState.touchCount<15 && Math.abs(input_mv3d._touchState.deltaX)<5 && Math.abs(input_mv3d._touchState.deltaY)<5;
			if(TouchInput._screenPressed){
				if(input_mv3d._touchState.isTouching){
					input_mv3d._touchState.deltaX=TouchInput.x-input_mv3d._touchState.lastX;
					input_mv3d._touchState.deltaY=TouchInput.y-input_mv3d._touchState.lastY;
					if(input_mv3d._touchState.deltaX && allowRotation){
						const increment = input_mv3d._touchState.deltaX / Graphics.width * 180;
						this.blendCameraYaw.setValue(this.blendCameraYaw.targetValue()-increment*input_mv3d.lookSensitivity,0.1);
					}
					if(input_mv3d._touchState.deltaY && allowPitch){
						const increment = input_mv3d._touchState.deltaY / Graphics.width * 180;
						this.blendCameraPitch.setValue(this.blendCameraPitch.targetValue()-increment*input_mv3d.lookSensitivity*(input_mv3d.invertY*-2+1),0.1);
					}
					++input_mv3d._touchState.touchCount;
				}else{
					input_mv3d._touchState.isTouching=true;
				}
			}else{
				input_mv3d._touchState.isTouching=false;
				input_mv3d._touchState.touchCount=0;
			}
			input_mv3d._touchState.lastX=TouchInput.x;
			input_mv3d._touchState.lastY=TouchInput.y;
		}
	},

	getStrafeKey(keyname){
		if(input_mv3d.is1stPerson()){
			switch(input_mv3d.KEYBOARD_STRAFE){
				case 'QE': return 'rot'+keyname;
				case 'AD': return keyname;
				default: return false;
			}
		}else{
			switch(input_mv3d.KEYBOARD_TURN){
				case 'QE': return keyname;
				case 'AD': return 'rot'+keyname;
				default: return keyname;
			}
		}
	},

	getTurnKey(keyname){
		if(input_mv3d.is1stPerson()){
			switch(input_mv3d.KEYBOARD_STRAFE){
				case 'QE': return keyname;
				case 'AD': return 'rot'+keyname;
				default: return keyname;
			}
		}else{
			switch(input_mv3d.KEYBOARD_TURN){
				case 'QE': return 'rot'+keyname;
				case 'AD': return keyname;
				default: return 'rot'+keyname;
			}
		}
	},
});

Object(util["override"])(Input,'_signX',o=>function _signX(){
	if(!input_mv3d.KEYBOARD_STRAFE && input_mv3d.is1stPerson()){ return 0; }
	const leftKey=input_mv3d.getStrafeKey('left'), rightKey=input_mv3d.getStrafeKey('right');

	let x = 0;
	if (this.isPressed(leftKey)) { --x; }
	if (this.isPressed(rightKey)) { ++x; }
	return x;
});

input_mv3d.setupInput=function(){
	if(!input_mv3d.WASD){ return; }
	Object.assign(Input.keyMapper,{
		81:'rotleft',  // Q
		69:'rotright', // E
		87:'up',       // W
		65:'left',     // A
		83:'down',     // S
		68:'right',    // D
	});

	if(input_mv3d.GAMEPAD_TURN_BUTTON){
		Object.assign(Input.gamepadMapper,input_mv3d.GAMEPAD_TURN_BUTTON===1?{
			4: 'rotleft',   // LB
			5: 'rotright',  // RB
			6: 'pageup',    // LT
			7: 'pagedown',  // RT
		}:{
			4: 'pageup',    // LB
			5: 'pagedown',  // RB
			6: 'rotleft',   // LT
			7: 'rotright',  // RT
		});
	}
	const descriptors={
		rotleft:getInputDescriptor('pageup','rotleft', 'rotleft'),
		rotright:getInputDescriptor('pagedown','rotright', 'rotright'),
	}
	Object.defineProperties(Input.keyMapper,{
		81:descriptors.rotleft, //Q
		69:descriptors.rotright,//E
	});
}

function getInputDescriptor(menumode,p3mode,p1mode){
	let assignedValue=undefined;
	return {
		configurable:true,
		get(){
			if(assignedValue!=undefined){ return assignedValue; }
			if(!(SceneManager._scene instanceof Scene_Map)){ return menumode; }
			if(input_mv3d.isDisabled()){ return p3mode; }
			if(input_mv3d.is1stPerson()){ return p1mode; }
			return p3mode;
		},
		set(v){ assignedValue=v; },
	};
}

const _getInputDirection = Game_Player.prototype.getInputDirection;
Game_Player.prototype.getInputDirection = function() {
	if (input_mv3d.isDisabled()){ 
		if(input_mv3d.DIR8MOVE && input_mv3d.DIR8_2D) { return Input.dir8; }
		return _getInputDirection.apply(this,arguments);
	 }
	return input_mv3d.getInputDirection();
};

input_mv3d.getInputDirection=function(){
	let dir = input_mv3d.DIR8MOVE ? Input.dir8 : Input.dir4;
	return input_mv3d.transformDirection(dir,input_mv3d.blendCameraYaw.currentValue());
}

const input_raycastPredicate=mesh=>{
	if(!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable){ return false; }
	if(mesh.character){
		if(mesh.character.isFollower||mesh.character.isPlayer){ return false; }
	}
	return true;
}

const _process_map_touch = Scene_Map.prototype.processMapTouch;
Scene_Map.prototype.processMapTouch = function() {
	if (input_mv3d.isDisabled()){ return _process_map_touch.apply(this,arguments); }
	if (TouchInput.isTriggered() || this._touchCount > 0) {
		
		if(input_mv3d.inputCameraMouse && !input_mv3d._touchState.isTapped){
			Graphics._canvas.requestPointerLock();
			this._touchCount=0;
			return;
		}

		if (TouchInput.isPressed() || input_mv3d._touchState.isTapped) {
			
			if (this._touchCount === 0 || this._touchCount >= 15 || input_mv3d._touchState.isTapped) {
				
				input_mv3d.processMapTouch();

			}
			this._touchCount++;
		} else {
			this._touchCount = 0;
		}
	}
};

input_mv3d.processMapTouch=Object(util["throttle"])(function(){
	const intersection = input_mv3d.scene.pick(TouchInput.x*input_mv3d.RES_SCALE,TouchInput.y*input_mv3d.RES_SCALE,input_raycastPredicate);
	if(intersection.hit){
		const point = {x:intersection.pickedPoint.x, y:-intersection.pickedPoint.z};
		const mesh = intersection.pickedMesh;
		if(mesh.character){
			point.x=mesh.character.x;
			point.y=mesh.character.y;
		}
		input_mv3d.setDestination(point.x,point.y);
	}
},100);

Object(util["override"])(TouchInput,'_onMouseMove',o=>function(e){
	const allowRotation = input_mv3d.allowRotation || input_mv3d.is1stPerson();
	const allowPitch = input_mv3d.allowPitch;
	const movementX=e.movementX.clamp(-10,10);
	const movementY=e.movementY.clamp(-10,10);
	if(movementX && allowRotation){
		const increment = movementX / Graphics.width * 180 * input_mv3d.lookSensitivity;
		input_mv3d.blendCameraYaw.setValue(input_mv3d.blendCameraYaw.targetValue()-increment,0.1,false);
	}
	if(movementY && allowPitch){
		const increment = movementY / Graphics.width * 180 * input_mv3d.lookSensitivity;
		input_mv3d.blendCameraPitch.setValue(input_mv3d.blendCameraPitch.targetValue()-increment*(input_mv3d.invertY*-2+1),0.1,false);
	}
},()=> !input_mv3d.isDisabled() && !input_mv3d.lockCamera && input_mv3d.inputCameraMouse && document.pointerLockElement && input_mv3d.blendCameraYaw );

mz3d._relockPointer = false;
Object(util["override"])(Scene_Map.prototype,'isMapTouchOk',o=>function(){
	const isOk = o.apply(this,arguments);
	if(!isOk||!input_mv3d.inputCameraMouse){
		if(document.pointerLockElement){
			document.exitPointerLock();
			mz3d._relockPointer=true;
		}
	}else{
		if(!document.pointerLockElement && mz3d._relockPointer){
			Graphics._canvas.requestPointerLock();
			mz3d._relockPointer=false;
		}
		if(Input.isPressed('escape')&&document.pointerLockElement){
			document.exitPointerLock();
			mz3d._relockPointer=false;
		}
	}
	return isOk;
},true);

Object(util["override"])(Scene_Map.prototype,'stop',o=>function(){
	o.apply(this,arguments);
	document.exitPointerLock();
	if(document.pointerLockElement){mz3d._relockPointer=true;}
},true);

input_mv3d.setDestination=function(x,y){
	$gameTemp.setDestination(Math.round(x), Math.round(y));
};

const _player_findDirectionTo=Game_Player.prototype.findDirectionTo;
Game_Player.prototype.findDirectionTo=function(){
	const dir = _player_findDirectionTo.apply(this,arguments);
	if(input_mv3d.isDisabled()){ return dir; }
	if(input_mv3d.is1stPerson() && dir){
		let yaw = input_mv3d.dirToYaw(dir);

		input_mv3d.blendCameraYaw.setValue(yaw,0.25);
	}
	return dir;
}






// CONCATENATED MODULE: ./src/input_directions.js
const input_directions_mv3d = window.mv3d;



Object.assign(input_directions_mv3d,{
	
	playerFaceYaw(){
		let dir = this.yawToDir(input_directions_mv3d.blendCameraYaw.targetValue(),true);
		$gamePlayer.mv3d_setDirection(dir);
	},

	yawToDir(yaw=input_directions_mv3d.blendCameraYaw.targetValue(),dir8=false){
		const divisor = dir8?45:90;
		yaw=Math.round(yaw/divisor)*divisor;
		while(yaw<0){yaw+=360;} while(yaw>=360){yaw-=360;}
		switch(yaw){
			case 0: return 8;
			case 45: return 7;
			case 90: return 4;
			case 135: return 1;
			case 180: return 2;
			case 225: return 3;
			case 270: return 6;
			case 315: return 9;
			default: return 0;
		}
	},

	dirToYaw(dir){
		switch(dir){
			case 3: return -135;
			case 6: return -90;
			case 9: return -45;
			case 8: return 0;
			case 7: return 45;
			case 4: return 90;
			case 1: return 135;
			case 2: return 180;
			default: return NaN;
		}
	},
	
	transformDirection(dir,yaw=this.blendCameraYaw.currentValue(),dir8=input_directions_mv3d.DIR8MOVE){
		return input_directions_mv3d.yawToDir(input_directions_mv3d.dirToYaw(dir)+yaw,dir8);
	},

	transformFacing(dir,yaw=this.blendCameraYaw.currentValue(),dir8=false){
		return input_directions_mv3d.yawToDir(input_directions_mv3d.dirToYaw(dir)-yaw,dir8);
	},

	updateDirection(){
		if ( input_directions_mv3d.is1stPerson() ) {
			input_directions_mv3d.playerFaceYaw();
		}
	},
});

let _oldDir=0;
Object(util["override"])(Game_Player.prototype,'update',o=>function update(){
	o.apply(this,arguments);
	if(this._direction!==_oldDir){
		input_directions_mv3d.updateDirection();
		_oldDir=this._direction;
	}
});

Object(util["override"])(Game_Player.prototype,'moveStraight',o=>function moveStraight(){
	o.apply(this,arguments);
	input_directions_mv3d.updateDirection();
});

Object(util["override"])(Game_Player.prototype,'direction',o=>function direction(){
	if(input_directions_mv3d.is1stPerson() && this.isMoving() && !this.isDirectionFixed()){
		return input_directions_mv3d.yawToDir(input_directions_mv3d.blendCameraYaw.targetValue(),false);
	}else{
		return o.apply(this,arguments);
	}
});


const _setDirection=Game_CharacterBase.prototype.setDirection;
Game_CharacterBase.prototype.setDirection=function(){
	_setDirection.apply(this,arguments);
	this._mv3d_direction=this._direction;
};
Game_CharacterBase.prototype.mv3d_setDirection=function(d){
	if( this.isDirectionFixed() ){ return; }
	this._direction=input_directions_mv3d.yawToDir(input_directions_mv3d.dirToYaw(d),false);
	if(input_directions_mv3d.DIR8MOVE){
		this._mv3d_direction=d;
	}else{
		this._mv3d_direction=this._direction;
	}
};
Game_CharacterBase.prototype.mv3d_direction=function(){
	return this._mv3d_direction||this.direction();
};

Object(util["override"])(Game_CharacterBase.prototype,'copyPosition',o=>function(character) {
	o.apply(this,arguments);
	this._mv3d_direction = character._mv3d_direction;
});

Object(util["override"])(Game_Player.prototype,'processMoveCommand',o=>function processMoveCommand(command){
	o.apply(this,arguments);
	const  gc = Game_Character;
	switch(command.code){
		case gc.ROUTE_TURN_DOWN:
		case gc.ROUTE_TURN_LEFT:
		case gc.ROUTE_TURN_RIGHT:
		case gc.ROUTE_TURN_UP:
		case gc.ROUTE_TURN_90D_R:
		case gc.ROUTE_TURN_90D_L:
		case gc.ROUTE_TURN_180D:
		case gc.ROUTE_TURN_90D_R_L:
		case gc.ROUTE_TURN_RANDOM:
		case gc.ROUTE_TURN_TOWARD:
		case gc.ROUTE_TURN_AWAY:
			let yaw = input_directions_mv3d.dirToYaw(this._direction);
			input_directions_mv3d.blendCameraYaw.setValue(yaw,0.25);
	}
},()=>!input_directions_mv3d.isDisabled()&&input_directions_mv3d.is1stPerson());


// CONCATENATED MODULE: ./src/configuration.js
const configuration_mv3d = window.mv3d;





class ConfigurationFunction{
	constructor(parameters,func){
		this.groups = parameters.match(/\[?[^[\]|]+\]?/g);
		this.labels={};
		for(let i=0;i<this.groups.length;++i){
			while(this.groups[i]&&this.groups[i][0]==='['){
				this.labels[this.groups[i].slice(1,-1)]=i;
				this.groups.splice(i,1);
			}
			if( i > this.groups.length ){ break; }
			this.groups[i]=this.groups[i].split(',').map(s=>s.trim());
		}
		this.func=func;
	}
	run(conf,rawparams){
		const r=/([,|]+)? *(?:(\w+) *: *)?([^,|\r\n]+)/g
		let match;
		let i=0;
		let gi=0;
		const params={};
		for(let _gi=0;_gi<this.groups.length;++_gi){
			params[`group${_gi+1}`]=[];
		}
		while(match=r.exec(rawparams)){
			if(match[1])for(const delimiter of match[1]){
				if(delimiter===','){ ++i; }
				if(delimiter==='|'||i>=this.groups[gi].length){
					i=0; ++gi;
				}
			}
			if(match[2]){
				match[2] = match[2].toLowerCase();
				if(match[2] in this.labels){
					gi=this.labels[match[2]];
				}else{
					let foundMatch=false;
					grouploop:for(let _gi=0;_gi<this.groups.length;++_gi) for(let _i=0;_i<this.groups[_gi].length;++_i){
						if(this.groups[_gi][_i]===match[2]){
							foundMatch=true;
							gi=_gi; i=_i;
							break grouploop;
						}
					}
					if(!foundMatch){ break; }
				}
			}
			if(gi>this.groups.length){ break; }
			params[this.groups[gi][i]]=params[`group${gi+1}`][i]=match[3].trim();
		}
		this.func(conf,params);
	}
}
configuration_mv3d.ConfigurationFunction=ConfigurationFunction;

function TextureConfigurator(name,extraParams='',apply){
	const paramlist = `img,x,y,w,h|${extraParams}|alpha|glow[anim]animx,animy`;
	return new ConfigurationFunction(paramlist,function(conf,params){
		switch(params.group1.length){
		case 5:{
			const [img,x,y,w,h] = params.group1;
			readTextureConfigurations(name,conf,img,x,y,w,h);
			break;}
		case 4:{
			const [x,y,w,h] = params.group1;
			readTextureConfigurations(name,conf,null,x,y,w,h);
			break;}
		case 3:{
			const [img,x,y] = params.group1;
			readTextureConfigurations(name,conf,img,x,y,'1','1');
			break;}
		case 2:{
			const [x,y] = params.group1;
			readTextureConfigurations(name,conf,null,x,y,'1','1');
			break;}
		case 1:{
			const [img] = params.group1;
			readTextureConfigurations(name,conf,img,0,0,'100%','100%');
			//conf[`${name}_img`]=img;
			//conf[`${name}_id`] = 1;
			//conf[`${name}_rect`] = new PIXI.Rectangle(x,y,w,h);
			break;}
		}
		if(params.animx||params.animy){
			conf[`${name}_animData`]={ animX:Number(params.animx|0), animY:Number(params.animy|0) };
		}
		if(params.alpha){
			conf[`${name}_alpha`]=Number(params.alpha);
		}
		if(params.glow){
			if(isNaN(params.glow)){
				conf[`${name}_glow`] = Object(util["makeColor"])(params.glow);
			}else{
				conf[`${name}_glow`] = new babylon["Color4"](Number(params.glow),Number(params.glow),Number(params.glow),1);
			}
		}
		if(apply){
			apply.call(this,conf,params);
		}
	});
}

function readTextureConfigurations(name,conf,img,xstr,ystr,wstr='1',hstr='1'){
	const validImg = configuration_mv3d.validTilesheetName(img);
	if(validImg){ img=img.toUpperCase(); }
	conf[`${name}_img`]=img;
	conf[`${name}_changed`]=true;
	let hasPixelValue=false;
	let hasPercentValue=false;
	const coords=[xstr,ystr,wstr,hstr].map(str=>{
		const coord = interpretTextureCoodinate(str);
		if(coord.isPixelValue){ hasPixelValue=true; }
		if(coord.percentValue){ hasPercentValue=true; }
		return coord;
	});
	coords.forEach(coord=>{
		if(hasPixelValue){ coord.usePixelValue(); }
	});
	let [xcoord,ycoord,wcoord,hcoord]=coords;
	let [x,y,w,h] = coords.map(coord=>coord.collapseValue());
	if(hasPercentValue){
	}else if(hasPixelValue){
		if(validImg&&!xcoord.isOffsetValue&&!ycoord.isOffsetValue){
			conf[`${name}_id`] = configuration_mv3d.constructTileId(img,1,0);
			conf[`${name}_rect`] = new PIXI.Rectangle(x,y,w,h);
			return;
		}
	}else if(w===1&&h===1){
		if((!img||validImg)&&xcoord.isOffsetValue&&ycoord.isOffsetValue){
			conf[`${name}_offset`] = new babylon["Vector2"](Number(x),Number(y));
			return;
		}
		if(validImg&&!xcoord.isOffsetValue&&!ycoord.isOffsetValue){
			conf[`${name}_id`] = configuration_mv3d.constructTileId(img,x,y);
			return;
		}
	}
	wcoord.usePixelValue(); hcoord.usePixelValue();
	const textureCoords = {x:xcoord,y:ycoord,w:wcoord.collapseValue(),h:hcoord.collapseValue()};
	if(hasPercentValue){
		textureCoords.percentRect = new PIXI.Rectangle(xcoord.percentValue,ycoord.percentValue,wcoord.percentValue,hcoord.percentValue);
	}
	conf[`${name}_texture`] = textureCoords;
}

configuration_mv3d.finalizeTextureRect = function(rect,width,height){
	let {x,y,width:w,height:h} = rect;
	if(rect.percentRect){
		const pr = rect.percentRect;
		x+=pr.x*width; 
		y+=pr.y*height;
		w+=pr.width*width;
		h+=pr.height*height;
	}
	while(y>=height){
		y-=height;
		x+=width/2;
	}
	return new PIXI.Rectangle(x,y,w,h);
}

function interpretTextureCoodinate(nstr){
	const r = /(\+?-?)(\d+\.\d*|\d*\.?\d+)(px?|t|%)?/g;
	const coord = new configuration_TextureCoordinate();
	let match;
	while(match=r.exec(nstr)){
		const isRelative = Boolean(match[1]);
		const isNegative = match[1].includes('-');
		let unit = (match[3]||'t')[0];
		let num = Number(match[2]);
		if(isNegative){ num*=-1; }
		if(unit==='t'&&num%1||!match[3]&&match[2].includes('.')){ num=num*Object(util["tileSize"])(); unit='p'; }
		if(unit==='t'){
			if(isRelative) coord.offsetTileValue(num);
			else coord.setTileValue(num);
		}else if(unit==='p'){
			if(isRelative) coord.offsetPixelValue(num);
			else coord.setPixelValue(num);
		}else if(unit==='%'){
			if(isRelative) coord.offsetPercentValue(num);
			else coord.setPercentValue(num);
		}
	}
	return coord;
}

class configuration_TextureCoordinate{
	constructor(){
		this.isPixelValue=false;
		this.baseValue=null;
		this.offsetValue=0;
		this.percentValue=0;
	}
	usePixelValue(){
		if(this.isPixelValue){ return; }
		this.isPixelValue=true;
		if(this.baseValue!=null){ this.baseValue*=Object(util["tileSize"])(); }
		this.offsetValue*=Object(util["tileSize"])();
	}
	setTileValue(v){
		if(this.isPixelValue){
			this.setPixelValue(v*Object(util["tileSize"])());
			return;
		}
		this.baseValue=v;
	}
	setPixelValue(v){
		this.usePixelValue();
		this.baseValue=v;
	}
	offsetTileValue(v){
		if(this.isPixelValue){
			this.offsetPixelValue(v*Object(util["tileSize"])());
			return;
		}
		this.offsetValue+=v;
	}
	offsetPixelValue(v){
		this.usePixelValue();
		this.offsetValue+=v;
	}
	setPercentValue(v){
		this.usePixelValue();
		if(this.baseValue===null){ this.baseValue=0; }
		this.percentValue=v/100;
	}
	offsetPercentValue(v){
		this.usePixelValue();
		this.percentValue+=v/100
	}
	collapseValue(){
		return (this.baseValue||0)+this.offsetValue;
	}
	get isOffsetValue(){
		return this.baseValue==null;
	}
}

Object.assign(configuration_mv3d,{
	tilesetConfigurations:{},
	loadTilesetSettings(){
		//tileset
		this.tilesetConfigurations={};
		const lines = this.readConfigurationBlocks($gameMap.tileset().note)
		+'\n'+this.readConfigurationBlocks(this.getDataMap().note,'m[vz]3d-tiles');
		//const readLines = /^\s*([abcde]\d?\s*,\s*\d+\s*,\s*\d+)\s*:(.*)$/gmi;
		const readLines = /^\s*([abcde]\d?)\s*,\s*(\d+(?:-\d+)?)\s*,\s*(\d+(?:-\d+)?)\s*:(.*)$/gmi;
		let match;
		while(match = readLines.exec(lines)){
			const conf = this.readConfigurationFunctions(match[4],this.tilesetConfigurationFunctions);
			const range1 = match[2].split('-').map(s=>Number(s));
			const range2 = match[3].split('-').map(s=>Number(s));
			for(let kx=range1[0];kx<=range1[range1.length-1];++kx)
			for(let ky=range2[0];ky<=range2[range2.length-1];++ky){
				const key = `${match[1]},${kx},${ky}`;
				const tileId=this.constructTileId(...key.split(','));
				const appliedConf=configuration_mv3d.applyTextureConfigs(Object.assign({},conf),match[1],kx,ky);
				if(!(tileId in this.tilesetConfigurations)){
					this.tilesetConfigurations[tileId]={};
				}
				Object.assign(this.tilesetConfigurations[tileId],appliedConf);
			}

		}
	},
	mapConfigurations:{},
	loadMapSettings(){
		const dataMap = this.getDataMap();
		//map
		const mapconf=this.mapConfigurations=JSON.parse(JSON.stringify(this.MAP_DEFAULTS));
		this.readConfigurationFunctions(
			this.readConfigurationBlocks(dataMap.note),
			this.mapConfigurationFunctions,
			mapconf,
		);
		this._REGION_DATA_MAP={};
		const regionBlocks=this.readConfigurationBlocks(dataMap.note,'m[vz]3d-regions');
		if(regionBlocks){
			const readLines = /^\s*(\d+)\s*:(.*)$/gm;
			let match;
			while(match = readLines.exec(regionBlocks)){
				if(!(match[1] in this._REGION_DATA_MAP)){
					if(match[1] in this._REGION_DATA){
						this._REGION_DATA_MAP[match[1]]=JSON.parse(JSON.stringify(this._REGION_DATA[match[1]]));
					}else{
						this._REGION_DATA_MAP[match[1]]={};
					}
				}
				this.readConfigurationFunctions(
					match[2],
					configuration_mv3d.tilesetConfigurationFunctions,
					this._REGION_DATA_MAP[match[1]],
				);
			}
		}
		for (const id in this._REGION_DATA_MAP){
			this.applyTextureConfigs(this._REGION_DATA_MAP[id],'B',0,0);
			this.collapseCeilingOffsets(this._REGION_DATA_MAP[id]);
		}
	},
	applyMapSettings(){
		const mapconf = this.mapConfigurations;
		if('fog' in mapconf){
			const fog = mapconf.fog;
			if('color' in fog){ this.blendFogColor.setValue(fog.color,0); }
			if('near' in fog){ this.blendFogNear.setValue(fog.near,0); }
			if('far' in fog){ this.blendFogFar.setValue(fog.far,0); }
			this.blendFogColor.update();
		}
		if('light' in mapconf){
			this.blendAmbientColor.setValue(mapconf.light.color,0);
			//this.blendLightIntensity.setValue(mapconf.light.intensity,0);
		}
		if('cameraDist' in mapconf){
			this.blendCameraDist.setValue(mapconf.cameraDist,0);
		}
		if ('cameraHeight' in mapconf){
			this.blendCameraHeight.setValue(mapconf.cameraHeight,0);
		}
		if('cameraMode' in mapconf){
			this.cameraMode=mapconf.cameraMode;
		}
		if('cameraPitch' in mapconf){
			this.blendCameraPitch.setValue(mapconf.cameraPitch,0);
		}
		if('cameraYaw' in mapconf){
			this.blendCameraYaw.setValue(mapconf.cameraYaw,0);
		}

		this.callFeatures('applyMapSettings',mapconf);
	},

	beforeMapLoad(newmap){
		if(newmap){
			if($gameVariables.mv3d){ delete $gameVariables.mv3d.disabled; }
			delete $gamePlayer._mv3d_z;
		}
		this.callFeatures('beforeMapLoad',newmap);
	},

	afterMapLoad(newmap){
		Blender.reset();

		configuration_mv3d.updateClearColor();

		this.callFeatures('afterMapLoad',newmap);
	},
    

	getMapConfig(key,dfault){
		return this.getConfig(this.mapConfigurations,key,dfault);
	},

	getConfig(conf,key,dfault){
		if(key in conf){
			return conf[key];
		}
		return dfault;
	},

	getCeilingConfig(tileConf={}){
		let conf={};
		const reassign=entry=>{
			const [key,value] = entry;
			if(key.startsWith('ceiling_')){
				conf[key.replace('ceiling_','bottom_')]=value;
			}
		}
		Object.entries(this.mapConfigurations).forEach(reassign);
		Object.entries(tileConf).forEach(reassign);
		const getConfig=(key,dfault)=>{
			return this.getConfig(tileConf,key,this.getMapConfig(key,dfault));
		};
		conf.bottom_id = getConfig('ceiling_id',0);
		conf.height = getConfig('ceiling_height',this.CEILING_HEIGHT);
		conf.twosided = getConfig('ceiling_backface',true);
		conf.isCeiling = true;
		return conf;
	},

	readConfigurationBlocksAndTags(note,tag='m[vz]3d'){
		return this.readConfigurationBlocks(note,tag)+this.readConfigurationTags(note,tag);
	},

	readConfigurationBlocks(note,tag='m[vz]3d'){
		const findBlocks = new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`,'gi');
		let contents = '';
		let match;
		while(match = findBlocks.exec(note)){
			contents += match[1]+'\n';
		}
		return contents;
	},

	readConfigurationTags(note,tag='m[vz]3d'){
		const findTags = new RegExp(`<${tag}:([\\s\\S]*?)>`,'gi');
		let contents='';
		let match;
		while(match = findTags.exec(note)){
			contents+=match[1]+'\n';
		}
		return contents;
	},

	readConfigurationFunctions(line,functionset=configuration_mv3d.tilesetConfigurationFunctions,conf={}){
		const readConfigurations = /(\w+)\((.*?)\)/g
		let match;
		while(match = readConfigurations.exec(line)){
			const key = match[1].toLowerCase();
			if(key in functionset){
				//functionset[key](conf, ...match[2].split('|').map(s=>s?s.split(','):[]) );
				if(functionset[key] instanceof ConfigurationFunction){
					functionset[key].run(conf,match[2]);
				}else{
					const args = match[2].split(',');
					if(args.length===1 && args[0]===''){ args.length=0; }
					functionset[key](conf, ...args);
				}
			}
		}
		return conf;
	},
	get configurationSides(){ return this.enumSides; },
	get configurationShapes(){ return this.enumShapes; },
	get configurationPassage(){ return this.enumPassage; },
	enumSides:{
		front:mod_babylon["d" /* FRONTSIDE */],
		back:mod_babylon["a" /* BACKSIDE */],
		double:mod_babylon["b" /* DOUBLESIDE */],
	},
	enumShapes:{
		FLAT:1,
		TREE:2,
		BOARD:2,
		BILLBOARD:2,
		CARDBOARD:2,
		SPRITE:3,
		FENCE:4,
		WALL:5,
		CROSS:6,
		XCROSS:7,
		'8CROSS':8,
		SLOPE:9,
		MESH:91,
		MODEL:92,
	},
	enumPassage:{
		WALL:0,
		FLOOR:1,
		THROUGH:2,
	},
	enumRenderGroups:{
		BACK:0,
		MAIN:1,
		FRONT:2,
	},
    

	tilesetConfigurationFunctions:{
		width(conf,n){ conf.width=Number(n); },
		height(conf,n){ conf.height=Number(n); },
		depth(conf,n){ conf.depth=Number(n); },
		fringe(conf,n){ conf.fringe=Number(n); },
		float(conf,n){ conf.float=Number(n); },
		slope(conf,n=1,d=null){
			conf.shape=configuration_mv3d.enumShapes.SLOPE;
			conf.slopeHeight=Number(n);
			if(d){ conf.slopeDirection=({n:2, s:8, e:4, w:6})[d.toLowerCase()[0]]; }
		},
		top:TextureConfigurator('top'),
		side:TextureConfigurator('side'),
		inside:TextureConfigurator('inside'),
		bottom:TextureConfigurator('bottom'),
		north:TextureConfigurator('north'),
		south:TextureConfigurator('south'),
		east:TextureConfigurator('east'),
		west:TextureConfigurator('west'),
		texture:Object.assign(TextureConfigurator('hybrid'),{
			func(conf,params){
				configuration_mv3d.tilesetConfigurationFunctions.top.func(conf,params);
				configuration_mv3d.tilesetConfigurationFunctions.side.func(conf,params);
			}
		}),
		get ceiling(){ return configuration_mv3d.mapConfigurationFunctions.ceiling; },
		shape(conf,name,data){
			conf.shape=configuration_mv3d.enumShapes[name.toUpperCase()];
			if(conf.shape===configuration_mv3d.enumShapes.SLOPE && data||!('slopeHeight' in conf)){ conf.slopeHeight=Number(data)||1; }
			if(data){
				if(conf.shape===configuration_mv3d.enumShapes.FENCE){ conf.fencePosts=Object(util["booleanString"])(data); }
			}
		},
		alpha(conf,n){
			conf.transparent=true;
			conf.alpha=Number(n);
		},
		glow(conf,n,a=0){
			if(isNaN(n)){
				conf.glow = Object(util["makeColor"])(n);
			}else{
				conf.glow = new babylon["Color4"](Number(n),Number(n),Number(n),1);
			}
			conf.glow.a=Object(util["booleanNumber"])(a);
		},
		ambient(conf,c){
			if(isNaN(c)){
				conf.ambient = Object(util["makeColor"])(c);
			}else{
				conf.ambient = new babylon["Color3"](Number(c),Number(c),Number(c));
			}
		},
		pass(conf,s=''){
			s=Object(util["falseString"])(s.toLowerCase());
			if(!s || s[0]==='x'){
				conf.pass=configuration_mv3d.enumPassage.WALL;
			}else if(s[0]==='o'){
				conf.pass=configuration_mv3d.enumPassage.FLOOR;
			}else{
				conf.pass=configuration_mv3d.enumPassage.THROUGH;
			}
		},
		shadow(conf,b=true){
			conf.shadow=Object(util["booleanString"])(b);
		},
		rot(conf,n){ conf.rot=Number(n); },
	},
	eventConfigurationFunctions:{
		height(conf,n){
			const height = Number(n);
			if(height<0){
				conf.zoff=height;
			}else{
				conf.height=height;
			}
			Object(util["deprecated"])('event config height() is deprecated. Use elevation(), offset(), or zoff() instead.');
		},
		elevation(conf,n){ conf.height=Number(n); },
		z(conf,n){ conf.zlock=Number(n); },
		x(conf,n){ conf.xoff=Number(n); Object(util["deprecated"])('event config x() is deprecated. Use offset() or xoff() instead.'); },
		y(conf,n){ conf.yoff=Number(n); Object(util["deprecated"])('event config y() is deprecated. Use offset() or yoff() instead.'); },
		xoff(conf,n){ conf.xoff=Number(n); },
		yoff(conf,n){ conf.yoff=Number(n); },
		zoff(conf,n){ conf.zoff=Number(n); },
		offset:new ConfigurationFunction('x,y,z',function(conf,params){
			if(params.x)conf.xoff=Number(params.x);
			if(params.y)conf.yoff=Number(params.y);
			if(params.z)conf.zoff=Number(params.z);
		}),
		pos:new ConfigurationFunction('x,y,z',function(conf,params){
			if(!conf.pos){conf.pos={};}
			if(params.x){ conf.pos.x=params.x; }
			if(params.y){ conf.pos.y=params.y; }
			if(params.z){ conf.pos.z=params.z; }
		}),
		scale(conf,x,y=x){ conf.scale = new babylon["Vector2"](Number(x),Number(y)); },
		rot(conf,n){ conf.rot=Number(n); },
		yaw(conf,n){ conf.yaw=Number(n); },
		pitch(conf,n){ conf.pitch=Number(n); },
		bush(conf,bool){ conf.bush = Object(util["booleanString"])(bool); },
		shadow:new ConfigurationFunction('size,dist|3d',function(conf,params){
			let {size,dist,'3d':dyn} = params;
			if(dyn==null){ dyn=size!=null?size:true; }
			conf.dynShadow = dyn = Object(util["booleanString"])(dyn);
			if(size!=null){ conf.shadow = Object(util["booleanNumber"])(size); }
			if(dist!=null){ conf.shadowDist=Number(dist); }
		}),
		shape(conf,name){
			conf.shape=configuration_mv3d.enumShapes[name.toUpperCase()];
		},
		lamp:new ConfigurationFunction('color,intensity,range',function(conf,params){
			const {color='white',intensity=1,range=configuration_mv3d.LIGHT_DIST} = params;
			conf.lamp={color:Object(util["makeColor"])(color).toNumber(),intensity:Number(intensity),distance:Number(range)};
		}),
		flashlight:new ConfigurationFunction('color,intensity,range,angle[dir]yaw,pitch',function(conf,params){
			const {color='white',intensity=1,range=configuration_mv3d.LIGHT_DIST,angle=configuration_mv3d.LIGHT_ANGLE} = params;
			conf.flashlight={color:Object(util["makeColor"])(color).toNumber(),intensity:Number(intensity),distance:Number(range),angle:Number(angle)};
			if(params.yaw){ conf.flashlightYaw=params.yaw; }
			if(params.pitch){ conf.flashlightPitch=Number(params.pitch); }
		}),
		flashlightpitch(conf,deg='90'){ conf.flashlightPitch=Number(deg); },
		flashlightyaw(conf,deg='+0'){ conf.flashlightYaw=deg; },
		lightoffset:new ConfigurationFunction('x,y,z',function(conf,params){
			if(params.x){ conf.lampXoff = conf.flashlightXoff = +params.x; }
			if(params.y){ conf.lampYoff = conf.flashlightYoff = +params.y; }
			if(params.z){ conf.lampZoff = conf.flashlightZoff = +params.z; }
		}),
		lampoffset:new ConfigurationFunction('x,y,z',function(conf,params){
			if(params.x){ conf.lampXoff = +params.x; }
			if(params.y){ conf.lampYoff = +params.y; }
			if(params.z){ conf.lampZoff = +params.z; }
		}),
		flashlightoffset:new ConfigurationFunction('x,y,z',function(conf,params){
			if(params.x){ conf.flashlightXoff = +params.x; }
			if(params.y){ conf.flashlightYoff = +params.y; }
			if(params.z){ conf.flashlightZoff = +params.z; }
		}),
		lightheight(conf,n=1){
			Object(util["deprecated"])('event lightHeight() is deprecated. Use lightOffset(z:) instead.');
			conf.lampZoff = conf.flashlightZoff = +n;
		},
		lampheight(conf,n=1){
			conf.lampZoff = Number(n);
			Object(util["deprecated"])('event lampHeight() is deprecated. Use lampOffset(z:) instead.');
		},
		flashlightheight(conf,n=1){
			Object(util["deprecated"])('event flashlightheight() is deprecated. Use flashlightOffset(z:) instead.');
			conf.flashlightZoff = Number(n);
		},
		
		alpha(conf,n){
			conf.alpha=Number(n);
		},
		glow(conf,n,a=0){
			if(isNaN(n)){
				conf.glow = Object(util["makeColor"])(n);
			}else{
				conf.glow = new babylon["Color4"](Number(n),Number(n),Number(n),1);
			}
			conf.glow.a=Object(util["booleanNumber"])(a);
		},
		get ambient(){ return configuration_mv3d.tilesetConfigurationFunctions.ambient; },
		dirfix(conf,b){
			conf.dirfix=Object(util["booleanString"])(b);
		},
		gravity(conf,b){
			conf.gravity=Object(util["booleanNumber"])(b);
		},
		platform(conf,b){
			conf.platform=Object(util["booleanString"])(b);
		},
		collide(conf,n){ conf.collide=Object(util["booleanNumber"])(n); },
		trigger(conf,up,down=0){
			conf.trigger={
				up:Number(up),
				down:Number(down),
			}
		},
		pass(conf,s=''){
			s=Object(util["falseString"])(s.toLowerCase());
			if(!s || s[0]==='x'){
				conf.platform=false;
				conf.collide=true;
			}else if(s[0]==='o'){
				conf.platform=true;
				if(conf.collide===false||conf.collide==null)conf.collide=true;
			}else{
				conf.platform=false;
				conf.collide=false;
			}
		},
		texture:(()=>{
			const configurator = TextureConfigurator('texture');
			return new ConfigurationFunction('img,x,y,w,h',(conf,params)=>{
				let img;
				if (params.img){
					img=(configuration_mv3d.validTilesheetName(params.img)?params.img.toUpperCase():params.img)||'B';
				}else{
					img=configuration_mv3d.getSetName(conf._eventTileId||0);
				}
				const defaultTileId = `TILE_ID_${img}` in Tilemap ? Tilemap[`TILE_ID_${img}`] : 0;
				delete conf.texture_id;
				delete conf.texture_img;
				delete conf.texture_rect;
				delete conf.texture_offset;
				delete conf.texture_texture;
				configurator.func(conf,params);
				let tx=0,ty=0;
				if(conf._eventTileId!==undefined){
					tx=conf._eventTileId%8||0;
					ty=Math.floor((conf._eventTileId-defaultTileId)/8);
				}
				configuration_mv3d.applyTextureSideConfigs(conf,'texture',img||'B',tx,ty);
				configuration_mv3d._tileTextureOffset(conf,'texture',defaultTileId,defaultTileId);
				conf.texture_symbol=Symbol(`${img},${params.x},${params.y},${params.w},${params.h}`);
			});
		})(),
	},
	mapConfigurationFunctions:{
		get ambient(){ return this.light; },
		light(conf,color){
			if(color.toLowerCase()==='default'){ color=configuration_mv3d.AMBIENT_COLOR; }
			else{ color=Object(util["makeColor"])(color).toNumber(); }
			conf.light={color:color};
		},
		fog:new ConfigurationFunction('color|near,far',function(conf,params){
			const {color,near,far} = params;
			if(!conf.fog){ conf.fog={}; }
			if(color){ conf.fog.color=Object(util["makeColor"])(color).toNumber(); }
			if(near){ conf.fog.near=Number(near); }
			if(far){ conf.fog.far=Number(far); }
		}),
		camera:new ConfigurationFunction('yaw,pitch|dist|height|mode',function(conf,params){
			const {yaw,pitch,dist,height,mode}=params;
			if(yaw){ conf.cameraYaw=Number(yaw); }
			if(pitch){ conf.cameraPitch=Number(pitch) }
			if(dist){ conf.cameraDist=Number(dist); }
			if(height){ conf.cameraHeight=Number(height); }
			if(mode){ conf.cameraMode=mode; }
		}),
		ceiling:TextureConfigurator('ceiling','height,backface',function(conf,params){
			if(params.height){
				conf[`ceiling_height`]=Number(params.height);
			}
			if(params.backface){
				conf[`ceiling_backface`]=Object(util["booleanString"])(params.backface);
			}
		}),
		edge(conf,b,data){
			b=b.toLowerCase();
			switch(b){
				case 'clamp':
					conf.edgeData=data==null?1:Number(data);
					conf.edge=b;
					break;
				default:
					conf.edge=Object(util["booleanString"])(b);
			}
		},
		disable(conf,b=true){
			conf.disabled=Object(util["booleanString"])(b);
		},
		enable(conf,b=true){
			conf.disabled=!Object(util["booleanString"])(b);
		},
		base(conf,n){
			conf.baseHeight=Number(n);
		},
	},

	validTilesheetName(img){
		return /^(?:a[12345]|[bcde])$/i.test(img);
	},
	applyTextureConfigs(conf,img,tx,ty){
		for (const side of ['top','side','inside','bottom','north','south','east','west','ceiling']){
			this.applyTextureSideConfigs(conf,side,img,tx,ty);
		}
		return conf;
	},
	applyTextureSideConfigs(conf,side,img,tx,ty){
		let textureCoords = conf[`${side}_texture`];
		if(`${side}_img` in conf){ img=conf[`${side}_img`]; }
		//else{ conf[`${side}_img`]=img; }
		if(textureCoords){
			const {x:xcoord,y:ycoord,w,h}=textureCoords;
			if(!xcoord.isPixelValue){
				if(xcoord.isOffsetValue){ tx+=xcoord.offsetValue; }
				else{ tx=xcoord.collapseValue(); }
			}
			if(!ycoord.isPixelValue){
				if(ycoord.isOffsetValue){ ty+=ycoord.offsetValue; }
				else{ ty=ycoord.collapseValue(); }
			}
			let corner;
			const validImg=configuration_mv3d.validTilesheetName(img);
			if(validImg){
				let id=this.constructTileId(img,tx,ty);
				corner = configuration_mv3d.getTileCorner(id);
				corner.x*=Object(util["tileWidth"])(); corner.y*=Object(util["tileHeight"])();
			}else{
				corner={x:tx*Object(util["tileWidth"])(),y:ty*Object(util["tileHeight"])()};
			}
			if(xcoord.isPixelValue){
				if(xcoord.isOffsetValue){ corner.x+=xcoord.offsetValue; }
				else{ corner.x=xcoord.collapseValue(); }
			}
			if(ycoord.isPixelValue){
				if(ycoord.isOffsetValue){ corner.y+=ycoord.offsetValue; }
				else{ corner.y=ycoord.collapseValue(); }
			}
			
			const rect = new PIXI.Rectangle(corner.x,corner.y,w,h);
			if(textureCoords.percentRect){
				rect.percentRect=textureCoords.percentRect;
			}
			conf[`${side}_id`] = validImg?configuration_mv3d.constructTileId(img,1,0):1;
			conf[`${side}_rect`]=rect;
		}
	},
	collapseCeilingOffsets(conf){
		const img = conf.ceiling_img||'B';
		let defaultTileId = `TILE_ID_${img}` in Tilemap ? Tilemap[`TILE_ID_${img}`] : 0;
		this._tileTextureOffset(conf,'ceiling',defaultTileId,defaultTileId);
	},

});

// event config
const _event_setupPage = Game_Event.prototype.setupPage;
Game_Event.prototype.setupPage = function() {
	_event_setupPage.apply(this,arguments);
	if(this.mv3d_sprite){
		this.mv3d_needsConfigure=true;
		this.mv3d_sprite.eventConfigure();
	}
};

const _event_init = Game_Event.prototype.initialize;
Game_Event.prototype.initialize = async function() {
	_event_init.apply(this,arguments);
	const event = this.event();
	let config = {};
	configuration_mv3d.readConfigurationFunctions(
		configuration_mv3d.readConfigurationTags(event.note),
		configuration_mv3d.eventConfigurationFunctions,
		config,
	);
	if('pos' in config){
		const pos = config.pos;
		if('x' in pos||'y' in pos){
			this.locate(
				Object(util["relativeNumber"])(event.x,pos.x),
				Object(util["relativeNumber"])(event.y,pos.y),
			);
		}
		if('z' in pos){
			this._mv3d_z = Object(util["relativeNumber"])(configuration_mv3d.getWalkHeight(event.x,event.y),pos.z);
		}
	}
	if(!this.mv3d_blenders){
		this.mv3d_blenders={};
	}
	if('lamp' in config){
		this.mv3d_blenders.lampColor_r=config.lamp.color>>16;
		this.mv3d_blenders.lampColor_g=config.lamp.color>>8&0xff;
		this.mv3d_blenders.lampColor_b=config.lamp.color&0xff;
		this.mv3d_blenders.lampIntensity=config.lamp.intensity;
		this.mv3d_blenders.lampDistance=config.lamp.distance
	}
	if('flashlight' in config){
		this.mv3d_blenders.flashlightColor_r=config.flashlight.color>>16;
		this.mv3d_blenders.flashlightColor_g=config.flashlight.color>>8&0xff;
		this.mv3d_blenders.flashlightColor_b=config.flashlight.color&0xff;
		this.mv3d_blenders.flashlightIntensity=config.flashlight.intensity;
		this.mv3d_blenders.flashlightDistance=config.flashlight.distance;
		this.mv3d_blenders.flashlightAngle=config.flashlight.angle;
	}
	if('flashlightPitch' in config){
		this.mv3d_blenders.flashlightPitch=Number(config.flashlightPitch);
	}
	if('flashlightYaw' in config){
		this.mv3d_blenders.flashlightYaw=config.flashlightYaw;
	}
	this.mv3d_needsConfigure=true;

	await Object(util["sleep"])();
	if(configuration_mv3d.mapLoaded){
		configuration_mv3d.createCharacterFor(this);
	}
};
// CONCATENATED MODULE: ./src/plugin_commands.js
const plugin_commands_mv3d = window.mv3d;


const _pluginCommand = Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function(command, args) {
	if(command.toLowerCase() !== 'mv3d'){
		return _pluginCommand.apply(this,arguments);
	}
	runPluginCommand(this,args);
};

function runPluginCommand(interpreter,args){
	const pc = new plugin_commands_mv3d.PluginCommand();
	pc.INTERPRETER=interpreter;
	pc.FULL_COMMAND=['mv3d',...args].join(' ');
	args=args.filter(v=>v);
	pc.CHAR=$gameMap.event(interpreter._eventId)||$gamePlayer;
	if(args[0]){
		const firstChar = args[0][0];
		if(firstChar==='@'||firstChar==='＠'){
			pc.CHAR = pc.TARGET_CHAR(args.shift());
		}
	}

	const com = args.shift().toLowerCase();
	if(com in pc){
		pc[com](...args);
	}
}

plugin_commands_mv3d.PluginCommand=class{
	async animation(id,...a){
		const char = (await this.AWAIT_CHAR(this.CHAR)).char;
		char.requestAnimation(id);
		if(plugin_commands_mv3d.isDisabled()){ return; }
		let depth=true, scale=1;
		for(let i=0;i<a.length;++i){
			switch(a[i].toLowerCase()){
				case 'depth': if(a[i+1]!=null)depth=Object(util["booleanString"])(a[i+1]); break;
				case 'scale': if(a[i+1]!=null)scale=Number(a[i+1]); break;
			}
		}
		char._mv3d_animationSettings={depth,scale};
	}
	resolution(...a){
		let i=0;
		if(a[i].toLowerCase()==='scale'){ ++i; }
		let time=this._TIME(a[2]);
		this._RELATIVE_BLEND(plugin_commands_mv3d.blendResolutionScale,a[1],time);
	}
	camera(...a){
		let time=this._TIME(a[2]);
		switch(a[0].toLowerCase()){
			case 'pitch'    : this.pitch (a[1],time); return;
			case 'yaw'      : this.yaw   (a[1],time); return;
			case 'roll'     : this.roll  (a[1],time); return;
			case 'dist'     :
			case 'distance' : this.dist  (a[1],time); return;
			case 'zoom'     : this.zoom  (a[1],time); return;
			case 'height'   : this.height(a[1],time); return;
			case 'mode'     : this.cameramode(a[1]); return;
			case 'follow'   :
			case 'target'   : this._cameraTarget(a[1],time); return;
			case 'track'    : this._cameraTrack(...a); return
			case 'pan'      : this.pan(a[1],a[2],a[3]); return;
		}
	}
	yaw(deg,time=1){
		this._RELATIVE_BLEND(plugin_commands_mv3d.blendCameraYaw,deg,time);
		if ( plugin_commands_mv3d.is1stPerson() ) { plugin_commands_mv3d.playerFaceYaw(); }
	}
	pitch(deg,time=1){ this._RELATIVE_BLEND(plugin_commands_mv3d.blendCameraPitch,deg,time); }
	roll(deg,time=1){ this._RELATIVE_BLEND(plugin_commands_mv3d.blendCameraRoll,deg,time); }
	dist(n,time=1){ this._RELATIVE_BLEND(plugin_commands_mv3d.blendCameraDist,n,time); }
	zoom(n,time=1){ this._RELATIVE_BLEND(plugin_commands_mv3d.blendCameraZoom,n,time); }
	height(n,time=1){ this._RELATIVE_BLEND(plugin_commands_mv3d.blendCameraHeight,n,time); }
	_cameraTarget(target,time){
		plugin_commands_mv3d.setCameraTarget(this.TARGET_CHAR(target), time);
	}
	_cameraTrack(...a){
		a.shift();
		let mode = 3;
		switch(a[0].toLowerCase()){
			case 'pitch': mode=2; a.shift(); break;
			case 'yaw': mode=1; a.shift(); break;
		}
		let target = Object(util["falseString"])(a[0]);
		if(target){ target = this.TARGET_CHAR(target); }
		const time = this._TIME(a[1]);
		plugin_commands_mv3d.setCameraTrack(target,time,mode);
	}
	pan(x,y,time=1){
		console.log(x,y,time);
		time=this._TIME(time);
		this._RELATIVE_BLEND(plugin_commands_mv3d.blendPanX,x,time);
		this._RELATIVE_BLEND(plugin_commands_mv3d.blendPanY,y,time);
	}

	get rotationmode(){ return this.allowrotation; }
	get pitchmode(){ return this.allowpitch; }

	allowrotation(b){ plugin_commands_mv3d.allowRotation = Object(util["booleanString"])(b); }
	allowpitch(b){ plugin_commands_mv3d.allowPitch = Object(util["booleanString"])(b); }
	lockcamera(b){ plugin_commands_mv3d.lockCamera = Object(util["booleanString"])(b); }

	cameramode(mode){ plugin_commands_mv3d.cameraMode=mode; }
	fog(...a){
		var time=this._TIME(a[2]);
		switch(a[0].toLowerCase()){
			case 'color': this._fogColor(a[1],time); return;
			case 'near': this._fogNear(a[1],time); return;
			case 'far': this._fogFar(a[1],time); return;
			case 'dist': case 'distance':
				time=this._TIME(a[3]);
				this._fogNear(a[1],time);
				this._fogFar(a[2],time);
				return;
		}
		time=this._TIME(a[3]);
		this._fogColor(a[0],time);
		this._fogNear(a[1],time);
		this._fogFar(a[2],time);
	}
	_fogColor(color,time){ plugin_commands_mv3d.blendFogColor.setValue(Object(util["makeColor"])(color).toNumber(),time); }
	_fogNear(n,time){ this._RELATIVE_BLEND(plugin_commands_mv3d.blendFogNear,n,time); }
	_fogFar(n,time){ this._RELATIVE_BLEND(plugin_commands_mv3d.blendFogFar,n,time); }
	get ambient(){ return this.light; }
	light(...a){
		var time=this._TIME(a[2]);
		switch(a[0].toLowerCase()){
			case 'color'    : this._lightColor    (a[1],time); return;
			//case 'intensity': this._lightIntensity(a[1],time); return;
		}
		time=this._TIME(a[1]);
		this._lightColor(a[0],time);
		//this._lightintensity(a[0],time);
	}
	_lightColor(color,time=1){ plugin_commands_mv3d.blendAmbientColor.setValue(Object(util["makeColor"])(color).toNumber(),time); }
	//_lightIntensity(n,time=1){ this._RELATIVE_BLEND(mv3d.blendLightIntensity,n,time); }
	async lamp(...a){
		const char = await this.AWAIT_CHAR(this.CHAR);
		char.setupLamp();
		var time=this._TIME(a[2]);
		switch(a[0].toLowerCase()){
			case 'color'    : this._lampColor    (char,a[1],time); return;
			case 'intensity': this._lampIntensity(char,a[1],time); return;
			case 'dist'     :
			case 'distance' : this._lampDistance (char,a[1],time); return;
		}
		time=this._TIME(a[3]);
		this._lampColor(char,a[0],time);
		this._lampIntensity(char,a[1],time);
		this._lampDistance(char,a[2],time);
	}
	_lampColor(char,color,time=1){ char.blendLampColor.setValue(Object(util["makeColor"])(color).toNumber(),time); }
	_lampIntensity(char,n,time=1){ this._RELATIVE_BLEND(char.blendLampIntensity,n,time); }
	_lampDistance(char,n,time=1){ this._RELATIVE_BLEND(char.blendLampDistance,n,time); }
	async flashlight(...a){
		const char = await this.AWAIT_CHAR(this.CHAR);
		char.setupFlashlight();
		var time=this._TIME(a[2]);
		switch(a[0].toLowerCase()){
			case 'color'    : this._flashlightColor    (char,a[1],time); return;
			case 'intensity': this._flashlightIntensity(char,a[1],time); return;
			case 'dist'     :
			case 'distance' : this._flashlightDistance (char,a[1],time); return;
			case 'angle'    : this._flashlightAngle    (char,a[1],time); return;
			case 'yaw'      : this._flashlightYaw      (char,a[1]); return;
			case 'pitch'    : this._flashlightPitch    (char,a[1],time); return;
		}
		time=this._TIME(a[4]);
		this._flashlightColor(char,a[0],time);
		this._flashlightIntensity(char,a[1],time);
		this._flashlightDistance(char,a[2],time);
		this._flashlightAngle(char,a[3],time);
	}
	_flashlightColor(char,color,time){ char.blendFlashlightColor.setValue(Object(util["makeColor"])(color).toNumber(),time); }
	_flashlightIntensity(char,n,time){ this._RELATIVE_BLEND(char.blendFlashlightIntensity,n,time); }
	_flashlightDistance(char,n,time){ this._RELATIVE_BLEND(char.blendFlashlightDistance,n,time); }
	_flashlightAngle(char,n,time){ this._RELATIVE_BLEND(char.blendFlashlightAngle,n,time); }
	_flashlightPitch(char,n,time){ this._RELATIVE_BLEND(char.blendFlashlightPitch,n,time); }
	_flashlightYaw(char,yaw){ this.configure(`flashlightYaw(${yaw})`); }
	async elevation(...a){
		const char = await this.AWAIT_CHAR(this.CHAR);
		let time=this._TIME(a[1]);
		this._RELATIVE_BLEND(char.blendElevation,a[0],time);
	}
	async configure(...a){
		const char = await this.AWAIT_CHAR(this.CHAR);
		plugin_commands_mv3d.readConfigurationFunctions(
			a.join(' '),
			plugin_commands_mv3d.eventConfigurationFunctions,
			char.settings,
		);
		char.pageConfigure(char.settings);
	}
	set(key,...a){
		key=key.toLowerCase();
		const value=a.join(' ');
		if(key in plugin_commands_mv3d.attributes){
			plugin_commands_mv3d.attributes[key]=value;
		}
	}
	disable(fadeType){ plugin_commands_mv3d.disable(fadeType); }
	enable(fadeType){ plugin_commands_mv3d.enable(fadeType); }
	get _RELATIVE_BLEND(){ return util["relativeBlend"]; }
	_TIME(time){
		if(typeof time==='number'){ return time; }
		time=Number(time);
		if(Number.isNaN(time)){ return 1; }
		return time;
	}
	ERROR_CHAR(){
		console.warn(`MV3D: Plugin command \`${this.FULL_COMMAND}\` failed because target character was invalid.`);
		//console.log(this.CHAR);
	}
	async AWAIT_CHAR(char){
		if(!plugin_commands_mv3d.characters.length){
			plugin_commands_mv3d.createCharacters();
		}
		if(!char){ return this.ERROR_CHAR(); }
		let w=0;
		while(!char.mv3d_sprite){
			await Object(util["sleep"])(100);
			if(++w>10){ return this.ERROR_CHAR(); }
		}
		return char.mv3d_sprite;
	}
	TARGET_CHAR(target){
		return plugin_commands_mv3d.targetChar(target,$gameMap.event(this.INTERPRETER._eventId),this.CHAR);
	}
};

plugin_commands_mv3d.targetChar=function(target,self=null,dfault=self){
	if(!target){ return dfault; }
	let m=target.toLowerCase().match(/[a-z]+/);
	const mode=m?m[0]:'e';
	m=target.match(/\d+/);
	const id=m?Number(m[0]):0;
	switch(mode[0]){
		case 's': return self;
		case 'p': return $gamePlayer;
		case 'e':
			if(!id){ return self; }
			return $gameMap.event(id);
		case 'v':
			return $gameMap.vehicle(id);
		case 'f':
			return $gamePlayer.followers()._data[id];
	}
	return char;
}
plugin_commands_mv3d.getTargetString=function(char){
	if( char instanceof Game_Player){
		return `@p`;
	}
	if( char instanceof Game_Event ){
		return `@e${char._eventId}`;
	}
	if( char instanceof Game_Follower){
		return `@f${$gamePlayer._followers._data.indexOf(char)}`;
	}
	if( char instanceof Game_Vehicle){
		return `@v${$gameMap._vehicles.indexOf(char)}`;
	}
}

Game_CharacterBase.prototype.mv3d_requestAnimation = function(id,opts={}) {
	this.requestAnimation(id);
	this._mv3d_animationSettings=opts;
};

Game_Character.prototype.mv3d_configure = function(data){
	plugin_commands_mv3d.readConfigurationFunctions(
		data,
		plugin_commands_mv3d.eventConfigurationFunctions,
		this.mv3d_settings,
	);
	if(this.mv3d_sprite){
		this.mv3d_sprite.pageConfigure(this.mv3d_settings);
	}
};

plugin_commands_mv3d.command=function(...s){
	s=s.join(' ').split(' ');
	runPluginCommand({
		_mapId: $gameMap.mapId(),
		_eventId: 0,
	},s);
};
// CONCATENATED MODULE: ./src/MapCellBuilder.js
const MapCellBuilder_mz3d = window.mz3d;



class MapCellBuilder_CellMeshBuilder{
	constructor(){
		this.submeshBuilders={};
	}
	build(){
		const submeshBuildersArray=Object.values(this.submeshBuilders);
		if(!submeshBuildersArray.length){ return null; }
		const submeshes = submeshBuildersArray.map(builder=>builder.build());
		const totalVertices = submeshes.reduce((total,mesh)=>{
			if(typeof total!=='number'){ total=total.getTotalVertices(); }
			return total+mesh.getTotalVertices();
		});
		const mesh = babylon["Mesh"].MergeMeshes(submeshes,true,totalVertices>64000,undefined,false,true);
		return mesh;
	}
	getBuilder(material){
		if(!(material.name in this.submeshBuilders)){
			this.submeshBuilders[material.name] = new MapCellBuilder_SubMeshBuilder(material);
		}
		return this.submeshBuilders[material.name];
	}
	addWallFace(material,rect,x,y,z,w,h,rot,options={}){
		const builder = this.getBuilder(material);
		const uvRect = MapCellBuilder_SubMeshBuilder.getUvRect(material.diffuseTexture,rect);
		builder.addWallFace(x,y,z,w,h,rot,uvRect,options);
		if(options.double){
			options.flip=!options.flip;
			builder.addWallFace(x,y,z,w,h,rot,uvRect,options);
		}
	}
	addFloorFace(material,rect,x,y,z,w,h,options={}){
		const builder = this.getBuilder(material);
		const uvRect = MapCellBuilder_SubMeshBuilder.getUvRect(material.diffuseTexture,rect);
		builder.addFloorFace(x,y,z,w,h,uvRect,options);
		if(options.double){
			options.flip=!options.flip;
			builder.addFloorFace(x,y,z,w,h,uvRect,options);
		}
	}
	addSlopeFace(material,rect,x,y,z,w,h,rot,options={}){
		const builder = this.getBuilder(material);
		const uvRect = MapCellBuilder_SubMeshBuilder.getUvRect(material.diffuseTexture,rect);
		builder.addSlopeFace(x,y,z,w,h,rot,uvRect,options);
		if(options.double){
			options.flip=!options.flip;
			builder.addSlopeFace(x,y,z,w,h,rot,uvRect,options);
		}
	}
	addSlopeSide(material,rect,x,y,z,w,h,rot,options={}){
		const builder = this.getBuilder(material);
		const uvRect = MapCellBuilder_SubMeshBuilder.getUvRect(material.diffuseTexture,rect);
		builder.addSlopeSide(x,y,z,w,h,rot,uvRect,options);
		if(options.double){
			options.flip=!options.flip;
			builder.addSlopeSide(x,y,z,w,h,rot,uvRect,options);
		}
	}
}

class MapCellBuilder_SubMeshBuilder{
	constructor(material){
		this.material=material;
		this.positions=[];
		this.indices=[];
		this.normals=[];
		this.uvs=[];
	}
	build(){
		const mesh = new babylon["Mesh"]('cell mesh', MapCellBuilder_mz3d.scene);
		//VertexData.ComputeNormals(this.positions,this.indices,this.normals);
		const vdata = new babylon["VertexData"]();
		vdata.positions=this.positions;
		vdata.indices=this.indices;
		vdata.normals=this.normals;
		vdata.uvs=this.uvs;
		vdata.applyToMesh(mesh);
		mesh.material=this.material;
		return mesh;
	}
	addWallFace(x,z,y,w,h,rot,uvr,options){
		z=-z;y=y;
		const xf=Object(util["cos"])(rot);
		const zf=Object(util["sin"])(rot);
		const ww=w/2, hh=h/2;
		const positions = [
			x-ww*xf, y+hh, z+ww*zf,
			x+ww*xf, y+hh, z-ww*zf,
			x-ww*xf, y-hh, z+ww*zf,
			x+ww*xf, y-hh, z-ww*zf,
		];
		let normals = [ -zf,0,-xf, -zf,0,-xf, -zf,0,-xf, -zf,0,-xf ];
		const uvs = MapCellBuilder_SubMeshBuilder.getDefaultUvs(uvr);
		const indices=MapCellBuilder_SubMeshBuilder.getDefaultIndices();
		if(options.flip){ MapCellBuilder_SubMeshBuilder.flipFace(indices,normals); }
		if(options.abnormal){ normals=[ 0,1,0, 0,1,0, 0,1,0, 0,1,0]; }
		this.pushNewData(positions,indices,normals,uvs);
	}
	addFloorFace(x,z,y,w,h,uvr,options){
		z=-z;y=y;
		//const f=Boolean(options.flip)*-2+1;
		//const ww=f*w/2, hh=h/2;
		const ww=w/2, hh=h/2;
		const positions = [
			x-ww, y, z+hh,
			x+ww, y, z+hh,
			x-ww, y, z-hh,
			x+ww, y, z-hh,
		];
		//const normals=[ 0,f,0, 0,f,0, 0,f,0, 0,f,0 ];
		const normals=[ 0,1,0, 0,1,0, 0,1,0, 0,1,0 ];
		const uvs = MapCellBuilder_SubMeshBuilder.getDefaultUvs(uvr);
		const indices=MapCellBuilder_SubMeshBuilder.getDefaultIndices();
		if(options.flip){ MapCellBuilder_SubMeshBuilder.flipFace(indices,normals); }
		this.pushNewData(positions,indices,normals,uvs);
	}
	addSlopeFace(x,z,y,w,h,rot,uvr,options){
		z=-z;y=y;
		const xf=Object(util["cos"])(rot);
		const zf=Object(util["sin"])(rot);
		const ww=w/2, hh=h/2;
		const positions = options.autotile ? [
			x-ww, y+hh+hh*Math.round(Object(util["sin"])(-rot+util["PI"]*1/4)), z+ww,
			x+ww, y+hh+hh*Math.round(Object(util["sin"])(-rot+util["PI"]*3/4)), z+ww,
			x-ww, y+hh+hh*Math.round(Object(util["sin"])(-rot+util["PI"]*7/4)), z-ww,
			x+ww, y+hh+hh*Math.round(Object(util["sin"])(-rot+util["PI"]*5/4)), z-ww,
		] : [
			x-ww*xf+ww*zf, y+h, z+ww*zf+ww*xf,
			x+ww*xf+ww*zf, y+h, z-ww*zf+ww*xf,
			x-ww*xf-ww*zf, y, z+ww*zf-ww*xf,
			x+ww*xf-ww*zf, y, z-ww*zf-ww*xf,
		];
		const hn=Math.pow(2,-h);
		const ihn=1-hn;
		const normals=[ -zf*ihn,hn,-xf*ihn, -zf*ihn,hn,-xf*ihn, -zf*ihn,hn,-xf*ihn, -zf*ihn,hn,-xf*ihn ];
		let uvs = MapCellBuilder_SubMeshBuilder.getDefaultUvs(uvr);
		const indices=MapCellBuilder_SubMeshBuilder.getDefaultIndices();
		if(options.flip){ MapCellBuilder_SubMeshBuilder.flipFace(indices,normals); }
		this.pushNewData(positions,indices,normals,uvs);
	}
	addSlopeSide(x,z,y,w,h,rot,uvr,options){
		z=-z;y=y;
		const xf=Object(util["cos"])(rot);
		const zf=Object(util["sin"])(rot);
		const ww=w/2, hh=h/2;
		const positions = [
			x-ww*xf, y+h, z+ww*zf,
			x-ww*xf, y, z+ww*zf,
			x+ww*xf, y, z-ww*zf,
		];
		const normals=[ -zf,0,-xf, -zf,0,-xf, -zf,0,-xf ];
		const uvs = [
			uvr.x1,uvr.y1,
			uvr.x1,uvr.y2,
			uvr.x2,uvr.y2,
		];
		const indices=[0,1,2];
		if(options.flip){ MapCellBuilder_SubMeshBuilder.flipFace(indices,normals); }
		this.pushNewData(positions,indices,normals,uvs);
	}
	pushNewData(positions,indices,normals,uvs){
		this.indices.push(...indices.map(i=>i+this.positions.length/3));
		this.positions.push(...positions);
		this.normals.push(...normals);
		this.uvs.push(...uvs);
	}
	static getUvRect(tsTexture,rect){
		const { width, height } = tsTexture.getBaseSize();
		rect = MapCellBuilder_mz3d.finalizeTextureRect(rect,width,height);
		let {x,y,width:w,height:h} = rect;
		if(MapCellBuilder_mz3d.EDGE_FIX){ x+=MapCellBuilder_mz3d.EDGE_FIX;y+=MapCellBuilder_mz3d.EDGE_FIX;w-=MapCellBuilder_mz3d.EDGE_FIX*2;h-=MapCellBuilder_mz3d.EDGE_FIX*2; }
		return {
			x1:x/width,
			y1:(height-y)/height,
			x2:(x+w)/width,
			y2:(height-y-h)/height,
		};
	}
	static getDefaultUvs(uvr){
		return [
			uvr.x1,uvr.y1,
			uvr.x2,uvr.y1,
			uvr.x1,uvr.y2,
			uvr.x2,uvr.y2,
		];
	}
	static getDefaultIndices(){ return [1,0,2,1,2,3]; }
	static flipFace(indices,normals){
		indices.reverse();
		for(let i=0;i<normals.length;++i){ normals[i]*=-1; }
	}
}
// CONCATENATED MODULE: ./src/model.js
const model_mz3d = window.mz3d;



const modelInstanceCache={};
model_mz3d.modelInstanceCache=modelInstanceCache;

const orphanModelList=[];

model_mz3d.clearModelCache=function(){
	for (const key in modelInstanceCache){
		const mesh = modelInstanceCache[key];
		delete modelInstanceCache[key];
		mesh.dispose(false,true);
	}
};

class model_Model extends babylon["TransformNode"]{
	constructor(opts={}){
		super('model',model_mz3d.scene);
		this.mesh=null;
		this.textureLoaded=false;
		const {orphan=true}=opts;
		if(orphan){ orphanModelList.push(this); }
	}
	get meshes(){ return this.mesh instanceof model_MeshGroup ? this.mesh.meshes : this.mesh ? [this.mesh] : []; }
	get materials(){ return !this.mesh ? [] : this.mesh.mv3d_materials ? this.mesh.mv3d_materials : this.material ? [this.material] : []; }
	setupMesh(){
		if(!this.mesh||this.mesh.mv3d_isSetup){ return; }
		this.mesh.mv3d_isSetup=true;
		model_mz3d.callFeatures('createCharMesh',this.mesh);
		this.mesh.parent=this;
		this.mesh.yaw=0;
		this.mesh.pitch=0;
		if(this.shape===model_mz3d.enumShapes.XCROSS){
			this.mesh.yaw=45;
		}
		if(this.material && !this.isComplexMesh()){
			this.mesh.material=this.material;
		}
		if(this.character){
			this.character.setupMesh();
		}
		if(this.order!=null){ this.mesh.order=this.order; }
	}
	isComplexMesh(){
		return this.shape === model_mz3d.enumShapes.MODEL || this.shape === model_mz3d.enumShapes.MESH;
	}
	async setMaterial(src){
		let newTexture;
		if(src==='error'){
			newTexture = await model_mz3d.getErrorTexture();
		}else{
			newTexture = await model_mz3d.createTexture(src);
		}
		await model_mz3d.waitTextureLoaded(newTexture);
		this.disposeMaterial();
		this.texture = newTexture;
		this.texture.hasAlpha=true;
		this.texture.updateSamplingMode(1);
		this.textureLoaded=true;
		this.material = new babylon["StandardMaterial"]('sprite material',model_mz3d.scene);
		this.material.diffuseTexture=this.texture;
		this.material.alphaCutOff = model_mz3d.ALPHA_CUTOFF;
		this.material.ambientColor.set(1,1,1);
		this.material.specularColor.set(0,0,0);
		this.material.maxSimultaneousLights=model_mz3d.LIGHT_LIMIT;
		this.material.backFaceCulling=false;
		this.material.twoSidedLighting=true;
		if(!this.isComplexMesh()){
			this.mesh.material=this.material;
		}
	}
	disposeMaterial(){
		if(this.material){
			this.material.dispose();
			this.texture.dispose();
			this.material=null;
			this.texture=null;
		}
	}
	dispose(...args){
		this.disposeMaterial();
		if(this.isComplexMesh()){
			if(this.mesh instanceof babylon["InstancedMesh"]){
				super.dispose(false,false);
			}else{
				super.dispose(false,true);
			}
		}else{
			super.dispose(...args);
		}
	}
	clearShape(){
		this.shape=null;
		this.model_filename=null;
		this.mesh_text=null;
	}
	clearMesh(){
		if(!this.mesh){ return; }
		model_mz3d.callFeatures('destroyCharMesh',this.mesh);
		this.mesh.dispose();
	}
	setMesh(mesh){
		this.clearMesh();
		this.mesh=mesh;
		this.setupMesh();
	}
	setMeshForShape(shape){
		if(this.shape===shape){ return; }
		this.clearShape();
		this.shape=shape;
		let geometry = model_mz3d.Meshes.SPRITE;
		const shapes = model_mz3d.enumShapes;
		switch(this.shape){
		case shapes.FLAT:
			geometry = model_mz3d.Meshes.FLAT;
			break;
		case shapes.XCROSS:
		case shapes.CROSS:
			geometry = model_mz3d.Meshes.CROSS;
			break;
		case shapes['8CROSS']:
			geometry = model_mz3d.Meshes['8CROSS'];
			break;
		case shapes.FENCE:
		case shapes.WALL:
			geometry = model_mz3d.Meshes.WALL;
			break;
		case shapes.BOARD:
			geometry = model_mz3d.Meshes.BOARD;
			break;
		}
		this.setMesh(geometry.clone());
	}
	async importModel(filename,opts={}){
		if(this.shape === model_mz3d.enumShapes.MODEL && this.model_filename === filename){
			return;
		}
		this.clearShape();
		this.model_filename = filename;
		this.shape = model_mz3d.enumShapes.MODEL;
		if(opts.useInstance){
			if(filename in modelInstanceCache){
				while(modelInstanceCache[filename]==='loading'){ await Object(util["sleep"])(10); }
				var mesh = modelInstanceCache[filename];
				mesh.receiveShadows=true;
			}else{
				modelInstanceCache[filename]='loading';
				var mesh = await model_mz3d.importModel(filename);
				modelInstanceCache[filename]=mesh;
				model_mz3d.scene.removeMesh(mesh);
			}
			mesh = mesh.createInstance();
		}else{
			var mesh = await model_mz3d.importModel(filename);
		}
		if(!opts.nodelay){
			mesh.setEnabled(false);
			await Object(util["sleep"])(100);
			mesh.setEnabled(true);
		}
		this.setMesh(mesh);
	}
	update(){
		if(this.mesh&&this.shape){
			if(this.shape===model_mz3d.enumShapes.SPRITE){
				this.mesh.pitch = model_mz3d.blendCameraPitch.currentValue()-90;
				this.mesh.yaw = model_mz3d.blendCameraYaw.currentValue();
			}else if(this.shape===model_mz3d.enumShapes.BOARD){
				this.mesh.yaw = model_mz3d.blendCameraYaw.currentValue();
				if(this.character){ this.mesh.yaw -= this.character.spriteOrigin.yaw; }
			}
		}
	}
}
model_mz3d.Model = model_Model;

class model_MeshGroup extends babylon["TransformNode"]{
	constructor(){
		super('meshGroup',model_mz3d.scene);
		this.meshes=[];
	}
	addMesh(){
		this.meshes.push(...arguments);
		for(const mesh of arguments){
			mesh.parent=this;
		}
	}
	dispose(doNotRecurse,disposeMaterialAndTextures){
		super.dispose(doNotRecurse,disposeMaterialAndTextures);
		if(doNotRecurse) for(const mesh of this.meshes){
			mesh.dispose(doNotRecurse,disposeMaterialAndTextures);
		}
	}
}
model_mz3d.MeshGroup = model_MeshGroup;
for(const property of ['receiveShadows','renderingGroupId','visibility','character']){
	Object.defineProperty(model_MeshGroup.prototype,property,{
		get(){ const p=this[`_${property}`]; return p!==undefined?p:this.meshes[0][property]; },
		set(v){
			this[`_${property}`]=v;
			for(const mesh of this.meshes){
				mesh[property]=v;
			}
		},
	});
}


// CONCATENATED MODULE: ./src/mapCell.js
const mapCell_mz3d = window.mz3d;





class mapCell_MapCell extends babylon["TransformNode"]{
	constructor(cx,cy){
		const key = [cx,cy].toString();
		super(`MapCell[${key}]`,mapCell_mz3d.scene);
		this.parent=mapCell_mz3d.map;
		//mv3d.cells[key]=this;
		this.cx=cx; this.cy=cy;
		this.ox=cx*mapCell_mz3d.CELL_SIZE; this.oy=cy*mapCell_mz3d.CELL_SIZE;
		this.x=this.ox; this.y=this.oy;
		this.key=key;
		this.characters=[];
		this.doodads=[];

		//this.load();
	}
	update(){
		const loopPos = mapCell_mz3d.loopCoords((this.cx+0.5)*mapCell_mz3d.CELL_SIZE,(this.cy+0.5)*mapCell_mz3d.CELL_SIZE);
		this.x=loopPos.x-mapCell_mz3d.CELL_SIZE/2;
		this.y=loopPos.y-mapCell_mz3d.CELL_SIZE/2;
		for (const doodad of this.doodads){
			doodad.update();
			if(doodad.shape===mapCell_mz3d.enumShapes.SPRITE){
				const billboardOffset = new babylon["Vector2"](Math.sin(-mapCell_mz3d.cameraNode.rotation.y),Math.cos(mapCell_mz3d.cameraNode.rotation.y));
				doodad.mesh.x=billboardOffset.x*mapCell_mz3d.SPRITE_OFFSET;
				doodad.mesh.y=billboardOffset.y*mapCell_mz3d.SPRITE_OFFSET;
			}
		}
	}
	async load(){
		const shapes = mapCell_mz3d.enumShapes;
		this.builder = new MapCellBuilder_CellMeshBuilder();
		// load all tiles in mesh
		let cellWidth=mapCell_mz3d.CELL_SIZE,cellHeight=mapCell_mz3d.CELL_SIZE;
		if(mapCell_mz3d.getMapConfig('edge')!=='clamp'){
			cellWidth = Math.min(mapCell_mz3d.CELL_SIZE,mapCell_mz3d.mapWidth()-this.cx*mapCell_mz3d.CELL_SIZE);
			cellHeight = Math.min(mapCell_mz3d.CELL_SIZE,mapCell_mz3d.mapHeight()-this.cy*mapCell_mz3d.CELL_SIZE);
		}
		const ceilingConf = mapCell_mz3d.getCeilingConfig();
		for (let y=0; y<cellHeight; ++y)
		for (let x=0; x<cellWidth; ++x){
			let ceiling = ceilingConf;
			const tileData = mapCell_mz3d.getTileData(this.ox+x,this.oy+y);
			const zeroConf = mapCell_mz3d.getTileTextureOffsets(tileData[0],this.ox+x,this.oy+y,0);
			if(zeroConf.ceiling_changed){
				ceiling = mapCell_mz3d.getCeilingConfig(zeroConf);
			}
			ceiling.cull=false;
			let lastZ=Infinity;
			const cullHeight = mapCell_mz3d.getCullingHeight(this.ox+x,this.oy+y);
			for (let l=3; l>=0; --l){
				if(mapCell_mz3d.isTileEmpty(tileData[l])){ continue; }
				let z = mapCell_mz3d.getStackHeight(this.ox+x,this.oy+y,l);
				const tileConf = l===0?zeroConf:mapCell_mz3d.getTileTextureOffsets(tileData[l],this.ox+x,this.oy+y,l);
				const shape = tileConf.shape;
				tileConf.realId = tileData[l];
				//tileConf.isAutotile = Tilemap.isAutotile(tileData[l]);
				//tileConf.isFringe = mv3d.isStarTile(tileData[l]);
				//tileConf.isTable = mv3d.isTableTile(tileData[l]);
				let wallHeight = mapCell_mz3d.getTileHeight(this.ox+x,this.oy+y,l)||tileConf.height||0;
				let pitCull = false;
				if(lastZ<z){ pitCull=true; }
				if(!mapCell_mz3d.getTileFringe(this.ox+x,this.oy+y,l)){
					lastZ=z;
				}
				//z+=tileConf.fringe;
				//if(mv3d.isStarTile(tileData[l])){ z+=tileConf.fringeHeight; }
				if(!shape||shape===shapes.FLAT||shape===shapes.SLOPE){
					const hasWall=wallHeight||l===0;
					const hasBottom=wallHeight>0&&z-wallHeight>cullHeight||tileConf.fringe>0;
					if(!shape||shape===shapes.FLAT){
						if(!pitCull){
							await this.loadTile(tileConf,x,y,z+l*mapCell_mz3d.LAYER_DIST*!hasWall,l);
						}
						if(hasWall){
							await this.loadWalls(tileConf,x,y,z,l,wallHeight);
						}
						if(hasBottom){
							await this.loadTile(tileConf,x,y,z-wallHeight,l,true);
						}
					}else if(shape===shapes.SLOPE){
						const slopeHeight = tileConf.slopeHeight||1;
						wallHeight -= slopeHeight;
						await this.loadSlope(tileConf,x,y,z,l,slopeHeight);
						if(hasWall){
							await this.loadWalls(tileConf,x,y,z-slopeHeight,l,wallHeight);
						}
						if(hasBottom){
							await this.loadTile(tileConf,x,y,z-slopeHeight-Math.max(0,wallHeight),l,true);
						}
					}
					if(z>=ceiling.height){ ceiling.cull=true; }
				}
				if(shape===shapes.FENCE){
					await this.loadFence(tileConf,x,y,z,l,wallHeight);
				}else if(shape===shapes.WALL){
					await this.loadShapeWall(tileConf,x,y,z,l,wallHeight);
				}else if(shape===shapes.CROSS||shape===shapes.XCROSS){
					await this.loadCross(tileConf,x,y,z,l,wallHeight,shape===shapes.XCROSS ? 45 : 0);
				}else if(shape===shapes['8CROSS']){
					await this.loadCross(tileConf,x,y,z,l,wallHeight,0);
					await this.loadCross(tileConf,x,y,z,l,wallHeight,45);
				}else if(shape===shapes.SPRITE||shape===shapes.BOARD||shape===shapes.MODEL){
					//await
					this.loadDoodad(tileConf,x,y,z-wallHeight,shape);
				}
			}
			if(!mapCell_mz3d.isTileEmpty(ceiling.bottom_id) && !ceiling.cull){
				await this.loadTile(ceiling,x,y,ceiling.height,0,true,false);
			}

			//if(mv3d.mapReady){ await sleep(); }
			//if(!mv3d.mapLoaded){ this.earlyExit(); return; }
		}
		
		this.mesh=this.builder.build();
		if(this.mesh){
			this.mesh.isPickable=false;
			Object(util["sleep"])(10).then(()=>this.mesh.isPickable=true);
			this.mesh.parent=this;
			this.mesh.alphaIndex=0;
			this.mesh.renderingGroupId=mapCell_mz3d.enumRenderGroups.MAIN;
			mapCell_mz3d.callFeatures('createCellMesh',this.mesh);
		}
		delete this.builder
	}
	dispose(){
		super.dispose(...arguments);
		if(this.mesh){
			mapCell_mz3d.callFeatures('destroyCellMesh',this.mesh);
		}
		for (const doodad of this.doodads){
			doodad.dispose();
		}
	}
	async loadDoodad(tileConf,x,y,z,shape){
		const tileId = tileConf.top_id;
		const configRect = tileConf.top_rect;
		const rect = configRect ? configRect : mapCell_mz3d.getTileRects(tileId)[0];
		tileConf.cropTexture = rect;
		tileConf.twosided = true;
		const complexShape = shape === mapCell_mz3d.enumShapes.MODEL || shape === mapCell_mz3d.enumShapes.MESH
		if(complexShape){
		}else{
			var tsMaterial = await mapCell_mz3d.getCachedTilesetMaterialForTile(tileConf,'top');
		}
		const doodad = new model_Model({orphan:false});
		this.doodads.push(doodad);
		if(shape === mapCell_mz3d.enumShapes.MODEL){
			await doodad.importModel(tileConf.model,{nodelay:true, useInstance:true});
		}else{
			doodad.setMeshForShape(shape);
		}
		if(tsMaterial){
			doodad.mesh.material = tsMaterial;
		}
		doodad.parent=this;
		doodad.x=x; doodad.y=y; doodad.z=z;
		
		if(shape!==mapCell_mz3d.enumShapes.SPRITE && shape!==mapCell_mz3d.enumShapes.BOARD){
			doodad.yaw = mapCell_mz3d.getTileRot(tileConf,this.ox+x,this.oy+y);
		}

		if(complexShape){
			var {x:scaleX,y:scaleY} = mapCell_mz3d.getConfig(tileConf,'scale',new babylon["Vector2"](1,1));
		}else{
			var scaleX = tileConf.width||(rect.width / Object(util["tileWidth"])()) || 1;
			var scaleY = tileConf.height||(rect.height/Object(util["tileHeight"])()) || 1;
		}
		doodad.scaling.set(scaleX,scaleY,scaleX);
	}
	async loadTile(tileConf,x,y,z,l,ceiling=false,double=false){
		const tileId = ceiling?tileConf.bottom_id:tileConf.top_id;
		if(mapCell_mz3d.isTileEmpty(tileId)){ return; }
		const configRect = ceiling?tileConf.bottom_rect:tileConf.top_rect;
		const isAutotile = Tilemap.isAutotile(tileId)&&!configRect;
		let rects;
		if(configRect){
			rects=[configRect];
		}else{
			rects = mapCell_mz3d.getTileRects(tileId);
		}
		const tsMaterial = await mapCell_mz3d.getCachedTilesetMaterialForTile(tileConf,ceiling?'bottom':'top');
		for (const rect of rects){
			this.builder.addFloorFace(tsMaterial,rect,
				x + (rect.ox|0)/Object(util["tileSize"])() - 0.25*isAutotile,
				y + (rect.oy|0)/Object(util["tileSize"])() - 0.25*isAutotile,
				z,
				1-isAutotile/2, 1-isAutotile/2, {flip:ceiling,double:double}
			);
		}
	}
	async loadWalls(tileConf,x,y,z,l,wallHeight){
		for (const np of mapCell_MapCell.neighborPositions){
			await this.loadWall(tileConf,x,y,z,l,wallHeight,np);
		}
	}
	async loadWall(tileConf,x,y,z,l,wallHeight,np){
		//const isFringe = mz3d.isStarTile(tileConf.realId)||tileConf.fringe>0;
		const isFringe = tileConf.fringe>0;
		// don't render walls on edge of map (unless it loops)
		if( !mapCell_mz3d.getMapConfig('edge',true) )
		if((this.ox+x+np.x>=mapCell_mz3d.mapWidth()||this.ox+x+np.x<0)&&!mapCell_mz3d.loopHorizontal()
		||(this.oy+y+np.y>=mapCell_mz3d.mapHeight()||this.oy+y+np.y<0)&&!mapCell_mz3d.loopVertical()){
			return;
		}

		let neededHeight=wallHeight;
		let textureChanged='side_changed' in tileConf;
		let tileId=tileConf.side_id,configRect,texture_side='side';
		if(mapCell_mz3d.isTileEmpty(tileId)){ return; }
		
		const neighborHeight = mapCell_mz3d.getCullingHeight(this.ox+x+np.x,this.oy+y+np.y,tileConf.depth>0?3:l,{
			ignorePits:!(tileConf.depth>0),
			dir:Input._makeNumpadDirection(np.x,np.y),
		});
		neededHeight = z-neighborHeight;
		if(neededHeight>0&&(l>0||isFringe)){ neededHeight=Math.min(wallHeight,neededHeight); }

		if(tileConf.depth>0&&neededHeight<0){
			if(mapCell_mz3d.tileHasPit(this.ox+x+np.x,this.oy+y+np.y,l)){ return; }
			//if(mv3d.isTilePit(this.ox+x+np.x,this.oy+y+np.y,l)){ return; }
			neededHeight = Math.max(neededHeight,-tileConf.depth);
			if(tileConf.inside_changed){
				texture_side='inside';
			}
		}
		else if(neededHeight<=0){ return; }

		if(texture_side==='inside'){
			textureChanged=textureChanged||('inside_changed' in tileConf);
			tileId=tileConf.inside_id;
			if(tileConf.inside_rect){ configRect = tileConf.inside_rect; }
		}else{
			if(np.y>0){
				if(tileConf.south_changed){ texture_side='south'; }
			}else if(np.y<0){
				if(tileConf.north_changed){ texture_side='north'; }
			}else if(np.x>0){
				if(tileConf.east_changed){ texture_side='east'; }
			}else if(np.x<0){
				if(tileConf.west_changed){ texture_side='west'; }
			}
			textureChanged=textureChanged||(`${texture_side}_changed` in tileConf);
			const side_id = tileConf[`${texture_side}_id`];
			if(side_id!=null){ tileId=side_id; }
			const side_rect = tileConf[`${texture_side}_rect`];
			if(side_rect){ configRect = side_rect; }
		}
		if(mapCell_mz3d.isTileEmpty(tileId)){ return; }

		const tsMaterial = await mapCell_mz3d.getCachedTilesetMaterialForTile(tileConf,texture_side);

		const wallPos = new babylon["Vector3"]( x+np.x/2, y+np.y/2, z );
		const rot = -Math.atan2(np.x, np.y);
		if(configRect || !Tilemap.isAutotile(tileId)){
			const rect = configRect ? configRect : mapCell_mz3d.getTileRects(tileId)[0];
			const builderOptions={};
			if(neededHeight<0){ builderOptions.flip=true; }
			this.builder.addWallFace(tsMaterial,rect,
				wallPos.x,
				wallPos.y,
				z - neededHeight/2,
				1,Math.abs(neededHeight), rot, builderOptions
			);
		}else{ // Autotile
			//const npl=MapCell.neighborPositions[(+ni-1).mod(4)];
			//const npr=MapCell.neighborPositions[(+ni+1).mod(4)];
			const npl=new babylon["Vector2"](-np.y,np.x);
			const npr=new babylon["Vector2"](np.y,-np.x);
			const ndir = Input._makeNumpadDirection(-np.x,-np.y);
			const leftHeight = mapCell_mz3d.getCullingHeight(this.ox+x+npl.x,this.oy+y+npl.y,l,{dir:Input._makeNumpadDirection(npl.x,npl.y),dir2:ndir});
			const rightHeight = mapCell_mz3d.getCullingHeight(this.ox+x+npr.x,this.oy+y+npr.y,l,{dir:Input._makeNumpadDirection(npr.x,npr.y),dir2:ndir});
			const {x:bx,y:by} = this.getAutotileCorner(tileId,textureChanged,true);
			let wallParts=Math.max(1,Math.abs(Math.round(neededHeight*2)));
			let partHeight=Math.abs(neededHeight/wallParts);
			let sw = Object(util["tileSize"])()/2;
			let sh = Object(util["tileSize"])()/2;
			if(mapCell_mz3d.isTableTile(tileConf.realId)){
				sh=Object(util["tileSize"])()/3;
				wallParts=1;
				partHeight=wallHeight;
				//partHeight=neededHeight;
			}
			for (let ax=-1; ax<=1; ax+=2){
				for(let az=0;az<wallParts;++az){
					let hasLeftEdge,hasRightEdge;
					if(mapCell_mz3d.isTableTile(tileConf.realId)){
						hasLeftEdge = leftHeight!=z;
						hasRightEdge = rightHeight!=z;
					}else{
						hasLeftEdge = leftHeight<z-az*partHeight;
						hasRightEdge = rightHeight<z-az*partHeight;
					}
					let sx,sy;
					sx=bx*Object(util["tileSize"])();
					sy=by*Object(util["tileSize"])();
					sx=(bx+(ax>0?0.5+hasRightEdge:1-hasLeftEdge))*Object(util["tileSize"])();
					if(mapCell_mz3d.isWaterfallTile(tileId)){
						sy=(by+az%2/2)*Object(util["tileSize"])();
					}else if(mapCell_mz3d.isTableTile(tileId)){
						sy=(by+5/3)*Object(util["tileSize"])();
					}else{
						sy=(by+(az===0?0:az===wallParts-1?1.5:1-az%2*0.5))*Object(util["tileSize"])();
					}
					const builderOptions={};
					if(neededHeight<0){ builderOptions.flip=true; }
					const sourceRect = new PIXI.Rectangle(sx,sy,sw,sh);
					this.builder.addWallFace(tsMaterial,sourceRect,
						wallPos.x+0.25*ax*Math.cos(rot),
						wallPos.y+0.25*ax*Math.sin(rot),
						z - neededHeight*(neededHeight<0) - partHeight/2 - partHeight*az,
						0.5,partHeight, rot, builderOptions
					);
				}
			}
		}
	}
	async loadFence(tileConf,x,y,z,l,wallHeight){
		const tileId = tileConf.side_id;
		if(mapCell_mz3d.isTileEmpty(tileId)){ return; }
		const configRect = tileConf.side_rect;
		const tsMaterial = await mapCell_mz3d.getCachedTilesetMaterialForTile(tileConf,'side');
		const isAutotile = Tilemap.isAutotile(tileId);
		const edges = [];
		const fenceposts = tileConf.fencePosts==null?true:tileConf.fencePosts;
		for (let ni=0; ni<mapCell_MapCell.neighborPositions.length; ++ni){
			const np = mapCell_MapCell.neighborPositions[ni];
			const neighborHeight = mapCell_mz3d.getTileHeight(this.ox+x+np.x,this.oy+y+np.y,l);
			if(neighborHeight!==wallHeight){ edges.push(ni); }
		}
		for (let ni=0; ni<mapCell_MapCell.neighborPositions.length; ++ni){
			const np = mapCell_MapCell.neighborPositions[ni];

			let edge = edges.includes(ni);
			if(!isAutotile||!fenceposts){
				let connect = !(edge&&edges.length<4);
				if(edges.length===3 && !edges.includes((ni+2)%4)){ connect=true; }
				if(!connect){ continue; }
			}

			const rightSide = np.x>0||np.y<0;
			let rot = Math.atan2(np.x, np.y)+Math.PI/2;
			if(rightSide){
				rot-=Math.PI;
			}

			if(isAutotile&&!configRect){
				const {x:bx,y:by} = this.getAutotileCorner(tileId,'side_changed' in tileConf,true);
				for (let az=0;az<=1;++az){
					const sourceRect = new PIXI.Rectangle(
						(edge ? (bx+rightSide*1.5) : (bx+1-rightSide*0.5) )*Object(util["tileWidth"])(),
						(by+az*1.5)*Object(util["tileHeight"])(),
						Object(util["tileWidth"])()/2, Object(util["tileHeight"])()/2,
					);
					this.builder.addWallFace(tsMaterial,sourceRect,
						x+np.x/4,
						y+np.y/4,
						z-wallHeight/4-az*wallHeight/2,
						0.5,wallHeight/2, -rot, {double:true, abnormal:mapCell_mz3d.ABNORMAL}
					);
				}
			}else{
				const rect = configRect ? configRect : mapCell_mz3d.getTileRects(tileId)[0];
				const sourceRect = new PIXI.Rectangle(
					rect.x+rect.width/2*(np.x>0||np.y>0),
					rect.y,
					rect.width/2, rect.height,
				);
				this.builder.addWallFace(tsMaterial,sourceRect,
					x+np.x/4,
					y+np.y/4,
					z-wallHeight/2,
					0.5,wallHeight, rot, {double:true}
				);
			}
		}
	}
	async loadCross(tileConf,x,y,z,l,wallHeight,angle=0){
		const tileId = tileConf.side_id;
		if(mapCell_mz3d.isTileEmpty(tileId)){ return; }
		const configRect = tileConf.side_rect;
		const tsMaterial = await mapCell_mz3d.getCachedTilesetMaterialForTile(tileConf,'side');
		let isAutotile = Tilemap.isAutotile(tileId);
		let rects;
		if(configRect){
			rects=[configRect];
			isAutotile=false;
		}else{
			rects = mapCell_mz3d.getTileRects(tileId);
		}
		angle += mapCell_mz3d.getTileRot(tileConf,this.ox+x,this.oy+y);
		const rot = tileConf.shape===mapCell_mz3d.enumShapes.XCROSS ? Math.PI/4 : Object(util["degtorad"])(angle);
		const partHeight = isAutotile ? wallHeight/2 : wallHeight;
		const partWidth = (tileConf.width||rects[0].width/Object(util["tileWidth"])())/(isAutotile?2:1);
		for (let i=0; i<=1; ++i){
			for (const rect of rects){
				const irot = -Math.PI/2*i+rot;
				const trans= isAutotile?(-partWidth/2+Math.sign(rect.ox|0)*partWidth):0;
				this.builder.addWallFace(tsMaterial,rect,
					x+trans*Math.cos(irot),
					y+trans*Math.sin(irot),
					z - (rect.oy|0)/Object(util["tileHeight"])()*wallHeight - partHeight/2,
					partWidth, partHeight, irot, {double:true, abnormal:mapCell_mz3d.ABNORMAL}
				);
			}
		}
	}
	async loadShapeWall(tileConf,x,y,z,l,wallHeight,angle=0){
		const tileId = tileConf.side_id;
		if(mapCell_mz3d.isTileEmpty(tileId)){ return; }
		const configRect = tileConf.side_rect;
		const tsMaterial = await mapCell_mz3d.getCachedTilesetMaterialForTile(tileConf,'side');
		const isAutotile = Tilemap.isAutotile(tileId);
		let rects;
		if(configRect){
			rects=[configRect];
		}else{
			rects = mapCell_mz3d.getTileRects(tileId);
		}
		angle += mapCell_mz3d.getTileRot(tileConf,this.ox+x,this.oy+y);
		const rot = Object(util["degtorad"])(angle);
		const partHeight = isAutotile ? wallHeight/2 : wallHeight;
		const partWidth = (tileConf.width||rects[0].width/Object(util["tileWidth"])())/(isAutotile?2:1);
		for (const rect of rects){
			const trans= isAutotile?(-partWidth/2+Math.sign(rect.ox)*partWidth):0;
			this.builder.addWallFace(tsMaterial,rect,
				x+trans*Math.cos(rot),
				y+trans*Math.sin(rot),
				z - (rect.oy|0)/Object(util["tileHeight"])()*wallHeight - partHeight/2,
				partWidth, partHeight, rot, {double:true, abnormal:mapCell_mz3d.ABNORMAL}
			);
		}
	}
	async loadSlope(tileConf,x,y,z,l,slopeHeight){
		//const rot = Math.random()*Math.PI*2;
		//const rot = Math.round((Math.random()*Math.PI*2)/(Math.PI/2))*Math.PI/2;
		const {dir,rot} = mapCell_mz3d.getSlopeDirection(this.ox+x,this.oy+y,l,true);
		const n1=new babylon["Vector2"](-Object(util["sin"])(rot+Math.PI),Object(util["cos"])(rot+Math.PI));
		if(mapCell_mz3d.getCullingHeight(this.ox+x+n1.x,this.oy+y+n1.y,l)<z){
			await this.loadWall(tileConf,x,y,z,l+1,slopeHeight,n1);
		}
		const n2=new babylon["Vector2"](n1.y,-n1.x);
		const n2x=this.ox+x+n2.x, n2y=this.oy+y+n2.y;
		if(mapCell_mz3d.getCullingHeight(n2x,n2y,l)<z){
			let otherslope = mapCell_mz3d.isRampAt(n2x,n2y,z);
			if(!otherslope||otherslope.z2!==z||otherslope.z1!==z-slopeHeight
			||dir!=mapCell_mz3d.getSlopeDirection(n2x,n2y,otherslope.l,true).dir){
				await this.loadSlopeSide(tileConf,x+n2.x/2,y+n2.y/2,z,l,slopeHeight,rot+Math.PI/2);
			}
		}
		const n3=new babylon["Vector2"](-n1.y,n1.x);
		const n3x=this.ox+x+n3.x, n3y=this.oy+y+n3.y;
		if(mapCell_mz3d.getCullingHeight(n3x,n3y,l)<z){
			let otherslope = mapCell_mz3d.isRampAt(n3x,n3y,z);
			if(!otherslope||otherslope.z2!==z||otherslope.z1!==z-slopeHeight
			||dir!=mapCell_mz3d.getSlopeDirection(n3x,n3y,otherslope.l,true).dir){
				await this.loadSlopeSide(tileConf,x+n3.x/2,y+n3.y/2,z,l,slopeHeight,rot+Math.PI/2,{flip:true});
			}
		}
		await this.loadSlopeTop(tileConf,x,y,z,l,slopeHeight,rot);
	}
	async loadSlopeTop(tileConf,x,y,z,l,slopeHeight,rot){
		const tileId=tileConf.top_id;
		const tsMaterial = await mapCell_mz3d.getCachedTilesetMaterialForTile(tileConf,'top');
		const isAutotile = Tilemap.isAutotile(tileId)&&!tileConf.top_rect;
		if(isAutotile){
			const rects = mapCell_mz3d.getTileRects(tileId);
			for (let i=0;i<rects.length;++i){
				const rect = rects[i];
				const ix=(i+1)%2*-2+1, iy=(Math.floor(i/2)+1)%2*2-1;
				const hx=Math.max(0,Object(util["sin"])(rot)*ix)*slopeHeight/2;
				const hy=Math.max(0,Object(util["cos"])(rot)*iy)*slopeHeight/2;
				this.builder.addSlopeFace(tsMaterial,rect,
					x + rect.ox/Object(util["tileSize"])() - 0.25,
					y + rect.oy/Object(util["tileSize"])() - 0.25,
					z - slopeHeight + hx + hy,
					0.5, slopeHeight/2, rot, {autotile:true}
				);
			}
		}else{
			const rect = tileConf.top_rect?tileConf.top_rect:mapCell_mz3d.getTileRects(tileId)[0];
			this.builder.addSlopeFace(tsMaterial,rect,
				x, y, z - slopeHeight,
				1, slopeHeight, rot, {}
			);
		}
	}
	async loadSlopeSide(tileConf,x,y,z,l,slopeHeight,rot,options={}){
		const tileId=tileConf.side_id;
		if(mapCell_mz3d.isTileEmpty(tileId)){ return; }
		const tsMaterial = await mapCell_mz3d.getCachedTilesetMaterialForTile(tileConf,'side');
		const isAutotile = Tilemap.isAutotile(tileId)&&!tileConf.side_rect;
		let rect;
		if(isAutotile){
			const {x:bx,y:by} = this.getAutotileCorner(tileId,'side_changed' in tileConf,true);
			rect={x:(bx+0.5)*Object(util["tileWidth"])(),y:(by+0.5)*Object(util["tileHeight"])(),width:Object(util["tileWidth"])(),height:Object(util["tileHeight"])()};
		}else{
			rect = tileConf.side_rect?tileConf.side_rect:mapCell_mz3d.getTileRects(tileId)[0];
		}
		this.builder.addSlopeSide(tsMaterial,rect,
			x, y, z - slopeHeight,
			1, slopeHeight, rot, options
		);
	}
	getAutotileCorner(tileId,textureChanged,excludeTop=true){
		return mapCell_mz3d.getTileCorner(tileId,{
			useSideWall:!textureChanged,
			excludeTop,
		});
	}
}
mapCell_MapCell.neighborPositions = [
	new babylon["Vector2"]( 0, 1),
	new babylon["Vector2"]( 1, 0),
	new babylon["Vector2"]( 0,-1),
	new babylon["Vector2"](-1, 0),
];
mapCell_MapCell.meshCache={};

mapCell_mz3d.getTileCorner=function(tileId,opts={}){
	const useSideWall=Boolean(opts.useSideWall);
	const excludeTop=Boolean(opts.excludeTop);
	const kind = Tilemap.getAutotileKind(tileId);
	let tx = kind%8;
	let ty = Math.floor(kind / 8);
	if(useSideWall && mapCell_mz3d.isWallTile(tileId)==1){ ++ty; }
	var bx,by;
	bx=tx*2;
	by=ty;
	if(Tilemap.isAutotile(tileId)){
		if(Tilemap.isTileA1(tileId)){
			if(kind<4){
				bx=6*Math.floor(kind/2);
				by=3*(kind%2) + excludeTop;
			}else{
				bx=8*Math.floor(tx/4) + (kind%2)*6;
				by=ty*6 + Math.floor(tx%4/2)*3 + excludeTop*!(tx%2);
				//if(excludeTop&&!(kind%2)){ by+=1; }
			}
			if(excludeTop&&kind>=4&&!(kind%2)){ by+=1; }
		}else if(Tilemap.isTileA2(tileId)){
			by=(ty-2)*3 + excludeTop;
		}else if (Tilemap.isTileA3(tileId)){
			by=(ty-6)*2;
		}else if (Tilemap.isTileA4(tileId)){
			if(excludeTop){
				by=Math.ceil((ty-10)*2.5+0.5);
			}else{
				by=(ty-10)*2.5+(ty%2?0.5:0);
			}
		}
	}else{
		bx = (Math.floor(tileId / 128) % 2 * 8 + tileId % 8);
		by = (Math.floor(tileId % 256 / 8) % 16);
	}

	return {x:bx,y:by};
}


// CONCATENATED MODULE: ./src/tileData.js
const tileData_mz3d = window.mz3d;



Object.assign(tileData_mz3d,{

	_tilemap:null,
	getTilemap(){
		if(SceneManager._scene&&SceneManager._scene._spriteset){
			this._tilemap = SceneManager._scene._spriteset._tilemap;
		}
		return this._tilemap;
	},
	getDataMap(){
		if($dataMap){ this._dataMap=$dataMap }
		return this._dataMap;
	},
	mapWidth(){ return this.getDataMap().width; },
	mapHeight(){ return this.getDataMap().height; },
	loopHorizontal(){ return this.getDataMap().scrollType&2; },
	loopVertical(){ return this.getDataMap().scrollType&1; },

	getRegion(x,y){
		return this.getTileId(x,y,5);
	},

	getSetNumber(id){
		if(Tilemap.isAutotile(id)){
			return Tilemap.isTileA1(id)?0
				: Tilemap.isTileA2(id)?1 : Tilemap.isTileA3(id)?2 : 3;
		}else{
			return Tilemap.isTileA5(id)?4:5+Math.floor(id/256);
		}
	},
	SETNUMBERS:{A1:0,A2:1,A3:2,A4:3,A5:4,B:5,C:6,D:7,E:8},
	SETNAMES:['A1','A2','A3','A4','A5','B','C','D','E'],
	getSetName(id){
		return this.SETNAMES[this.getSetNumber(id)];
	},
	getTsImgUrl(name){
		if(name in this.SETNUMBERS){
			const setN = this.SETNUMBERS[name];
			const tsName = $gameMap.tileset().tilesetNames[setN];
			if(!tsName){ return Object(util["file"])(tileData_mz3d.MV3D_FOLDER,`${tileData_mz3d.TEXTURE_ERROR}.png`); }
			return ImageManager.loadTileset(tsName)._url;
		}
		return Object(util["file"])(tileData_mz3d.MV3D_FOLDER,name);
	},

	getShadowBits(x,y){
		return this.getTileId(x,y,4);
	},

	getTerrainTag(tileId){
		return $gameMap.tilesetFlags()[tileId]>>12;
	},

	getTilePassage:Object(util["overload"])({
		1(tileId){ return this.getTilePassage(tileId,this.getTileConfig(tileId)); },
		2(tileId,conf){
			if('pass' in conf){
				return conf.pass;
			}
			const flag = $gameMap.tilesetFlags()[tileId];
			if( (flag&0x10) ){ return this.enumPassage.THROUGH; }
			if( (flag&0x0f)===0x0f ){ return this.enumPassage.WALL; }
			else{ return this.enumPassage.FLOOR; }
		},
		3(x,y,l){
			const tileId=this.getTileId(x,y,l);
			return this.getTilePassage(tileId,this.getTileConfig(tileId,x,y,l));
		},
		default(tileId,x,y,l){
			return this.getTilePassage(tileId,this.getTileConfig(tileId,x,y,l));
		}
	}),

	getTileAnimationData(tileConf,side){
		const tileId=tileConf[`${side}_id`];
		if(`${side}_animData` in tileConf){
			return tileConf[`${side}_animData`];
		}
		const animData={animX:0,animY:0};
		if(`${side}_rect` in tileConf){ return animData; }
		if(Tilemap.isTileA1(tileId)){
			const kind = Tilemap.getAutotileKind(tileId);
			animData.animX=kind<=1?2:kind<=3?0:kind%2?0:2;
			animData.animY=kind<=3?0:kind%2?1:0; 
		}
		return animData;
	},

	getTileConfig:Object(util["overload"])({
		3(x,y,l){ return this.getTileConfig(this.getTileData(x,y)[l],x,y,l); },
		default(tileId,x,y,l){
			const conf = {};
			if(!this.isTileEmpty(tileId)){
				if(this.isWallTile(tileId)){
					Object.assign(conf,this.TILE_SETTINGS_WALL);
				}else if(this.isTableTile(tileId)){
					Object.assign(conf,this.TILE_SETTINGS_TABLE);
				}
				if(this.isStarTile(tileId)){
					Object.assign(conf,this.TILE_SETTINGS_STAR);
				}
				const ttag = this.getTerrainTag(tileId);
				if(ttag && ttag in this.TTAG_DATA){
					Object.assign(conf,this.TTAG_DATA[ttag]);
				}
				const ts_conf = this.tilesetConfigurations[this.normalizeAutotileId(tileId)];
				if(ts_conf){
					Object.assign(conf,ts_conf);
				}
			}
			if(l===0){
				const region = this.getRegion(x,y);
				if(region && region in tileData_mz3d.REGION_DATA){
					Object.assign(conf,this.REGION_DATA[region]);
				}
			}
			return conf;
		},
	}),

	getTileTextureOffsets(tileId,x,y,l){
		const conf = this.getTileConfig(tileId,x,y,l);
		this._tileTextureOffset(conf,'top',tileId,tileId);
		this._tileTextureOffset(conf,'side',tileId,tileId);
		this._tileTextureOffset(conf,'inside',tileId,'side');
		this._tileTextureOffset(conf,'bottom',tileId,'top');
		this._tileTextureOffset(conf,'north',tileId,'side');
		this._tileTextureOffset(conf,'south',tileId,'side');
		this._tileTextureOffset(conf,'east',tileId,'side');
		this._tileTextureOffset(conf,'west',tileId,'side');
		if(!('pass' in conf)){
			conf.pass = this.getTilePassage(tileId,conf);
		}
		return conf;
	},

	_tileTextureOffset(conf,side,tileId,dfault){
		const tileRange = Tilemap.isAutotile(tileId)?48:1;
		let id = conf[`${side}_id`];
		if(id==null){
			let offset = conf[`${side}_offset`];
			if(offset){
				id=conf[`${side}_id`]=tileId+offset.x*tileRange+offset.y*tileRange*8;
			}else{
				if(typeof dfault === 'string'){
					id=conf[`${side}_id`]=conf[`${dfault}_id`];
					conf[`${side}_img`]=conf[`${dfault}_img`];
					if(`${dfault}_rect` in conf){ conf[`${side}_rect`]=conf[`${dfault}_rect`]; }
				}else{
					id=conf[`${side}_id`]=dfault;
				}
			}
		}
		let img = conf[`${side}_img`];
		if(img==null){
			conf[`${side}_img`]=this.getSetName(id);
		}
	},

	getTileId(x,y,l=0){
		const dataMap = this.getDataMap(); if(!dataMap){ return 0; }
		const {data,width,height} = dataMap;
		if(this.loopHorizontal()){ x=x.mod(width); }
		if(this.loopVertical()){ y=y.mod(height); }
		if(x<0||x>=width||y<0||y>=height){
			if(this.getMapConfig('edge')==='clamp'){
				const clamp = this.getMapConfig('edgeData',1);
				if(x>=width){ x=width+(x-width).mod(clamp)-clamp; }
				else if(x<0){x=x.mod(clamp);}
				if(y>=height){ y=height+(y-height).mod(clamp)-clamp; }
				else if(y<0){y=y.mod(clamp);}
			}else{
				return 0; 
			}
		}
		return data[(l * height + y) * width + x] || 0
	},

	getTileData(x,y){
		const dataMap = this.getDataMap(); if(!dataMap){ return [0,0,0,0]; }
		const {data,width,height} = dataMap;
		if(this.loopHorizontal()){
			x=x.mod(width);
		}
		if(this.loopVertical()){
			y=y.mod(height);
		}
		if(x<0||x>=width||y<0||y>=height){
			if(this.getMapConfig('edge')==='clamp'){
				const clamp = this.getMapConfig('edgeData',1);
				if(x>=width){ x=width+(x-width).mod(clamp)-clamp; }
				else if(x<0){x=x.mod(clamp);}
				if(y>=height){ y=height+(y-height).mod(clamp)-clamp; }
				else if(y<0){y=y.mod(clamp);}
			}else{
				return [0,0,0,0]; 
			}
		}
		if(x<0||x>=width||y<0||y>=height){ return [0,0,0,0]; }
		const tileData=[];
		for (let z=0;z<4;++z){//4 tile layers. Ignore shadow bits.
			tileData[z] = data[(z * height + y) * width + x] || 0;
		}
		return tileData;
	},


	getTileHeight(x,y,l=0){

		if(this.loopHorizontal()){ x=x.mod(this.mapWidth()); }
		if(this.loopVertical()){ y=y.mod(this.mapHeight()); }

		const tileId=this.getTileData(x,y)[l];
		if(this.isTileEmpty(tileId)&&l>0){ return 0; }
		// finge tiles don't stack normally. fringeHeight property should be used when drawing them.
		//if(this.isStarTile(tileId)){ return 0; }

		const shapes=this.enumShapes;
		const conf =this.getTileConfig(tileId,x,y,l);
		let height = 0;
		if('height' in conf){
			height = conf.height;
		}else if(this.isSpecialShape(conf.shape)){
			switch(conf.shape){
				case shapes.SLOPE: height=0; break;
				default: height=1; break;
			}
		}
		if('depth' in conf){
			height -= conf.depth;
		}
		if(conf.shape===shapes.SLOPE){
			height += conf.slopeHeight||1;
		}
		return height;
	},

	getStackHeight(x,y,layerId=3){
		let height=0;
		for(let l=0; l<=layerId; ++l){
			height += this.getTileFringe(x,y,l);
			height += this.getTileHeight(x,y,l);
		}
		return height;
	},

	getTileRot(tileConf,x,y){
		const shadowBits = this.getShadowBits(x,y);
		if(shadowBits in this._SHADOW_ROTS){ return this._SHADOW_ROTS[shadowBits]; }
		return this.getConfig(tileConf,'rot',0);
	},
	_SHADOW_ROTS: {
		0b0011: 180,
		0b1010: 90,
		0b0101: 270,
		0b1100: 0,
	},

	getSlopeDirection(x,y,l,fullData=false){
		const stackHeight = this.getStackHeight(x,y,l);
		const tileId = this.getTileData(x,y)[l];
		const conf = this.getTileConfig(tileId,x,y,l);
		const slopeHeight = conf.slopeHeight||1;
		const neighborPositions = mapCell_MapCell.neighborPositions;
		const flag = $gameMap.tilesetFlags()[tileId];
		const shadowBits = this.getShadowBits(x,y);
		const shadowBitDirections=[0,0b0011,0b1010,0b0101,0b1100];
		//const shadowBitDirections=[0,0b1100,0b0101,0b1010,0b0011];
		let direction;
		for(let i=0;i<neighborPositions.length;++i){
			const n=neighborPositions[i];
			const d={neighbor: n,favor:0};
			d.dir = 5-3*n.y+n.x;
			const nHeights = this.getCollisionHeights(x+n.x,y+n.y,{slopeMax:true});
			const oHeights = this.getCollisionHeights(x-n.x,y-n.y,{slopeMin:true});
			if(nHeights.some(c=>Math.abs(stackHeight-slopeHeight-c.z2)<=tileData_mz3d.STAIR_THRESH)){ d.favor+=1; }
			if(oHeights.some(c=>Math.abs(stackHeight-c.z2)<=tileData_mz3d.STAIR_THRESH)){ d.favor+=1; }
			if(flag&(1<<(d.dir/2-1))){ d.favor=-2; }
			if(flag&(1<<((10-d.dir)/2-1))){ d.favor=-1; }
			if((shadowBits&shadowBitDirections[d.dir/2])===shadowBitDirections[d.dir/2]){ d.favor=30; }
			if(conf.slopeDirection===d.dir){ d.favor=100; }
			if(!direction||d.favor>direction.favor){ direction=d; }
		}
		direction.rot=Object(util["degtorad"])(180-this.dirToYaw(direction.dir));
		if(fullData){ return direction; }
		return direction.rot;
	},

	getWalkHeight(x,y){
		// get top height at x,y. Used for jumping and initializing z.
		const heights = this.getCollisionHeights(x,y);
		return heights[heights.length-1].z2;
	},

	getSlopeHeight(x,y,l,data=null){
		const rx=Math.round(x), ry=Math.round(y);
		if(data==null){ data = this.getTileConfig(this.getTileData(rx,ry)[l],rx,ry,l); }
		const rot=this.getSlopeDirection(rx,ry,l);
		const xf=Object(util["sin"])(rot), yf=-Object(util["cos"])(rot);
		let px=(x+0.5)%1, py=(y+0.5)%1;
		if(Math.sign(xf<0)){ px=1-px; }
		if(Math.sign(yf<0)){ py=1-py; }
		const sf=Math.abs(xf)*px + Math.abs(yf)*py;
		return (data.slopeHeight||1)*sf;
	},

	getCollisionHeights(x,y,opts={}){
		const rx=Math.round(x),ry=Math.round(y);
		let z = 0;
		const collisions=[{z1:-Infinity,z2:0}];
		if(opts.layers){ collisions.layers=[]; }
		const tileData=this.getTileData(rx,ry);
		for(let l=0; l<=3; ++l){
			let h = this.getTileHeight(rx,ry,l);
			const tileId=tileData[l];
			const conf = this.getTileConfig(tileId,rx,ry,l);
			const shape = conf.shape;
			const passage = this.getTilePassage(tileId,conf);
			let skip = false;
			if(passage===this.enumPassage.THROUGH){
				h=0; skip=true;
			}else if(shape===this.enumShapes.SLOPE){
				if(opts.slopeMax){
					h = h;
				}else if(opts.slopeMin){
					h = h-(conf.slopeHeight||1);
				}else{
					h = h-(conf.slopeHeight||1)+this.getSlopeHeight(x,y,l,conf);
				}
			}
			const fringe = this.getTileFringe(rx,ry,l);
			z+=fringe;
			if(skip){ continue; }
			if(h<0){
				if(fringe+h<0){
					collisions[collisions.length-1].z2+=fringe+h;
				}
			}else if(l===0){
				collisions[0].z2=z+h;
			}else{
				collisions.push({z1:z,z2:z+h});
			}
			z+=h;
			if(opts.layers){ collisions.layers[l]=collisions[collisions.length-1]; }
			if(shape===this.enumShapes.SLOPE){ collisions[collisions.length-1].isSlope=true; }
		}
		return collisions;
	},

	getTileLayers(x,y,z,gte=true){
		const heights = tileData_mz3d.getCollisionHeights(x,y,{layers:true,slopeMin:true}).layers;
		let closest_diff = Infinity;
		let layers = [0];
		for (let l=0; l<=3; ++l){
			if(!(l in heights)){ continue; }
			const conf = this.getTileConfig(x,y,l);
			const isSlope=conf.shape===this.enumShapes.SLOPE;
			const h = heights[l].z2;
			const diff = z-h;
			if( gte ? z>=h : z>h ){
				if(diff<closest_diff||isSlope&&diff<=closest_diff){
					layers=[l];
					closest_diff=diff;
				}else if(diff===closest_diff){
					layers.push(l);
				}
			}
		}
		return layers;
	},

	getFloatHeight(x,y,z=null,gte=true){
		const tileData=this.getTileData(x,y);
		const layers = z==null?[0,1,2,3]:this.getTileLayers(x,y,z,gte);
		let float=0;
		for(const l of layers){
			const tileId=tileData[l];
			if(this.isTileEmpty(tileId)){ continue; }
			const conf = this.getTileConfig(tileId,x,y,l);
			if(conf && 'float' in conf){
				float += conf.float;
			}
		}
		return float;
	},

	getStackFringeHeight(x,y,l=3){
		return this.getStackHeight(x,y,l);
	},

	getTileFringe(x,y,l){
		const tileId=this.getTileData(x,y)[l];
		if(this.isTileEmpty(tileId)){ return 0; }
		const conf = this.getTileConfig(tileId,x,y,l);
		if(conf && 'fringe' in conf){ return conf.fringe; }
		//if(this.isStarTile(tileId)){
		//	return this.FRINGE_HEIGHT;
		//}
		return 0;
	},

	getCullingHeight(x,y,layerId=3,opts={}){
		let height=0;
		const dataMap=this.getDataMap();
		const isEdge = !this.loopHorizontal()&&(x<0||x>=dataMap.width)
					||!this.loopVertical()&&(y<0||y>=dataMap.height);
		if(isEdge){
			if(!this.getMapConfig('edge',true)){ return Infinity; }
		}
		if(isEdge||this.isTileEmpty(this.getTileId(x,y,0))){
			height=-this.getMapConfig('baseHeight',tileData_mz3d.BASE_HEIGHT);
		}
		const tileData=this.getTileData(x,y);
		for(let l=0; l<=layerId; ++l){
			if(this.getTileFringe(x,y,l)){ return height; }
			const tileId=tileData[l];
			const data = this.getTileConfig(tileId,x,y,l);
			const shape = data.shape;
			if(this.isSpecialShape(shape)){
				if(shape===this.enumShapes.SLOPE){
					height+=this.getTileHeight(x,y,l);
					const slopeDir = this.getSlopeDirection(x,y,l,true).dir;
					if((!opts.dir||opts.dir!==slopeDir)
					&&(!opts.dir2||opts.dir2!==slopeDir)){
						height-=data.slopeHeight||1;
					}
				}
				return height;
			}
			if(opts.ignorePits&&data.depth>0){
				height+=data.depth;
			}
			height+=this.getTileHeight(x,y,l);
		}
		return height;
	},

	tileHasPit(x,y,layerId=3){
		const tileData=this.getTileData(x,y);
		for(let l=0; l<=layerId; ++l){
			const tileId=tileData[l];
			const conf = this.getTileConfig(tileId,x,y,l);
			if(conf.depth>0){ return true; }
		}
		return false;
	},

	isTilePit(x,y,l){
		const tileId=this.getTileData(x,y)[l];
		const conf = this.getTileConfig(tileId,x,y,l);
		return conf.depth>0;
	},

	isTileEmpty(tileId){
		return !tileId||tileId===1544;
	},

	isWallTile(tileId){
		const kind = Tilemap.getAutotileKind(tileId);
		const ty = Math.floor(kind / 8);
		const isWall = Tilemap.isTileA3(tileId) || Tilemap.isTileA4(tileId);
		if (isWall && ty%2){ return 2; }
		return isWall;
	},

	isTableTile(tileId){
		return Boolean(Tilemap.isTileA2(tileId) && ($gameMap.tilesetFlags()[tileId] & 0x80));
	},

	isStarTile(tileId){
		return Boolean($gameMap.tilesetFlags()[tileId] & 0x10);
	},

	isWaterfallTile(tileId){
		const kind = Tilemap.getAutotileKind(tileId);
		return Tilemap.isTileA1(tileId)&&kind>=4&&kind%2;
	},

	isSpecialShape(shape){
		const shapes = tileData_mz3d.enumShapes;
		return shape===shapes.FENCE||shape===shapes.WALL||shape===shapes.CROSS||shape===shapes.XCROSS||shape===shapes['8CROSS']||shape===shapes.SLOPE;
	},
	isPlatformShape(shape){
		const shapes = tileData_mz3d.enumShapes;
		return shape==null||shape===shapes.FLAT||shape===shapes.SLOPE;
	},

	constructTileId(img,x,y){
		const key = `TILE_ID_${img.toUpperCase()}`
		let tileId = key in Tilemap ? Tilemap[key] : 0;
		const tileRange = Tilemap.isAutotile(tileId) ? 48 : 1;
		tileId += Number(x)*tileRange + Number(y)*tileRange*8;
		return tileId;
	},
	normalizeAutotileId(tileId){
		if(!Tilemap.isAutotile(tileId)){ return tileId; }
		const kind = Tilemap.getAutotileKind(tileId);
		return Tilemap.TILE_ID_A1 + kind*48;
	},

});
// CONCATENATED MODULE: ./src/tileDataRects.js


const tileDataRects_mz3d = window.mz3d;

Object.assign(tileDataRects_mz3d,{

	getTileRects(tileId){
		const rects = [];
		const isTable=tileDataRects_mz3d.isTableTile(tileId);
		addTile(rects, tileId, 0,0);
		if (isTable) for (let i=rects.length-1;i>=0;--i){
			if(rects[i].oy>Object(util["tileHeight"])()/2){
				rects[i-1].y+=Object(util["tileHeight"])()*2/3;
				rects.splice(i,1);
			}
		}
		return rects;
	},

});

const addRect=(rects,setNumber,sx,sy,dx,dy,width,height,animX,animY)=>{
	rects.push({setN:setNumber,x:sx,y:sy,width:width,height:height,ox:dx,oy:dy});
};

// The following is a modified version of MV's draw tile functions.
function addTile(rects, tileId, dx, dy) {
	if (Tilemap.isVisibleTile(tileId)) {
		if (Tilemap.isAutotile(tileId)) {
			addAutotile(rects, tileId, dx, dy);
		} else {
			addNormalTile(rects, tileId, dx, dy);
		}
	}
}

function addNormalTile(rects, tileId, dx, dy) {
	let setNumber = 0;

	if (Tilemap.isTileA5(tileId)) {
		setNumber = 4;
	} else {
		setNumber = 5 + Math.floor(tileId / 256);
	}

	const tilemap = tileDataRects_mz3d.getTilemap();

	const w = tilemap._tileWidth;
	const h = tilemap._tileHeight;
	const sx = (Math.floor(tileId / 128) % 2 * 8 + tileId % 8) * w;
	const sy = (Math.floor(tileId % 256 / 8) % 16) * h;

	addRect(rects, setNumber, sx, sy, dx, dy, w, h);
}


function addAutotile(rects, tileId, dx, dy) {
	var autotileTable = Tilemap.FLOOR_AUTOTILE_TABLE;
	var kind = Tilemap.getAutotileKind(tileId);
	var shape = Tilemap.getAutotileShape(tileId);
	var tx = kind % 8;
	var ty = Math.floor(kind / 8);
	var bx = 0;
	var by = 0;
	var setNumber = 0;
	var isTable = false;
	var animX = 0, animY = 0;

	const tilemap = tileDataRects_mz3d.getTilemap();

	if (Tilemap.isTileA1(tileId)) {
		setNumber = 0;
		if (kind === 0) {
			animX = 2;
			by = 0;
		} else if (kind === 1) {
			animX = 2;
			by = 3;
		} else if (kind === 2) {
			bx = 6;
			by = 0;
		} else if (kind === 3) {
			bx = 6;
			by = 3;
		} else {
			bx = Math.floor(tx / 4) * 8;
			by = ty * 6 + Math.floor(tx / 2) % 2 * 3;
			if (kind % 2 === 0) {
				animX = 2;
			}
			else {
				bx += 6;
				autotileTable = Tilemap.WATERFALL_AUTOTILE_TABLE;
				animY = 1;
			}
		}
	} else if (Tilemap.isTileA2(tileId)) {
		setNumber = 1;
		bx = tx * 2;
		by = (ty - 2) * 3;
		isTable = tilemap._isTableTile(tileId);
	} else if (Tilemap.isTileA3(tileId)) {
		setNumber = 2;
		bx = tx * 2;
		by = (ty - 6) * 2;
		autotileTable = Tilemap.WALL_AUTOTILE_TABLE;
	} else if (Tilemap.isTileA4(tileId)) {
		setNumber = 3;
		bx = tx * 2;
		by = Math.floor((ty - 10) * 2.5 + (ty % 2 === 1 ? 0.5 : 0));
		if (ty % 2 === 1) {
			autotileTable = Tilemap.WALL_AUTOTILE_TABLE;
		}
	}

	var table = autotileTable[shape];
	var w1 = tilemap._tileWidth / 2;
	var h1 = tilemap._tileHeight / 2;
	for (var i = 0; i < 4; i++) {
		var qsx = table[i][0];
		var qsy = table[i][1];
		var sx1 = (bx * 2 + qsx) * w1;
		var sy1 = (by * 2 + qsy) * h1;
		var dx1 = dx + (i % 2) * w1;
		var dy1 = dy + Math.floor(i / 2) * h1;
		if (isTable && (qsy === 1 || qsy === 5)) {
			var qsx2 = qsx;
			var qsy2 = 3;
			if (qsy === 1) {
				//qsx2 = [0, 3, 2, 1][qsx];
				qsx2 = (4-qsx)%4;
			}
			var sx2 = (bx * 2 + qsx2) * w1;
			var sy2 = (by * 2 + qsy2) * h1;
			addRect(rects, setNumber, sx2, sy2, dx1, dy1, w1, h1, animX, animY);
			addRect(rects, setNumber, sx1, sy1, dx1, dy1+h1/2, w1, h1/2, animX, animY);
		} else {
			addRect(rects, setNumber, sx1, sy1, dx1, dy1, w1, h1, animX, animY);
		}
	}
}
// CONCATENATED MODULE: ./src/loadMap.js
const loadMap_mv3d = window.mv3d;




Object.assign(loadMap_mv3d,{

	mapLoaded: false,
	mapReady: false,
	clearMap(){
		this.mapLoaded=false;
		this.clearMapCells();
		for (let i=this.characters.length-1; i>=0; --i){
			this.characters[i].dispose(false,true);
		}
		this.characters.length=0;
		this.resetCameraTarget();

		this.callFeatures('clearMap');
	},
	clearMapCells(){
		// clear materials and textures
		for (const key in this.textureCache){
			this.textureCache[key].dispose();
		}
		for (const key in this.materialCache){
			this.materialCache[key].dispose();
		}
		this.animatedTextures.length=0;
		this.textureCache={};
		this.materialCache={};
		// clear map cells
		for (const key in this.cells){
			this.cells[key].dispose(false,true);
		}
		this.cells={};
		// clear model cache
		this.clearModelCache();
	},
	reloadMap(){
		this.clearMapCells();
		if(loadMap_mv3d.mapReady) { this.updateMap(); }
		this.callFeatures('reloadMap');
	},

	loadMap(){
		//this.cameraStick.x=$gamePlayer._realX;
		//this.cameraStick.y=$gamePlayer._realY;
		this.updateBlenders();
		this.updateMap();
		this.createCharacters();
		this.rememberCameraTarget();

		this.callFeatures('loadMap');
	},

	async updateMap(){
		if(this.mapUpdating){ return; }
		this.mapLoaded=true;
		this.mapUpdating=true;
		// unload Far cells
		for (const key in this.cells){
			this.cells[key].unload=true;
		}
		// get range of cells based on render distance
		const bounds = {
			left:Math.floor((this.cameraStick.x-this.renderDist)/this.CELL_SIZE),
			right:Math.floor((this.cameraStick.x+this.renderDist)/this.CELL_SIZE),
			top:Math.floor((this.cameraStick.y-this.renderDist)/this.CELL_SIZE),
			bottom:Math.floor((this.cameraStick.y+this.renderDist)/this.CELL_SIZE),
		}
		//clamp cell range to map
		if(this.getMapConfig('edge')!=='clamp'){
			if(!this.loopHorizontal()){
				bounds.left=Math.max(0,bounds.left);
				bounds.right=Math.min(bounds.right,Math.ceil(this.mapWidth()/this.CELL_SIZE)-1);
			}
			if(!this.loopVertical()){
				bounds.top=Math.max(0,bounds.top);
				bounds.bottom=Math.min(bounds.bottom,Math.ceil(this.mapHeight()/this.CELL_SIZE)-1);
			}
		}
		const cellsToLoad=[];
		for (let ix=bounds.left;ix<=bounds.right;++ix)
		for (let iy=bounds.top;iy<=bounds.bottom;++iy){
			let cx=ix, cy=iy;
			if(this.loopHorizontal()){ cx = cx.mod(Math.ceil(this.mapWidth()/this.CELL_SIZE)); }
			if(this.loopVertical()){ cy = cy.mod(Math.ceil(this.mapHeight()/this.CELL_SIZE)); }
			const key = [cx,cy].toString();
			if(key in this.cells){
				this.cells[key].unload=false;
			}else{
				cellsToLoad.push(new babylon["Vector2"](cx,cy));
			}
		}
		for (const key in this.cells){
			if(loadMap_mv3d.UNLOAD_CELLS && this.cells[key].unload){
				this.cells[key].dispose();
				delete this.cells[key];
			}
		}
		const cameraCellPos = new babylon["Vector2"](Math.round(this.cameraStick.x/this.CELL_SIZE-0.5),Math.round(this.cameraStick.y/this.CELL_SIZE-0.5));
		cellsToLoad.sort((a,b)=>babylon["Vector2"].DistanceSquared(a,cameraCellPos)-babylon["Vector2"].DistanceSquared(b,cameraCellPos));
		if(this.mapReady){
			cellsToLoad.length=Math.min(25,cellsToLoad.length);
		}
		for (const cellpos of cellsToLoad){
			let {x:cx,y:cy} = cellpos;
			await this.loadMapCell(cx,cy);
			if(this.mapReady){ await Object(util["sleep"])(10); }
			if(!this.mapLoaded){ this.endMapUpdate(); return; }
		}
		this.endMapUpdate();
	},

	endMapUpdate(){
		this.mapUpdating=false;
		this.mapReady=true;
	},

	async loadMapCell(cx,cy){
		const key = [cx,cy].toString();
		if(key in this.cells){ return; }
		const cell = new mapCell_MapCell(cx,cy);
		this.cells[key]=cell;
		await cell.load();
	},

	_cellsNeedingIntensiveUpdate:[],
	intensiveUpdate(){
		if(this._cellsNeedingIntensiveUpdate.length===0){ return; }
		const now = performance.now();
		let cell,index=null;
		for (cell of this._cellsNeedingIntensiveUpdate){
			if(now-cell._lastIntensiveUpdate<=300){ continue; }
			index=this._cellsNeedingIntensiveUpdate.indexOf(cell);
			break;
		}
		if(index==null||index<0){ return; }
		this._cellsNeedingIntensiveUpdate.splice(index,1);
		cell._lastIntensiveUpdate=now;
		cell._needsIntensiveUpdate=false;
		for(let character of cell.characters){
			character.intensiveUpdate();
		}
		loadMap_mv3d.scene.sortLightsByPriority();
	}

});
// CONCATENATED MODULE: ./src/assets.js
const assets_mv3d = window.mv3d;



Object.assign(mz3d,{

	animatedTextures:[],
	textureCache:{},
	materialCache:{},

	async createTexture(url){
		const textureUrl = await this.getTextureUrl(url);
		const texture = new BABYLON.Texture(textureUrl,mz3d.scene,!mz3d.MIPMAP,true,BABYLON.Texture.NEAREST_SAMPLINGMODE);
		return texture;
	},

	//getTextureUrl was here

	waitTextureLoaded(texture){return new Promise((resolve,reject)=>{
		if(texture.isReady()){ resolve(); }
		texture.onLoadObservable.addOnce(()=>{
			resolve(texture);
		});
	})},

	waitBitmapLoaded(bitmap){
		return new Promise(resolve=>bitmap.addLoadListener(()=>resolve(bitmap)));
	},

	async getCachedTilesetTexture(setN,animX=0,animY=0,options={}){
		const setImg = options.img||this.SETNAMES[setN];
		const key = `TS:${setImg}|${animX},${animY}${this.getExtraBit2(options)}`;
		if(key in this.textureCache){
			return this.textureCache[key];
		}
		const textureSrc = mz3d.getTsImgUrl(setImg);
		const texture = await this.createTexture(textureSrc);
		texture.hasAlpha=true;
		this.textureCache[key]=texture;

		await this.waitTextureLoaded(texture);

		if(this.textureCache[key]!==texture){ return await this.getErrorTexture(); }
		texture.updateSamplingMode(1);
		//texture.wrapU = Texture.CLAMP_ADDRESSMODE;
		//texture.wrapV = Texture.CLAMP_ADDRESSMODE;
		if(options.cropTexture){
			const { width, height } = texture.getBaseSize();
			let {x,y,width:w,height:h} = mz3d.finalizeTextureRect(options.cropTexture,width,height);
			texture.crop(x,y,w,h);
		}
		if(animX||animY){
			const { width, height } = texture.getBaseSize();
			texture.frameData = options.cropTexture || {x:0,y:0,width,height};
			texture.animX = animX;
			texture.animY = animY;
			this.animatedTextures.push(texture);
		}
		return texture;
		
	},

	async getErrorTexture(){
		if(this.errorTexture){ return this.errorTexture; }
		this.errorTexture = await this.createTexture(`${mz3d.MV3D_FOLDER}/${mz3d.TEXTURE_ERROR}.png`);
		this.errorTexture.isError=true;
		this.errorTexture.dispose=()=>{};
		return this.errorTexture;
	},

	async getBushAlphaTexture(){
		if(this.bushAlphaTexture){ return this.bushAlphaTexture; }
		this.getBushAlphaTexture.getting=true;
		this.bushAlphaTexture = await this.createTexture(`${mz3d.MV3D_FOLDER}/${mz3d.TEXTURE_BUSHALPHA}.png`);
		this.bushAlphaTexture.getAlphaFromRGB=true;
		this.bushAlphaTexture.dispose=()=>{};
		this.getBushAlphaTexture.getting=false;
		return this.bushAlphaTexture;
	},
	getBushAlphaTextureSync(){
		if(this.bushAlphaTexture){ return this.bushAlphaTexture; }
		if(!this.getBushAlphaTexture.getting){
			this.getBushAlphaTexture();
		}
		return null;
	},

	async getCachedTilesetMaterial(setN,animX=0,animY=0,options={}){
		this.processMaterialOptions(options);
		const key = `TS:${options.img||this.SETNAMES[setN]}|${animX},${animY}|${this.getExtraBit(options)}${this.getExtraBit2(options)}`;
		if(key in this.materialCache){
			return this.materialCache[key];
		}
		const texture = await this.getCachedTilesetTexture(setN,animX,animY,options);
		const material = new babylon["StandardMaterial"](key, this.scene);
		material.diffuseTexture=texture;
		if(options.transparent){
			material.opacityTexture=texture;
			material.alpha=options.alpha;
		}
		if(options.through){
			material.mv3d_through=true;
		}
		material.mv3d_noShadow=!options.shadow;
		material.alphaCutOff = mz3d.ALPHA_CUTOFF;
		//material.ambientColor.set(1,1,1);
		material.ambientColor.copyFrom(options.ambient);
		material.mv3d_glowColor=options.glow;
		material.emissiveColor.copyFrom(options.glow);
		material.specularColor.set(0,0,0);
		material.backFaceCulling=options.backfaceCulling;
		material.twoSidedLighting=options.twosided;
		material.maxSimultaneousLights=this.LIGHT_LIMIT;
		//material.mv3d_is_cached=true;
		this.materialCache[key]=material;
		return material;
	},

	async getCachedTilesetMaterialForTile(tileConf,side){
		const setN = mz3d.getSetNumber(tileConf[`${side}_id`]);
		const options = mz3d.getMaterialOptions(tileConf,side);
		const animData = mz3d.getTileAnimationData(tileConf,side);
		//console.log(options);
		return await mz3d.getCachedTilesetMaterial(setN,animData.animX,animData.animY,options);
	},

	getMaterialOptions(conf,side){
		const options={};
		if ('cropTexture' in conf){ options.cropTexture=conf.cropTexture; }
		if ('pass' in conf){ options.through=conf.pass===this.enumPassage.THROUGH; }
		if ('alpha' in conf){ options.alpha=conf.alpha; }
		if ('glow' in conf){ options.glow=conf.glow; }
		if ('ambient' in conf){ options.ambient=conf.ambient; }
		if ('shadow' in conf){ options.shadow=conf.shadow; }
		if(side){
			if(`${side}_alpha` in conf){ options.alpha=conf[`${side}_alpha`]; }
			if(`${side}_glow` in conf){ options.glow=conf[`${side}_glow`]; }
			if(`${side}_shadow` in conf){ options.shadow=conf[`${side}_shadow`]; }
			if(`${side}_img` in conf){ options.img=conf[`${side}_img`]; }
		}
		if(conf.isCeiling){
			options.through = !conf.twosided;
		}
		if(conf.twosided){ options.backfaceCulling=false;options.twosided=true; }
		if('alpha' in options){ options.transparent=true; }
		return options;
	},

	processMaterialOptions(options){
		if('alpha' in options){
			options.alpha = Math.round(options.alpha*7)/7;
			if(options.alph<1){
				options.transparent=true;
			}
		}else{ options.alpha=1; }
		if('glow' in options){
			options.glow.r = Object(util["unround"])(options.glow.r,255);
			options.glow.g = Object(util["unround"])(options.glow.g,255);
			options.glow.b = Object(util["unround"])(options.glow.b,255);
			options.glow.a = Object(util["unround"])(options.glow.a,7);
		}else{ options.glow=new babylon["Color4"](0,0,0,0); }
		if('ambient' in options){
			options.ambient.r = Object(util["unround"])(options.ambient.r,255);
			options.ambient.g = Object(util["unround"])(options.ambient.g,255);
			options.ambient.b = Object(util["unround"])(options.ambient.b,255);
		}else{ options.ambient=new babylon["Color3"](1,1,1); }
		if(!('shadow' in options)){options.shadow=true;}
		if(!('backfaceCulling' in options)){ options.backfaceCulling = mz3d.BACKFACE_CULLING; }
	},

	getExtraBit(options){
		let extra = 0;
		extra|=Boolean(options.transparent)<<0;
		extra|=7-options.alpha*7<<1;
		extra|=(!options.shadow)<<4;
		extra|=options.glow.a*7<<5;
		extra|=options.glow.toNumber()<<8;
		// out of bits.
		let string = extra.toString(36);
		extra = 0;
		extra|=Boolean(options.through)<<0;
		extra|=(!options.backfaceCulling)<<1;
		extra|=Boolean(options.twosided)<<2;
		// 5 empty bits here
		extra|=(0xffffff-options.ambient.toNumber())<<8;
		// 
		string += ','+extra.toString(36);
		return string;
	},

	getExtraBit2(options){
		let string = '';
		if(options.cropTexture){
			const ct=options.cropTexture
			string += `|crop:${ct.x},${ct.y},${ct.width},${ct.height}`;
		}
		return string;
	},

	// animations

	lastAnimUpdate:0,
	animXFrame:0,
	animYFrame:0,
	animDirection:1,
	updateAnimations(){
		if( performance.now()-this.lastAnimUpdate <= this.ANIM_DELAY){ return; }
		this.lastAnimUpdate=performance.now();

		if(this.animXFrame<=0){
			this.animDirection=1;
		}else if(this.animXFrame>=2){
			this.animDirection=-1;
		}
		this.animXFrame += this.animDirection;
		this.animYFrame=(this.animYFrame+1)%3;
		for (const texture of this.animatedTextures){
			texture.crop(
				texture.frameData.x+texture.animX*this.animXFrame*Object(util["tileWidth"])(),
				texture.frameData.y+texture.animY*this.animYFrame*Object(util["tileHeight"])(),
				texture.frameData.width,
				texture.frameData.height,
			);
		}
	},

});
// CONCATENATED MODULE: ./src/characters.js







Object.assign(main["a" /* default */],{
	createCharacters(){
		const events = $gameMap.events();
		for (const event of events){
			this.createCharacterFor(event,0);
		}
		const vehicles = $gameMap.vehicles();
		for (const vehicle of vehicles){
			this.createCharacterFor(vehicle,1);
		}
		const followers = $gamePlayer.followers()._data;
		for (let f=followers.length-1; f>=0; --f){
			this.createCharacterFor(followers[f],29-f);
		}
		this.createCharacterFor($gamePlayer,30);
	},

	createCharacterFor(char,order){
		if(!char.mv3d_sprite){
			const sprite = new characters_Character(char,order);
			Object.defineProperty(char,'mv3d_sprite',{
				value:sprite,
				enumerable:false,
				configurable:true,
			});
			this.characters.push(sprite);
			return sprite;
		}
		return char.mv3d_sprite;
	},

	updateCharacters(){
		for (let i=this.characters.length-1; i>=0; --i){
			this.characters[i].update();
		}
	},

	updateDynamicNormals(){
		if(!main["a" /* default */].DYNAMIC_NORMALS||!this.blendSunColor){ return; }
		const pitch = this.blendSunColor.averageCurrentValue()<128 ? this.blendSunColor.averageCurrentValue()/128 * this.blendCameraPitch.currentValue() : this.blendCameraPitch.currentValue();
		const y = Object(util["sin"])(Object(util["degtorad"])(pitch));
		const z = -Object(util["cos"])(Object(util["degtorad"])(pitch));
		this.Meshes.SPRITE.updateVerticesData(BABYLON.VertexBuffer.NormalKind, [ 0,y,z, 0,y,z, 0,y,z, 0,y,z ]);
	},

	setupSpriteMeshes(){
		const meshes = this.Meshes = {};

		const vdata = new babylon["VertexData"]();
		vdata.indices=[1,0,2,1,2,3];
		vdata.uvs=[0,1,1,1,0,0,1,0];
		const normals_up = [ 0,1,0, 0,1,0, 0,1,0, 0,1,0 ];
		const normals_front = [ 0,0,-1, 0,0,-1, 0,0,-1, 0,0,-1 ]

		vdata.positions=[ -0.5,0.5,0, 0.5,0.5,0, -0.5,-0.5,0, 0.5,-0.5,0 ];
		vdata.normals=normals_front;
		meshes.BASIC = new babylon["Mesh"]('basic mesh', main["a" /* default */].scene);
		vdata.applyToMesh(meshes.BASIC,false);

		vdata.positions=[ -0.5,0,0.5, 0.5,0,0.5, -0.5,0,-0.5, 0.5,0,-0.5 ];
		vdata.normals=normals_up;
		meshes.FLAT = new babylon["Mesh"]('flat mesh', main["a" /* default */].scene);
		vdata.applyToMesh(meshes.FLAT,false);

		vdata.positions=[ -0.5,1,0, 0.5,1,0, -0.5,0,0, 0.5,0,0 ];
		vdata.normals=main["a" /* default */].DYNAMIC_NORMALS?normals_up:normals_front;
		meshes.SPRITE = new babylon["Mesh"]('sprite mesh', main["a" /* default */].scene);
		vdata.applyToMesh(meshes.SPRITE,true);
		meshes.BOARD = new babylon["Mesh"]('board mesh', main["a" /* default */].scene);
		vdata.applyToMesh(meshes.BOARD,false);

		vdata.normals=normals_front;
		meshes.WALL = new babylon["Mesh"]('wall mesh', main["a" /* default */].scene);
		vdata.applyToMesh(meshes.WALL,false);

		vdata.normals=main["a" /* default */].ABNORMAL?normals_up:normals_front;
		meshes.TEMP_CROSS = new babylon["Mesh"]('cross mesh', main["a" /* default */].scene);
		vdata.applyToMesh(meshes.TEMP_CROSS,false);
		meshes.CROSS=babylon["Mesh"].MergeMeshes([
			meshes.TEMP_CROSS.clone(),
			meshes.TEMP_CROSS.clone().rotate(util["YAxis"],Math.PI/2,mod_babylon["h" /* WORLDSPACE */]),
		]);
		meshes['8CROSS']=babylon["Mesh"].MergeMeshes([
			meshes.CROSS.clone(),
			meshes.CROSS.clone().rotate(util["YAxis"],Math.PI/4,mod_babylon["h" /* WORLDSPACE */]),
		]);

		for (const key in meshes){
			meshes[key].renderingGroupId=main["a" /* default */].enumRenderGroups.MAIN;
			main["a" /* default */].scene.removeMesh(meshes[key]);
			if(key.startsWith('TEMP_')){
				meshes[key].dispose();
				delete meshes[key];
			}
		}
	},

	async getShadowMaterial(){
		if(this._shadowMaterial){ return this._shadowMaterial; }
		const shadowTexture = await main["a" /* default */].createTexture(`${main["a" /* default */].MV3D_FOLDER}/${main["a" /* default */].TEXTURE_SHADOW}.png`);
		const shadowMaterial = new babylon["StandardMaterial"]('shadow material', main["a" /* default */].scene);
		this._shadowMaterial=shadowMaterial;
		shadowMaterial.diffuseTexture=shadowTexture;
		shadowMaterial.opacityTexture=shadowTexture;
		shadowMaterial.specularColor.set(0,0,0);
		shadowMaterial.dispose=()=>{};
		return shadowMaterial;
	},
	async getShadowMesh(){
		let shadowMesh;
		while(this.getShadowMesh.getting){ await Object(util["sleep"])(100); }
		if(this._shadowMesh){ shadowMesh=this._shadowMesh}
		else{
			this.getShadowMesh.getting=true;
			shadowMesh=main["a" /* default */].Meshes.FLAT.clone('shadow mesh');
			shadowMesh.material=await this.getShadowMaterial();
			this._shadowMesh=shadowMesh;
			main["a" /* default */].scene.removeMesh(shadowMesh);
			this.getShadowMesh.getting=false;
		}
		return shadowMesh.clone();
	},

	ACTOR_SETTINGS: [],
});

const z_descriptor = {
	configurable: true,
	enumerable:false,
	get(){ return this._mv3d_z; },
	set(v){
		this._mv3d_z=v;
		if(this.mv3d_sprite){ this.mv3d_sprite.position.y=v; }
	}
}
const z_descriptor2 = {
	configurable: true,
	enumerable:false,
	get(){ return this.char._mv3d_z; },
	set(v){
		this.char._mv3d_z=v;
		this.position.y=v;
	}
}

class characters_Character extends babylon["TransformNode"]{
	constructor(char,order){
		super('character',main["a" /* default */].scene);
		this.spriteOrigin = new babylon["TransformNode"]('sprite origin',main["a" /* default */].scene);
		this.spriteOrigin.parent=this;
		this.model = new model_Model({orphan:false});
		this.model.parent = this.spriteOrigin;
		this.model.order=order;
		this.model.character = this;

		//this.order=order;
		//this.mesh.order=this.order;
		//this.mesh.character=this;
		
		this._character=this.char=char;
		this.charName='';
		this.charIndex=0;
		
		if(this.char.mv_sprite){
			this.char.mv_sprite.updateBitmap();
		}

		if(!this.char.mv3d_settings){ this.char.mv3d_settings={}; }
		if(!this.char.mv3d_blenders){ this.char.mv3d_blenders={}; }

		this.isVehicle = this.char instanceof Game_Vehicle;
		this.isBoat = this.isVehicle && this.char.isBoat();
		this.isShip = this.isVehicle && this.char.isShip();
		this.isAirship = this.isVehicle && this.char.isAirship();
		this.isEvent = this.char instanceof Game_Event;
		this.isPlayer = this.char instanceof Game_Player;
		this.isFollower = this.char instanceof Game_Follower;

		this.updateCharacter();
		this.updateShape();

		if(!('_mv3d_z' in this.char)){
			this.char._mv3d_z = main["a" /* default */].getWalkHeight(this.char.x,this.char.y);
		}
		Object.defineProperty(this.char,'z',z_descriptor);
		Object.defineProperty(this,'z',z_descriptor2);
		this.z=this.z;
		this.platformHeight = this.z;
		this.targetElevation = this.z;
		this.prevZ = this.z;
		this.needsPositionUpdate=true;
		this.needsMaterialUpdate=true;
		this.needsScaleUpdate=false;
		//this.elevation = 0;

		main["a" /* default */].getShadowMesh().then(shadow=>{
			this.shadow = shadow;
			this.shadow.parent = this;
		});

		this.blendElevation = this.makeBlender('elevation',0);

		this.lightOrigin = new babylon["TransformNode"]('light origin',main["a" /* default */].scene);
		this.lightOrigin.parent=this;
		this.setupLights();
		
		if(this.isEvent){
			this.eventConfigure();
		}else{
			this.initialConfigure();
			this.needsMaterialUpdate=true;
		}

		this.intensiveUpdate();
	}

	dispose(...args){
		this.model.dispose();
		super.dispose(...args);
	}

	//===========================
	//  Texture & Model
	//===========================

	async setMaterial(src){
		await this.model.setMaterial(src);
		this.updateScale();
		this.needsMaterialUpdate=true;
	}

	get settings(){ return this.char.mv3d_settings; }

	isBitmapReady(){
		return Boolean(this.mv_sprite && this.bitmap && this.bitmap.isReady() && !this._waitingForBitmap);
	}

	isTextureReady(){
		const texture = this.model.texture
		return Boolean(
			texture && texture.isReady() && this.isBitmapReady()
		);
	}

	get mv_sprite(){
		return this.char.mv_sprite;
	}
	get bitmap(){
		return this.mv_sprite.bitmap;
	}
	get shape(){
		return this.model.shape;
	}
	get tileId(){
		return this.getConfig('texture_id',this._tileId);
	}

	setTileMaterial(tileId){
		const textureSrc = main["a" /* default */].getTsImgUrl(main["a" /* default */].getSetName(tileId));
		this.setMaterial(textureSrc);
	}
	async setRectMaterial(img,rect){
		const textureSrc = main["a" /* default */].getTsImgUrl(img);
		await this.setMaterial(textureSrc);
		this.dontCrop=true;
		const { width, height } = this.model.texture.getBaseSize();
		rect = main["a" /* default */].finalizeTextureRect(rect,width,height);
		this.textureRect = rect;
		this.model.texture.crop(rect.x,rect.y,rect.width,rect.height);
		this.updateScale();
	}

	async waitBitmapLoaded(){
		if(!this.char.mv_sprite){
			await Object(util["sleep"])();
			if(!this.char.mv_sprite){
				console.warn('mv_sprite is undefined');
				return;
			}
		}
		this._waitingForBitmap=true;
		this.char.mv_sprite.updateBitmap();
		await main["a" /* default */].waitBitmapLoaded(this.char.mv_sprite.bitmap);
		this._waitingForBitmap=false;
	}

	async waitTextureLoaded(texture=this.model.texture){
		await this.waitBitmapLoaded();
		await main["a" /* default */].waitTextureLoaded(texture);
	}

	isImageChanged(){
		return (this._tilesetId !== $gameMap.tilesetId()
		||this._tileId !== this._character._tileId
		||this._characterName !== this._character.characterName()
		//||this._characterIndex !== this._character.characterIndex()
		||this._texture_symbol !== this.getConfig('texture_symbol')
		||this.isComplex !== this.model.isComplexMesh()
		);
	}
	updateCharacter(){
		//if(!this.isBitmapReady()){ return; }
		this.needsPositionUpdate=true;
		this._tilesetId = $gameMap.tilesetId();
		this._tileId = this._character._tileId;
		this._characterName = this._character.characterName();
		this._characterIndex = this._character.characterIndex();
		this._isBigCharacter = ImageManager.isBigCharacter(this._characterName);
		this._texture_symbol = this.getConfig('texture_symbol');
		this.isEmpty=false;
		this.isComplex=this.model.isComplexMesh();
		this.model.setEnabled(true);
		this.dontCrop=false;
		delete this.textureRect;
		if(this.hasConfig('texture_rect')){
			this.setRectMaterial(this.getConfig('texture_img','B'),this.getConfig('texture_rect'));
		}else if(this.tileId>0 || this.isComplex){
			this.setTileMaterial(this.tileId);
		}else if(this._characterName){
			this.setMaterial(`img/characters/${this._characterName}.png`);
		}else{
			this.isEmpty=true;
			this.model.textureLoaded=false;
			this.model.disposeMaterial();
			this.model.setEnabled(false);
			this.spriteWidth=1;
			this.spriteHeight=1;
			this.updateScale();
		}
	}
	setFrame(x,y,w,h){
		if(!this.isTextureReady()||this.dontCrop){ return; }
		this.model.texture.crop(x,y,w,h);
	}

	async updateScale(){
		this.needsScaleUpdate=false;
		if(this.isEmpty){
			this.spriteWidth=1;
			this.spriteHeight=1;
			if(this.model.mesh)this.model.scaling.set(1,1,1);
			return;
		}
		const configScale = this.getConfig('scale',new babylon["Vector2"](1,1));
		if(this.isComplex){
			this.spriteWidth = configScale.x;
			this.spriteHeight = configScale.y;
		}else{
			if(!this.isBitmapReady()){ this.needsScaleUpdate=true; return; }
			this.mv_sprite.updateBitmap();
			if(this.textureRect){
				var width = this.textureRect.width;
				var height = this.textureRect.height;
			}else{
				var width = this.mv_sprite.patternWidth();
				var height = this.mv_sprite.patternHeight();
			}
			this.spriteWidth = width/Object(util["tileWidth"])() * configScale.x;
			this.spriteHeight = height/Object(util["tileHeight"])() * configScale.y;
		}
		const xscale = this.spriteWidth;
		const yscale = this.spriteHeight;
		if(this.model.mesh){
			if(this.model.shape===main["a" /* default */].enumShapes.SPRITE){
				this.model.scaling.set(1,1,1);
				this.model.mesh.scaling.set(xscale,yscale,yscale);
			}else if(this.model.shape===main["a" /* default */].enumShapes.FLAT){
				this.model.scaling.set(xscale,yscale,yscale);
				this.model.mesh.scaling.set(1,1,1);
			}else{
				this.model.scaling.set(xscale,yscale,xscale);
				this.model.mesh.scaling.set(1,1,1);
			}
		}
	}

	getShape(){
		return this.getConfig('shape', main["a" /* default */].enumShapes.SPRITE );
	}
	async updateShape(){
		const shape = this.getShape();
		if(shape===main["a" /* default */].enumShapes.MODEL){
			await this.model.importModel(this.getConfig('model'));
		}else{
			this.model.setMeshForShape(shape);
		}
		this.updateConfiguration();
		this.dirtyNearbyCells();
	}

	updateEmissive(){
		const materials = this.model.materials;
		if(!materials.length){ return; }
		const glow = this.getConfig('glow', new babylon["Color4"](0,0,0,0));
		if(this.lamp){
			var lampColor = this.lamp.diffuse;
			var intensity = Math.max(0,Math.min(1,this.lamp.intensity,this.lamp.range,this.lamp.intensity/4+this.lamp.range/4));	
		}
		const blendColor = this.mv_sprite._blendColor;
		const blendAlpha=blendColor[3]/255;
		const noShadow = !this.getConfig('dynShadow',true);
		for(const material of materials){
			const emissiveColor = material.emissiveColor;
			if(!material._mv3d_orig_emissiveColor){ material._mv3d_orig_emissiveColor = emissiveColor.clone(); }
			const orig_emissive = material._mv3d_orig_emissiveColor;
			material.mv3d_glowColor=glow;
			if(this.lamp){
				emissiveColor.set(
					Math.max(glow.r,lampColor.r*intensity,orig_emissive.r),
					Math.max(glow.g,lampColor.g*intensity,orig_emissive.g),
					Math.max(glow.b,lampColor.b*intensity,orig_emissive.b)
				);
			}else{
				emissiveColor.set(
					Math.max(glow.r,orig_emissive.r),
					Math.max(glow.g,orig_emissive.g),
					Math.max(glow.b,orig_emissive.b)
				);
			}
			emissiveColor.r+=(2-emissiveColor.r)*Math.pow(blendColor[0]/255*blendAlpha,0.5);
			emissiveColor.g+=(2-emissiveColor.g)*Math.pow(blendColor[1]/255*blendAlpha,0.5);
			emissiveColor.b+=(2-emissiveColor.b)*Math.pow(blendColor[2]/255*blendAlpha,0.5);

			if(this.hasConfig('ambient')){
				material.ambientColor.copyFrom(this.getConfig('ambient'));
			}else{
				material.ambientColor.set(1,1,1);
			}
	
			material.mv3d_noShadow=noShadow;
		}
	}

	setupMesh(){
		if(!this.model.mesh){ return; }
		if(this.isEmpty){
			this.model.setEnabled(false);
		}else{
			this.model.setEnabled(true);
		}
		if(this.flashlight){
			this.flashlight.excludedMeshes.splice(0,Infinity);
			this.flashlight.excludedMeshes.push(...this.model.meshes);
		}
		this.updateScale();
		this.model.mesh.character=this;
	}

	//===========================
	//	CONFIGURATION & LIGHTS
	//===========================

	getDefaultConfigObject(){
		if(this.isVehicle){
			return main["a" /* default */][`${this.char._type.toUpperCase()}_SETTINGS`].conf;
		}
		if(this.char.isTile()){
			return main["a" /* default */].EVENT_TILE_SETTINGS;
		}else if(this.isEvent && this.char.isObjectCharacter()){
			return main["a" /* default */].EVENT_OBJ_SETTINGS;
		}else{
			return main["a" /* default */].EVENT_CHAR_SETTINGS;
		}
	}

	getActorConfigObject(){
		const id = $gameParty._actors[ this.isFollower ? this.char._memberIndex : 0 ];
		if(!id){ return {}; }
		if(!(id in main["a" /* default */].ACTOR_SETTINGS)){
			const data = $dataActors[id];
			main["a" /* default */].ACTOR_SETTINGS[id]=main["a" /* default */].readConfigurationFunctions(
				main["a" /* default */].readConfigurationBlocksAndTags(data.note),
				main["a" /* default */].eventConfigurationFunctions
			);
		}
		return main["a" /* default */].ACTOR_SETTINGS[id];
	}

	getConfig(key,dfault=undefined){
		if(key in this.settings){ return this.settings[key]; }
		if(this.isEvent){
			if(this.settings_event_page && key in this.settings_event_page){
				return this.settings_event_page[key];
			}else if(this.settings_event && key in this.settings_event){
				return this.settings_event[key];
			}
		}else if(this.isPlayer||this.isFollower){
			const ACTOR_SETTINGS = this.getActorConfigObject();
			if(key in ACTOR_SETTINGS){
				return ACTOR_SETTINGS[key];
			}
		}
		const EVENT_SETTINGS = this.getDefaultConfigObject();
		if(key in EVENT_SETTINGS){
			return EVENT_SETTINGS[key];
		}
		return dfault;
	}
	hasConfig(key){
		return key in this.settings
		||this.isEvent &&
			(this.settings_event_page && key in this.settings_event_page
			|| this.settings_event && key in this.settings_event)
		|| (this.isPlayer||this.isFollower) && key in this.getActorConfigObject()
		|| key in this.getDefaultConfigObject();
	}

	eventConfigure(){
		if(!this.settings_event){
			this.settings_event={};
			const note = this.char.event().note;
			this.settings_event._eventTileId=this.char._tileId;
			main["a" /* default */].readConfigurationFunctions(
				main["a" /* default */].readConfigurationTags(note),
				main["a" /* default */].eventConfigurationFunctions,
				this.settings_event,
			);

			this.initialConfigure();
		}
		this.settings_event_page={};
		const page = this.char.page();
		if(!page){ return; }
		let comments = '';
		for (const command of page.list){
			if(command.code===108||command.code===408){
				comments+=command.parameters[0];
			}
		}
		this.settings_event_page._eventTileId=this.char._tileId;
		main["a" /* default */].readConfigurationFunctions(
			main["a" /* default */].readConfigurationTags(comments),
			main["a" /* default */].eventConfigurationFunctions,
			this.settings_event_page,
		);
		this.updateShape();

		if(this.char.mv3d_needsConfigure){
			this.char.mv3d_needsConfigure=false;
			this.needsPositionUpdate=true;
		}else{ return; }

		this.pageConfigure();

	}

	initialConfigure(){
		this.configureHeight();
		this.updateConfiguration();
	}

	pageConfigure(settings=this.settings_event_page){
		const transient = settings===this.settings;
		if('pos' in settings){
			const event=this.char.event();
			const pos = settings.pos;
			if('x' in pos||'y' in pos){
				this.char.locate(
					'x' in pos?Object(util["relativeNumber"])(event.x,pos.x):this.char.x,
					'y' in pos?Object(util["relativeNumber"])(event.y,pos.y):this.char.y,
				);
			}
			if('z' in pos){
				this.z = Object(util["relativeNumber"])(main["a" /* default */].getWalkHeight(event.x,event.y),pos.z);
			}
			if(transient)delete settings.pos;
		}
		this.setupEventLights();

		if(this.lamp){
			if('lamp' in settings){
				const lampConfig = this.getConfig('lamp');
				this.blendLampColor.setValue(lampConfig.color,0.5);
				this.blendLampIntensity.setValue(lampConfig.intensity,0.5);
				this.blendLampDistance.setValue(lampConfig.distance,0.5);
			}
			if(transient)delete settings.lamp;
		}
		if(this.flashlight){
			if('flashlight' in settings){
				const flashlightConfig = this.getConfig('flashlight');
				this.blendFlashlightColor.setValue(flashlightConfig.color,0.5);
				this.blendFlashlightIntensity.setValue(flashlightConfig.intensity,0.5);
				this.blendFlashlightDistance.setValue(flashlightConfig.distance,0.5);
				this.blendFlashlightAngle.setValue(flashlightConfig.angle,0.5);
				if(transient)delete settings.flashlight;
			}
			if('flashlightPitch' in settings){
				this.blendFlashlightPitch.setValue(this.getConfig('flashlightPitch',90),0.25);
				if(transient)delete settings.flashlightPitch;
			}
		}
		if('height' in settings || this.isAbove!==(this.char._priorityType===2)){
			this.configureHeight();
			if(transient)delete settings.height;
		}

		this.updateScale();
		this.updateShape();
		this.needsMaterialUpdate=true;
		this.needsPositionUpdate=true;
		this.updateLightOffsets();
	}

	configureHeight(){
		this.isAbove = this.char._priorityType===2;
		let height = Math.max(0, this.getConfig('height',this.isAbove&&!this.hasConfig('zlock')&&!this.isAirship?main["a" /* default */].EVENT_HEIGHT:0) );
		this.blendElevation.setValue(height,0);
		if(this.isEvent) this.z = this.platformHeight + height;
	}

	updateConfiguration(){
		const shapes = main["a" /* default */].enumShapes;
		if(this.model.shape===shapes.SPRITE){
			this.spriteOrigin.pitch=0;
			this.spriteOrigin.yaw=0;
		}else if(this.model.shape===shapes.BOARD){
			this.spriteOrigin.pitch=this.getConfig('pitch',0);
			this.spriteOrigin.yaw=this.getConfig('yaw',0);
		}else{
			this.model.yaw=this.getConfig('rot',0);
			this.spriteOrigin.pitch=this.getConfig('pitch',0);
			this.spriteOrigin.yaw=this.getConfig('yaw',0);
			//if(this.shape===shapes.XCROSS){this.mesh.yaw+=45;}
		}
		this.updateScale();
	}

	dirtyNearbyCells(){
		if(!this.cell){ return; }
		characters_Character.dirtyNearbyCells(this.cell.cx,this.cell.cy);
	}
	static dirtyNearbyCells(cx,cy){
		for(let ix=cx-1; ix<=cx+1; ++ix)
		for(let iy=cy-1; iy<=cy+1; ++iy){
			let x=ix, y=iy;
			if(main["a" /* default */].loopHorizontal()){ x=x.mod(Math.ceil(main["a" /* default */].mapWidth()/main["a" /* default */].CELL_SIZE)); }
			if(main["a" /* default */].loopVertical()){ y=y.mod(Math.ceil(main["a" /* default */].mapHeight()/main["a" /* default */].CELL_SIZE)); }
			const cell = main["a" /* default */].cells[[x,y]];
			if(!cell){ continue; }
			if(!cell._needsIntensiveUpdate){
				cell._needsIntensiveUpdate=true;
				main["a" /* default */]._cellsNeedingIntensiveUpdate.push(cell);
			}
		}
	}

	intensiveUpdate(){
		this.setupLightInclusionLists();
		this.updateScale();
	}

	setupLightInclusionLists(){
		if(this.flashlight){
			this.flashlight.includedOnlyMeshes.splice(0,Infinity);
			this.flashlight.includedOnlyMeshes.push(...this.getMeshesInRangeOfLight(this.flashlight));
		}
		if(this.lamp){
			this.lamp.includedOnlyMeshes.splice(0,Infinity);
			this.lamp.includedOnlyMeshes.push(...this.getMeshesInRangeOfLight(this.lamp));
		}
	}

	getMeshesInRangeOfLight(light){
		if(!this.cell){ return []; }
		const pos = babylon["Vector3"].TransformCoordinates(light.position,light.getWorldMatrix());
		const meshes=[];
		for(let _cx=this.cell.cx-1; _cx<=this.cell.cx+1; ++_cx)
		for(let _cy=this.cell.cy-1; _cy<=this.cell.cy+1; ++_cy){
			let cx=_cx, cy=_cy;
			if(main["a" /* default */].loopHorizontal()){ cx=cx.mod(Math.ceil(main["a" /* default */].mapWidth()/main["a" /* default */].CELL_SIZE)); }
			if(main["a" /* default */].loopVertical()){ cy=cy.mod(Math.ceil(main["a" /* default */].mapHeight()/main["a" /* default */].CELL_SIZE)); }
			const cell = main["a" /* default */].cells[[cx,cy]];
			if(!cell||!cell.mesh){ continue; }
			const sphere = cell.mesh.getBoundingInfo().boundingSphere;
			const dist = babylon["Vector3"].Distance(pos,sphere.centerWorld);
			if(dist>=sphere.radiusWorld+light.range){ continue; }
			meshes.push(cell.mesh);
			for(const character of cell.characters)for(const mesh of character.model.meshes){
				const sphere = mesh.getBoundingInfo().boundingSphere;
				const dist = babylon["Vector3"].Distance(pos,sphere.centerWorld);
				if(dist>=sphere.radiusWorld+light.range){ continue; }
				meshes.push(mesh);
			}
		}
		return meshes;
	}

	setupEventLights(){
		const flashlightConfig = this.getConfig('flashlight');
		const lampConfig = this.getConfig('lamp');
		if(flashlightConfig && !this.flashlight){
			this.setupFlashlight();
		}
		if(lampConfig && !this.lamp){
			this.setupLamp();
		}
	}
	setupLights(){
		if('flashlightColor' in this.char.mv3d_blenders){
			this.setupFlashlight();
		}
		if('lampColor' in this.char.mv3d_blenders){
			this.setupLamp();
		}
	}

	setupFlashlight(){
		if(this.flashlight){ return; }
		const config = this.getConfig('flashlight',{
			color:0xffffff,
			intensity:1,
			distance:main["a" /* default */].LIGHT_DIST,
			angle:main["a" /* default */].LIGHT_ANGLE,
		});
		this.blendFlashlightColor = this.makeColorBlender('flashlightColor',config.color);
		this.blendFlashlightIntensity = this.makeBlender('flashlightIntensity',config.intensity);
		this.blendFlashlightDistance = this.makeBlender('flashlightDistance',config.distance);
		const lightDist = this.blendFlashlightDistance.targetValue();
		this.blendFlashlightDistance.setValue(0,0); this.blendFlashlightDistance.setValue(lightDist,0.25);
		this.blendFlashlightAngle = this.makeBlender('flashlightAngle',config.angle);
		this.flashlight = new babylon["SpotLight"]('flashlight',babylon["Vector3"].Zero(),babylon["Vector3"].Zero(),
			Object(util["degtorad"])(this.blendFlashlightAngle.targetValue()+main["a" /* default */].FLASHLIGHT_EXTRA_ANGLE),0,main["a" /* default */].scene);
		this.flashlight.renderPriority=2;
		this.updateFlashlightExp();
		this.flashlight.range = this.blendFlashlightDistance.targetValue();
		this.flashlight.intensity=this.blendFlashlightIntensity.targetValue()*main["a" /* default */].FLASHLIGHT_INTENSITY_MULTIPLIER;
		this.flashlight.diffuse.set(...this.blendFlashlightColor.targetComponents());
		this.flashlight.specular.set(0,0,0);
		//this.flashlight.projectionTexture = mv3d.getFlashlightTexture();
		this.flashlight.direction.y=-1;
		this.flashlightOrigin=new babylon["TransformNode"]('flashlight origin',main["a" /* default */].scene);
		this.flashlightOrigin.parent=this.lightOrigin;
		this.flashlight.parent=this.flashlightOrigin;
		this.blendFlashlightPitch = this.makeBlender('flashlightPitch',90);
		this.blendFlashlightYaw = this.makeBlender('flashlightYaw', 0);
		this.blendFlashlightYaw.cycle=360;
		this.updateFlashlightDirection();
		this.setupMesh();
		this.updateLightOffsets();
	}

	updateFlashlightExp(){
		this.flashlight.exponent = 64800*Math.pow(this.blendFlashlightAngle.currentValue(),-2);
	}

	setupLamp(){
		if(this.lamp){ return; }
		const config = this.getConfig('lamp',{
			color:0xffffff,
			intensity:1,
			distance:main["a" /* default */].LIGHT_DIST,
		});
		this.blendLampColor = this.makeColorBlender('lampColor',config.color);
		this.blendLampIntensity = this.makeBlender('lampIntensity',config.intensity);
		this.blendLampDistance = this.makeBlender('lampDistance',config.distance);
		const lightDist = this.blendLampDistance.targetValue();
		this.blendLampDistance.setValue(0,0); this.blendLampDistance.setValue(lightDist,0.25);
		this.lamp = new babylon["PointLight"]('lamp',babylon["Vector3"].Zero(),main["a" /* default */].scene);
		this.lamp.renderPriority=1;
		this.lamp.diffuse.set(...this.blendLampColor.targetComponents());
		this.lamp.specular.set(0,0,0);
		this.lamp.intensity=this.blendLampIntensity.targetValue();
		this.lamp.range=this.blendLampDistance.targetValue();
		this.lampOrigin=new babylon["TransformNode"]('lamp origin',main["a" /* default */].scene);
		this.lampOrigin.parent = this.lightOrigin;
		this.lamp.parent=this.lampOrigin;
		this.updateLightOffsets();
	}

	updateFlashlightDirection(){
		this.flashlightOrigin.yaw=this.blendFlashlightYaw.currentValue();
		this.flashlightOrigin.pitch=-this.blendFlashlightPitch.currentValue();
		//this.flashlightOrigin.position.set(0,0,0);
		//let flashlightOffset = Math.tan(degtorad(90-this.blendFlashlightAngle.currentValue()-Math.max(90,this.blendFlashlightPitch.currentValue())+90))*mv3d.LIGHT_HEIGHT;
		//flashlightOffset = Math.max(0,Math.min(1,flashlightOffset));
		//this.flashlight.range+=flashlightOffset;
		//this.flashlightOrigin.translate(YAxis,flashlightOffset,LOCALSPACE);
	}

	updateLights(){
		if(this.flashlight){
			let flashlightYaw = 180+Object(util["relativeNumber"])( main["a" /* default */].dirToYaw( this.char.mv3d_direction(),main["a" /* default */].DIR8MOVE ), this.getConfig('flashlightYaw','+0'));
			let firstPerson=this.isPlayer&&main["a" /* default */].is1stPerson();
			if(this.isPlayer){
				let flashlightPitch = this.getConfig('flashlightPitch',90);
				if(firstPerson){
					flashlightYaw=180+main["a" /* default */].blendCameraYaw.currentValue();
					flashlightPitch=main["a" /* default */].blendCameraPitch.currentValue();
				}
				this.blendFlashlightPitch.setValue(flashlightPitch,firstPerson?0:0.25);
			}
			if(flashlightYaw !== this.blendFlashlightYaw.targetValue()){
				this.blendFlashlightYaw.setValue(flashlightYaw,firstPerson?0:0.25);
			}
			if(this.blendFlashlightColor.update()|this.blendFlashlightIntensity.update()
			|this.blendFlashlightDistance.update()|this.blendFlashlightAngle.update()
			|this.blendFlashlightYaw.update()|this.blendFlashlightPitch.update()){
				this.flashlight.diffuse.set(...this.blendFlashlightColor.currentComponents());
				this.flashlight.intensity=this.blendFlashlightIntensity.currentValue()*main["a" /* default */].FLASHLIGHT_INTENSITY_MULTIPLIER;
				this.flashlight.range=this.blendFlashlightDistance.currentValue();
				this.flashlight.angle=Object(util["degtorad"])(this.blendFlashlightAngle.currentValue()+main["a" /* default */].FLASHLIGHT_EXTRA_ANGLE);
				this.updateFlashlightExp();
				this.updateFlashlightDirection();
			}
		}
		if(this.lamp){
			if(this.blendLampColor.update()|this.blendLampIntensity.update()|this.blendLampDistance.update()){
				this.lamp.diffuse.set(...this.blendLampColor.currentComponents());
				this.lamp.intensity=this.blendLampIntensity.currentValue();
				this.lamp.range=this.blendLampDistance.currentValue();
				this.needsMaterialUpdate=true;
			}
		}
	}

	makeBlender(key,dfault,clazz=Blender){
		if(key in this.char.mv3d_blenders){
			dfault = this.char.mv3d_blenders[key];
		}else{
			this.char.mv3d_blenders[key]=dfault;
		}
		const blender=new clazz(key,dfault,false);
		blender.storageLocation=()=>this.char.mv3d_blenders;
		return blender;
	}
	makeColorBlender(key,dfault){
		return this.makeBlender(key,dfault,ColorBlender);
	}

	hasBush(){
		if(this.platformChar){ return false; }
		return this.getConfig('bush',!(
			this.char.isTile() || this.isVehicle
			|| this.isEvent && this.char.isObjectCharacter()
		))&&!(this.blendElevation.currentValue()||this.falling);
	}

	//===========================
	//	Update Functions
	//===========================

	update(){
		if(this.char._erased){
			this.dispose();
		}

		const bitmapReady = this.isBitmapReady();

		this.visible=bitmapReady&&(this.mv_sprite.visible||this.isEmpty);
		if(typeof this.char.isVisible === 'function'){
			this.visible=this.visible&&this.char.isVisible();
		}
		const inRenderDist = this.char.mv3d_inRenderDist();
		//this.disabled=!this.visible;
		if(this.char.isTransparent() || !inRenderDist
		|| (this.char._characterName||this.tileId)&&!this.model.textureLoaded&&!this.isComplex
		|| main["a" /* default */].is1stPerson()&&this.isFollower&&this.char._realX===$gamePlayer._realX&&this.char._realY===$gamePlayer._realY){
			this.visible=false;
		}

		if(!this._isEnabled){
			if(this.visible){ this.setEnabled(true); this.needsPositionUpdate=true; }
		}else{
			if(!this.visible){ this.setEnabled(false); }
		}

		if(this.isImageChanged()){
			this.updateCharacter();
		}
		//if(this.patternChanged()){
		//	this.updateFrame();
		//}

		if(!inRenderDist||!bitmapReady){
			//this.updateAnimations();
			return;
		}

		if(this.blendElevation.update()){
			this.needsPositionUpdate=true;
		}else if(this.x!==this.char._realX || this.y!==this.char._realY
		|| this.falling || this.prevZ !== this.z
		|| this.platformChar&&this.platformChar.needsPositionUpdate
		|| this.isPlayer || this.char===$gamePlayer.vehicle()
		){
			this.needsPositionUpdate=true;
			this.prevZ = this.z;
		}

		if(!this.isEmpty && this._isEnabled){
			this.updateNormal();
		}else{
			this.updateEmpty();
		}
		this.updateAnimations();
		
		if(this.needsMaterialUpdate){
			this.updateEmissive();
			this.needsMaterialUpdate=false;
		}
		if(this.needsScaleUpdate){
			this.updateScale();
			this.needsScaleUpdate=false;
		}
		this.char.mv3d_positionUpdated=this.needsPositionUpdate;
		this.needsPositionUpdate=false;
		//this.mesh.renderOutline=true;
		//this.mesh.outlineWidth=1;
	}
	//get needsPositionUpdate(){return this._needsPositionUpdate; }
	//set needsPositionUpdate(v){ this._needsPositionUpdate=v; }

	updateNormal(){

		this.model.update();

		if(this.isPlayer){
			if(this.model.mesh) this.model.mesh.visibility = +!main["a" /* default */].is1stPerson(true);
		}

		this.updateAlpha();

		this.updatePosition();
		this.updateElevation();
		if(this.shadow){ this.updateShadow(); }
		this.updateLights();

		// updating the scale every frame still doesn't fix all problems with ChronoEngine.
		//this.updateScale();
	}

	updateEmpty(){
		this.updatePosition();
		this.updateElevation();
		this.updateLights();
		if(this.shadow&&this.shadow._isEnabled){ this.shadow.setEnabled(false); }
	}

	updateAlpha(){
		const materials = this.model.materials;
		if(!materials.length){ return; }
		
		this.bush = Boolean(this.char.bushDepth());
		if(this.model.material){
			const material = this.model.material;
			if(this.bush && this.hasBush()){
				if(!material.opacityTexture){
					const bushAlpha = main["a" /* default */].getBushAlphaTextureSync();
					if(bushAlpha&&bushAlpha.isReady()){
						material.opacityTexture=bushAlpha;
					}
				}
			}else{
				if(material.opacityTexture){
					material.opacityTexture=null;
				}
			}
		}

		const alpha = this.getConfig('alpha',1)*this.char.opacity()/255;
		const _hasAlpha=this.hasConfig('alpha')||alpha<1;
		const blendMode = main["a" /* default */].blendModes[this.char.blendMode()];
		for(const material of materials){
			if(!material._mv3d_orig_alpha){ material._mv3d_orig_alpha=material.alpha; }
			let hasAlpha = _hasAlpha||material._mv3d_orig_alpha<1;
			if(material.alphaMode!==blendMode){
				material.alphaMode=blendMode;
			}
			if(blendMode!==main["a" /* default */].blendModes.NORMAL){
				hasAlpha=true;
			}
			if(hasAlpha||material.opacityTexture){
				material.useAlphaFromDiffuseTexture=true;
				material.alpha=alpha*material._mv3d_orig_alpha;
			}else{
				material.useAlphaFromDiffuseTexture=false;
				material.alpha=1;
			}
		}
	}

	updateLightOffsets(){
		if(this.lamp){
			const offset = {
				x: this.getConfig('lampXoff',0),
				y: this.getConfig('lampYoff',0),
				z: this.getConfig('lampZoff',main["a" /* default */].LAMP_HEIGHT),
			}
			this.lampOrigin.x=offset.x;
			this.lampOrigin.y=offset.y;
			this.lampOrigin.z=offset.z;
		}
		if(this.flashlight){
			const offset = {
				x: this.getConfig('flashlightXoff',0),
				y: this.getConfig('flashlightYoff',0),
				z: this.getConfig('flashlightZoff',main["a" /* default */].FLASHLIGHT_HEIGHT),
			}
			this.flashlightOrigin.x=offset.x;
			this.flashlightOrigin.y=offset.y;
			this.flashlightOrigin.z=offset.z;
		}
	}

	updatePositionOffsets(){
		this.spriteOrigin.position.set(0,0,0);
		if(this.model.shape===main["a" /* default */].enumShapes.FLAT){
			const elevation = this.blendElevation.currentValue();
			const offsetDist = main["a" /* default */].LAYER_DIST*4;
			if(this.hasConfig('zlock')){
				this.spriteOrigin.z = 0;
			}else if(elevation){
				this.spriteOrigin.z = Math.max(0,offsetDist - elevation);
			}else{
				this.spriteOrigin.z = offsetDist;
			}
		}else if(this.model.shape===main["a" /* default */].enumShapes.SPRITE){
			this.spriteOrigin.z = main["a" /* default */].LAYER_DIST*4 * (1-Math.max(0,Math.min(90,main["a" /* default */].blendCameraPitch.currentValue()))/90);
		
			const billboardOffset = new babylon["Vector2"](Math.sin(-main["a" /* default */].cameraNode.rotation.y),Math.cos(main["a" /* default */].cameraNode.rotation.y));
			const spriteOffset = main["a" /* default */].SPRITE_OFFSET * Math.sin(Math.max(0,main["a" /* default */].cameraNode.rotation.x));
			this.spriteOrigin.x=billboardOffset.x*spriteOffset;
			this.spriteOrigin.y=billboardOffset.y*spriteOffset;
		}

		if(this.isPlayer&&main["a" /* default */].is1stPerson()){
			this.lightOrigin.x=0;
			this.lightOrigin.y=0;
		}else{
			this.lightOrigin.x=this.spriteOrigin.x;
			this.lightOrigin.y=this.spriteOrigin.y;
		}

		this.spriteOrigin.x += this.getConfig('xoff',0);
		this.spriteOrigin.y += this.getConfig('yoff',0);
		this.spriteOrigin.z += this.getConfig('zoff',0);
		
	}

	updatePosition(){
		this.updatePositionOffsets();

		const loopPos = main["a" /* default */].loopCoords(this.char._realX,this.char._realY);
		this.x = loopPos.x;
		this.y = loopPos.y;

		if(!this.needsPositionUpdate) { return; }

		const cellX=Math.floor(Math.round(this.char._realX)/main["a" /* default */].CELL_SIZE);
		const cellY=Math.floor(Math.round(this.char._realY)/main["a" /* default */].CELL_SIZE);
		const cell = main["a" /* default */].cells[[cellX,cellY]];
		if(this.cell&&this.cell!==cell){
			this.removeFromCell();
		}
		if(cell&&!this.cell){
			this.cell=cell;
			cell.characters.push(this);
		}
		this.dirtyNearbyCells();
	}

	updateElevation(){
		if(!this.needsPositionUpdate) { return; }

		//don't update when moving on tile corners
		if(this.char.isMoving() && !((this.x-0.5)%1)&&!((this.y-0.5)%1)){ return; }

		this.falling=false;

		if(this.isPlayer){
			const vehicle = this.char.vehicle();
			if(vehicle&&vehicle.mv3d_sprite){
			//if(vehicle&&vehicle._driving){
				const vehicle_sprite = vehicle.mv3d_sprite;
				this.z = vehicle_sprite.z;
				this.targetElevation = vehicle_sprite.targetElevation;
				this.platformChar = vehicle_sprite.platformChar;
				this.platformHeight = vehicle_sprite.platformHeight;
				if(vehicle._driving){ return; }
			}
		}

		if(this.hasConfig('zlock')){
			this.z=this.getConfig('zlock',0);
			this.z += this.blendElevation.currentValue();
			this.targetElevation = this.z;
			return;
		}

		this.hasFloat = this.isVehicle || (this.isPlayer||this.isFollower)&&$gamePlayer.vehicle();

		const platform = this.getPlatform(this.char._realX,this.char._realY);
		this.platform = platform;
		this.platformHeight = platform.z2;
		this.platformChar = platform.char;

		this.targetElevation = this.getTargetElevation(this.char._realX,this.char._realY,{platform});
		let gravity = this.getConfig('gravity',main["a" /* default */].GRAVITY)/60;

		if(this.char.isJumping()){
			let jumpProgress = 1-(this.char._jumpCount/(this.char._jumpPeak*2));
			let jumpHeight = Math.pow(jumpProgress-0.5,2)*-4+1;
			let jumpDiff = Math.abs(this.char.mv3d_jumpHeightEnd - this.char.mv3d_jumpHeightStart);
			this.z = this.char.mv3d_jumpHeightStart*(1-jumpProgress)
			+ this.char.mv3d_jumpHeightEnd*jumpProgress + jumpHeight*jumpDiff/2
			+this.char.jumpHeight()/Object(util["tileSize"])();
		}else if(gravity){
			const gap = Math.abs(this.targetElevation-this.z);
			if(gap<gravity){ gravity=gap; }
			//if(this.z>this.targetElevation||this.z<this.platformHeight){
			if(this.z<this.platformHeight){
				this.z=this.platformHeight;
			}
			if(this.z>this.targetElevation){
				this.z-=gravity;
				if(main["a" /* default */].tileCollision(this,this.char._realX,this.char._realY,false,false)){
					this.z=this.platformHeight;
				}
			}else if(this.z<this.targetElevation){
				this.z+=gravity
				if(main["a" /* default */].tileCollision(this,this.char._realX,this.char._realY,false,false)){
					this.z-=gravity;
				}
			}
			this.falling=this.z>this.targetElevation;
		}
		return;
	}

	getTargetElevation(x=this.char._realX,y=this.char._realY,opts={}){
		if(this.isPlayer){
			const vehicle = this.char.vehicle();
			if(vehicle&&vehicle.mv3d_sprite&&vehicle._driving){
				return vehicle.mv3d_sprite.getTargetElevation(x,y);
			}
		}
		if(this.hasConfig('zlock')){
			return this.getConfig('zlock',0)+this.blendElevation.currentValue();
		}

		if(!opts.platform){ opts.platform = this.getPlatform(x,y,opts); }
		const platform = opts.platform;
		let targetElevation;
		if(this.hasFloat && !this.platformChar){
			targetElevation = this.getPlatformFloat(x,y,{platform});
		}else{
			targetElevation = platform.z2;
		}

		targetElevation += this.blendElevation.currentValue()

		if(this.isAirship && $gamePlayer.vehicle()===this.char){
			targetElevation += main["a" /* default */].airshipHeight*this.char._altitude/this.char.maxAltitude();
		}
		return targetElevation;
	}

	getPlatform(x=this.char._realX,y=this.char._realY,opts={}){
		return main["a" /* default */].getPlatformForCharacter(this,x,y,opts);
	}

	getPlatformFloat(x=this.char._realX,y=this.char._realY,opts={}){
		if(!opts.platform){ opts.platform = this.getPlatform(x,y,opts); }
		const platform = opts.platform;
		let z = platform.z2;
		if(this.hasFloat&&!platform.char){
			const cHeight = this.getCHeight();
			z += main["a" /* default */].getFloatHeight(Math.round(x),Math.round(y),this.z+Math.max(cHeight,main["a" /* default */].STAIR_THRESH),main["a" /* default */].STAIR_THRESH>=cHeight);
		}
		return z;
	}

	updateShadow(){
		let shadowVisible = Boolean(this.getConfig('shadow', this.model.shape!=main["a" /* default */].enumShapes.FLAT ));

		if(shadowVisible&&(this.isPlayer||this.isFollower)){
			const myIndex = main["a" /* default */].characters.indexOf(this);
			if(myIndex>=0)
			for (let i=myIndex+1; i<main["a" /* default */].characters.length; ++i){
				const other = main["a" /* default */].characters[i];
				if(!other.shadow||!other.visible){ continue; }
				if(other.char._realX===this.char._realX&&other.char._realY===this.char._realY){
					shadowVisible=false;
					break;
				}
			}
		}
		if(!this.shadow._isEnabled){
			if(shadowVisible){ this.shadow.setEnabled(true); }
		}else{
			if(!shadowVisible){ this.shadow.setEnabled(false); }
		}
		if(!shadowVisible){ return; }

		const shadowDist = Math.max(this.z - this.platformHeight, 0);
		const shadowFadeDist = this.getConfig('shadowDist',4);
		const shadowStrength = Math.max(0,1-Math.abs(shadowDist)/shadowFadeDist);
		this.shadow.z = -shadowDist + main["a" /* default */].LAYER_DIST*3.5;
		this.shadow.x=this.spriteOrigin.x;this.shadow.y=this.spriteOrigin.y;
		const shadowScale = this.getConfig('shadow',1);
		this.shadow.scaling.setAll(shadowScale*shadowStrength);
		if(!this.shadow.isAnInstance){
			this.shadow.visibility=shadowStrength-0.5*this.bush;//visibility doesn't work with instancing
		}
	}

	updateAnimations(){
		if(this.char.isBalloonPlaying()){
			if(!this._balloon){
				this._balloon=main["a" /* default */].showBalloon(this);
			}
			this._balloon.update();
		}else{
			this.disposeBalloon();
		}
		
		if(main["a" /* default */].isMV){
			for(const animation of this.char.mv_sprite._animationSprites){
				if(animation.mv3d_animation){
					animation.mv3d_animation.update();
				}
			}
			if(this.char.mv_sprite._animationSprites.length){
				this.needsMaterialUpdate=true;
			}
		}
	}

	disposeBalloon(){
		if(this._balloon){
			this._balloon.dispose();
			this._balloon=null;
		}
	}

	dispose(...args){
		super.dispose(...args);
		delete this.char.mv3d_sprite;
		const index = main["a" /* default */].characters.indexOf(this);
		main["a" /* default */].characters.splice(index,1);
		this.disposeBalloon();
		this.removeFromCell();
	}

	removeFromCell(){
		if(this.cell){
			const index = this.cell.characters.indexOf(this);
			if(index>=0){ this.cell.characters.splice(index,1); }
			this.cell=null;
		}
	}

	getCHeight(){
		const dfault = this.model.shape===main["a" /* default */].enumShapes.FLAT||this.char._priorityType===0?0:this.spriteHeight;
		let collide = this.getConfig('collide',dfault);
		return collide===true ? dfault : Number(collide);
	}

	getCollider(){
		if(this._collider){ return this._collider; }
		const collider = {char:this};
		this._collider=collider;
		Object.defineProperties(collider,{
			z1:{get:()=>this.z },
			z2:{get:()=>{
				return Math.max(this.z,this.z+this.getCHeight());
			}}
		});
		return collider;
	}
	getTriggerCollider(){
		if(this._triggerCollider){ return this._triggerCollider; }
		const collider = {};
		this._triggerCollider=collider;
		Object.defineProperties(collider,{
			z1:{get:()=>{
				const trigger = this.getConfig('trigger');
				if(trigger){
					return this.z-trigger.down;
				}else if(main["a" /* default */].TRIGGER_INFINITE || this.isEmpty){
					return -Infinity;
				}else{
					return this.getCollider().z1;
				}
			}},
			z2:{get:()=>{
				const trigger = this.getConfig('trigger');
				if(trigger){
					return this.z-trigger.up;
				}else if(main["a" /* default */].TRIGGER_INFINITE || this.isEmpty){
					return Infinity;
				}else{
					return this.getCollider().z2;
				}
			}}
		});
		return collider;
	}

	getCollisionHeight(z=this.z){
		const cHeight=this.getCHeight();
		return {z1:z, z2:z+cHeight, char:this};
	}

	getTriggerHeight(z=this.z){
		const trigger = this.getConfig('trigger');
		if(trigger){
			return {z1:z-trigger.down, z2:z+trigger.up};
		}else if(main["a" /* default */].TRIGGER_INFINITE || this.isEmpty){
			return {z1:-Infinity, z2: Infinity};
		}else{
			return this.getCollisionHeight();
		}
	}
}

Object(util["override"])(Sprite_Character.prototype,'characterPatternY',o=>function(){
	const sprite = this._character.mv3d_sprite;
	if(!sprite){ return o.apply(this,arguments); }
	const dirfix = sprite.getConfig('dirfix', sprite.isEvent && sprite.char.isObjectCharacter());
	const ddir=this._character.mv3d_direction();
	const useDiagonal = !this._isBigCharacter&&this._characterIndex<4&&this._characterName.includes(main["a" /* default */].DIAG_SYMBOL);
	let dir;
	if(dirfix||main["a" /* default */].isDisabled()){
		if(useDiagonal){ dir=ddir; }
		else{ dir=this._character.direction(); }
	}else if(useDiagonal){
		dir = main["a" /* default */].transformFacing(ddir,main["a" /* default */].blendCameraYaw.currentValue(),true);
	}else{
		dir = main["a" /* default */].transformFacing(ddir,main["a" /* default */].blendCameraYaw.currentValue(),false);
	}
	if(dir%2){
		return diagRow[dir];
	}else{
		return dir/2-1;
	}
},()=> !main["a" /* default */].isDisabled() || main["a" /* default */].DIR8MOVE&&main["a" /* default */].DIR8_2D);
const diagRow={
	3:4,
	1:5,
	9:6,
	7:7,
};

Object(util["override"])(Sprite_Character.prototype,'setFrame',o=>function(x, y, width, height){
	o.apply(this,arguments);
	const sprite = this._character.mv3d_sprite; if(!sprite){ return; }
	if(sprite.isImageChanged()){ return; }
	sprite.setFrame(x,y,this.patternWidth(),this.patternHeight());
});

Object(util["override"])(Sprite_Character.prototype,'setBlendColor',o=>function(){
	o.apply(this,arguments);
	const sprite = this._character.mv3d_sprite; if(!sprite){ return; }
	sprite.needsMaterialUpdate=true;
});

Object(util["override"])(Game_CharacterBase.prototype,'tileId',o=>function(){
	if(this.mv3d_sprite){ return this.mv3d_sprite.tileId; }
	return this._tileId;
});

main["a" /* default */].Character = characters_Character;


Object(util["override"])(Game_CharacterBase.prototype,'isOnBush',o=>function(){
	if(!this.mv3d_sprite){ return o.apply(this,arguments); }
	const rx=Math.round(this._realX), ry=Math.round(this._realY);
	const tileData=main["a" /* default */].getTileData(rx,ry);
	const layers = main["a" /* default */].getTileLayers(rx,ry,this.mv3d_sprite.z+this.mv3d_sprite.getCHeight(),false);
	const flags = $gameMap.tilesetFlags();
	for( const l of layers ){
		if( (flags[tileData[l]] & 0x40) !== 0 ){ return true; }
	}
	return false;
});
// CONCATENATED MODULE: ./src/animations.js
const animations_mv3d = window.mv3d;




Object.assign(animations_mv3d,{
	showBalloon(char){
		if(!char){ char=$gamePlayer.mv3d_sprite; }
		return new animations_Balloon(char);
	}
});

class animations_AnimSprite extends babylon["TransformNode"]{
	constructor(src,w,h,smooth){
		super('animSprite',animations_mv3d.scene);
		this.cellWidth=w; this.cellHeight=h;
		this.cellIndex=0;
		this.isSmooth=smooth;
		this.mesh = animations_mv3d.Meshes.BASIC.clone();
		this.mesh.isPickable=false;
		this.mesh.parent=this;
		this.mesh.setEnabled(false);
		this.material = new babylon["StandardMaterial"]('anim material',animations_mv3d.scene);
		this.mesh.material=this.material;
		this.material.useAlphaFromDiffuseTexture=true;
		//this.material.alphaCutOff = mv3d.ALPHA_CUTOFF;
		this.material.alphaCutOff = 0;
		this.material.disableLighting=true;
		this.material.emissiveColor.set(1,1,1);
		this.material.ambientColor.set(1,1,1);
		this.material.specularColor.set(0,0,0);
		this.loadTexture(src)
	}
	async loadTexture(src){
		this.texture = await animations_mv3d.createTexture(src);
		this.texture.hasAlpha=true;
		this.material.diffuseTexture=this.texture;
		await animations_mv3d.waitTextureLoaded(this.texture);
		this.texture.updateSamplingMode( this.isSmooth
			? babylon["Texture"].BILINEAR_SAMPLINGMODE
			: babylon["Texture"].NEAREST_SAMPLINGMODE
		);
		this.textureLoaded=true;
		const size = this.texture.getBaseSize();
		this.cellCols = Math.floor(size.width/this.cellWidth);
	}
	update(){
		if(!this.textureLoaded){ return; }
		if(!this.mesh.isEnabled()){ this.mesh.setEnabled(true); }
		this.pitch = animations_mv3d.blendCameraPitch.currentValue()-90;
		this.yaw = animations_mv3d.blendCameraYaw.currentValue();
		this.texture.crop(
			this.cellIndex%this.cellCols*this.cellWidth,
			Math.floor(this.cellIndex/this.cellCols)*this.cellHeight,
			this.cellWidth, this.cellHeight
		);
	}
	dispose(){
		super.dispose(false,true);
	}
}
animations_mv3d.AnimSprite=animations_AnimSprite;

// Balloons
class animations_Balloon extends animations_AnimSprite{
	constructor(char){
		super('img/system/Balloon.png',48,48,false);
		this.char=char;
	}
	update(){
		if(!this.char){ return; }
		const pos = transformVectorForCharacter(new babylon["Vector3"](0,0.5+this.char.spriteHeight,0),this.char);
		this.position.copyFrom(pos);
		const bs = this.char.char.mv_sprite._balloonSprite;
		if(!bs){ return; }
		this.cellIndex = (bs._balloonId-1)*8 + Math.max(0,bs.frameIndex());
		super.update();
	}
}
animations_mv3d.Balloon=animations_Balloon;

// depth animations

class animations_DepthAnimation{
	constructor(animation){
		this.animation=animation;
		this.spriteList=[];
		this.char = this.animation._target._character.mv3d_sprite;
		animations_DepthAnimation.list.push(this);
	}
	resetSpriteList(){
		for(const animationSprite of this.spriteList ){
			animationSprite.unused=true;
		}
	}
	clearUnusedSprites(){
		for(let i=this.spriteList.length-1;i>=0;--i){
			const animationSprite = this.spriteList[i];
			if(animationSprite.unused){
				animationSprite.setEnabled(false);
			}
		}
	}
	update(){
		const char = this.char;
		if(!char){ return; }
		const cameraDirection = animations_mv3d.camera.getDirection(animations_mv3d.camera.getTarget());
		this.resetSpriteList();
		const frameData = this.animation._animation.frames[this.animation.currentFrameIndex()];
		if(frameData)
		for(let i=0; i<Math.min(this.animation._cellSprites.length); ++i){
			const cell = this.animation._cellSprites[i];
			if(!cell.visible || !cell.bitmap){ continue; }
			const anim = this.getAnimationSprite(cell.bitmap._url);
			anim.material.alphaMode = animations_mv3d.blendModes[cell.blendMode];

			anim.mesh.roll=Object(util["radtodeg"])(cell.rotation);
			const scale = this.animation._mv3d_animationSettings.scale||1;
			anim.mesh.scaling.x=4*cell.scale.x*scale;
			anim.mesh.scaling.y=4*cell.scale.y*scale;
			anim.material.alpha=cell.opacity/255;

			const offsetVector = new babylon["Vector3"](
				cell.position.x/48*scale,
				getAnimationOffset(this.animation)-cell.position.y/48*scale,
				0);
			const animationOrigin = transformVectorForCharacter(offsetVector,char);
			anim.position.copyFrom(animationOrigin);
			const scale2=Math.pow(scale,2);
			anim.mesh.position.set(
				-cameraDirection.x*0.1*(i+1)*scale2,
				-cameraDirection.y*0.1*(i+1)*scale2,
				-cameraDirection.z*0.1*(i+1)*scale2
			);

			const pattern = frameData[i][0];
			anim.cellIndex=pattern;
			anim.update();
			//console.log(anim.isVisible);
		}
		//console.log(this.spriteList.length);
		this.clearUnusedSprites();
	}
	getAnimationSprite(url){
		let sprite;
		for(const animationSprite of this.spriteList ){
			if(animationSprite._mv3d_sprite_url===url
			&&animationSprite.unused){
				//console.log("Found reusable sprite!", animationSprite);
				animationSprite.unused=false;
				animationSprite.setEnabled(true);
				sprite=animationSprite;
				break;
			}
		}
		if(!sprite){
			sprite = new animations_AnimSprite(url,192,192,true);
			this.spriteList.push(sprite);
			sprite._mv3d_sprite_url=url;
			//sprite.parent=this.char.spriteOrigin;
			const settings = this.animation._mv3d_animationSettings
			if(settings.depth==false&&settings.depth!=null){
				sprite.mesh.renderingGroupId=animations_mv3d.enumRenderGroups.FRONT;
			}
		}
		return sprite;
	}
	remove(){
		for(const animationSprite of this.spriteList ){
			animationSprite.dispose();
		}
		this.spriteList.length=0;
		const index = animations_DepthAnimation.list.indexOf(this);
		if(index>=0){
			animations_DepthAnimation.list.splice(index,1);
		}
	}
}
animations_DepthAnimation.list = [];
animations_mv3d.Animation=animations_DepthAnimation;

function transformVectorForCharacter(vector,char){
	if(!char.isEmpty&&char.shape===animations_mv3d.enumShapes.SPRITE){
		return babylon["Vector3"].TransformCoordinates(vector,animations_mv3d.getUnscaledMatrix(char.model.mesh));
	}else{
		return babylon["Vector3"].TransformCoordinates(vector,animations_mv3d.getTranslationMatrix(char.model.mesh));
	}
}


// mod animations

const _start_animation = Sprite_Character.prototype.startAnimation;
Sprite_Character.prototype.startAnimation = function(){
	_start_animation.apply(this,arguments);
	if(animations_mv3d.mapDisabled||!(SceneManager._scene instanceof Scene_Map)){ return; }
	const animationSprite = this._animationSprites[this._animationSprites.length-1];
	animationSprite._mv3d_animationSettings=this._character._mv3d_animationSettings;
	delete this._character._mv3d_animationSettings;
	if(animationSprite._mv3d_animationSettings){
		animationSprite.mv3d_animation=new animations_DepthAnimation(animationSprite);
		animations_mv3d.pixiContainer.addChild(animationSprite._screenFlashSprite);
		return;
	}
	animations_mv3d.pixiContainer.addChild(animationSprite);
};

const _animation_remove = Sprite_Animation.prototype.remove;
Sprite_Animation.prototype.remove=function(){
	if(!animations_mv3d.mapDisabled && this.mv3d_animation){
		if(this._screenFlashSprite){
			this.addChild(this._screenFlashSprite);
		}
		this.mv3d_animation.remove();
	}
	_animation_remove.apply(this,arguments);
};

const _map_terminate = Scene_Map.prototype.terminate;
Scene_Map.prototype.terminate=function(){
	_map_terminate.apply(this,arguments);
	for(let i=animations_DepthAnimation.list.length-1;i>=0;--i){
		animations_DepthAnimation.list[i].remove();
	}
};


const _animation_updateScreenFlash=Sprite_Animation.prototype.updateScreenFlash;
Sprite_Animation.prototype.updateScreenFlash = function() {
	_animation_updateScreenFlash.apply(this,arguments);
	if(!animations_mv3d.mapDisabled&&(SceneManager._scene instanceof Scene_Map)){
		this._screenFlashSprite.x = 0;
		this._screenFlashSprite.y = 0;
	}
};

function getAnimationOffset(animation){
	const p = animation._animation.position;
	const offset = p===3?0:1-p/2;
	const char = animation._target._character;
	if(!char.mv3d_sprite){ return offset; }
	return offset * char.mv3d_sprite.spriteHeight;
}

const _update_animation_sprites = Sprite_Character.prototype.updateAnimationSprites;
Sprite_Character.prototype.updateAnimationSprites = function() {
	_update_animation_sprites.apply(this,arguments);
	if(animations_mv3d.mapDisabled||!this._animationSprites.length||!(SceneManager._scene instanceof Scene_Map)){ return; }
	if(!this._character.mv3d_sprite){ return; }
	for (const animationSprite of this._animationSprites){
		if(animationSprite.mv3d_animation){ continue; }
		if(animationSprite._animation.position===3){
			animationSprite.update();
			continue;
		}

		const offsetVector = new babylon["Vector3"](0, getAnimationOffset(animationSprite), 0);
		const animationOrigin = transformVectorForCharacter(offsetVector,this._character.mv3d_sprite);
		const pos = animations_mv3d.getScreenPosition(animationOrigin);
		const dist = babylon["Vector3"].Distance(
			BABYLON.Vector3.TransformCoordinates(animations_mv3d.camera.position,animations_mv3d.getTranslationMatrix(animations_mv3d.camera)),
			animationOrigin);
		const scale = animations_mv3d.camera.mode===mod_babylon["f" /* ORTHOGRAPHIC_CAMERA */] ? animations_mv3d.getScaleForDist() : animations_mv3d.getScaleForDist(dist);

		animationSprite.behindCamera = pos.behindCamera;
		animationSprite.update();
		animationSprite.x=pos.x;
		animationSprite.y=pos.y;
		animationSprite.scale.set(scale,scale);
	}
};

const _update_cell = Sprite_Animation.prototype.updateCellSprite;
Sprite_Animation.prototype.updateCellSprite = function(sprite,cell) {
	_update_cell.apply(this,arguments);
	if(this.behindCamera){ sprite.visible=false; }
};
// CONCATENATED MODULE: ./src/parallax.js
const parallax_mv3d = window.mv3d;


Object(util["override"])(Game_Map.prototype,'setupParallax',o=>function(){
	o.apply(this,arguments);
	this.mv3d_parallaxX=0;
	this.mv3d_parallaxY=0;
},true);

Object(util["override"])(Game_Map.prototype,'changeParallax',o=>function(name, loopX, loopY, sx, sy){
	if (this._parallaxLoopX && !loopX || this._parallaxSx && !sx) {
		this.mv3d_parallaxX=0;
	}
	if (this._parallaxLoopY && !loopY || this._parallaxSy && !sy) {
		this.mv3d_parallaxY=0;
	}
	o.apply(this,arguments);
});

Object(util["override"])(Game_Map.prototype,'updateParallax',o=>function(){
	if (this._parallaxLoopX) {
		this.mv3d_parallaxX += this._parallaxSx / 8;
	}
	if (this._parallaxLoopY) {
		this.mv3d_parallaxY += this._parallaxSy / 8;
	}
});

Object(util["override"])(Game_Map.prototype,'parallaxOx',o=>function(){
	let ox = this.mv3d_parallaxX;
	if(this._parallaxLoopX){
		return ox - parallax_mv3d.blendCameraYaw.currentValue()*816/90;
	}
	return ox;
});

Object(util["override"])(Game_Map.prototype,'parallaxOy',o=>function(){
	let oy = this.mv3d_parallaxY;
	if(this._parallaxLoopY){
		return oy - parallax_mv3d.blendCameraPitch.currentValue()*816/90;
	}
	return 0;
});

/*
['setDisplayPos','scrollUp','scrollDown','scrollLeft','scrollRight'].forEach(method=>{
	const _oldMethod=Game_Map.prototype[method];
	Game_Map.prototype[method]=function(){
		if (mv3d.isDisabled()){ _oldMethod.apply(this,arguments); }
	}
});
const _updateScroll = Game_Map.prototype.updateScroll;
Game_Map.prototype.updateScroll = function() {
	if (mv3d.mapDisabled){ return _updateScroll.apply(this,arguments); }
	this._displayX = -mv3d.blendCameraYaw.currentValue()*816/3600;
	this._displayY = -mv3d.blendCameraPitch.currentValue()*816/3600;
};
*/

Game_CharacterBase.prototype.mv3d_inRenderDist=function(){
	const loopPos = parallax_mv3d.loopCoords(this.x,this.y);
	return Math.abs(loopPos.x - parallax_mv3d.cameraStick.x)<=parallax_mv3d.renderDist
	&& Math.abs(loopPos.y - parallax_mv3d.cameraStick.y)<=parallax_mv3d.renderDist;
};

Object(util["override"])(Game_CharacterBase.prototype,'isNearTheScreen',o=>function(){
	if(!parallax_mv3d.EVENTS_UPDATE_NEAR){ return o.apply(this,arguments); }
	return this.mv3d_inRenderDist() || o.apply(this,arguments);
});


Object(util["override"])(Game_Screen.prototype,'shake',o=>function(){
	return 0;
},()=> !parallax_mv3d.isDisabled() && SceneManager._scene instanceof Scene_Map );

Object(util["override"])(Game_CharacterBase.prototype,'screenX',o=>function(){
	const sprite = this.mv3d_sprite;
	if(!sprite){ return o.apply(this,arguments); }
	if(SceneManager.isNextScene(Scene_Battle) && this===$gamePlayer){
		return Graphics.width/2;
	}
	return parallax_mv3d.getScreenPosition(sprite).x;
});

Object(util["override"])(Game_CharacterBase.prototype,'screenY',o=>function(){
	const sprite = this.mv3d_sprite;
	if(!sprite){ return o.apply(this,arguments); }
	if(SceneManager.isNextScene(Scene_Battle) && this===$gamePlayer){
		return Graphics.height/2;
	}
	return parallax_mv3d.getScreenPosition(sprite).y;
});

Game_CharacterBase.prototype.mv3d_screenWidth=function(){
	const sprite = this.mv3d_sprite; if(!sprite)return this.mv3d_sprite?this.mv3d_sprite.width:0;
	return sprite.spriteWidth*Object(util["tileWidth"])()*parallax_mv3d.getScaleForDist();
};

Game_CharacterBase.prototype.mv3d_screenHeight=function(){
	const sprite = this.mv3d_sprite; if(!sprite)return this.mv3d_sprite?this.mv3d_sprite.height:0;
	return sprite.spriteHeight*Object(util["tileHeight"])()*parallax_mv3d.getScaleForDist();
};

Game_CharacterBase.prototype.mv3d_screenBounds=function(){
	const sprite = this.mv3d_sprite;
	if(!sprite){
		const width = this.mv3d_screenWidth();
		const height = this.mv3d_screenHeight();
		return new PIXI.Rectangle(this.screenX()-width/2,this.screenY()-height,width/2,height);
	}
	const bbox = sprite.mesh.getBoundingInfo().boundingBox;
	const projections = bbox.vectorsWorld.map(v=>parallax_mv3d.getScreenPosition(v));
	let minX=Graphics.width, minY=Graphics.height, maxX=0, maxY=0;
	let pointsBehindCamera=0;
	for (const projection of projections){
		if(projection.x<minX){ minX=projection.x; }
		if(projection.y<minY){ minY=projection.y; }
		if(projection.x>maxX){ maxX=projection.x; }
		if(projection.y>maxY){ maxY=projection.y; }
		if(projection.behindCamera){ ++pointsBehindCamera; }
	}
	const rect = new PIXI.Rectangle(minX,minY,maxX-minX,maxY-minY);
	rect.behindCamera = pointsBehindCamera<8;
	return rect;
};
// CONCATENATED MODULE: ./src/features.js
const features_mv3d = window.mv3d;

features_mv3d.features={};

features_mv3d.callFeature=function(name,method,...args){
	if(!this.featureEnabled(name)){ return; }
	const feature = this.features[name];
	if(method in feature.methods){
		feature.methods[method](...args);
	}
}

features_mv3d.callFeatures=function(method,...args){
	for(const name in this.features){
		this.callFeature(name,method,...args);
	}
}

features_mv3d.featureEnabled=function(name){
	if( !(name in this.features) ){ return false; }
	if(!this.features[name].enabled()){ return false; }
	return true;
}

class Feature{
	constructor(name,methods,condition=true){
		Object.assign(this,{name,condition,methods});
		features_mv3d.features[name]=this;
	}
	enabled(){
		if(typeof this.condition==='function'){
			return this.condition();
		}
		return Boolean(this.condition);
	}
}
features_mv3d.Feature = Feature;

// EXTERNAL MODULE: ./src/plugin_support/plugin_support.js
var plugin_support = __webpack_require__(8);

// CONCATENATED MODULE: ./src/index.js

















//import './data.js';





//import './premium/index.js';

/***/ })
/******/ ]);
//# sourceMappingURL=mv3d.js.map