spriteManager.ts 32 KB

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