babylon.scene.ts 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413
  1. module BABYLON {
  2. export interface IDisposable {
  3. dispose(): void;
  4. }
  5. /**
  6. * Represents a scene to be rendered by the engine.
  7. * @see http://doc.babylonjs.com/page.php?p=21911
  8. */
  9. export class Scene {
  10. // Statics
  11. private static _FOGMODE_NONE = 0;
  12. private static _FOGMODE_EXP = 1;
  13. private static _FOGMODE_EXP2 = 2;
  14. private static _FOGMODE_LINEAR = 3;
  15. public static MinDeltaTime = 1.0;
  16. public static MaxDeltaTime = 1000.0;
  17. public static get FOGMODE_NONE(): number {
  18. return Scene._FOGMODE_NONE;
  19. }
  20. public static get FOGMODE_EXP(): number {
  21. return Scene._FOGMODE_EXP;
  22. }
  23. public static get FOGMODE_EXP2(): number {
  24. return Scene._FOGMODE_EXP2;
  25. }
  26. public static get FOGMODE_LINEAR(): number {
  27. return Scene._FOGMODE_LINEAR;
  28. }
  29. // Members
  30. public autoClear = true;
  31. public clearColor: any = new Color3(0.2, 0.2, 0.3);
  32. public ambientColor = new Color3(0, 0, 0);
  33. /**
  34. * A function to be executed before rendering this scene
  35. * @type {Function}
  36. */
  37. public beforeRender: () => void;
  38. /**
  39. * A function to be executed after rendering this scene
  40. * @type {Function}
  41. */
  42. public afterRender: () => void;
  43. /**
  44. * A function to be executed when this scene is disposed.
  45. * @type {Function}
  46. */
  47. public onDispose: () => void;
  48. public beforeCameraRender: (camera: Camera) => void;
  49. public afterCameraRender: (camera: Camera) => void;
  50. public forceWireframe = false;
  51. public forcePointsCloud = false;
  52. public forceShowBoundingBoxes = false;
  53. public clipPlane: Plane;
  54. public animationsEnabled = true;
  55. public constantlyUpdateMeshUnderPointer = false;
  56. // Pointers
  57. private _onPointerMove: (evt: PointerEvent) => void;
  58. private _onPointerDown: (evt: PointerEvent) => void;
  59. private _onPointerUp: (evt: PointerEvent) => void;
  60. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  61. public onPointerUp: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  62. public cameraToUseForPointers: Camera = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  63. private _pointerX: number;
  64. private _pointerY: number;
  65. private _meshUnderPointer: AbstractMesh;
  66. // Mirror
  67. public _mirroredCameraPosition: Vector3;
  68. // Keyboard
  69. private _onKeyDown: (evt: Event) => void;
  70. private _onKeyUp: (evt: Event) => void;
  71. // Fog
  72. /**
  73. * is fog enabled on this scene.
  74. * @type {boolean}
  75. */
  76. public fogEnabled = true;
  77. public fogMode = Scene.FOGMODE_NONE;
  78. public fogColor = new Color3(0.2, 0.2, 0.3);
  79. public fogDensity = 0.1;
  80. public fogStart = 0;
  81. public fogEnd = 1000.0;
  82. // Lights
  83. /**
  84. * is shadow enabled on this scene.
  85. * @type {boolean}
  86. */
  87. public shadowsEnabled = true;
  88. /**
  89. * is light enabled on this scene.
  90. * @type {boolean}
  91. */
  92. public lightsEnabled = true;
  93. /**
  94. * All of the lights added to this scene.
  95. * @see BABYLON.Light
  96. * @type {BABYLON.Light[]}
  97. */
  98. public lights = new Array<Light>();
  99. public onNewLightAdded: (newLight?: Light, positionInArray?: number, scene?: Scene) => void;
  100. public onLightRemoved: (removedLight?: Light) => void;
  101. // Cameras
  102. /**
  103. * All of the cameras added to this scene.
  104. * @see BABYLON.Camera
  105. * @type {BABYLON.Camera[]}
  106. */
  107. public cameras = new Array<Camera>();
  108. public onNewCameraAdded: (newCamera?: Camera, positionInArray?: number, scene?: Scene) => void;
  109. public onCameraRemoved: (removedCamera?: Camera) => void;
  110. public activeCameras = new Array<Camera>();
  111. public activeCamera: Camera;
  112. // Meshes
  113. /**
  114. * All of the (abstract) meshes added to this scene.
  115. * @see BABYLON.AbstractMesh
  116. * @type {BABYLON.AbstractMesh[]}
  117. */
  118. public meshes = new Array<AbstractMesh>();
  119. public onNewMeshAdded: (newMesh?: AbstractMesh, positionInArray?: number, scene?: Scene) => void;
  120. public onMeshRemoved: (removedMesh?: AbstractMesh) => void;
  121. // Geometries
  122. private _geometries = new Array<Geometry>();
  123. public onGeometryAdded: (newGeometry?: Geometry) => void;
  124. public onGeometryRemoved: (removedGeometry?: Geometry) => void;
  125. public materials = new Array<Material>();
  126. public multiMaterials = new Array<MultiMaterial>();
  127. public defaultMaterial = new StandardMaterial("default material", this);
  128. // Textures
  129. public texturesEnabled = true;
  130. public textures = new Array<BaseTexture>();
  131. // Particles
  132. public particlesEnabled = true;
  133. public particleSystems = new Array<ParticleSystem>();
  134. // Sprites
  135. public spritesEnabled = true;
  136. public spriteManagers = new Array<SpriteManager>();
  137. // Layers
  138. public layers = new Array<Layer>();
  139. // Skeletons
  140. public skeletonsEnabled = true;
  141. public skeletons = new Array<Skeleton>();
  142. // Lens flares
  143. public lensFlaresEnabled = true;
  144. public lensFlareSystems = new Array<LensFlareSystem>();
  145. // Collisions
  146. public collisionsEnabled = true;
  147. private _workerCollisions;
  148. public collisionCoordinator: ICollisionCoordinator;
  149. public gravity = new Vector3(0, -9.807, 0);
  150. // Postprocesses
  151. public postProcessesEnabled = true;
  152. public postProcessManager: PostProcessManager;
  153. public postProcessRenderPipelineManager: PostProcessRenderPipelineManager;
  154. // Customs render targets
  155. public renderTargetsEnabled = true;
  156. public dumpNextRenderTargets = false;
  157. public customRenderTargets = new Array<RenderTargetTexture>();
  158. // Delay loading
  159. public useDelayedTextureLoading: boolean;
  160. // Imported meshes
  161. public importedMeshesFiles = new Array<String>();
  162. // Probes
  163. public probesEnabled = true;
  164. public reflectionProbes = new Array<ReflectionProbe>();
  165. // Database
  166. public database; //ANY
  167. // Actions
  168. /**
  169. * This scene's action manager
  170. * @type {BABYLON.ActionManager}
  171. */
  172. public actionManager: ActionManager;
  173. public _actionManagers = new Array<ActionManager>();
  174. private _meshesForIntersections = new SmartArray<AbstractMesh>(256);
  175. // Procedural textures
  176. public proceduralTexturesEnabled = true;
  177. public _proceduralTextures = new Array<ProceduralTexture>();
  178. // Sound Tracks
  179. public mainSoundTrack: SoundTrack;
  180. public soundTracks = new Array<SoundTrack>();
  181. private _audioEnabled = true;
  182. private _headphone = false;
  183. //Simplification Queue
  184. public simplificationQueue: SimplificationQueue;
  185. // Private
  186. private _engine: Engine;
  187. private _totalVertices = 0;
  188. public _activeIndices = 0;
  189. public _activeParticles = 0;
  190. private _lastFrameDuration = 0;
  191. private _evaluateActiveMeshesDuration = 0;
  192. private _renderTargetsDuration = 0;
  193. public _particlesDuration = 0;
  194. private _renderDuration = 0;
  195. public _spritesDuration = 0;
  196. private _animationRatio = 0;
  197. private _animationStartDate: number;
  198. public _cachedMaterial: Material;
  199. private _renderId = 0;
  200. private _executeWhenReadyTimeoutId = -1;
  201. public _toBeDisposed = new SmartArray<IDisposable>(256);
  202. private _onReadyCallbacks = new Array<() => void>();
  203. private _pendingData = [];//ANY
  204. private _onBeforeRenderCallbacks = new Array<() => void>();
  205. private _onAfterRenderCallbacks = new Array<() => void>();
  206. private _activeMeshes = new SmartArray<Mesh>(256);
  207. private _processedMaterials = new SmartArray<Material>(256);
  208. private _renderTargets = new SmartArray<RenderTargetTexture>(256);
  209. public _activeParticleSystems = new SmartArray<ParticleSystem>(256);
  210. private _activeSkeletons = new SmartArray<Skeleton>(32);
  211. private _softwareSkinnedMeshes = new SmartArray<Mesh>(32);
  212. public _activeBones = 0;
  213. private _renderingManager: RenderingManager;
  214. private _physicsEngine: PhysicsEngine;
  215. public _activeAnimatables = new Array<Animatable>();
  216. private _transformMatrix = Matrix.Zero();
  217. private _pickWithRayInverseMatrix: Matrix;
  218. private _edgesRenderers = new SmartArray<EdgesRenderer>(16);
  219. private _boundingBoxRenderer: BoundingBoxRenderer;
  220. private _outlineRenderer: OutlineRenderer;
  221. private _viewMatrix: Matrix;
  222. private _projectionMatrix: Matrix;
  223. private _frustumPlanes: Plane[];
  224. private _selectionOctree: Octree<AbstractMesh>;
  225. private _pointerOverMesh: AbstractMesh;
  226. private _debugLayer: DebugLayer;
  227. private _depthRenderer: DepthRenderer;
  228. private _uniqueIdCounter = 0;
  229. /**
  230. * @constructor
  231. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  232. */
  233. constructor(engine: Engine) {
  234. this._engine = engine;
  235. engine.scenes.push(this);
  236. this._renderingManager = new RenderingManager(this);
  237. this.postProcessManager = new PostProcessManager(this);
  238. this.postProcessRenderPipelineManager = new PostProcessRenderPipelineManager();
  239. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  240. if (OutlineRenderer) {
  241. this._outlineRenderer = new OutlineRenderer(this);
  242. }
  243. this.attachControl();
  244. this._debugLayer = new DebugLayer(this);
  245. if (SoundTrack) {
  246. this.mainSoundTrack = new SoundTrack(this, { mainTrack: true });
  247. }
  248. //simplification queue
  249. if (SimplificationQueue) {
  250. this.simplificationQueue = new SimplificationQueue();
  251. }
  252. //collision coordinator initialization. For now legacy per default.
  253. this.workerCollisions = false;//(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  254. }
  255. // Properties
  256. public get debugLayer(): DebugLayer {
  257. return this._debugLayer;
  258. }
  259. public set workerCollisions(enabled: boolean) {
  260. enabled = (enabled && !!Worker);
  261. this._workerCollisions = enabled;
  262. if (this.collisionCoordinator) {
  263. this.collisionCoordinator.destroy();
  264. }
  265. this.collisionCoordinator = enabled ? new CollisionCoordinatorWorker() : new CollisionCoordinatorLegacy();
  266. this.collisionCoordinator.init(this);
  267. }
  268. public get workerCollisions(): boolean {
  269. return this._workerCollisions;
  270. }
  271. public get SelectionOctree(): Octree<AbstractMesh> {
  272. return this._selectionOctree;
  273. }
  274. /**
  275. * The mesh that is currently under the pointer.
  276. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  277. */
  278. public get meshUnderPointer(): AbstractMesh {
  279. return this._meshUnderPointer;
  280. }
  281. /**
  282. * Current on-screen X position of the pointer
  283. * @return {number} X position of the pointer
  284. */
  285. public get pointerX(): number {
  286. return this._pointerX;
  287. }
  288. /**
  289. * Current on-screen Y position of the pointer
  290. * @return {number} Y position of the pointer
  291. */
  292. public get pointerY(): number {
  293. return this._pointerY;
  294. }
  295. public getCachedMaterial(): Material {
  296. return this._cachedMaterial;
  297. }
  298. public getBoundingBoxRenderer(): BoundingBoxRenderer {
  299. return this._boundingBoxRenderer;
  300. }
  301. public getOutlineRenderer(): OutlineRenderer {
  302. return this._outlineRenderer;
  303. }
  304. public getEngine(): Engine {
  305. return this._engine;
  306. }
  307. public getTotalVertices(): number {
  308. return this._totalVertices;
  309. }
  310. public getActiveIndices(): number {
  311. return this._activeIndices;
  312. }
  313. public getActiveParticles(): number {
  314. return this._activeParticles;
  315. }
  316. public getActiveBones(): number {
  317. return this._activeBones;
  318. }
  319. // Stats
  320. public getLastFrameDuration(): number {
  321. return this._lastFrameDuration;
  322. }
  323. public getEvaluateActiveMeshesDuration(): number {
  324. return this._evaluateActiveMeshesDuration;
  325. }
  326. public getActiveMeshes(): SmartArray<Mesh> {
  327. return this._activeMeshes;
  328. }
  329. public getRenderTargetsDuration(): number {
  330. return this._renderTargetsDuration;
  331. }
  332. public getRenderDuration(): number {
  333. return this._renderDuration;
  334. }
  335. public getParticlesDuration(): number {
  336. return this._particlesDuration;
  337. }
  338. public getSpritesDuration(): number {
  339. return this._spritesDuration;
  340. }
  341. public getAnimationRatio(): number {
  342. return this._animationRatio;
  343. }
  344. public getRenderId(): number {
  345. return this._renderId;
  346. }
  347. public incrementRenderId(): void {
  348. this._renderId++;
  349. }
  350. private _updatePointerPosition(evt: PointerEvent): void {
  351. var canvasRect = this._engine.getRenderingCanvasClientRect();
  352. this._pointerX = evt.clientX - canvasRect.left;
  353. this._pointerY = evt.clientY - canvasRect.top;
  354. if (this.cameraToUseForPointers) {
  355. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  356. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  357. }
  358. }
  359. // Pointers handling
  360. public attachControl() {
  361. var spritePredicate = (sprite: Sprite): boolean => {
  362. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  363. };
  364. this._onPointerMove = (evt: PointerEvent) => {
  365. var canvas = this._engine.getRenderingCanvas();
  366. this._updatePointerPosition(evt);
  367. // Meshes
  368. var pickResult = this.pick(this._pointerX, this._pointerY,
  369. (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && (this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined),
  370. false,
  371. this.cameraToUseForPointers);
  372. if (pickResult.hit && pickResult.pickedMesh) {
  373. this._meshUnderPointer = pickResult.pickedMesh;
  374. this.setPointerOverMesh(pickResult.pickedMesh);
  375. if (this._meshUnderPointer.actionManager && this._meshUnderPointer.actionManager.hasPointerTriggers) {
  376. canvas.style.cursor = "pointer";
  377. } else {
  378. canvas.style.cursor = "";
  379. }
  380. } else {
  381. // Sprites
  382. pickResult = this.pickSprite(this._pointerX, this._pointerY, spritePredicate, false, this.cameraToUseForPointers);
  383. if (pickResult.hit && pickResult.pickedSprite) {
  384. canvas.style.cursor = "pointer";
  385. return;
  386. }
  387. // Restore pointer
  388. this.setPointerOverMesh(null);
  389. canvas.style.cursor = "";
  390. this._meshUnderPointer = null;
  391. }
  392. };
  393. this._onPointerDown = (evt: PointerEvent) => {
  394. this._updatePointerPosition(evt);
  395. var predicate = null;
  396. // Meshes
  397. if (!this.onPointerDown) {
  398. predicate = (mesh: AbstractMesh): boolean => {
  399. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  400. };
  401. }
  402. var pickResult = this.pick(this._pointerX, this._pointerY, predicate, false, this.cameraToUseForPointers);
  403. if (pickResult.hit && pickResult.pickedMesh) {
  404. if (pickResult.pickedMesh.actionManager) {
  405. switch (evt.button) {
  406. case 0:
  407. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  408. break;
  409. case 1:
  410. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  411. break;
  412. case 2:
  413. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  414. break;
  415. }
  416. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  417. }
  418. }
  419. if (this.onPointerDown) {
  420. this.onPointerDown(evt, pickResult);
  421. }
  422. // Sprites
  423. if (this.spriteManagers.length > 0) {
  424. pickResult = this.pickSprite(this._pointerX, this._pointerY, spritePredicate, false, this.cameraToUseForPointers);
  425. if (pickResult.hit && pickResult.pickedSprite) {
  426. if (pickResult.pickedSprite.actionManager) {
  427. switch (evt.button) {
  428. case 0:
  429. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  430. break;
  431. case 1:
  432. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  433. break;
  434. case 2:
  435. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  436. break;
  437. }
  438. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  439. }
  440. }
  441. }
  442. };
  443. this._onPointerUp = (evt: PointerEvent) => {
  444. var predicate = null;
  445. this._updatePointerPosition(evt);
  446. if (!this.onPointerUp) {
  447. predicate = (mesh: AbstractMesh): boolean => {
  448. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(ActionManager.OnPickUpTrigger);
  449. };
  450. }
  451. // Meshes
  452. var pickResult = this.pick(this._pointerX, this._pointerY, predicate, false, this.cameraToUseForPointers);
  453. if (pickResult.hit && pickResult.pickedMesh) {
  454. if (pickResult.pickedMesh.actionManager) {
  455. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  456. }
  457. }
  458. if (this.onPointerUp) {
  459. this.onPointerUp(evt, pickResult);
  460. }
  461. // Sprites
  462. if (this.spriteManagers.length > 0) {
  463. pickResult = this.pickSprite(this._pointerX, this._pointerY, spritePredicate, false, this.cameraToUseForPointers);
  464. if (pickResult.hit && pickResult.pickedSprite) {
  465. if (pickResult.pickedSprite.actionManager) {
  466. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  467. }
  468. }
  469. }
  470. };
  471. this._onKeyDown = (evt: Event) => {
  472. if (this.actionManager) {
  473. this.actionManager.processTrigger(ActionManager.OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  474. }
  475. };
  476. this._onKeyUp = (evt: Event) => {
  477. if (this.actionManager) {
  478. this.actionManager.processTrigger(ActionManager.OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  479. }
  480. };
  481. var eventPrefix = Tools.GetPointerPrefix();
  482. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  483. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  484. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  485. // Wheel
  486. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  487. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  488. Tools.RegisterTopRootEvents([
  489. { name: "keydown", handler: this._onKeyDown },
  490. { name: "keyup", handler: this._onKeyUp }
  491. ]);
  492. }
  493. public detachControl() {
  494. var eventPrefix = Tools.GetPointerPrefix();
  495. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  496. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  497. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  498. // Wheel
  499. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  500. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  501. Tools.UnregisterTopRootEvents([
  502. { name: "keydown", handler: this._onKeyDown },
  503. { name: "keyup", handler: this._onKeyUp }
  504. ]);
  505. }
  506. // Ready
  507. public isReady(): boolean {
  508. if (this._pendingData.length > 0) {
  509. return false;
  510. }
  511. var index: number;
  512. for (index = 0; index < this._geometries.length; index++) {
  513. var geometry = this._geometries[index];
  514. if (geometry.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  515. return false;
  516. }
  517. }
  518. for (index = 0; index < this.meshes.length; index++) {
  519. var mesh = this.meshes[index];
  520. if (!mesh.isReady()) {
  521. return false;
  522. }
  523. var mat = mesh.material;
  524. if (mat) {
  525. if (!mat.isReady(mesh)) {
  526. return false;
  527. }
  528. }
  529. }
  530. return true;
  531. }
  532. public resetCachedMaterial(): void {
  533. this._cachedMaterial = null;
  534. }
  535. public registerBeforeRender(func: () => void): void {
  536. this._onBeforeRenderCallbacks.push(func);
  537. }
  538. public unregisterBeforeRender(func: () => void): void {
  539. var index = this._onBeforeRenderCallbacks.indexOf(func);
  540. if (index > -1) {
  541. this._onBeforeRenderCallbacks.splice(index, 1);
  542. }
  543. }
  544. public registerAfterRender(func: () => void): void {
  545. this._onAfterRenderCallbacks.push(func);
  546. }
  547. public unregisterAfterRender(func: () => void): void {
  548. var index = this._onAfterRenderCallbacks.indexOf(func);
  549. if (index > -1) {
  550. this._onAfterRenderCallbacks.splice(index, 1);
  551. }
  552. }
  553. public _addPendingData(data): void {
  554. this._pendingData.push(data);
  555. }
  556. public _removePendingData(data): void {
  557. var index = this._pendingData.indexOf(data);
  558. if (index !== -1) {
  559. this._pendingData.splice(index, 1);
  560. }
  561. }
  562. public getWaitingItemsCount(): number {
  563. return this._pendingData.length;
  564. }
  565. /**
  566. * Registers a function to be executed when the scene is ready.
  567. * @param {Function} func - the function to be executed.
  568. */
  569. public executeWhenReady(func: () => void): void {
  570. this._onReadyCallbacks.push(func);
  571. if (this._executeWhenReadyTimeoutId !== -1) {
  572. return;
  573. }
  574. this._executeWhenReadyTimeoutId = setTimeout(() => {
  575. this._checkIsReady();
  576. }, 150);
  577. }
  578. public _checkIsReady() {
  579. if (this.isReady()) {
  580. this._onReadyCallbacks.forEach(func => {
  581. func();
  582. });
  583. this._onReadyCallbacks = [];
  584. this._executeWhenReadyTimeoutId = -1;
  585. return;
  586. }
  587. this._executeWhenReadyTimeoutId = setTimeout(() => {
  588. this._checkIsReady();
  589. }, 150);
  590. }
  591. // Animations
  592. /**
  593. * Will start the animation sequence of a given target
  594. * @param target - the target
  595. * @param {number} from - from which frame should animation start
  596. * @param {number} to - till which frame should animation run.
  597. * @param {boolean} [loop] - should the animation loop
  598. * @param {number} [speedRatio] - the speed in which to run the animation
  599. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  600. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  601. * @return {BABYLON.Animatable} the animatable object created for this animation
  602. * @see BABYLON.Animatable
  603. * @see http://doc.babylonjs.com/page.php?p=22081
  604. */
  605. public beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio: number = 1.0, onAnimationEnd?: () => void, animatable?: Animatable): Animatable {
  606. this.stopAnimation(target);
  607. if (!animatable) {
  608. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  609. }
  610. // Local animations
  611. if (target.animations) {
  612. animatable.appendAnimations(target, target.animations);
  613. }
  614. // Children animations
  615. if (target.getAnimatables) {
  616. var animatables = target.getAnimatables();
  617. for (var index = 0; index < animatables.length; index++) {
  618. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  619. }
  620. }
  621. return animatable;
  622. }
  623. public beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable {
  624. if (speedRatio === undefined) {
  625. speedRatio = 1.0;
  626. }
  627. var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  628. return animatable;
  629. }
  630. public getAnimatableByTarget(target: any): Animatable {
  631. for (var index = 0; index < this._activeAnimatables.length; index++) {
  632. if (this._activeAnimatables[index].target === target) {
  633. return this._activeAnimatables[index];
  634. }
  635. }
  636. return null;
  637. }
  638. /**
  639. * Will stop the animation of the given target
  640. * @param target - the target
  641. * @see beginAnimation
  642. */
  643. public stopAnimation(target: any): void {
  644. var animatable = this.getAnimatableByTarget(target);
  645. if (animatable) {
  646. animatable.stop();
  647. }
  648. }
  649. private _animate(): void {
  650. if (!this.animationsEnabled) {
  651. return;
  652. }
  653. if (!this._animationStartDate) {
  654. this._animationStartDate = Tools.Now;
  655. }
  656. // Getting time
  657. var now = Tools.Now;
  658. var delay = now - this._animationStartDate;
  659. for (var index = 0; index < this._activeAnimatables.length; index++) {
  660. this._activeAnimatables[index]._animate(delay);
  661. }
  662. }
  663. // Matrix
  664. public getViewMatrix(): Matrix {
  665. return this._viewMatrix;
  666. }
  667. public getProjectionMatrix(): Matrix {
  668. return this._projectionMatrix;
  669. }
  670. public getTransformMatrix(): Matrix {
  671. return this._transformMatrix;
  672. }
  673. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  674. this._viewMatrix = view;
  675. this._projectionMatrix = projection;
  676. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  677. }
  678. // Methods
  679. public addMesh(newMesh: AbstractMesh) {
  680. newMesh.uniqueId = this._uniqueIdCounter++;
  681. var position = this.meshes.push(newMesh);
  682. //notify the collision coordinator
  683. this.collisionCoordinator.onMeshAdded(newMesh);
  684. if (this.onNewMeshAdded) {
  685. this.onNewMeshAdded(newMesh, position, this);
  686. }
  687. }
  688. public removeMesh(toRemove: AbstractMesh): number {
  689. var index = this.meshes.indexOf(toRemove);
  690. if (index !== -1) {
  691. // Remove from the scene if mesh found
  692. this.meshes.splice(index, 1);
  693. }
  694. //notify the collision coordinator
  695. this.collisionCoordinator.onMeshRemoved(toRemove);
  696. if (this.onMeshRemoved) {
  697. this.onMeshRemoved(toRemove);
  698. }
  699. return index;
  700. }
  701. public removeLight(toRemove: Light): number {
  702. var index = this.lights.indexOf(toRemove);
  703. if (index !== -1) {
  704. // Remove from the scene if mesh found
  705. this.lights.splice(index, 1);
  706. }
  707. if (this.onLightRemoved) {
  708. this.onLightRemoved(toRemove);
  709. }
  710. return index;
  711. }
  712. public removeCamera(toRemove: Camera): number {
  713. var index = this.cameras.indexOf(toRemove);
  714. if (index !== -1) {
  715. // Remove from the scene if mesh found
  716. this.cameras.splice(index, 1);
  717. }
  718. // Remove from activeCameras
  719. var index2 = this.activeCameras.indexOf(toRemove);
  720. if (index2 !== -1) {
  721. // Remove from the scene if mesh found
  722. this.activeCameras.splice(index2, 1);
  723. }
  724. // Reset the activeCamera
  725. if (this.activeCamera === toRemove) {
  726. if (this.cameras.length > 0) {
  727. this.activeCamera = this.cameras[0];
  728. } else {
  729. this.activeCamera = null;
  730. }
  731. }
  732. if (this.onCameraRemoved) {
  733. this.onCameraRemoved(toRemove);
  734. }
  735. return index;
  736. }
  737. public addLight(newLight: Light) {
  738. newLight.uniqueId = this._uniqueIdCounter++;
  739. var position = this.lights.push(newLight);
  740. if (this.onNewLightAdded) {
  741. this.onNewLightAdded(newLight, position, this);
  742. }
  743. }
  744. public addCamera(newCamera: Camera) {
  745. newCamera.uniqueId = this._uniqueIdCounter++;
  746. var position = this.cameras.push(newCamera);
  747. if (this.onNewCameraAdded) {
  748. this.onNewCameraAdded(newCamera, position, this);
  749. }
  750. }
  751. /**
  752. * sets the active camera of the scene using its ID
  753. * @param {string} id - the camera's ID
  754. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  755. * @see activeCamera
  756. */
  757. public setActiveCameraByID(id: string): Camera {
  758. var camera = this.getCameraByID(id);
  759. if (camera) {
  760. this.activeCamera = camera;
  761. return camera;
  762. }
  763. return null;
  764. }
  765. /**
  766. * sets the active camera of the scene using its name
  767. * @param {string} name - the camera's name
  768. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  769. * @see activeCamera
  770. */
  771. public setActiveCameraByName(name: string): Camera {
  772. var camera = this.getCameraByName(name);
  773. if (camera) {
  774. this.activeCamera = camera;
  775. return camera;
  776. }
  777. return null;
  778. }
  779. /**
  780. * get a material using its id
  781. * @param {string} the material's ID
  782. * @return {BABYLON.Material|null} the material or null if none found.
  783. */
  784. public getMaterialByID(id: string): Material {
  785. for (var index = 0; index < this.materials.length; index++) {
  786. if (this.materials[index].id === id) {
  787. return this.materials[index];
  788. }
  789. }
  790. return null;
  791. }
  792. /**
  793. * get a material using its name
  794. * @param {string} the material's name
  795. * @return {BABYLON.Material|null} the material or null if none found.
  796. */
  797. public getMaterialByName(name: string): Material {
  798. for (var index = 0; index < this.materials.length; index++) {
  799. if (this.materials[index].name === name) {
  800. return this.materials[index];
  801. }
  802. }
  803. return null;
  804. }
  805. public getLensFlareSystemByName(name: string): LensFlareSystem {
  806. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  807. if (this.lensFlareSystems[index].name === name) {
  808. return this.lensFlareSystems[index];
  809. }
  810. }
  811. return null;
  812. }
  813. public getCameraByID(id: string): Camera {
  814. for (var index = 0; index < this.cameras.length; index++) {
  815. if (this.cameras[index].id === id) {
  816. return this.cameras[index];
  817. }
  818. }
  819. return null;
  820. }
  821. public getCameraByUniqueID(uniqueId: number): Camera {
  822. for (var index = 0; index < this.cameras.length; index++) {
  823. if (this.cameras[index].uniqueId === uniqueId) {
  824. return this.cameras[index];
  825. }
  826. }
  827. return null;
  828. }
  829. /**
  830. * get a camera using its name
  831. * @param {string} the camera's name
  832. * @return {BABYLON.Camera|null} the camera or null if none found.
  833. */
  834. public getCameraByName(name: string): Camera {
  835. for (var index = 0; index < this.cameras.length; index++) {
  836. if (this.cameras[index].name === name) {
  837. return this.cameras[index];
  838. }
  839. }
  840. return null;
  841. }
  842. /**
  843. * get a light node using its name
  844. * @param {string} the light's name
  845. * @return {BABYLON.Light|null} the light or null if none found.
  846. */
  847. public getLightByName(name: string): Light {
  848. for (var index = 0; index < this.lights.length; index++) {
  849. if (this.lights[index].name === name) {
  850. return this.lights[index];
  851. }
  852. }
  853. return null;
  854. }
  855. /**
  856. * get a light node using its ID
  857. * @param {string} the light's id
  858. * @return {BABYLON.Light|null} the light or null if none found.
  859. */
  860. public getLightByID(id: string): Light {
  861. for (var index = 0; index < this.lights.length; index++) {
  862. if (this.lights[index].id === id) {
  863. return this.lights[index];
  864. }
  865. }
  866. return null;
  867. }
  868. /**
  869. * get a light node using its scene-generated unique ID
  870. * @param {number} the light's unique id
  871. * @return {BABYLON.Light|null} the light or null if none found.
  872. */
  873. public getLightByUniqueID(uniqueId: number): Light {
  874. for (var index = 0; index < this.lights.length; index++) {
  875. if (this.lights[index].uniqueId === uniqueId) {
  876. return this.lights[index];
  877. }
  878. }
  879. return null;
  880. }
  881. /**
  882. * get a geometry using its ID
  883. * @param {string} the geometry's id
  884. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  885. */
  886. public getGeometryByID(id: string): Geometry {
  887. for (var index = 0; index < this._geometries.length; index++) {
  888. if (this._geometries[index].id === id) {
  889. return this._geometries[index];
  890. }
  891. }
  892. return null;
  893. }
  894. /**
  895. * add a new geometry to this scene.
  896. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  897. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  898. * @return {boolean} was the geometry added or not
  899. */
  900. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  901. if (!force && this.getGeometryByID(geometry.id)) {
  902. return false;
  903. }
  904. this._geometries.push(geometry);
  905. //notify the collision coordinator
  906. this.collisionCoordinator.onGeometryAdded(geometry);
  907. if (this.onGeometryAdded) {
  908. this.onGeometryAdded(geometry);
  909. }
  910. return true;
  911. }
  912. /**
  913. * Removes an existing geometry
  914. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  915. * @return {boolean} was the geometry removed or not
  916. */
  917. public removeGeometry(geometry: Geometry): boolean {
  918. var index = this._geometries.indexOf(geometry);
  919. if (index > -1) {
  920. this._geometries.splice(index, 1);
  921. //notify the collision coordinator
  922. this.collisionCoordinator.onGeometryDeleted(geometry);
  923. if (this.onGeometryRemoved) {
  924. this.onGeometryRemoved(geometry);
  925. }
  926. return true;
  927. }
  928. return false;
  929. }
  930. public getGeometries(): Geometry[] {
  931. return this._geometries;
  932. }
  933. /**
  934. * Get the first added mesh found of a given ID
  935. * @param {string} id - the id to search for
  936. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  937. */
  938. public getMeshByID(id: string): AbstractMesh {
  939. for (var index = 0; index < this.meshes.length; index++) {
  940. if (this.meshes[index].id === id) {
  941. return this.meshes[index];
  942. }
  943. }
  944. return null;
  945. }
  946. /**
  947. * Get a mesh with its auto-generated unique id
  948. * @param {number} uniqueId - the unique id to search for
  949. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  950. */
  951. public getMeshByUniqueID(uniqueId: number): AbstractMesh {
  952. for (var index = 0; index < this.meshes.length; index++) {
  953. if (this.meshes[index].uniqueId === uniqueId) {
  954. return this.meshes[index];
  955. }
  956. }
  957. return null;
  958. }
  959. /**
  960. * Get a the last added mesh found of a given ID
  961. * @param {string} id - the id to search for
  962. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  963. */
  964. public getLastMeshByID(id: string): AbstractMesh {
  965. for (var index = this.meshes.length - 1; index >= 0; index--) {
  966. if (this.meshes[index].id === id) {
  967. return this.meshes[index];
  968. }
  969. }
  970. return null;
  971. }
  972. /**
  973. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  974. * @param {string} id - the id to search for
  975. * @return {BABYLON.Node|null} the node found or null if not found at all.
  976. */
  977. public getLastEntryByID(id: string): Node {
  978. var index: number;
  979. for (index = this.meshes.length - 1; index >= 0; index--) {
  980. if (this.meshes[index].id === id) {
  981. return this.meshes[index];
  982. }
  983. }
  984. for (index = this.cameras.length - 1; index >= 0; index--) {
  985. if (this.cameras[index].id === id) {
  986. return this.cameras[index];
  987. }
  988. }
  989. for (index = this.lights.length - 1; index >= 0; index--) {
  990. if (this.lights[index].id === id) {
  991. return this.lights[index];
  992. }
  993. }
  994. return null;
  995. }
  996. public getNodeByID(id: string): Node {
  997. var mesh = this.getMeshByID(id);
  998. if (mesh) {
  999. return mesh;
  1000. }
  1001. var light = this.getLightByID(id);
  1002. if (light) {
  1003. return light;
  1004. }
  1005. return this.getCameraByID(id);
  1006. }
  1007. public getNodeByName(name: string): Node {
  1008. var mesh = this.getMeshByName(name);
  1009. if (mesh) {
  1010. return mesh;
  1011. }
  1012. var light = this.getLightByName(name);
  1013. if (light) {
  1014. return light;
  1015. }
  1016. return this.getCameraByName(name);
  1017. }
  1018. public getMeshByName(name: string): AbstractMesh {
  1019. for (var index = 0; index < this.meshes.length; index++) {
  1020. if (this.meshes[index].name === name) {
  1021. return this.meshes[index];
  1022. }
  1023. }
  1024. return null;
  1025. }
  1026. public getSoundByName(name: string): Sound {
  1027. var index: number;
  1028. if (AudioEngine) {
  1029. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  1030. if (this.mainSoundTrack.soundCollection[index].name === name) {
  1031. return this.mainSoundTrack.soundCollection[index];
  1032. }
  1033. }
  1034. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  1035. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  1036. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  1037. return this.soundTracks[sdIndex].soundCollection[index];
  1038. }
  1039. }
  1040. }
  1041. }
  1042. return null;
  1043. }
  1044. public getLastSkeletonByID(id: string): Skeleton {
  1045. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  1046. if (this.skeletons[index].id === id) {
  1047. return this.skeletons[index];
  1048. }
  1049. }
  1050. return null;
  1051. }
  1052. public getSkeletonById(id: string): Skeleton {
  1053. for (var index = 0; index < this.skeletons.length; index++) {
  1054. if (this.skeletons[index].id === id) {
  1055. return this.skeletons[index];
  1056. }
  1057. }
  1058. return null;
  1059. }
  1060. public getSkeletonByName(name: string): Skeleton {
  1061. for (var index = 0; index < this.skeletons.length; index++) {
  1062. if (this.skeletons[index].name === name) {
  1063. return this.skeletons[index];
  1064. }
  1065. }
  1066. return null;
  1067. }
  1068. public isActiveMesh(mesh: Mesh): boolean {
  1069. return (this._activeMeshes.indexOf(mesh) !== -1);
  1070. }
  1071. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  1072. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  1073. var material = subMesh.getMaterial();
  1074. if (mesh.showSubMeshesBoundingBox) {
  1075. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  1076. }
  1077. if (material) {
  1078. // Render targets
  1079. if (material.getRenderTargetTextures) {
  1080. if (this._processedMaterials.indexOf(material) === -1) {
  1081. this._processedMaterials.push(material);
  1082. this._renderTargets.concat(material.getRenderTargetTextures());
  1083. }
  1084. }
  1085. // Dispatch
  1086. this._activeIndices += subMesh.indexCount;
  1087. this._renderingManager.dispatch(subMesh);
  1088. }
  1089. }
  1090. }
  1091. private _evaluateActiveMeshes(): void {
  1092. this.activeCamera._activeMeshes.reset();
  1093. this._activeMeshes.reset();
  1094. this._renderingManager.reset();
  1095. this._processedMaterials.reset();
  1096. this._activeParticleSystems.reset();
  1097. this._activeSkeletons.reset();
  1098. this._softwareSkinnedMeshes.reset();
  1099. this._boundingBoxRenderer.reset();
  1100. this._edgesRenderers.reset();
  1101. if (!this._frustumPlanes) {
  1102. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  1103. } else {
  1104. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  1105. }
  1106. // Meshes
  1107. var meshes: AbstractMesh[];
  1108. var len: number;
  1109. if (this._selectionOctree) { // Octree
  1110. var selection = this._selectionOctree.select(this._frustumPlanes);
  1111. meshes = selection.data;
  1112. len = selection.length;
  1113. } else { // Full scene traversal
  1114. len = this.meshes.length;
  1115. meshes = this.meshes;
  1116. }
  1117. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  1118. var mesh = meshes[meshIndex];
  1119. if (mesh.isBlocked) {
  1120. continue;
  1121. }
  1122. this._totalVertices += mesh.getTotalVertices();
  1123. if (!mesh.isReady() || !mesh.isEnabled()) {
  1124. continue;
  1125. }
  1126. mesh.computeWorldMatrix();
  1127. // Intersections
  1128. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([ActionManager.OnIntersectionEnterTrigger, ActionManager.OnIntersectionExitTrigger])) {
  1129. this._meshesForIntersections.pushNoDuplicate(mesh);
  1130. }
  1131. // Switch to current LOD
  1132. var meshLOD = mesh.getLOD(this.activeCamera);
  1133. if (!meshLOD) {
  1134. continue;
  1135. }
  1136. mesh._preActivate();
  1137. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  1138. this._activeMeshes.push(mesh);
  1139. this.activeCamera._activeMeshes.push(mesh);
  1140. mesh._activate(this._renderId);
  1141. this._activeMesh(meshLOD);
  1142. }
  1143. }
  1144. // Particle systems
  1145. var beforeParticlesDate = Tools.Now;
  1146. if (this.particlesEnabled) {
  1147. Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  1148. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  1149. var particleSystem = this.particleSystems[particleIndex];
  1150. if (!particleSystem.isStarted()) {
  1151. continue;
  1152. }
  1153. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  1154. this._activeParticleSystems.push(particleSystem);
  1155. particleSystem.animate();
  1156. }
  1157. }
  1158. Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  1159. }
  1160. this._particlesDuration += Tools.Now - beforeParticlesDate;
  1161. }
  1162. private _activeMesh(mesh: AbstractMesh): void {
  1163. if (mesh.skeleton && this.skeletonsEnabled) {
  1164. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  1165. if (!mesh.computeBonesUsingShaders) {
  1166. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  1167. }
  1168. }
  1169. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  1170. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  1171. }
  1172. if (mesh._edgesRenderer) {
  1173. this._edgesRenderers.push(mesh._edgesRenderer);
  1174. }
  1175. if (mesh && mesh.subMeshes) {
  1176. // Submeshes Octrees
  1177. var len: number;
  1178. var subMeshes: SubMesh[];
  1179. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  1180. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  1181. len = intersections.length;
  1182. subMeshes = intersections.data;
  1183. } else {
  1184. subMeshes = mesh.subMeshes;
  1185. len = subMeshes.length;
  1186. }
  1187. for (var subIndex = 0; subIndex < len; subIndex++) {
  1188. var subMesh = subMeshes[subIndex];
  1189. this._evaluateSubMesh(subMesh, mesh);
  1190. }
  1191. }
  1192. }
  1193. public updateTransformMatrix(force?: boolean): void {
  1194. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  1195. }
  1196. private _renderForCamera(camera: Camera): void {
  1197. var engine = this._engine;
  1198. this.activeCamera = camera;
  1199. if (!this.activeCamera)
  1200. throw new Error("Active camera not set");
  1201. Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  1202. // Viewport
  1203. engine.setViewport(this.activeCamera.viewport);
  1204. // Camera
  1205. this.resetCachedMaterial();
  1206. this._renderId++;
  1207. this.updateTransformMatrix();
  1208. if (this.beforeCameraRender) {
  1209. this.beforeCameraRender(this.activeCamera);
  1210. }
  1211. // Meshes
  1212. var beforeEvaluateActiveMeshesDate = Tools.Now;
  1213. Tools.StartPerformanceCounter("Active meshes evaluation");
  1214. this._evaluateActiveMeshes();
  1215. this._evaluateActiveMeshesDuration += Tools.Now - beforeEvaluateActiveMeshesDate;
  1216. Tools.EndPerformanceCounter("Active meshes evaluation");
  1217. // Skeletons
  1218. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  1219. var skeleton = this._activeSkeletons.data[skeletonIndex];
  1220. skeleton.prepare();
  1221. }
  1222. // Software skinning
  1223. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  1224. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  1225. mesh.applySkeleton(mesh.skeleton);
  1226. }
  1227. // Render targets
  1228. var beforeRenderTargetDate = Tools.Now;
  1229. if (this.renderTargetsEnabled) {
  1230. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  1231. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  1232. var renderTarget = this._renderTargets.data[renderIndex];
  1233. if (renderTarget._shouldRender()) {
  1234. this._renderId++;
  1235. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  1236. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  1237. }
  1238. }
  1239. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  1240. this._renderId++;
  1241. }
  1242. if (this._renderTargets.length > 0) { // Restore back buffer
  1243. engine.restoreDefaultFramebuffer();
  1244. }
  1245. this._renderTargetsDuration += Tools.Now - beforeRenderTargetDate;
  1246. // Prepare Frame
  1247. this.postProcessManager._prepareFrame();
  1248. var beforeRenderDate = Tools.Now;
  1249. // Backgrounds
  1250. var layerIndex;
  1251. var layer;
  1252. if (this.layers.length) {
  1253. engine.setDepthBuffer(false);
  1254. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  1255. layer = this.layers[layerIndex];
  1256. if (layer.isBackground) {
  1257. layer.render();
  1258. }
  1259. }
  1260. engine.setDepthBuffer(true);
  1261. }
  1262. // Render
  1263. Tools.StartPerformanceCounter("Main render");
  1264. this._renderingManager.render(null, null, true, true);
  1265. Tools.EndPerformanceCounter("Main render");
  1266. // Bounding boxes
  1267. this._boundingBoxRenderer.render();
  1268. // Edges
  1269. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  1270. this._edgesRenderers.data[edgesRendererIndex].render();
  1271. }
  1272. // Lens flares
  1273. if (this.lensFlaresEnabled) {
  1274. Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  1275. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  1276. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  1277. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  1278. lensFlareSystem.render();
  1279. }
  1280. }
  1281. Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  1282. }
  1283. // Foregrounds
  1284. if (this.layers.length) {
  1285. engine.setDepthBuffer(false);
  1286. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  1287. layer = this.layers[layerIndex];
  1288. if (!layer.isBackground) {
  1289. layer.render();
  1290. }
  1291. }
  1292. engine.setDepthBuffer(true);
  1293. }
  1294. this._renderDuration += Tools.Now - beforeRenderDate;
  1295. // Finalize frame
  1296. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  1297. // Update camera
  1298. this.activeCamera._updateFromScene();
  1299. // Reset some special arrays
  1300. this._renderTargets.reset();
  1301. if (this.afterCameraRender) {
  1302. this.afterCameraRender(this.activeCamera);
  1303. }
  1304. Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  1305. }
  1306. private _processSubCameras(camera: Camera): void {
  1307. if (camera.cameraRigMode === Camera.RIG_MODE_NONE) {
  1308. this._renderForCamera(camera);
  1309. return;
  1310. }
  1311. // rig cameras
  1312. for (var index = 0; index < camera._rigCameras.length; index++) {
  1313. this._renderForCamera(camera._rigCameras[index]);
  1314. }
  1315. this.activeCamera = camera;
  1316. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  1317. // Update camera
  1318. this.activeCamera._updateFromScene();
  1319. }
  1320. private _checkIntersections(): void {
  1321. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  1322. var sourceMesh = this._meshesForIntersections.data[index];
  1323. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  1324. var action = sourceMesh.actionManager.actions[actionIndex];
  1325. if (action.trigger === ActionManager.OnIntersectionEnterTrigger || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  1326. var parameters = action.getTriggerParameter();
  1327. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  1328. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  1329. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  1330. if (areIntersecting && currentIntersectionInProgress === -1) {
  1331. if (action.trigger === ActionManager.OnIntersectionEnterTrigger) {
  1332. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  1333. sourceMesh._intersectionsInProgress.push(otherMesh);
  1334. } else if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  1335. sourceMesh._intersectionsInProgress.push(otherMesh);
  1336. }
  1337. } else if (!areIntersecting && currentIntersectionInProgress > -1) {
  1338. //They intersected, and now they don't.
  1339. //is this trigger an exit trigger? execute an event.
  1340. if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  1341. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  1342. }
  1343. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  1344. if (!sourceMesh.actionManager.hasSpecificTrigger(ActionManager.OnIntersectionExitTrigger) || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  1345. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  1346. }
  1347. }
  1348. }
  1349. }
  1350. }
  1351. }
  1352. public render(): void {
  1353. var startDate = Tools.Now;
  1354. this._particlesDuration = 0;
  1355. this._spritesDuration = 0;
  1356. this._activeParticles = 0;
  1357. this._renderDuration = 0;
  1358. this._renderTargetsDuration = 0;
  1359. this._evaluateActiveMeshesDuration = 0;
  1360. this._totalVertices = 0;
  1361. this._activeIndices = 0;
  1362. this._activeBones = 0;
  1363. this.getEngine().resetDrawCalls();
  1364. this._meshesForIntersections.reset();
  1365. this.resetCachedMaterial();
  1366. Tools.StartPerformanceCounter("Scene rendering");
  1367. // Actions
  1368. if (this.actionManager) {
  1369. this.actionManager.processTrigger(ActionManager.OnEveryFrameTrigger, null);
  1370. }
  1371. //Simplification Queue
  1372. if (this.simplificationQueue && !this.simplificationQueue.running) {
  1373. this.simplificationQueue.executeNext();
  1374. }
  1375. // Animations
  1376. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  1377. this._animationRatio = deltaTime * (60.0 / 1000.0);
  1378. this._animate();
  1379. // Physics
  1380. if (this._physicsEngine) {
  1381. Tools.StartPerformanceCounter("Physics");
  1382. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  1383. Tools.EndPerformanceCounter("Physics");
  1384. }
  1385. // Before render
  1386. if (this.beforeRender) {
  1387. this.beforeRender();
  1388. }
  1389. var callbackIndex: number;
  1390. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  1391. this._onBeforeRenderCallbacks[callbackIndex]();
  1392. }
  1393. // Customs render targets
  1394. var beforeRenderTargetDate = Tools.Now;
  1395. var engine = this.getEngine();
  1396. var currentActiveCamera = this.activeCamera;
  1397. if (this.renderTargetsEnabled) {
  1398. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  1399. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  1400. var renderTarget = this.customRenderTargets[customIndex];
  1401. if (renderTarget._shouldRender()) {
  1402. this._renderId++;
  1403. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  1404. if (!this.activeCamera)
  1405. throw new Error("Active camera not set");
  1406. // Viewport
  1407. engine.setViewport(this.activeCamera.viewport);
  1408. // Camera
  1409. this.updateTransformMatrix();
  1410. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  1411. }
  1412. }
  1413. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  1414. this._renderId++;
  1415. }
  1416. if (this.customRenderTargets.length > 0) { // Restore back buffer
  1417. engine.restoreDefaultFramebuffer();
  1418. }
  1419. this._renderTargetsDuration += Tools.Now - beforeRenderTargetDate;
  1420. this.activeCamera = currentActiveCamera;
  1421. // Procedural textures
  1422. if (this.proceduralTexturesEnabled) {
  1423. Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  1424. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  1425. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  1426. if (proceduralTexture._shouldRender()) {
  1427. proceduralTexture.render();
  1428. }
  1429. }
  1430. Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  1431. }
  1432. // Clear
  1433. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  1434. // Shadows
  1435. if (this.shadowsEnabled) {
  1436. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  1437. var light = this.lights[lightIndex];
  1438. var shadowGenerator = light.getShadowGenerator();
  1439. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  1440. this._renderTargets.push(shadowGenerator.getShadowMap());
  1441. }
  1442. }
  1443. }
  1444. // Depth renderer
  1445. if (this._depthRenderer) {
  1446. this._renderTargets.push(this._depthRenderer.getDepthMap());
  1447. }
  1448. // RenderPipeline
  1449. this.postProcessRenderPipelineManager.update();
  1450. // Multi-cameras?
  1451. if (this.activeCameras.length > 0) {
  1452. var currentRenderId = this._renderId;
  1453. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  1454. this._renderId = currentRenderId;
  1455. this._processSubCameras(this.activeCameras[cameraIndex]);
  1456. }
  1457. } else {
  1458. if (!this.activeCamera) {
  1459. throw new Error("No camera defined");
  1460. }
  1461. this._processSubCameras(this.activeCamera);
  1462. }
  1463. // Intersection checks
  1464. this._checkIntersections();
  1465. // Update the audio listener attached to the camera
  1466. if (AudioEngine) {
  1467. this._updateAudioParameters();
  1468. }
  1469. // After render
  1470. if (this.afterRender) {
  1471. this.afterRender();
  1472. }
  1473. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  1474. this._onAfterRenderCallbacks[callbackIndex]();
  1475. }
  1476. // Cleaning
  1477. for (var index = 0; index < this._toBeDisposed.length; index++) {
  1478. this._toBeDisposed.data[index].dispose();
  1479. this._toBeDisposed[index] = null;
  1480. }
  1481. this._toBeDisposed.reset();
  1482. if (this.dumpNextRenderTargets) {
  1483. this.dumpNextRenderTargets = false;
  1484. }
  1485. Tools.EndPerformanceCounter("Scene rendering");
  1486. this._lastFrameDuration = Tools.Now - startDate;
  1487. }
  1488. private _updateAudioParameters() {
  1489. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  1490. return;
  1491. }
  1492. var listeningCamera: Camera;
  1493. var audioEngine = Engine.audioEngine;
  1494. if (this.activeCameras.length > 0) {
  1495. listeningCamera = this.activeCameras[0];
  1496. } else {
  1497. listeningCamera = this.activeCamera;
  1498. }
  1499. if (listeningCamera && audioEngine.canUseWebAudio) {
  1500. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  1501. var mat = Matrix.Invert(listeningCamera.getViewMatrix());
  1502. var cameraDirection = Vector3.TransformNormal(new Vector3(0, 0, -1), mat);
  1503. cameraDirection.normalize();
  1504. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  1505. var i: number;
  1506. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1507. var sound = this.mainSoundTrack.soundCollection[i];
  1508. if (sound.useCustomAttenuation) {
  1509. sound.updateDistanceFromListener();
  1510. }
  1511. }
  1512. for (i = 0; i < this.soundTracks.length; i++) {
  1513. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1514. sound = this.soundTracks[i].soundCollection[j];
  1515. if (sound.useCustomAttenuation) {
  1516. sound.updateDistanceFromListener();
  1517. }
  1518. }
  1519. }
  1520. }
  1521. }
  1522. // Audio
  1523. public get audioEnabled(): boolean {
  1524. return this._audioEnabled;
  1525. }
  1526. public set audioEnabled(value: boolean) {
  1527. this._audioEnabled = value;
  1528. if (AudioEngine) {
  1529. if (this._audioEnabled) {
  1530. this._enableAudio();
  1531. }
  1532. else {
  1533. this._disableAudio();
  1534. }
  1535. }
  1536. }
  1537. private _disableAudio() {
  1538. var i: number;
  1539. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1540. this.mainSoundTrack.soundCollection[i].pause();
  1541. }
  1542. for (i = 0; i < this.soundTracks.length; i++) {
  1543. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1544. this.soundTracks[i].soundCollection[j].pause();
  1545. }
  1546. }
  1547. }
  1548. private _enableAudio() {
  1549. var i: number;
  1550. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1551. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  1552. this.mainSoundTrack.soundCollection[i].play();
  1553. }
  1554. }
  1555. for (i = 0; i < this.soundTracks.length; i++) {
  1556. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1557. if (this.soundTracks[i].soundCollection[j].isPaused) {
  1558. this.soundTracks[i].soundCollection[j].play();
  1559. }
  1560. }
  1561. }
  1562. }
  1563. public get headphone(): boolean {
  1564. return this._headphone;
  1565. }
  1566. public set headphone(value: boolean) {
  1567. this._headphone = value;
  1568. if (AudioEngine) {
  1569. if (this._headphone) {
  1570. this._switchAudioModeForHeadphones();
  1571. }
  1572. else {
  1573. this._switchAudioModeForNormalSpeakers();
  1574. }
  1575. }
  1576. }
  1577. private _switchAudioModeForHeadphones() {
  1578. this.mainSoundTrack.switchPanningModelToHRTF();
  1579. for (var i = 0; i < this.soundTracks.length; i++) {
  1580. this.soundTracks[i].switchPanningModelToHRTF();
  1581. }
  1582. }
  1583. private _switchAudioModeForNormalSpeakers() {
  1584. this.mainSoundTrack.switchPanningModelToEqualPower();
  1585. for (var i = 0; i < this.soundTracks.length; i++) {
  1586. this.soundTracks[i].switchPanningModelToEqualPower();
  1587. }
  1588. }
  1589. public enableDepthRenderer(): DepthRenderer {
  1590. if (this._depthRenderer) {
  1591. return this._depthRenderer;
  1592. }
  1593. this._depthRenderer = new DepthRenderer(this);
  1594. return this._depthRenderer;
  1595. }
  1596. public disableDepthRenderer(): void {
  1597. if (!this._depthRenderer) {
  1598. return;
  1599. }
  1600. this._depthRenderer.dispose();
  1601. this._depthRenderer = null;
  1602. }
  1603. public dispose(): void {
  1604. this.beforeRender = null;
  1605. this.afterRender = null;
  1606. this.skeletons = [];
  1607. this._boundingBoxRenderer.dispose();
  1608. if (this._depthRenderer) {
  1609. this._depthRenderer.dispose();
  1610. }
  1611. // Debug layer
  1612. this.debugLayer.hide();
  1613. // Events
  1614. if (this.onDispose) {
  1615. this.onDispose();
  1616. }
  1617. this._onBeforeRenderCallbacks = [];
  1618. this._onAfterRenderCallbacks = [];
  1619. this.detachControl();
  1620. // Release sounds & sounds tracks
  1621. if (AudioEngine) {
  1622. this.disposeSounds();
  1623. }
  1624. // Detach cameras
  1625. var canvas = this._engine.getRenderingCanvas();
  1626. var index;
  1627. for (index = 0; index < this.cameras.length; index++) {
  1628. this.cameras[index].detachControl(canvas);
  1629. }
  1630. // Release lights
  1631. while (this.lights.length) {
  1632. this.lights[0].dispose();
  1633. }
  1634. // Release meshes
  1635. while (this.meshes.length) {
  1636. this.meshes[0].dispose(true);
  1637. }
  1638. // Release cameras
  1639. while (this.cameras.length) {
  1640. this.cameras[0].dispose();
  1641. }
  1642. // Release materials
  1643. while (this.materials.length) {
  1644. this.materials[0].dispose();
  1645. }
  1646. // Release particles
  1647. while (this.particleSystems.length) {
  1648. this.particleSystems[0].dispose();
  1649. }
  1650. // Release sprites
  1651. while (this.spriteManagers.length) {
  1652. this.spriteManagers[0].dispose();
  1653. }
  1654. // Release layers
  1655. while (this.layers.length) {
  1656. this.layers[0].dispose();
  1657. }
  1658. // Release textures
  1659. while (this.textures.length) {
  1660. this.textures[0].dispose();
  1661. }
  1662. // Post-processes
  1663. this.postProcessManager.dispose();
  1664. // Physics
  1665. if (this._physicsEngine) {
  1666. this.disablePhysicsEngine();
  1667. }
  1668. // Remove from engine
  1669. index = this._engine.scenes.indexOf(this);
  1670. if (index > -1) {
  1671. this._engine.scenes.splice(index, 1);
  1672. }
  1673. this._engine.wipeCaches();
  1674. }
  1675. // Release sounds & sounds tracks
  1676. public disposeSounds() {
  1677. this.mainSoundTrack.dispose();
  1678. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  1679. this.soundTracks[scIndex].dispose();
  1680. }
  1681. }
  1682. // Octrees
  1683. public getWorldExtends(): { min: Vector3; max: Vector3 } {
  1684. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1685. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1686. for (var index = 0; index < this.meshes.length; index++) {
  1687. var mesh = this.meshes[index];
  1688. mesh.computeWorldMatrix(true);
  1689. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  1690. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  1691. Tools.CheckExtends(minBox, min, max);
  1692. Tools.CheckExtends(maxBox, min, max);
  1693. }
  1694. return {
  1695. min: min,
  1696. max: max
  1697. };
  1698. }
  1699. public createOrUpdateSelectionOctree(maxCapacity = 64, maxDepth = 2): Octree<AbstractMesh> {
  1700. if (!this._selectionOctree) {
  1701. this._selectionOctree = new Octree<AbstractMesh>(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  1702. }
  1703. var worldExtends = this.getWorldExtends();
  1704. // Update octree
  1705. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  1706. return this._selectionOctree;
  1707. }
  1708. // Picking
  1709. public createPickingRay(x: number, y: number, world: Matrix, camera: Camera, cameraViewSpace = false): Ray {
  1710. var engine = this._engine;
  1711. if (!camera) {
  1712. if (!this.activeCamera)
  1713. throw new Error("Active camera not set");
  1714. camera = this.activeCamera;
  1715. }
  1716. var cameraViewport = camera.viewport;
  1717. var viewport = cameraViewport.toGlobal(engine);
  1718. // Moving coordinates to local viewport world
  1719. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  1720. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  1721. return Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : Matrix.Identity(), cameraViewSpace ? Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  1722. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  1723. }
  1724. public createPickingRayInCameraSpace(x: number, y: number, camera: Camera): Ray {
  1725. var engine = this._engine;
  1726. if (!camera) {
  1727. if (!this.activeCamera)
  1728. throw new Error("Active camera not set");
  1729. camera = this.activeCamera;
  1730. }
  1731. var cameraViewport = camera.viewport;
  1732. var viewport = cameraViewport.toGlobal(engine);
  1733. var identity = Matrix.Identity();
  1734. // Moving coordinates to local viewport world
  1735. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  1736. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  1737. return Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  1738. }
  1739. private _internalPick(rayFunction: (world: Matrix) => Ray, predicate: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): PickingInfo {
  1740. var pickingInfo = null;
  1741. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  1742. var mesh = this.meshes[meshIndex];
  1743. if (predicate) {
  1744. if (!predicate(mesh)) {
  1745. continue;
  1746. }
  1747. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  1748. continue;
  1749. }
  1750. var world = mesh.getWorldMatrix();
  1751. var ray = rayFunction(world);
  1752. var result = mesh.intersects(ray, fastCheck);
  1753. if (!result || !result.hit)
  1754. continue;
  1755. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  1756. continue;
  1757. pickingInfo = result;
  1758. if (fastCheck) {
  1759. break;
  1760. }
  1761. }
  1762. return pickingInfo || new PickingInfo();
  1763. }
  1764. private _internalPickSprites(ray: Ray, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo {
  1765. var pickingInfo = null;
  1766. camera = camera || this.activeCamera;
  1767. if (this.spriteManagers.length > 0) {
  1768. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  1769. var spriteManager = this.spriteManagers[spriteIndex];
  1770. if (!spriteManager.isPickable) {
  1771. continue;
  1772. }
  1773. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  1774. if (!result || !result.hit)
  1775. continue;
  1776. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  1777. continue;
  1778. pickingInfo = result;
  1779. if (fastCheck) {
  1780. break;
  1781. }
  1782. }
  1783. }
  1784. return pickingInfo || new PickingInfo();
  1785. }
  1786. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo {
  1787. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  1788. /// <param name="x">X position on screen</param>
  1789. /// <param name="y">Y position on screen</param>
  1790. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  1791. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  1792. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  1793. return this._internalPick(world => this.createPickingRay(x, y, world, camera), predicate, fastCheck);
  1794. }
  1795. public pickSprite(x: number, y: number, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo {
  1796. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  1797. /// <param name="x">X position on screen</param>
  1798. /// <param name="y">Y position on screen</param>
  1799. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  1800. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  1801. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  1802. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  1803. }
  1804. public pickWithRay(ray: Ray, predicate: (mesh: Mesh) => boolean, fastCheck?: boolean) {
  1805. return this._internalPick(world => {
  1806. if (!this._pickWithRayInverseMatrix) {
  1807. this._pickWithRayInverseMatrix = Matrix.Identity();
  1808. }
  1809. world.invertToRef(this._pickWithRayInverseMatrix);
  1810. return Ray.Transform(ray, this._pickWithRayInverseMatrix);
  1811. }, predicate, fastCheck);
  1812. }
  1813. public setPointerOverMesh(mesh: AbstractMesh): void {
  1814. if (this._pointerOverMesh === mesh) {
  1815. return;
  1816. }
  1817. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  1818. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  1819. }
  1820. this._pointerOverMesh = mesh;
  1821. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  1822. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  1823. }
  1824. }
  1825. public getPointerOverMesh(): AbstractMesh {
  1826. return this._pointerOverMesh;
  1827. }
  1828. // Physics
  1829. public getPhysicsEngine(): PhysicsEngine {
  1830. return this._physicsEngine;
  1831. }
  1832. /**
  1833. * Enables physics to the current scene
  1834. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  1835. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  1836. * @return {boolean} was the physics engine initialized
  1837. */
  1838. public enablePhysics(gravity?: Vector3, plugin?: IPhysicsEnginePlugin): boolean {
  1839. if (this._physicsEngine) {
  1840. return true;
  1841. }
  1842. this._physicsEngine = new PhysicsEngine(plugin);
  1843. if (!this._physicsEngine.isSupported()) {
  1844. this._physicsEngine = null;
  1845. return false;
  1846. }
  1847. this._physicsEngine._initialize(gravity);
  1848. return true;
  1849. }
  1850. public disablePhysicsEngine(): void {
  1851. if (!this._physicsEngine) {
  1852. return;
  1853. }
  1854. this._physicsEngine.dispose();
  1855. this._physicsEngine = undefined;
  1856. }
  1857. public isPhysicsEnabled(): boolean {
  1858. return this._physicsEngine !== undefined;
  1859. }
  1860. /**
  1861. * Sets the gravity of the physics engine (and NOT of the scene)
  1862. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  1863. */
  1864. public setGravity(gravity: Vector3): void {
  1865. if (!this._physicsEngine) {
  1866. return;
  1867. }
  1868. this._physicsEngine._setGravity(gravity);
  1869. }
  1870. public createCompoundImpostor(parts: any, options: PhysicsBodyCreationOptions): any {
  1871. if (parts.parts) { // Old API
  1872. options = parts;
  1873. parts = parts.parts;
  1874. }
  1875. if (!this._physicsEngine) {
  1876. return null;
  1877. }
  1878. for (var index = 0; index < parts.length; index++) {
  1879. var mesh = parts[index].mesh;
  1880. mesh._physicImpostor = parts[index].impostor;
  1881. mesh._physicsMass = options.mass / parts.length;
  1882. mesh._physicsFriction = options.friction;
  1883. mesh._physicRestitution = options.restitution;
  1884. }
  1885. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  1886. }
  1887. public deleteCompoundImpostor(compound: any): void {
  1888. for (var index = 0; index < compound.parts.length; index++) {
  1889. var mesh = compound.parts[index].mesh;
  1890. mesh._physicImpostor = PhysicsEngine.NoImpostor;
  1891. this._physicsEngine._unregisterMesh(mesh);
  1892. }
  1893. }
  1894. // Misc.
  1895. public createDefaultCameraOrLight() {
  1896. // Light
  1897. if (this.lights.length === 0) {
  1898. new HemisphericLight("default light", Vector3.Up(), this);
  1899. }
  1900. // Camera
  1901. if (!this.activeCamera) {
  1902. var camera = new FreeCamera("default camera", Vector3.Zero(), this);
  1903. // Compute position
  1904. var worldExtends = this.getWorldExtends();
  1905. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  1906. camera.position = new Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  1907. camera.setTarget(worldCenter);
  1908. this.activeCamera = camera;
  1909. }
  1910. }
  1911. // Tags
  1912. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  1913. if (tagsQuery === undefined) {
  1914. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  1915. return list;
  1916. }
  1917. var listByTags = [];
  1918. forEach = forEach || ((item: any) => { return; });
  1919. for (var i in list) {
  1920. var item = list[i];
  1921. if (Tags.MatchesQuery(item, tagsQuery)) {
  1922. listByTags.push(item);
  1923. forEach(item);
  1924. }
  1925. }
  1926. return listByTags;
  1927. }
  1928. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  1929. return this._getByTags(this.meshes, tagsQuery, forEach);
  1930. }
  1931. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  1932. return this._getByTags(this.cameras, tagsQuery, forEach);
  1933. }
  1934. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  1935. return this._getByTags(this.lights, tagsQuery, forEach);
  1936. }
  1937. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  1938. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  1939. }
  1940. }
  1941. }