buffer.ts 22 KB

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