spriteManager.ts 28 KB

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