spriteManager.ts 36 KB

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