buffer.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. import { Nullable, DataArray } from "../types";
  2. import { Engine } from "../Engines/engine";
  3. import { DataBuffer } from './dataBuffer';
  4. /**
  5. * Class used to store data that will be store in GPU memory
  6. */
  7. export class Buffer {
  8. private _engine: Engine;
  9. private _buffer: Nullable<DataBuffer>;
  10. /** @hidden */
  11. public _data: Nullable<DataArray>;
  12. private _updatable: boolean;
  13. private _instanced: boolean;
  14. /**
  15. * Gets the byte stride.
  16. */
  17. public readonly byteStride: number;
  18. /**
  19. * Constructor
  20. * @param engine the engine
  21. * @param data the data to use for this buffer
  22. * @param updatable whether the data is updatable
  23. * @param stride the stride (optional)
  24. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  25. * @param instanced whether the buffer is instanced (optional)
  26. * @param useBytes set to true if the stride in in bytes (optional)
  27. */
  28. constructor(engine: any, data: DataArray, updatable: boolean, stride = 0, postponeInternalCreation = false, instanced = false, useBytes = false) {
  29. if (engine.getScene) { // old versions of VertexBuffer accepted 'mesh' instead of 'engine'
  30. this._engine = engine.getScene().getEngine();
  31. }
  32. else {
  33. this._engine = engine;
  34. }
  35. this._updatable = updatable;
  36. this._instanced = instanced;
  37. this._data = data;
  38. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  39. if (!postponeInternalCreation) { // by default
  40. this.create();
  41. }
  42. }
  43. /**
  44. * Create a new VertexBuffer based on the current buffer
  45. * @param kind defines the vertex buffer kind (position, normal, etc.)
  46. * @param offset defines offset in the buffer (0 by default)
  47. * @param size defines the size in floats of attributes (position is 3 for instance)
  48. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  49. * @param instanced defines if the vertex buffer contains indexed data
  50. * @param useBytes defines if the offset and stride are in bytes
  51. * @returns the new vertex buffer
  52. */
  53. public createVertexBuffer(kind: string, offset: number, size: number, stride?: number, instanced?: boolean, useBytes = false): VertexBuffer {
  54. const byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  55. const byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  56. // a lot of these parameters are ignored as they are overriden by the buffer
  57. return new VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  58. }
  59. // Properties
  60. /**
  61. * Gets a boolean indicating if the Buffer is updatable?
  62. * @returns true if the buffer is updatable
  63. */
  64. public isUpdatable(): boolean {
  65. return this._updatable;
  66. }
  67. /**
  68. * Gets current buffer's data
  69. * @returns a DataArray or null
  70. */
  71. public getData(): Nullable<DataArray> {
  72. return this._data;
  73. }
  74. /**
  75. * Gets underlying native buffer
  76. * @returns underlying native buffer
  77. */
  78. public getBuffer(): Nullable<DataBuffer> {
  79. return this._buffer;
  80. }
  81. /**
  82. * Gets the stride in float32 units (i.e. byte stride / 4).
  83. * May not be an integer if the byte stride is not divisible by 4.
  84. * DEPRECATED. Use byteStride instead.
  85. * @returns the stride in float32 units
  86. */
  87. public getStrideSize(): number {
  88. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  89. }
  90. // Methods
  91. /**
  92. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  93. * @param data defines the data to store
  94. */
  95. public create(data: Nullable<DataArray> = null): void {
  96. if (!data && this._buffer) {
  97. return; // nothing to do
  98. }
  99. data = data || this._data;
  100. if (!data) {
  101. return;
  102. }
  103. if (!this._buffer) { // create buffer
  104. if (this._updatable) {
  105. this._buffer = this._engine.createDynamicVertexBuffer(data);
  106. this._data = data;
  107. } else {
  108. this._buffer = this._engine.createVertexBuffer(data);
  109. }
  110. } else if (this._updatable) { // update buffer
  111. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  112. this._data = data;
  113. }
  114. }
  115. /** @hidden */
  116. public _rebuild(): void {
  117. this._buffer = null;
  118. this.create(this._data);
  119. }
  120. /**
  121. * Update current buffer data
  122. * @param data defines the data to store
  123. */
  124. public update(data: DataArray): void {
  125. this.create(data);
  126. }
  127. /**
  128. * Updates the data directly.
  129. * @param data the new data
  130. * @param offset the new offset
  131. * @param vertexCount the vertex count (optional)
  132. * @param useBytes set to true if the offset is in bytes
  133. */
  134. public updateDirectly(data: DataArray, offset: number, vertexCount?: number, useBytes: boolean = false): void {
  135. if (!this._buffer) {
  136. return;
  137. }
  138. if (this._updatable) { // update buffer
  139. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  140. this._data = null;
  141. }
  142. }
  143. /**
  144. * Release all resources
  145. */
  146. public dispose(): void {
  147. if (!this._buffer) {
  148. return;
  149. }
  150. if (this._engine._releaseBuffer(this._buffer)) {
  151. this._buffer = null;
  152. }
  153. }
  154. }
  155. /**
  156. * Specialized buffer used to store vertex data
  157. */
  158. export class VertexBuffer {
  159. /** @hidden */
  160. public _buffer: Buffer;
  161. private _kind: string;
  162. private _size: number;
  163. private _ownsBuffer: boolean;
  164. private _instanced: boolean;
  165. private _instanceDivisor: number;
  166. /**
  167. * The byte type.
  168. */
  169. public static readonly BYTE = 5120;
  170. /**
  171. * The unsigned byte type.
  172. */
  173. public static readonly UNSIGNED_BYTE = 5121;
  174. /**
  175. * The short type.
  176. */
  177. public static readonly SHORT = 5122;
  178. /**
  179. * The unsigned short type.
  180. */
  181. public static readonly UNSIGNED_SHORT = 5123;
  182. /**
  183. * The integer type.
  184. */
  185. public static readonly INT = 5124;
  186. /**
  187. * The unsigned integer type.
  188. */
  189. public static readonly UNSIGNED_INT = 5125;
  190. /**
  191. * The float type.
  192. */
  193. public static readonly FLOAT = 5126;
  194. /**
  195. * Gets or sets the instance divisor when in instanced mode
  196. */
  197. public get instanceDivisor(): number {
  198. return this._instanceDivisor;
  199. }
  200. public set instanceDivisor(value: number) {
  201. this._instanceDivisor = value;
  202. if (value == 0) {
  203. this._instanced = false;
  204. } else {
  205. this._instanced = true;
  206. }
  207. }
  208. /**
  209. * Gets the byte stride.
  210. */
  211. public readonly byteStride: number;
  212. /**
  213. * Gets the byte offset.
  214. */
  215. public readonly byteOffset: number;
  216. /**
  217. * Gets whether integer data values should be normalized into a certain range when being casted to a float.
  218. */
  219. public readonly normalized: boolean;
  220. /**
  221. * Gets the data type of each component in the array.
  222. */
  223. public readonly type: number;
  224. /**
  225. * Constructor
  226. * @param engine the engine
  227. * @param data the data to use for this vertex buffer
  228. * @param kind the vertex buffer kind
  229. * @param updatable whether the data is updatable
  230. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  231. * @param stride the stride (optional)
  232. * @param instanced whether the buffer is instanced (optional)
  233. * @param offset the offset of the data (optional)
  234. * @param size the number of components (optional)
  235. * @param type the type of the component (optional)
  236. * @param normalized whether the data contains normalized data (optional)
  237. * @param useBytes set to true if stride and offset are in bytes (optional)
  238. */
  239. constructor(engine: any, data: DataArray | Buffer, kind: string, updatable: boolean, postponeInternalCreation?: boolean, stride?: number, instanced?: boolean, offset?: number, size?: number, type?: number, normalized = false, useBytes = false) {
  240. if (data instanceof Buffer) {
  241. this._buffer = data;
  242. this._ownsBuffer = false;
  243. } else {
  244. this._buffer = new Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  245. this._ownsBuffer = true;
  246. }
  247. this._kind = kind;
  248. if (type == undefined) {
  249. const data = this.getData();
  250. this.type = VertexBuffer.FLOAT;
  251. if (data instanceof Int8Array) { this.type = VertexBuffer.BYTE; }
  252. else if (data instanceof Uint8Array) { this.type = VertexBuffer.UNSIGNED_BYTE; }
  253. else if (data instanceof Int16Array) { this.type = VertexBuffer.SHORT; }
  254. else if (data instanceof Uint16Array) { this.type = VertexBuffer.UNSIGNED_SHORT; }
  255. else if (data instanceof Int32Array) { this.type = VertexBuffer.INT; }
  256. else if (data instanceof Uint32Array) { this.type = VertexBuffer.UNSIGNED_INT; }
  257. }
  258. else {
  259. this.type = type;
  260. }
  261. const typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  262. if (useBytes) {
  263. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  264. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  265. this.byteOffset = offset || 0;
  266. }
  267. else {
  268. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  269. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  270. this.byteOffset = (offset || 0) * typeByteLength;
  271. }
  272. this.normalized = normalized;
  273. this._instanced = instanced !== undefined ? instanced : false;
  274. this._instanceDivisor = instanced ? 1 : 0;
  275. }
  276. /** @hidden */
  277. public _rebuild(): void {
  278. if (!this._buffer) {
  279. return;
  280. }
  281. this._buffer._rebuild();
  282. }
  283. /**
  284. * Returns the kind of the VertexBuffer (string)
  285. * @returns a string
  286. */
  287. public getKind(): string {
  288. return this._kind;
  289. }
  290. // Properties
  291. /**
  292. * Gets a boolean indicating if the VertexBuffer is updatable?
  293. * @returns true if the buffer is updatable
  294. */
  295. public isUpdatable(): boolean {
  296. return this._buffer.isUpdatable();
  297. }
  298. /**
  299. * Gets current buffer's data
  300. * @returns a DataArray or null
  301. */
  302. public getData(): Nullable<DataArray> {
  303. return this._buffer.getData();
  304. }
  305. /**
  306. * Gets underlying native buffer
  307. * @returns underlying native buffer
  308. */
  309. public getBuffer(): Nullable<DataBuffer> {
  310. return this._buffer.getBuffer();
  311. }
  312. /**
  313. * Gets the stride in float32 units (i.e. byte stride / 4).
  314. * May not be an integer if the byte stride is not divisible by 4.
  315. * DEPRECATED. Use byteStride instead.
  316. * @returns the stride in float32 units
  317. */
  318. public getStrideSize(): number {
  319. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  320. }
  321. /**
  322. * Returns the offset as a multiple of the type byte length.
  323. * DEPRECATED. Use byteOffset instead.
  324. * @returns the offset in bytes
  325. */
  326. public getOffset(): number {
  327. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  328. }
  329. /**
  330. * Returns the number of components per vertex attribute (integer)
  331. * @returns the size in float
  332. */
  333. public getSize(): number {
  334. return this._size;
  335. }
  336. /**
  337. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  338. * @returns true if this buffer is instanced
  339. */
  340. public getIsInstanced(): boolean {
  341. return this._instanced;
  342. }
  343. /**
  344. * Returns the instancing divisor, zero for non-instanced (integer).
  345. * @returns a number
  346. */
  347. public getInstanceDivisor(): number {
  348. return this._instanceDivisor;
  349. }
  350. // Methods
  351. /**
  352. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  353. * @param data defines the data to store
  354. */
  355. public create(data?: DataArray): void {
  356. this._buffer.create(data);
  357. }
  358. /**
  359. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  360. * This function will create a new buffer if the current one is not updatable
  361. * @param data defines the data to store
  362. */
  363. public update(data: DataArray): void {
  364. this._buffer.update(data);
  365. }
  366. /**
  367. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  368. * Returns the directly updated WebGLBuffer.
  369. * @param data the new data
  370. * @param offset the new offset
  371. * @param useBytes set to true if the offset is in bytes
  372. */
  373. public updateDirectly(data: DataArray, offset: number, useBytes: boolean = false): void {
  374. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  375. }
  376. /**
  377. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  378. */
  379. public dispose(): void {
  380. if (this._ownsBuffer) {
  381. this._buffer.dispose();
  382. }
  383. }
  384. /**
  385. * Enumerates each value of this vertex buffer as numbers.
  386. * @param count the number of values to enumerate
  387. * @param callback the callback function called for each value
  388. */
  389. public forEach(count: number, callback: (value: number, index: number) => void): void {
  390. VertexBuffer.ForEach(this._buffer.getData()!, this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  391. }
  392. // Enums
  393. /**
  394. * Positions
  395. */
  396. public static readonly PositionKind = "position";
  397. /**
  398. * Normals
  399. */
  400. public static readonly NormalKind = "normal";
  401. /**
  402. * Tangents
  403. */
  404. public static readonly TangentKind = "tangent";
  405. /**
  406. * Texture coordinates
  407. */
  408. public static readonly UVKind = "uv";
  409. /**
  410. * Texture coordinates 2
  411. */
  412. public static readonly UV2Kind = "uv2";
  413. /**
  414. * Texture coordinates 3
  415. */
  416. public static readonly UV3Kind = "uv3";
  417. /**
  418. * Texture coordinates 4
  419. */
  420. public static readonly UV4Kind = "uv4";
  421. /**
  422. * Texture coordinates 5
  423. */
  424. public static readonly UV5Kind = "uv5";
  425. /**
  426. * Texture coordinates 6
  427. */
  428. public static readonly UV6Kind = "uv6";
  429. /**
  430. * Colors
  431. */
  432. public static readonly ColorKind = "color";
  433. /**
  434. * Matrix indices (for bones)
  435. */
  436. public static readonly MatricesIndicesKind = "matricesIndices";
  437. /**
  438. * Matrix weights (for bones)
  439. */
  440. public static readonly MatricesWeightsKind = "matricesWeights";
  441. /**
  442. * Additional matrix indices (for bones)
  443. */
  444. public static readonly MatricesIndicesExtraKind = "matricesIndicesExtra";
  445. /**
  446. * Additional matrix weights (for bones)
  447. */
  448. public static readonly MatricesWeightsExtraKind = "matricesWeightsExtra";
  449. /**
  450. * Deduces the stride given a kind.
  451. * @param kind The kind string to deduce
  452. * @returns The deduced stride
  453. */
  454. public static DeduceStride(kind: string): number {
  455. switch (kind) {
  456. case VertexBuffer.UVKind:
  457. case VertexBuffer.UV2Kind:
  458. case VertexBuffer.UV3Kind:
  459. case VertexBuffer.UV4Kind:
  460. case VertexBuffer.UV5Kind:
  461. case VertexBuffer.UV6Kind:
  462. return 2;
  463. case VertexBuffer.NormalKind:
  464. case VertexBuffer.PositionKind:
  465. return 3;
  466. case VertexBuffer.ColorKind:
  467. case VertexBuffer.MatricesIndicesKind:
  468. case VertexBuffer.MatricesIndicesExtraKind:
  469. case VertexBuffer.MatricesWeightsKind:
  470. case VertexBuffer.MatricesWeightsExtraKind:
  471. case VertexBuffer.TangentKind:
  472. return 4;
  473. default:
  474. throw new Error("Invalid kind '" + kind + "'");
  475. }
  476. }
  477. /**
  478. * Gets the byte length of the given type.
  479. * @param type the type
  480. * @returns the number of bytes
  481. */
  482. public static GetTypeByteLength(type: number): number {
  483. switch (type) {
  484. case VertexBuffer.BYTE:
  485. case VertexBuffer.UNSIGNED_BYTE:
  486. return 1;
  487. case VertexBuffer.SHORT:
  488. case VertexBuffer.UNSIGNED_SHORT:
  489. return 2;
  490. case VertexBuffer.INT:
  491. case VertexBuffer.UNSIGNED_INT:
  492. case VertexBuffer.FLOAT:
  493. return 4;
  494. default:
  495. throw new Error(`Invalid type '${type}'`);
  496. }
  497. }
  498. /**
  499. * Enumerates each value of the given parameters as numbers.
  500. * @param data the data to enumerate
  501. * @param byteOffset the byte offset of the data
  502. * @param byteStride the byte stride of the data
  503. * @param componentCount the number of components per element
  504. * @param componentType the type of the component
  505. * @param count the number of values to enumerate
  506. * @param normalized whether the data is normalized
  507. * @param callback the callback function called for each value
  508. */
  509. public static ForEach(data: DataArray, byteOffset: number, byteStride: number, componentCount: number, componentType: number, count: number, normalized: boolean, callback: (value: number, index: number) => void): void {
  510. if (data instanceof Array) {
  511. let offset = byteOffset / 4;
  512. const stride = byteStride / 4;
  513. for (let index = 0; index < count; index += componentCount) {
  514. for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  515. callback(data[offset + componentIndex], index + componentIndex);
  516. }
  517. offset += stride;
  518. }
  519. }
  520. else {
  521. const dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  522. const componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  523. for (let index = 0; index < count; index += componentCount) {
  524. let componentByteOffset = byteOffset;
  525. for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  526. const value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  527. callback(value, index + componentIndex);
  528. componentByteOffset += componentByteLength;
  529. }
  530. byteOffset += byteStride;
  531. }
  532. }
  533. }
  534. private static _GetFloatValue(dataView: DataView, type: number, byteOffset: number, normalized: boolean): number {
  535. switch (type) {
  536. case VertexBuffer.BYTE: {
  537. let value = dataView.getInt8(byteOffset);
  538. if (normalized) {
  539. value = Math.max(value / 127, -1);
  540. }
  541. return value;
  542. }
  543. case VertexBuffer.UNSIGNED_BYTE: {
  544. let value = dataView.getUint8(byteOffset);
  545. if (normalized) {
  546. value = value / 255;
  547. }
  548. return value;
  549. }
  550. case VertexBuffer.SHORT: {
  551. let value = dataView.getInt16(byteOffset, true);
  552. if (normalized) {
  553. value = Math.max(value / 32767, -1);
  554. }
  555. return value;
  556. }
  557. case VertexBuffer.UNSIGNED_SHORT: {
  558. let value = dataView.getUint16(byteOffset, true);
  559. if (normalized) {
  560. value = value / 65535;
  561. }
  562. return value;
  563. }
  564. case VertexBuffer.INT: {
  565. return dataView.getInt32(byteOffset, true);
  566. }
  567. case VertexBuffer.UNSIGNED_INT: {
  568. return dataView.getUint32(byteOffset, true);
  569. }
  570. case VertexBuffer.FLOAT: {
  571. return dataView.getFloat32(byteOffset, true);
  572. }
  573. default: {
  574. throw new Error(`Invalid component type ${type}`);
  575. }
  576. }
  577. }
  578. }