babylon.scene.ts 46 KB

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