babylon.scene.ts 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457
  1. module BABYLON {
  2. export interface IDisposable {
  3. dispose(): void;
  4. }
  5. export class Scene {
  6. // Statics
  7. public static FOGMODE_NONE = 0;
  8. public static FOGMODE_EXP = 1;
  9. public static FOGMODE_EXP2 = 2;
  10. public static FOGMODE_LINEAR = 3;
  11. public static MinDeltaTime = 1.0;
  12. public static MaxDeltaTime = 1000.0;
  13. // Members
  14. public autoClear = true;
  15. public clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16. public ambientColor = new BABYLON.Color3(0, 0, 0);
  17. public beforeRender: () => void;
  18. public afterRender: () => void;
  19. public onDispose: () => void;
  20. public beforeCameraRender: (camera: Camera) => void;
  21. public afterCameraRender: (camera: Camera) => void;
  22. public forceWireframe = false;
  23. public clipPlane: Plane;
  24. // Pointers
  25. private _onPointerMove: (evt: PointerEvent) => void;
  26. private _onPointerDown: (evt: PointerEvent) => void;
  27. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  28. 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
  29. private _pointerX: number;
  30. private _pointerY: number;
  31. private _meshUnderPointer: AbstractMesh;
  32. // Keyboard
  33. private _onKeyDown: (evt: Event) => void;
  34. private _onKeyUp: (evt: Event) => void;
  35. // Fog
  36. public fogMode = BABYLON.Scene.FOGMODE_NONE;
  37. public fogColor = new Color3(0.2, 0.2, 0.3);
  38. public fogDensity = 0.1;
  39. public fogStart = 0;
  40. public fogEnd = 1000.0;
  41. // Lights
  42. public lightsEnabled = true;
  43. public lights = new Array<Light>();
  44. // Cameras
  45. public cameras = new Array<Camera>();
  46. public activeCameras = new Array<Camera>();
  47. public activeCamera: Camera;
  48. // Meshes
  49. public meshes = new Array<AbstractMesh>();
  50. // Geometries
  51. private _geometries = new Array<Geometry>();
  52. public materials = new Array<Material>();
  53. public multiMaterials = new Array<MultiMaterial>();
  54. public defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  55. // Textures
  56. public texturesEnabled = true;
  57. public textures = new Array<BaseTexture>();
  58. // Particles
  59. public particlesEnabled = true;
  60. public particleSystems = new Array<ParticleSystem>();
  61. // Sprites
  62. public spriteManagers = new Array<SpriteManager>();
  63. // Layers
  64. public layers = new Array<Layer>();
  65. // Skeletons
  66. public skeletons = new Array<Skeleton>();
  67. // Lens flares
  68. public lensFlareSystems = new Array<LensFlareSystem>();
  69. // Collisions
  70. public collisionsEnabled = true;
  71. public gravity = new BABYLON.Vector3(0, -9.0, 0);
  72. // Postprocesses
  73. public postProcessesEnabled = true;
  74. public postProcessManager: PostProcessManager;
  75. public postProcessRenderPipelineManager: PostProcessRenderPipelineManager;
  76. // Customs render targets
  77. public renderTargetsEnabled = true;
  78. public customRenderTargets = new Array<RenderTargetTexture>();
  79. // Delay loading
  80. public useDelayedTextureLoading: boolean;
  81. // Imported meshes
  82. public importedMeshesFiles = new Array<String>();
  83. // Database
  84. public database; //ANY
  85. // Actions
  86. public actionManager: ActionManager;
  87. public _actionManagers = new Array<ActionManager>();
  88. private _meshesForIntersections = new SmartArray<AbstractMesh>(256);
  89. // Private
  90. private _engine: Engine;
  91. private _totalVertices = 0;
  92. public _activeVertices = 0;
  93. public _activeParticles = 0;
  94. private _lastFrameDuration = 0;
  95. private _evaluateActiveMeshesDuration = 0;
  96. private _renderTargetsDuration = 0;
  97. public _particlesDuration = 0;
  98. private _renderDuration = 0;
  99. public _spritesDuration = 0;
  100. private _animationRatio = 0;
  101. private _animationStartDate: number;
  102. private _renderId = 0;
  103. private _executeWhenReadyTimeoutId = -1;
  104. public _toBeDisposed = new SmartArray<IDisposable>(256);
  105. private _onReadyCallbacks = new Array<() => void>();
  106. private _pendingData = [];//ANY
  107. private _onBeforeRenderCallbacks = new Array<() => void>();
  108. private _activeMeshes = new SmartArray<Mesh>(256);
  109. private _processedMaterials = new SmartArray<Material>(256);
  110. private _renderTargets = new SmartArray<RenderTargetTexture>(256);
  111. public _activeParticleSystems = new SmartArray<ParticleSystem>(256);
  112. private _activeSkeletons = new SmartArray<Skeleton>(32);
  113. private _renderingManager: RenderingManager;
  114. private _physicsEngine: PhysicsEngine;
  115. public _activeAnimatables = new Array<Animatable>();
  116. private _transformMatrix = Matrix.Zero();
  117. private _pickWithRayInverseMatrix: Matrix;
  118. private _scaledPosition = Vector3.Zero();
  119. private _scaledVelocity = Vector3.Zero();
  120. private _boundingBoxRenderer: BoundingBoxRenderer;
  121. private _viewMatrix: Matrix;
  122. private _projectionMatrix: Matrix;
  123. private _frustumPlanes: Plane[];
  124. private _selectionOctree: Octree<AbstractMesh>;
  125. private _pointerOverMesh: AbstractMesh;
  126. // Constructor
  127. constructor(engine: Engine) {
  128. this._engine = engine;
  129. engine.scenes.push(this);
  130. this._renderingManager = new RenderingManager(this);
  131. this.postProcessManager = new PostProcessManager(this);
  132. this.postProcessRenderPipelineManager = new PostProcessRenderPipelineManager();
  133. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  134. this.attachControl();
  135. }
  136. // Properties
  137. public get meshUnderPointer(): AbstractMesh {
  138. return this._meshUnderPointer;
  139. }
  140. public get pointerX(): number {
  141. return this._pointerX;
  142. }
  143. public get pointerY(): number {
  144. return this._pointerY;
  145. }
  146. public getBoundingBoxRenderer(): BoundingBoxRenderer {
  147. return this._boundingBoxRenderer;
  148. }
  149. public getEngine(): Engine {
  150. return this._engine;
  151. }
  152. public getTotalVertices(): number {
  153. return this._totalVertices;
  154. }
  155. public getActiveVertices(): number {
  156. return this._activeVertices;
  157. }
  158. public getActiveParticles(): number {
  159. return this._activeParticles;
  160. }
  161. // Stats
  162. public getLastFrameDuration(): number {
  163. return this._lastFrameDuration;
  164. }
  165. public getEvaluateActiveMeshesDuration(): number {
  166. return this._evaluateActiveMeshesDuration;
  167. }
  168. public getActiveMeshes(): SmartArray<Mesh> {
  169. return this._activeMeshes;
  170. }
  171. public getRenderTargetsDuration(): number {
  172. return this._renderTargetsDuration;
  173. }
  174. public getRenderDuration(): number {
  175. return this._renderDuration;
  176. }
  177. public getParticlesDuration(): number {
  178. return this._particlesDuration;
  179. }
  180. public getSpritesDuration(): number {
  181. return this._spritesDuration;
  182. }
  183. public getAnimationRatio(): number {
  184. return this._animationRatio;
  185. }
  186. public getRenderId(): number {
  187. return this._renderId;
  188. }
  189. private _updatePointerPosition(evt: PointerEvent): void {
  190. var canvasRect = this._engine.getRenderingCanvasClientRect();
  191. this._pointerX = evt.clientX - canvasRect.left;
  192. this._pointerY = evt.clientY - canvasRect.top;
  193. if (this.cameraToUseForPointers) {
  194. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  195. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  196. }
  197. }
  198. // Pointers handling
  199. public attachControl() {
  200. this._onPointerMove = (evt: PointerEvent) => {
  201. var canvas = this._engine.getRenderingCanvas();
  202. this._updatePointerPosition(evt);
  203. var pickResult = this.pick(this._pointerX, this._pointerY,
  204. (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers,
  205. false,
  206. this.cameraToUseForPointers);
  207. if (pickResult.hit) {
  208. this.setPointerOverMesh(pickResult.pickedMesh);
  209. canvas.style.cursor = "pointer";
  210. this._meshUnderPointer = pickResult.pickedMesh;
  211. } else {
  212. this.setPointerOverMesh(null);
  213. canvas.style.cursor = "";
  214. this._meshUnderPointer = null;
  215. }
  216. };
  217. this._onPointerDown = (evt: PointerEvent) => {
  218. var predicate = null;
  219. if (!this.onPointerDown) {
  220. predicate = (mesh: AbstractMesh): boolean => {
  221. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  222. };
  223. }
  224. this._updatePointerPosition(evt);
  225. var pickResult = this.pick(this._pointerX, this._pointerY, predicate, false, this.cameraToUseForPointers);
  226. if (pickResult.hit) {
  227. if (pickResult.pickedMesh.actionManager) {
  228. switch (evt.button) {
  229. case 0:
  230. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh));
  231. break;
  232. case 1:
  233. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh));
  234. break;
  235. case 2:
  236. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh));
  237. break;
  238. }
  239. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh));
  240. }
  241. }
  242. if (this.onPointerDown) {
  243. this.onPointerDown(evt, pickResult);
  244. }
  245. };
  246. this._onKeyDown = (evt: Event) => {
  247. if (this.actionManager) {
  248. this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  249. }
  250. };
  251. this._onKeyUp = (evt: Event) => {
  252. if (this.actionManager) {
  253. this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  254. }
  255. };
  256. var eventPrefix = Tools.GetPointerPrefix();
  257. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  258. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  259. window.addEventListener("keydown", this._onKeyDown, false);
  260. window.addEventListener("keyup", this._onKeyUp, false);
  261. }
  262. public detachControl() {
  263. var eventPrefix = Tools.GetPointerPrefix();
  264. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  265. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  266. window.removeEventListener("keydown", this._onKeyDown);
  267. window.removeEventListener("keyup", this._onKeyUp);
  268. }
  269. // Ready
  270. public isReady(): boolean {
  271. if (this._pendingData.length > 0) {
  272. return false;
  273. }
  274. for (var index = 0; index < this._geometries.length; index++) {
  275. var geometry = this._geometries[index];
  276. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  277. return false;
  278. }
  279. }
  280. for (index = 0; index < this.meshes.length; index++) {
  281. var mesh = this.meshes[index];
  282. if (!mesh.isReady()) {
  283. return false;
  284. }
  285. var mat = mesh.material;
  286. if (mat) {
  287. if (!mat.isReady(mesh)) {
  288. return false;
  289. }
  290. }
  291. }
  292. return true;
  293. }
  294. public registerBeforeRender(func: () => void): void {
  295. this._onBeforeRenderCallbacks.push(func);
  296. }
  297. public unregisterBeforeRender(func: () => void): void {
  298. var index = this._onBeforeRenderCallbacks.indexOf(func);
  299. if (index > -1) {
  300. this._onBeforeRenderCallbacks.splice(index, 1);
  301. }
  302. }
  303. public _addPendingData(data): void {
  304. this._pendingData.push(data);
  305. }
  306. public _removePendingData(data): void {
  307. var index = this._pendingData.indexOf(data);
  308. if (index !== -1) {
  309. this._pendingData.splice(index, 1);
  310. }
  311. }
  312. public getWaitingItemsCount(): number {
  313. return this._pendingData.length;
  314. }
  315. public executeWhenReady(func: () => void): void {
  316. this._onReadyCallbacks.push(func);
  317. if (this._executeWhenReadyTimeoutId !== -1) {
  318. return;
  319. }
  320. this._executeWhenReadyTimeoutId = setTimeout(() => {
  321. this._checkIsReady();
  322. }, 150);
  323. }
  324. public _checkIsReady() {
  325. if (this.isReady()) {
  326. this._onReadyCallbacks.forEach(func => {
  327. func();
  328. });
  329. this._onReadyCallbacks = [];
  330. this._executeWhenReadyTimeoutId = -1;
  331. return;
  332. }
  333. this._executeWhenReadyTimeoutId = setTimeout(() => {
  334. this._checkIsReady();
  335. }, 150);
  336. }
  337. // Animations
  338. public beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void, animatable?: Animatable): Animatable {
  339. if (speedRatio === undefined) {
  340. speedRatio = 1.0;
  341. }
  342. this.stopAnimation(target);
  343. if (!animatable) {
  344. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  345. }
  346. // Local animations
  347. if (target.animations) {
  348. animatable.appendAnimations(target, target.animations);
  349. }
  350. // Children animations
  351. if (target.getAnimatables) {
  352. var animatables = target.getAnimatables();
  353. for (var index = 0; index < animatables.length; index++) {
  354. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  355. }
  356. }
  357. return animatable;
  358. }
  359. public beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable {
  360. if (speedRatio === undefined) {
  361. speedRatio = 1.0;
  362. }
  363. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  364. return animatable;
  365. }
  366. public getAnimatableByTarget(target: any): Animatable {
  367. for (var index = 0; index < this._activeAnimatables.length; index++) {
  368. if (this._activeAnimatables[index].target === target) {
  369. return this._activeAnimatables[index];
  370. }
  371. }
  372. return null;
  373. }
  374. public stopAnimation(target: any): void {
  375. var animatable = this.getAnimatableByTarget(target);
  376. if (animatable) {
  377. animatable.stop();
  378. }
  379. }
  380. private _animate(): void {
  381. if (!this._animationStartDate) {
  382. this._animationStartDate = new Date().getTime();
  383. }
  384. // Getting time
  385. var now = new Date().getTime();
  386. var delay = now - this._animationStartDate;
  387. for (var index = 0; index < this._activeAnimatables.length; index++) {
  388. if (!this._activeAnimatables[index]._animate(delay)) {
  389. this._activeAnimatables.splice(index, 1);
  390. index--;
  391. }
  392. }
  393. }
  394. // Matrix
  395. public getViewMatrix(): Matrix {
  396. return this._viewMatrix;
  397. }
  398. public getProjectionMatrix(): Matrix {
  399. return this._projectionMatrix;
  400. }
  401. public getTransformMatrix(): Matrix {
  402. return this._transformMatrix;
  403. }
  404. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  405. this._viewMatrix = view;
  406. this._projectionMatrix = projection;
  407. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  408. }
  409. // Methods
  410. public setActiveCameraByID(id: string): Camera {
  411. var camera = this.getCameraByID(id);
  412. if (camera) {
  413. this.activeCamera = camera;
  414. return camera;
  415. }
  416. return null;
  417. }
  418. public setActiveCameraByName(name: string): Camera {
  419. var camera = this.getCameraByName(name);
  420. if (camera) {
  421. this.activeCamera = camera;
  422. return camera;
  423. }
  424. return null;
  425. }
  426. public getMaterialByID(id: string): Material {
  427. for (var index = 0; index < this.materials.length; index++) {
  428. if (this.materials[index].id === id) {
  429. return this.materials[index];
  430. }
  431. }
  432. return null;
  433. }
  434. public getMaterialByName(name: string): Material {
  435. for (var index = 0; index < this.materials.length; index++) {
  436. if (this.materials[index].name === name) {
  437. return this.materials[index];
  438. }
  439. }
  440. return null;
  441. }
  442. public getCameraByID(id: string): Camera {
  443. for (var index = 0; index < this.cameras.length; index++) {
  444. if (this.cameras[index].id === id) {
  445. return this.cameras[index];
  446. }
  447. }
  448. return null;
  449. }
  450. public getCameraByName(name: string): Camera {
  451. for (var index = 0; index < this.cameras.length; index++) {
  452. if (this.cameras[index].name === name) {
  453. return this.cameras[index];
  454. }
  455. }
  456. return null;
  457. }
  458. public getLightByName(name: string): Light {
  459. for (var index = 0; index < this.lights.length; index++) {
  460. if (this.lights[index].name === name) {
  461. return this.lights[index];
  462. }
  463. }
  464. return null;
  465. }
  466. public getLightByID(id: string): Light {
  467. for (var index = 0; index < this.lights.length; index++) {
  468. if (this.lights[index].id === id) {
  469. return this.lights[index];
  470. }
  471. }
  472. return null;
  473. }
  474. public getGeometryByID(id: string): Geometry {
  475. for (var index = 0; index < this._geometries.length; index++) {
  476. if (this._geometries[index].id === id) {
  477. return this._geometries[index];
  478. }
  479. }
  480. return null;
  481. }
  482. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  483. if (!force && this.getGeometryByID(geometry.id)) {
  484. return false;
  485. }
  486. this._geometries.push(geometry);
  487. return true;
  488. }
  489. public getGeometries(): Geometry[] {
  490. return this._geometries;
  491. }
  492. public getMeshByID(id: string): AbstractMesh {
  493. for (var index = 0; index < this.meshes.length; index++) {
  494. if (this.meshes[index].id === id) {
  495. return this.meshes[index];
  496. }
  497. }
  498. return null;
  499. }
  500. public getLastMeshByID(id: string): AbstractMesh {
  501. for (var index = this.meshes.length - 1; index >= 0; index--) {
  502. if (this.meshes[index].id === id) {
  503. return this.meshes[index];
  504. }
  505. }
  506. return null;
  507. }
  508. public getLastEntryByID(id: string): Node {
  509. for (var index = this.meshes.length - 1; index >= 0; index--) {
  510. if (this.meshes[index].id === id) {
  511. return this.meshes[index];
  512. }
  513. }
  514. for (index = this.cameras.length - 1; index >= 0; index--) {
  515. if (this.cameras[index].id === id) {
  516. return this.cameras[index];
  517. }
  518. }
  519. for (index = this.lights.length - 1; index >= 0; index--) {
  520. if (this.lights[index].id === id) {
  521. return this.lights[index];
  522. }
  523. }
  524. return null;
  525. }
  526. public getMeshByName(name: string): AbstractMesh {
  527. for (var index = 0; index < this.meshes.length; index++) {
  528. if (this.meshes[index].name === name) {
  529. return this.meshes[index];
  530. }
  531. }
  532. return null;
  533. }
  534. public getLastSkeletonByID(id: string): Skeleton {
  535. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  536. if (this.skeletons[index].id === id) {
  537. return this.skeletons[index];
  538. }
  539. }
  540. return null;
  541. }
  542. public getSkeletonById(id: string): Skeleton {
  543. for (var index = 0; index < this.skeletons.length; index++) {
  544. if (this.skeletons[index].id === id) {
  545. return this.skeletons[index];
  546. }
  547. }
  548. return null;
  549. }
  550. public getSkeletonByName(name: string): Skeleton {
  551. for (var index = 0; index < this.skeletons.length; index++) {
  552. if (this.skeletons[index].name === name) {
  553. return this.skeletons[index];
  554. }
  555. }
  556. return null;
  557. }
  558. public isActiveMesh(mesh: Mesh): boolean {
  559. return (this._activeMeshes.indexOf(mesh) !== -1);
  560. }
  561. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  562. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  563. var material = subMesh.getMaterial();
  564. if (mesh.showSubMeshesBoundingBox) {
  565. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  566. }
  567. if (material) {
  568. // Render targets
  569. if (material.getRenderTargetTextures) {
  570. if (this._processedMaterials.indexOf(material) === -1) {
  571. this._processedMaterials.push(material);
  572. this._renderTargets.concat(material.getRenderTargetTextures());
  573. }
  574. }
  575. // Dispatch
  576. this._activeVertices += subMesh.verticesCount;
  577. this._renderingManager.dispatch(subMesh);
  578. }
  579. }
  580. }
  581. private _evaluateActiveMeshes(): void {
  582. this._activeMeshes.reset();
  583. this._renderingManager.reset();
  584. this._processedMaterials.reset();
  585. this._activeParticleSystems.reset();
  586. this._activeSkeletons.reset();
  587. this._boundingBoxRenderer.reset();
  588. if (!this._frustumPlanes) {
  589. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  590. } else {
  591. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  592. }
  593. // Meshes
  594. var meshes: AbstractMesh[];
  595. var len: number;
  596. if (this._selectionOctree) { // Octree
  597. var selection = this._selectionOctree.select(this._frustumPlanes);
  598. meshes = selection.data;
  599. len = selection.length;
  600. } else { // Full scene traversal
  601. len = this.meshes.length;
  602. meshes = this.meshes;
  603. }
  604. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  605. var mesh = meshes[meshIndex];
  606. this._totalVertices += mesh.getTotalVertices();
  607. if (!mesh.isReady()) {
  608. continue;
  609. }
  610. mesh.computeWorldMatrix();
  611. mesh._preActivate();
  612. // Intersections
  613. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([ActionManager.OnIntersectionEnterTrigger, ActionManager.OnIntersectionExitTrigger])) {
  614. this._meshesForIntersections.pushNoDuplicate(mesh);
  615. }
  616. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  617. this._activeMeshes.push(mesh);
  618. mesh._activate(this._renderId);
  619. this._activeMesh(mesh);
  620. }
  621. }
  622. // Particle systems
  623. var beforeParticlesDate = new Date().getTime();
  624. if (this.particlesEnabled) {
  625. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  626. var particleSystem = this.particleSystems[particleIndex];
  627. if (!particleSystem.isStarted()) {
  628. continue;
  629. }
  630. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  631. this._activeParticleSystems.push(particleSystem);
  632. particleSystem.animate();
  633. }
  634. }
  635. }
  636. this._particlesDuration += new Date().getTime() - beforeParticlesDate;
  637. }
  638. private _activeMesh(mesh: AbstractMesh): void {
  639. if (mesh.skeleton) {
  640. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  641. }
  642. if (mesh.showBoundingBox) {
  643. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  644. }
  645. if (mesh.subMeshes) {
  646. // Submeshes Octrees
  647. var len: number;
  648. var subMeshes: SubMesh[];
  649. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  650. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  651. len = intersections.length;
  652. subMeshes = intersections.data;
  653. } else {
  654. subMeshes = mesh.subMeshes;
  655. len = subMeshes.length;
  656. }
  657. for (var subIndex = 0; subIndex < len; subIndex++) {
  658. var subMesh = subMeshes[subIndex];
  659. this._evaluateSubMesh(subMesh, mesh);
  660. }
  661. }
  662. }
  663. public updateTransformMatrix(force?: boolean): void {
  664. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  665. }
  666. private _renderForCamera(camera: Camera): void {
  667. var engine = this._engine;
  668. this.activeCamera = camera;
  669. if (!this.activeCamera)
  670. throw new Error("Active camera not set");
  671. // Viewport
  672. engine.setViewport(this.activeCamera.viewport);
  673. // Camera
  674. this._renderId++;
  675. this.updateTransformMatrix();
  676. if (this.beforeCameraRender) {
  677. this.beforeCameraRender(this.activeCamera);
  678. }
  679. // Meshes
  680. var beforeEvaluateActiveMeshesDate = new Date().getTime();
  681. this._evaluateActiveMeshes();
  682. this._evaluateActiveMeshesDuration += new Date().getTime() - beforeEvaluateActiveMeshesDate;
  683. // Skeletons
  684. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  685. var skeleton = this._activeSkeletons.data[skeletonIndex];
  686. skeleton.prepare();
  687. }
  688. // Customs render targets registration
  689. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  690. var renderTarget = this.customRenderTargets[customIndex];
  691. this._renderTargets.push(renderTarget);
  692. }
  693. // Render targets
  694. var beforeRenderTargetDate = new Date().getTime();
  695. if (this.renderTargetsEnabled) {
  696. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  697. renderTarget = this._renderTargets.data[renderIndex];
  698. if (renderTarget._shouldRender()) {
  699. this._renderId++;
  700. renderTarget.render();
  701. }
  702. }
  703. this._renderId++;
  704. }
  705. if (this._renderTargets.length > 0) { // Restore back buffer
  706. engine.restoreDefaultFramebuffer();
  707. }
  708. this._renderTargetsDuration = new Date().getTime() - beforeRenderTargetDate;
  709. // Prepare Frame
  710. this.postProcessManager._prepareFrame();
  711. var beforeRenderDate = new Date().getTime();
  712. // Backgrounds
  713. if (this.layers.length) {
  714. engine.setDepthBuffer(false);
  715. var layerIndex;
  716. var layer;
  717. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  718. layer = this.layers[layerIndex];
  719. if (layer.isBackground) {
  720. layer.render();
  721. }
  722. }
  723. engine.setDepthBuffer(true);
  724. }
  725. // Render
  726. this._renderingManager.render(null, null, true, true);
  727. // Bounding boxes
  728. this._boundingBoxRenderer.render();
  729. // Lens flares
  730. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  731. this.lensFlareSystems[lensFlareSystemIndex].render();
  732. }
  733. // Foregrounds
  734. if (this.layers.length) {
  735. engine.setDepthBuffer(false);
  736. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  737. layer = this.layers[layerIndex];
  738. if (!layer.isBackground) {
  739. layer.render();
  740. }
  741. }
  742. engine.setDepthBuffer(true);
  743. }
  744. this._renderDuration += new Date().getTime() - beforeRenderDate;
  745. // Finalize frame
  746. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  747. // Update camera
  748. this.activeCamera._updateFromScene();
  749. // Reset some special arrays
  750. this._renderTargets.reset();
  751. if (this.afterCameraRender) {
  752. this.afterCameraRender(this.activeCamera);
  753. }
  754. }
  755. private _processSubCameras(camera: Camera): void {
  756. if (camera.subCameras.length == 0) {
  757. this._renderForCamera(camera);
  758. return;
  759. }
  760. // Sub-cameras
  761. for (var index = 0; index < camera.subCameras.length; index++) {
  762. this._renderForCamera(camera.subCameras[index]);
  763. }
  764. this.activeCamera = camera;
  765. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  766. // Update camera
  767. this.activeCamera._updateFromScene();
  768. }
  769. private _checkIntersections(): void {
  770. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  771. var sourceMesh = this._meshesForIntersections.data[index];
  772. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  773. var action = sourceMesh.actionManager.actions[actionIndex];
  774. if (action.trigger == ActionManager.OnIntersectionEnterTrigger || action.trigger == ActionManager.OnIntersectionExitTrigger) {
  775. var otherMesh = action.getTriggerParameter();
  776. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  777. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  778. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == ActionManager.OnIntersectionEnterTrigger ) {
  779. sourceMesh.actionManager.processTrigger(ActionManager.OnIntersectionEnterTrigger, ActionEvent.CreateNew(sourceMesh));
  780. sourceMesh._intersectionsInProgress.push(otherMesh);
  781. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == ActionManager.OnIntersectionExitTrigger ) {
  782. sourceMesh.actionManager.processTrigger(ActionManager.OnIntersectionExitTrigger, ActionEvent.CreateNew(sourceMesh));
  783. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  784. if (indexOfOther > -1) {
  785. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  786. }
  787. }
  788. }
  789. }
  790. }
  791. }
  792. public render(): void {
  793. var startDate = new Date().getTime();
  794. this._particlesDuration = 0;
  795. this._spritesDuration = 0;
  796. this._activeParticles = 0;
  797. this._renderDuration = 0;
  798. this._evaluateActiveMeshesDuration = 0;
  799. this._totalVertices = 0;
  800. this._activeVertices = 0;
  801. this._meshesForIntersections.reset();
  802. // Actions
  803. if (this.actionManager) {
  804. this.actionManager.processTrigger(ActionManager.OnEveryFrameTrigger, null);
  805. }
  806. // Before render
  807. if (this.beforeRender) {
  808. this.beforeRender();
  809. }
  810. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  811. this._onBeforeRenderCallbacks[callbackIndex]();
  812. }
  813. // Animations
  814. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  815. this._animationRatio = deltaTime * (60.0 / 1000.0);
  816. this._animate();
  817. // Physics
  818. if (this._physicsEngine) {
  819. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  820. }
  821. // Clear
  822. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  823. // Shadows
  824. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  825. var light = this.lights[lightIndex];
  826. var shadowGenerator = light.getShadowGenerator();
  827. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  828. this._renderTargets.push(shadowGenerator.getShadowMap());
  829. }
  830. }
  831. // RenderPipeline
  832. this.postProcessRenderPipelineManager.update();
  833. // Multi-cameras?
  834. if (this.activeCameras.length > 0) {
  835. var currentRenderId = this._renderId;
  836. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  837. this._renderId = currentRenderId;
  838. this._processSubCameras(this.activeCameras[cameraIndex]);
  839. }
  840. } else {
  841. this._processSubCameras(this.activeCamera);
  842. }
  843. // Intersection checks
  844. this._checkIntersections();
  845. // After render
  846. if (this.afterRender) {
  847. this.afterRender();
  848. }
  849. // Cleaning
  850. for (var index = 0; index < this._toBeDisposed.length; index++) {
  851. this._toBeDisposed.data[index].dispose();
  852. this._toBeDisposed[index] = null;
  853. }
  854. this._toBeDisposed.reset();
  855. this._lastFrameDuration = new Date().getTime() - startDate;
  856. }
  857. public dispose(): void {
  858. this.beforeRender = null;
  859. this.afterRender = null;
  860. this.skeletons = [];
  861. this._boundingBoxRenderer.dispose();
  862. // Events
  863. if (this.onDispose) {
  864. this.onDispose();
  865. }
  866. this.detachControl();
  867. // Detach cameras
  868. var canvas = this._engine.getRenderingCanvas();
  869. var index;
  870. for (index = 0; index < this.cameras.length; index++) {
  871. this.cameras[index].detachControl(canvas);
  872. }
  873. // Release lights
  874. while (this.lights.length) {
  875. this.lights[0].dispose();
  876. }
  877. // Release meshes
  878. while (this.meshes.length) {
  879. this.meshes[0].dispose(true);
  880. }
  881. // Release cameras
  882. while (this.cameras.length) {
  883. this.cameras[0].dispose();
  884. }
  885. // Release materials
  886. while (this.materials.length) {
  887. this.materials[0].dispose();
  888. }
  889. // Release particles
  890. while (this.particleSystems.length) {
  891. this.particleSystems[0].dispose();
  892. }
  893. // Release sprites
  894. while (this.spriteManagers.length) {
  895. this.spriteManagers[0].dispose();
  896. }
  897. // Release layers
  898. while (this.layers.length) {
  899. this.layers[0].dispose();
  900. }
  901. // Release textures
  902. while (this.textures.length) {
  903. this.textures[0].dispose();
  904. }
  905. // Post-processes
  906. this.postProcessManager.dispose();
  907. // Physics
  908. if (this._physicsEngine) {
  909. this.disablePhysicsEngine();
  910. }
  911. // Remove from engine
  912. index = this._engine.scenes.indexOf(this);
  913. this._engine.scenes.splice(index, 1);
  914. this._engine.wipeCaches();
  915. }
  916. // Collisions
  917. public _getNewPosition(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, finalPosition: Vector3, excludedMesh: AbstractMesh = null): void {
  918. position.divideToRef(collider.radius, this._scaledPosition);
  919. velocity.divideToRef(collider.radius, this._scaledVelocity);
  920. collider.retry = 0;
  921. collider.initialVelocity = this._scaledVelocity;
  922. collider.initialPosition = this._scaledPosition;
  923. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  924. finalPosition.multiplyInPlace(collider.radius);
  925. }
  926. private _collideWithWorld(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, finalPosition: Vector3, excludedMesh: AbstractMesh = null): void {
  927. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  928. if (collider.retry >= maximumRetry) {
  929. finalPosition.copyFrom(position);
  930. return;
  931. }
  932. collider._initialize(position, velocity, closeDistance);
  933. // Check all meshes
  934. for (var index = 0; index < this.meshes.length; index++) {
  935. var mesh = this.meshes[index];
  936. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  937. mesh._checkCollision(collider);
  938. }
  939. }
  940. if (!collider.collisionFound) {
  941. position.addToRef(velocity, finalPosition);
  942. return;
  943. }
  944. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  945. collider._getResponse(position, velocity);
  946. }
  947. if (velocity.length() <= closeDistance) {
  948. finalPosition.copyFrom(position);
  949. return;
  950. }
  951. collider.retry++;
  952. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  953. }
  954. // Octrees
  955. public createOrUpdateSelectionOctree(maxCapacity = 64, maxDepth = 2): Octree<AbstractMesh> {
  956. if (!this._selectionOctree) {
  957. this._selectionOctree = new BABYLON.Octree<AbstractMesh>(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  958. }
  959. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  960. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  961. for (var index = 0; index < this.meshes.length; index++) {
  962. var mesh = this.meshes[index];
  963. mesh.computeWorldMatrix(true);
  964. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  965. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  966. Tools.CheckExtends(minBox, min, max);
  967. Tools.CheckExtends(maxBox, min, max);
  968. }
  969. // Update octree
  970. this._selectionOctree.update(min, max, this.meshes);
  971. return this._selectionOctree;
  972. }
  973. // Picking
  974. public createPickingRay(x: number, y: number, world: Matrix, camera: Camera): Ray {
  975. var engine = this._engine;
  976. if (!camera) {
  977. if (!this.activeCamera)
  978. throw new Error("Active camera not set");
  979. camera = this.activeCamera;
  980. }
  981. var cameraViewport = camera.viewport;
  982. var viewport = cameraViewport.toGlobal(engine);
  983. // Moving coordinates to local viewport world
  984. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  985. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  986. return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  987. }
  988. private _internalPick(rayFunction: (world: Matrix) => Ray, predicate: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): PickingInfo {
  989. var pickingInfo = null;
  990. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  991. var mesh = this.meshes[meshIndex];
  992. if (predicate) {
  993. if (!predicate(mesh)) {
  994. continue;
  995. }
  996. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  997. continue;
  998. }
  999. var world = mesh.getWorldMatrix();
  1000. var ray = rayFunction(world);
  1001. var result = mesh.intersects(ray, fastCheck);
  1002. if (!result || !result.hit)
  1003. continue;
  1004. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  1005. continue;
  1006. pickingInfo = result;
  1007. if (fastCheck) {
  1008. break;
  1009. }
  1010. }
  1011. return pickingInfo || new BABYLON.PickingInfo();
  1012. }
  1013. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo {
  1014. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  1015. /// <param name="x">X position on screen</param>
  1016. /// <param name="y">Y position on screen</param>
  1017. /// <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>
  1018. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  1019. /// <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>
  1020. return this._internalPick(world => this.createPickingRay(x, y, world, camera), predicate, fastCheck);
  1021. }
  1022. public pickWithRay(ray: Ray, predicate: (mesh: Mesh) => boolean, fastCheck?: boolean) {
  1023. return this._internalPick(world => {
  1024. if (!this._pickWithRayInverseMatrix) {
  1025. this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  1026. }
  1027. world.invertToRef(this._pickWithRayInverseMatrix);
  1028. return BABYLON.Ray.Transform(ray, this._pickWithRayInverseMatrix);
  1029. }, predicate, fastCheck);
  1030. }
  1031. public setPointerOverMesh(mesh: AbstractMesh): void {
  1032. if (this._pointerOverMesh === mesh) {
  1033. return;
  1034. }
  1035. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  1036. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  1037. }
  1038. this._pointerOverMesh = mesh;
  1039. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  1040. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  1041. }
  1042. }
  1043. public getPointerOverMesh(): AbstractMesh {
  1044. return this._pointerOverMesh;
  1045. }
  1046. // Physics
  1047. public getPhysicsEngine(): PhysicsEngine {
  1048. return this._physicsEngine;
  1049. }
  1050. public enablePhysics(gravity: Vector3, plugin?: IPhysicsEnginePlugin): boolean {
  1051. if (this._physicsEngine) {
  1052. return true;
  1053. }
  1054. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  1055. if (!this._physicsEngine.isSupported()) {
  1056. this._physicsEngine = null;
  1057. return false;
  1058. }
  1059. this._physicsEngine._initialize(gravity);
  1060. return true;
  1061. }
  1062. public disablePhysicsEngine(): void {
  1063. if (!this._physicsEngine) {
  1064. return;
  1065. }
  1066. this._physicsEngine.dispose();
  1067. this._physicsEngine = undefined;
  1068. }
  1069. public isPhysicsEnabled(): boolean {
  1070. return this._physicsEngine !== undefined;
  1071. }
  1072. public setGravity(gravity: Vector3): void {
  1073. if (!this._physicsEngine) {
  1074. return;
  1075. }
  1076. this._physicsEngine._setGravity(gravity);
  1077. }
  1078. public createCompoundImpostor(parts: any, options: PhysicsBodyCreationOptions): any {
  1079. if (parts.parts) { // Old API
  1080. options = parts;
  1081. parts = parts.parts;
  1082. }
  1083. if (!this._physicsEngine) {
  1084. return null;
  1085. }
  1086. for (var index = 0; index < parts.length; index++) {
  1087. var mesh = parts[index].mesh;
  1088. mesh._physicImpostor = parts[index].impostor;
  1089. mesh._physicsMass = options.mass / parts.length;
  1090. mesh._physicsFriction = options.friction;
  1091. mesh._physicRestitution = options.restitution;
  1092. }
  1093. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  1094. }
  1095. //ANY
  1096. public deleteCompoundImpostor(compound: any): void {
  1097. for (var index = 0; index < compound.parts.length; index++) {
  1098. var mesh = compound.parts[index].mesh;
  1099. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  1100. this._physicsEngine._unregisterMesh(mesh);
  1101. }
  1102. }
  1103. // Tags
  1104. private _getByTags(list: any[], tagsQuery: string): any[] {
  1105. if (tagsQuery === undefined) {
  1106. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  1107. return list;
  1108. }
  1109. var listByTags = [];
  1110. for (var i in list) {
  1111. var item = list[i];
  1112. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  1113. listByTags.push(item);
  1114. }
  1115. }
  1116. return listByTags;
  1117. }
  1118. public getMeshesByTags(tagsQuery: string): Mesh[] {
  1119. return this._getByTags(this.meshes, tagsQuery);
  1120. }
  1121. public getCamerasByTags(tagsQuery: string): Camera[] {
  1122. return this._getByTags(this.cameras, tagsQuery);
  1123. }
  1124. public getLightsByTags(tagsQuery: string): Light[] {
  1125. return this._getByTags(this.lights, tagsQuery);
  1126. }
  1127. public getMaterialByTags(tagsQuery: string): Material[] {
  1128. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  1129. }
  1130. }
  1131. }