spriteManager.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. import { IDisposable, Scene } from "../scene";
  2. import { Nullable } from "../types";
  3. import { Observable, Observer } from "../Misc/observable";
  4. import { Buffer } from "../Meshes/buffer";
  5. import { VertexBuffer } from "../Meshes/buffer";
  6. import { Vector3, TmpVectors } from "../Maths/math.vector";
  7. import { Sprite } from "./sprite";
  8. import { SpriteSceneComponent } from "./spriteSceneComponent";
  9. import { PickingInfo } from "../Collisions/pickingInfo";
  10. import { Camera } from "../Cameras/camera";
  11. import { Texture } from "../Materials/Textures/texture";
  12. import { Effect } from "../Materials/effect";
  13. import { Material } from "../Materials/material";
  14. import { SceneComponentConstants } from "../sceneComponent";
  15. import { Constants } from "../Engines/constants";
  16. import { Logger } from "../Misc/logger";
  17. import "../Shaders/sprites.fragment";
  18. import "../Shaders/sprites.vertex";
  19. import { DataBuffer } from '../Meshes/dataBuffer';
  20. declare type Ray = import("../Culling/ray").Ray;
  21. /**
  22. * Defines the minimum interface to fullfil in order to be a sprite manager.
  23. */
  24. export interface ISpriteManager extends IDisposable {
  25. /**
  26. * Restricts the camera to viewing objects with the same layerMask.
  27. * A camera with a layerMask of 1 will render spriteManager.layerMask & camera.layerMask!== 0
  28. */
  29. layerMask: number;
  30. /**
  31. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  32. */
  33. isPickable: boolean;
  34. /**
  35. * Specifies the rendering group id for this mesh (0 by default)
  36. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  37. */
  38. renderingGroupId: number;
  39. /**
  40. * Defines the list of sprites managed by the manager.
  41. */
  42. sprites: Array<Sprite>;
  43. /**
  44. * Tests the intersection of a sprite with a specific ray.
  45. * @param ray The ray we are sending to test the collision
  46. * @param camera The camera space we are sending rays in
  47. * @param predicate A predicate allowing excluding sprites from the list of object to test
  48. * @param fastCheck defines if the first intersection will be used (and not the closest)
  49. * @returns picking info or null.
  50. */
  51. intersects(ray: Ray, camera: Camera, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean): Nullable<PickingInfo>;
  52. /**
  53. * Intersects the sprites with a ray
  54. * @param ray defines the ray to intersect with
  55. * @param camera defines the current active camera
  56. * @param predicate defines a predicate used to select candidate sprites
  57. * @returns null if no hit or a PickingInfo array
  58. */
  59. multiIntersects(ray: Ray, camera: Camera, predicate?: (sprite: Sprite) => boolean): Nullable<PickingInfo[]>;
  60. /**
  61. * Renders the list of sprites on screen.
  62. */
  63. render(): void;
  64. }
  65. /**
  66. * Class used to manage multiple sprites on the same spritesheet
  67. * @see http://doc.babylonjs.com/babylon101/sprites
  68. */
  69. export class SpriteManager implements ISpriteManager {
  70. /** Gets the list of sprites */
  71. public sprites = new Array<Sprite>();
  72. /** Gets or sets the rendering group id (0 by default) */
  73. public renderingGroupId = 0;
  74. /** Gets or sets camera layer mask */
  75. public layerMask: number = 0x0FFFFFFF;
  76. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  77. public fogEnabled = true;
  78. /** Gets or sets a boolean indicating if the sprites are pickable */
  79. public isPickable = false;
  80. /** Defines the default width of a cell in the spritesheet */
  81. public cellWidth: number;
  82. /** Defines the default height of a cell in the spritesheet */
  83. public cellHeight: number;
  84. /** Associative array from JSON sprite data file */
  85. private _cellData: any;
  86. /** Array of sprite names from JSON sprite data file */
  87. private _spriteMap: Array<string>;
  88. /** True when packed cell data from JSON file is ready*/
  89. private _packedAndReady: boolean = false;
  90. private _textureContent: Nullable<Uint8Array>;
  91. /**
  92. * An event triggered when the manager is disposed.
  93. */
  94. public onDisposeObservable = new Observable<SpriteManager>();
  95. private _onDisposeObserver: Nullable<Observer<SpriteManager>>;
  96. /**
  97. * Callback called when the manager is disposed
  98. */
  99. public set onDispose(callback: () => void) {
  100. if (this._onDisposeObserver) {
  101. this.onDisposeObservable.remove(this._onDisposeObserver);
  102. }
  103. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  104. }
  105. private _capacity: number;
  106. private _fromPacked: boolean;
  107. private _spriteTexture: Texture;
  108. private _epsilon: number;
  109. private _scene: Scene;
  110. private _vertexData: Float32Array;
  111. private _buffer: Buffer;
  112. private _vertexBuffers: { [key: string]: VertexBuffer } = {};
  113. private _indexBuffer: DataBuffer;
  114. private _effectBase: Effect;
  115. private _effectFog: Effect;
  116. /**
  117. * Gets or sets the spritesheet texture
  118. */
  119. public get texture(): Texture {
  120. return this._spriteTexture;
  121. }
  122. public set texture(value: Texture) {
  123. this._spriteTexture = value;
  124. this._textureContent = null;
  125. }
  126. private _blendMode = Constants.ALPHA_COMBINE;
  127. /**
  128. * Blend mode use to render the particle, it can be any of
  129. * the static Constants.ALPHA_x properties provided in this class.
  130. * Default value is Constants.ALPHA_COMBINE
  131. */
  132. public get blendMode() { return this._blendMode; }
  133. public set blendMode(blendMode: number) {
  134. this._blendMode = blendMode;
  135. }
  136. /** Disables writing to the depth buffer when rendering the sprites.
  137. * It can be handy to disable depth writing when using textures without alpha channel
  138. * and setting some specific blend modes.
  139. */
  140. public disableDepthWrite: boolean = false;
  141. /**
  142. * Creates a new sprite manager
  143. * @param name defines the manager's name
  144. * @param imgUrl defines the sprite sheet url
  145. * @param capacity defines the maximum allowed number of sprites
  146. * @param cellSize defines the size of a sprite cell
  147. * @param scene defines the hosting scene
  148. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  149. * @param samplingMode defines the smapling mode to use with spritesheet
  150. * @param fromPacked set to false; do not alter
  151. * @param spriteJSON null otherwise a JSON object defining sprite sheet data; do not alter
  152. */
  153. constructor(
  154. /** defines the manager's name */
  155. public name: string,
  156. imgUrl: string, capacity: number, cellSize: any, scene: Scene, epsilon: number = 0.01, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE, fromPacked: boolean = false, spriteJSON: any | null = null) {
  157. if (!scene._getComponent(SceneComponentConstants.NAME_SPRITE)) {
  158. scene._addComponent(new SpriteSceneComponent(scene));
  159. }
  160. this._capacity = capacity;
  161. this._fromPacked = fromPacked;
  162. this._spriteTexture = new Texture(imgUrl, scene, true, false, samplingMode);
  163. this._spriteTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
  164. this._spriteTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
  165. if (cellSize.width && cellSize.height) {
  166. this.cellWidth = cellSize.width;
  167. this.cellHeight = cellSize.height;
  168. } else if (cellSize !== undefined) {
  169. this.cellWidth = cellSize;
  170. this.cellHeight = cellSize;
  171. } else {
  172. return;
  173. }
  174. this._epsilon = epsilon;
  175. this._scene = scene;
  176. this._scene.spriteManagers.push(this);
  177. var indices = [];
  178. var index = 0;
  179. for (var count = 0; count < capacity; count++) {
  180. indices.push(index);
  181. indices.push(index + 1);
  182. indices.push(index + 2);
  183. indices.push(index);
  184. indices.push(index + 2);
  185. indices.push(index + 3);
  186. index += 4;
  187. }
  188. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  189. // VBO
  190. // 18 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellLeft, cellTop, cellWidth, cellHeight, color r, color g, color b, color a)
  191. this._vertexData = new Float32Array(capacity * 18 * 4);
  192. this._buffer = new Buffer(scene.getEngine(), this._vertexData, true, 18);
  193. var positions = this._buffer.createVertexBuffer(VertexBuffer.PositionKind, 0, 4);
  194. var options = this._buffer.createVertexBuffer("options", 4, 4);
  195. var inverts = this._buffer.createVertexBuffer("inverts", 8, 2);
  196. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 10, 4);
  197. var colors = this._buffer.createVertexBuffer(VertexBuffer.ColorKind, 14, 4);
  198. this._vertexBuffers[VertexBuffer.PositionKind] = positions;
  199. this._vertexBuffers["options"] = options;
  200. this._vertexBuffers["inverts"] = inverts;
  201. this._vertexBuffers["cellInfo"] = cellInfo;
  202. this._vertexBuffers[VertexBuffer.ColorKind] = colors;
  203. // Effects
  204. this._effectBase = this._scene.getEngine().createEffect("sprites",
  205. [VertexBuffer.PositionKind, "options", "inverts", "cellInfo", VertexBuffer.ColorKind],
  206. ["view", "projection", "textureInfos", "alphaTest"],
  207. ["diffuseSampler"], "");
  208. this._effectFog = this._scene.getEngine().createEffect("sprites",
  209. [VertexBuffer.PositionKind, "options", "inverts", "cellInfo", VertexBuffer.ColorKind],
  210. ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"],
  211. ["diffuseSampler"], "#define FOG");
  212. if (this._fromPacked) {
  213. this._makePacked(imgUrl, spriteJSON);
  214. }
  215. }
  216. private _makePacked(imgUrl: string, spriteJSON: any) {
  217. if (spriteJSON !== null) {
  218. try {
  219. //Get the JSON and Check its stucture. If its an array parse it if its a JSON sring etc...
  220. let celldata: any;
  221. if (typeof spriteJSON === "string") {
  222. celldata = JSON.parse(spriteJSON);
  223. }else {
  224. celldata = spriteJSON;
  225. }
  226. if (celldata.frames.length) {
  227. let frametemp: any = {};
  228. for (let i = 0; i < celldata.frames.length; i++) {
  229. let _f = celldata.frames[i];
  230. if (typeof (Object.keys(_f))[0] !== "string") {
  231. throw new Error("Invalid JSON Format. Check the frame values and make sure the name is the first parameter.");
  232. }
  233. let name: string = _f[(Object.keys(_f))[0]];
  234. frametemp[name] = _f;
  235. }
  236. celldata.frames = frametemp;
  237. }
  238. let spritemap = (<string[]>(<any>Reflect).ownKeys(celldata.frames));
  239. this._spriteMap = spritemap;
  240. this._packedAndReady = true;
  241. this._cellData = celldata.frames;
  242. }
  243. catch (e) {
  244. this._fromPacked = false;
  245. this._packedAndReady = false;
  246. throw new Error("Invalid JSON from string. Spritesheet managed with constant cell size.");
  247. }
  248. }
  249. else {
  250. let re = /\./g;
  251. let li: number;
  252. do {
  253. li = re.lastIndex;
  254. re.test(imgUrl);
  255. } while (re.lastIndex > 0);
  256. let jsonUrl = imgUrl.substring(0, li - 1) + ".json";
  257. let xmlhttp = new XMLHttpRequest();
  258. xmlhttp.open("GET", jsonUrl, true);
  259. xmlhttp.onerror = () => {
  260. Logger.Error("JSON ERROR: Unable to load JSON file.");
  261. this._fromPacked = false;
  262. this._packedAndReady = false;
  263. };
  264. xmlhttp.onload = () => {
  265. try {
  266. let celldata = JSON.parse(xmlhttp.response);
  267. let spritemap = (<string[]>(<any>Reflect).ownKeys(celldata.frames));
  268. this._spriteMap = spritemap;
  269. this._packedAndReady = true;
  270. this._cellData = celldata.frames;
  271. }
  272. catch (e) {
  273. this._fromPacked = false;
  274. this._packedAndReady = false;
  275. throw new Error("Invalid JSON format. Please check documentation for format specifications.");
  276. }
  277. };
  278. xmlhttp.send();
  279. }
  280. }
  281. private _appendSpriteVertex(index: number, sprite: Sprite, offsetX: number, offsetY: number, baseSize: any): void {
  282. var arrayOffset = index * 18;
  283. if (offsetX === 0) {
  284. offsetX = this._epsilon;
  285. }
  286. else if (offsetX === 1) {
  287. offsetX = 1 - this._epsilon;
  288. }
  289. if (offsetY === 0) {
  290. offsetY = this._epsilon;
  291. }
  292. else if (offsetY === 1) {
  293. offsetY = 1 - this._epsilon;
  294. }
  295. // Positions
  296. this._vertexData[arrayOffset] = sprite.position.x;
  297. this._vertexData[arrayOffset + 1] = sprite.position.y;
  298. this._vertexData[arrayOffset + 2] = sprite.position.z;
  299. this._vertexData[arrayOffset + 3] = sprite.angle;
  300. // Options
  301. this._vertexData[arrayOffset + 4] = sprite.width;
  302. this._vertexData[arrayOffset + 5] = sprite.height;
  303. this._vertexData[arrayOffset + 6] = offsetX;
  304. this._vertexData[arrayOffset + 7] = offsetY;
  305. // Inverts
  306. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  307. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  308. // CellIfo
  309. if (this._packedAndReady) {
  310. if (!sprite.cellRef) {
  311. sprite.cellIndex = 0;
  312. }
  313. let num = sprite.cellIndex;
  314. if (typeof (num) === "number" && isFinite(num) && Math.floor(num) === num) {
  315. sprite.cellRef = this._spriteMap[sprite.cellIndex];
  316. }
  317. sprite._xOffset = this._cellData[sprite.cellRef].frame.x / baseSize.width;
  318. sprite._yOffset = this._cellData[sprite.cellRef].frame.y / baseSize.height;
  319. sprite._xSize = this._cellData[sprite.cellRef].frame.w;
  320. sprite._ySize = this._cellData[sprite.cellRef].frame.h;
  321. this._vertexData[arrayOffset + 10] = sprite._xOffset;
  322. this._vertexData[arrayOffset + 11] = sprite._yOffset;
  323. this._vertexData[arrayOffset + 12] = sprite._xSize / baseSize.width;
  324. this._vertexData[arrayOffset + 13] = sprite._ySize / baseSize.height;
  325. }
  326. else {
  327. if (!sprite.cellIndex) {
  328. sprite.cellIndex = 0;
  329. }
  330. var rowSize = baseSize.width / this.cellWidth;
  331. var offset = (sprite.cellIndex / rowSize) >> 0;
  332. sprite._xOffset = (sprite.cellIndex - offset * rowSize) * this.cellWidth / baseSize.width;
  333. sprite._yOffset = offset * this.cellHeight / baseSize.height;
  334. sprite._xSize = this.cellWidth;
  335. sprite._ySize = this.cellHeight;
  336. this._vertexData[arrayOffset + 10] = sprite._xOffset;
  337. this._vertexData[arrayOffset + 11] = sprite._yOffset;
  338. this._vertexData[arrayOffset + 12] = this.cellWidth / baseSize.width;
  339. this._vertexData[arrayOffset + 13] = this.cellHeight / baseSize.height;
  340. }
  341. // Color
  342. this._vertexData[arrayOffset + 14] = sprite.color.r;
  343. this._vertexData[arrayOffset + 15] = sprite.color.g;
  344. this._vertexData[arrayOffset + 16] = sprite.color.b;
  345. this._vertexData[arrayOffset + 17] = sprite.color.a;
  346. }
  347. private _checkTextureAlpha(sprite: Sprite, ray: Ray, distance: number, min: Vector3, max: Vector3) {
  348. if (!sprite.useAlphaForPicking || !this._spriteTexture) {
  349. return true;
  350. }
  351. let textureSize = this._spriteTexture.getSize();
  352. if (!this._textureContent) {
  353. this._textureContent = new Uint8Array(textureSize.width * textureSize.height * 4);
  354. this._spriteTexture.readPixels(0, 0, this._textureContent);
  355. }
  356. let contactPoint = TmpVectors.Vector3[0];
  357. contactPoint.copyFrom(ray.direction);
  358. contactPoint.normalize();
  359. contactPoint.scaleInPlace(distance);
  360. contactPoint.addInPlace(ray.origin);
  361. let contactPointU = ((contactPoint.x - min.x) / (max.x - min.x)) - 0.5;
  362. let contactPointV = (1.0 - (contactPoint.y - min.y) / (max.y - min.y)) - 0.5;
  363. // Rotate
  364. let angle = sprite.angle;
  365. let rotatedU = 0.5 + (contactPointU * Math.cos(angle) - contactPointV * Math.sin(angle));
  366. let rotatedV = 0.5 + (contactPointU * Math.sin(angle) + contactPointV * Math.cos(angle));
  367. let u = (sprite._xOffset * textureSize.width + rotatedU * sprite._xSize) | 0;
  368. let v = (sprite._yOffset * textureSize.height + rotatedV * sprite._ySize) | 0;
  369. let alpha = this._textureContent![(u + v * textureSize.width) * 4 + 3];
  370. return (alpha > 0.5);
  371. }
  372. /**
  373. * Intersects the sprites with a ray
  374. * @param ray defines the ray to intersect with
  375. * @param camera defines the current active camera
  376. * @param predicate defines a predicate used to select candidate sprites
  377. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  378. * @returns null if no hit or a PickingInfo
  379. */
  380. public intersects(ray: Ray, camera: Camera, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  381. var count = Math.min(this._capacity, this.sprites.length);
  382. var min = Vector3.Zero();
  383. var max = Vector3.Zero();
  384. var distance = Number.MAX_VALUE;
  385. var currentSprite: Nullable<Sprite> = null;
  386. var pickedPoint = TmpVectors.Vector3[0];
  387. var cameraSpacePosition = TmpVectors.Vector3[1];
  388. var cameraView = camera.getViewMatrix();
  389. for (var index = 0; index < count; index++) {
  390. var sprite = this.sprites[index];
  391. if (!sprite) {
  392. continue;
  393. }
  394. if (predicate) {
  395. if (!predicate(sprite)) {
  396. continue;
  397. }
  398. } else if (!sprite.isPickable) {
  399. continue;
  400. }
  401. Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  402. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  403. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  404. if (ray.intersectsBoxMinMax(min, max)) {
  405. var currentDistance = Vector3.Distance(cameraSpacePosition, ray.origin);
  406. if (distance > currentDistance) {
  407. if (!this._checkTextureAlpha(sprite, ray, currentDistance, min, max)) {
  408. continue;
  409. }
  410. distance = currentDistance;
  411. currentSprite = sprite;
  412. if (fastCheck) {
  413. break;
  414. }
  415. }
  416. }
  417. }
  418. if (currentSprite) {
  419. var result = new PickingInfo();
  420. cameraView.invertToRef(TmpVectors.Matrix[0]);
  421. result.hit = true;
  422. result.pickedSprite = currentSprite;
  423. result.distance = distance;
  424. // Get picked point
  425. let direction = TmpVectors.Vector3[2];
  426. direction.copyFrom(ray.direction);
  427. direction.normalize();
  428. direction.scaleInPlace(distance);
  429. ray.origin.addToRef(direction, pickedPoint);
  430. result.pickedPoint = Vector3.TransformCoordinates(pickedPoint, TmpVectors.Matrix[0]);
  431. return result;
  432. }
  433. return null;
  434. }
  435. /**
  436. * Intersects the sprites with a ray
  437. * @param ray defines the ray to intersect with
  438. * @param camera defines the current active camera
  439. * @param predicate defines a predicate used to select candidate sprites
  440. * @returns null if no hit or a PickingInfo array
  441. */
  442. public multiIntersects(ray: Ray, camera: Camera, predicate?: (sprite: Sprite) => boolean): Nullable<PickingInfo[]> {
  443. var count = Math.min(this._capacity, this.sprites.length);
  444. var min = Vector3.Zero();
  445. var max = Vector3.Zero();
  446. var distance: number;
  447. var results: Nullable<PickingInfo[]> = [];
  448. var pickedPoint = TmpVectors.Vector3[0].copyFromFloats(0, 0, 0);
  449. var cameraSpacePosition = TmpVectors.Vector3[1].copyFromFloats(0, 0, 0);
  450. var cameraView = camera.getViewMatrix();
  451. for (var index = 0; index < count; index++) {
  452. var sprite = this.sprites[index];
  453. if (!sprite) {
  454. continue;
  455. }
  456. if (predicate) {
  457. if (!predicate(sprite)) {
  458. continue;
  459. }
  460. } else if (!sprite.isPickable) {
  461. continue;
  462. }
  463. Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  464. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  465. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  466. if (ray.intersectsBoxMinMax(min, max)) {
  467. distance = Vector3.Distance(cameraSpacePosition, ray.origin);
  468. if (!this._checkTextureAlpha(sprite, ray, distance, min, max)) {
  469. continue;
  470. }
  471. var result = new PickingInfo();
  472. results.push(result);
  473. cameraView.invertToRef(TmpVectors.Matrix[0]);
  474. result.hit = true;
  475. result.pickedSprite = sprite;
  476. result.distance = distance;
  477. // Get picked point
  478. let direction = TmpVectors.Vector3[2];
  479. direction.copyFrom(ray.direction);
  480. direction.normalize();
  481. direction.scaleInPlace(distance);
  482. ray.origin.addToRef(direction, pickedPoint);
  483. result.pickedPoint = Vector3.TransformCoordinates(pickedPoint, TmpVectors.Matrix[0]);
  484. }
  485. }
  486. return results;
  487. }
  488. /**
  489. * Render all child sprites
  490. */
  491. public render(): void {
  492. // Check
  493. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture
  494. || !this._spriteTexture.isReady() || !this.sprites.length) {
  495. return;
  496. }
  497. if (this._fromPacked && (!this._packedAndReady || !this._spriteMap || !this._cellData)) {
  498. return;
  499. }
  500. var engine = this._scene.getEngine();
  501. var baseSize = this._spriteTexture.getBaseSize();
  502. // Sprites
  503. var deltaTime = engine.getDeltaTime();
  504. var max = Math.min(this._capacity, this.sprites.length);
  505. var offset = 0;
  506. let noSprite = true;
  507. for (var index = 0; index < max; index++) {
  508. var sprite = this.sprites[index];
  509. if (!sprite || !sprite.isVisible) {
  510. continue;
  511. }
  512. noSprite = false;
  513. sprite._animate(deltaTime);
  514. this._appendSpriteVertex(offset++, sprite, 0, 0, baseSize);
  515. this._appendSpriteVertex(offset++, sprite, 1, 0, baseSize);
  516. this._appendSpriteVertex(offset++, sprite, 1, 1, baseSize);
  517. this._appendSpriteVertex(offset++, sprite, 0, 1, baseSize);
  518. }
  519. if (noSprite) {
  520. return;
  521. }
  522. this._buffer.update(this._vertexData);
  523. // Render
  524. var effect = this._effectBase;
  525. if (this._scene.fogEnabled && this._scene.fogMode !== Scene.FOGMODE_NONE && this.fogEnabled) {
  526. effect = this._effectFog;
  527. }
  528. engine.enableEffect(effect);
  529. var viewMatrix = this._scene.getViewMatrix();
  530. effect.setTexture("diffuseSampler", this._spriteTexture);
  531. effect.setMatrix("view", viewMatrix);
  532. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  533. // Fog
  534. if (this._scene.fogEnabled && this._scene.fogMode !== Scene.FOGMODE_NONE && this.fogEnabled) {
  535. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  536. effect.setColor3("vFogColor", this._scene.fogColor);
  537. }
  538. // VBOs
  539. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  540. // Draw order
  541. engine.setDepthFunctionToLessOrEqual();
  542. if (!this.disableDepthWrite) {
  543. effect.setBool("alphaTest", true);
  544. engine.setColorWrite(false);
  545. engine.drawElementsType(Material.TriangleFillMode, 0, (offset / 4) * 6);
  546. engine.setColorWrite(true);
  547. effect.setBool("alphaTest", false);
  548. }
  549. engine.setAlphaMode(this._blendMode);
  550. engine.drawElementsType(Material.TriangleFillMode, 0, (offset / 4) * 6);
  551. engine.setAlphaMode(Constants.ALPHA_DISABLE);
  552. }
  553. /**
  554. * Release associated resources
  555. */
  556. public dispose(): void {
  557. if (this._buffer) {
  558. this._buffer.dispose();
  559. (<any>this._buffer) = null;
  560. }
  561. if (this._indexBuffer) {
  562. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  563. (<any>this._indexBuffer) = null;
  564. }
  565. if (this._spriteTexture) {
  566. this._spriteTexture.dispose();
  567. (<any>this._spriteTexture) = null;
  568. }
  569. this._textureContent = null;
  570. // Remove from scene
  571. var index = this._scene.spriteManagers.indexOf(this);
  572. this._scene.spriteManagers.splice(index, 1);
  573. // Callback
  574. this.onDisposeObservable.notifyObservers(this);
  575. this.onDisposeObservable.clear();
  576. }
  577. }