VertexArray.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. import Check from "../Core/Check.js";
  2. import ComponentDatatype from "../Core/ComponentDatatype.js";
  3. import defaultValue from "../Core/defaultValue.js";
  4. import defined from "../Core/defined.js";
  5. import destroyObject from "../Core/destroyObject.js";
  6. import DeveloperError from "../Core/DeveloperError.js";
  7. import Geometry from "../Core/Geometry.js";
  8. import IndexDatatype from "../Core/IndexDatatype.js";
  9. import CesiumMath from "../Core/Math.js";
  10. import RuntimeError from "../Core/RuntimeError.js";
  11. import Buffer from "./Buffer.js";
  12. import BufferUsage from "./BufferUsage.js";
  13. import ContextLimits from "./ContextLimits.js";
  14. function addAttribute(attributes, attribute, index, context) {
  15. var hasVertexBuffer = defined(attribute.vertexBuffer);
  16. var hasValue = defined(attribute.value);
  17. var componentsPerAttribute = attribute.value
  18. ? attribute.value.length
  19. : attribute.componentsPerAttribute;
  20. //>>includeStart('debug', pragmas.debug);
  21. if (!hasVertexBuffer && !hasValue) {
  22. throw new DeveloperError("attribute must have a vertexBuffer or a value.");
  23. }
  24. if (hasVertexBuffer && hasValue) {
  25. throw new DeveloperError(
  26. "attribute cannot have both a vertexBuffer and a value. It must have either a vertexBuffer property defining per-vertex data or a value property defining data for all vertices."
  27. );
  28. }
  29. if (
  30. componentsPerAttribute !== 1 &&
  31. componentsPerAttribute !== 2 &&
  32. componentsPerAttribute !== 3 &&
  33. componentsPerAttribute !== 4
  34. ) {
  35. if (hasValue) {
  36. throw new DeveloperError(
  37. "attribute.value.length must be in the range [1, 4]."
  38. );
  39. }
  40. throw new DeveloperError(
  41. "attribute.componentsPerAttribute must be in the range [1, 4]."
  42. );
  43. }
  44. if (
  45. defined(attribute.componentDatatype) &&
  46. !ComponentDatatype.validate(attribute.componentDatatype)
  47. ) {
  48. throw new DeveloperError(
  49. "attribute must have a valid componentDatatype or not specify it."
  50. );
  51. }
  52. if (defined(attribute.strideInBytes) && attribute.strideInBytes > 255) {
  53. // WebGL limit. Not in GL ES.
  54. throw new DeveloperError(
  55. "attribute must have a strideInBytes less than or equal to 255 or not specify it."
  56. );
  57. }
  58. if (
  59. defined(attribute.instanceDivisor) &&
  60. attribute.instanceDivisor > 0 &&
  61. !context.instancedArrays
  62. ) {
  63. throw new DeveloperError("instanced arrays is not supported");
  64. }
  65. if (defined(attribute.instanceDivisor) && attribute.instanceDivisor < 0) {
  66. throw new DeveloperError(
  67. "attribute must have an instanceDivisor greater than or equal to zero"
  68. );
  69. }
  70. if (defined(attribute.instanceDivisor) && hasValue) {
  71. throw new DeveloperError(
  72. "attribute cannot have have an instanceDivisor if it is not backed by a buffer"
  73. );
  74. }
  75. if (
  76. defined(attribute.instanceDivisor) &&
  77. attribute.instanceDivisor > 0 &&
  78. attribute.index === 0
  79. ) {
  80. throw new DeveloperError(
  81. "attribute zero cannot have an instanceDivisor greater than 0"
  82. );
  83. }
  84. //>>includeEnd('debug');
  85. // Shallow copy the attribute; we do not want to copy the vertex buffer.
  86. var attr = {
  87. index: defaultValue(attribute.index, index),
  88. enabled: defaultValue(attribute.enabled, true),
  89. vertexBuffer: attribute.vertexBuffer,
  90. value: hasValue ? attribute.value.slice(0) : undefined,
  91. componentsPerAttribute: componentsPerAttribute,
  92. componentDatatype: defaultValue(
  93. attribute.componentDatatype,
  94. ComponentDatatype.FLOAT
  95. ),
  96. normalize: defaultValue(attribute.normalize, false),
  97. offsetInBytes: defaultValue(attribute.offsetInBytes, 0),
  98. strideInBytes: defaultValue(attribute.strideInBytes, 0),
  99. instanceDivisor: defaultValue(attribute.instanceDivisor, 0),
  100. };
  101. if (hasVertexBuffer) {
  102. // Common case: vertex buffer for per-vertex data
  103. attr.vertexAttrib = function (gl) {
  104. var index = this.index;
  105. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer._getBuffer());
  106. gl.vertexAttribPointer(
  107. index,
  108. this.componentsPerAttribute,
  109. this.componentDatatype,
  110. this.normalize,
  111. this.strideInBytes,
  112. this.offsetInBytes
  113. );
  114. gl.enableVertexAttribArray(index);
  115. if (this.instanceDivisor > 0) {
  116. context.glVertexAttribDivisor(index, this.instanceDivisor);
  117. context._vertexAttribDivisors[index] = this.instanceDivisor;
  118. context._previousDrawInstanced = true;
  119. }
  120. };
  121. attr.disableVertexAttribArray = function (gl) {
  122. gl.disableVertexAttribArray(this.index);
  123. if (this.instanceDivisor > 0) {
  124. context.glVertexAttribDivisor(index, 0);
  125. }
  126. };
  127. } else {
  128. // Less common case: value array for the same data for each vertex
  129. switch (attr.componentsPerAttribute) {
  130. case 1:
  131. attr.vertexAttrib = function (gl) {
  132. gl.vertexAttrib1fv(this.index, this.value);
  133. };
  134. break;
  135. case 2:
  136. attr.vertexAttrib = function (gl) {
  137. gl.vertexAttrib2fv(this.index, this.value);
  138. };
  139. break;
  140. case 3:
  141. attr.vertexAttrib = function (gl) {
  142. gl.vertexAttrib3fv(this.index, this.value);
  143. };
  144. break;
  145. case 4:
  146. attr.vertexAttrib = function (gl) {
  147. gl.vertexAttrib4fv(this.index, this.value);
  148. };
  149. break;
  150. }
  151. attr.disableVertexAttribArray = function (gl) {};
  152. }
  153. attributes.push(attr);
  154. }
  155. function bind(gl, attributes, indexBuffer) {
  156. for (var i = 0; i < attributes.length; ++i) {
  157. var attribute = attributes[i];
  158. if (attribute.enabled) {
  159. attribute.vertexAttrib(gl);
  160. }
  161. }
  162. if (defined(indexBuffer)) {
  163. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer._getBuffer());
  164. }
  165. }
  166. /**
  167. * Creates a vertex array, which defines the attributes making up a vertex, and contains an optional index buffer
  168. * to select vertices for rendering. Attributes are defined using object literals as shown in Example 1 below.
  169. *
  170. * @param {Object} options Object with the following properties:
  171. * @param {Context} options.context The context in which the VertexArray gets created.
  172. * @param {Object[]} options.attributes An array of attributes.
  173. * @param {IndexBuffer} [options.indexBuffer] An optional index buffer.
  174. *
  175. * @returns {VertexArray} The vertex array, ready for use with drawing.
  176. *
  177. * @exception {DeveloperError} Attribute must have a <code>vertexBuffer</code>.
  178. * @exception {DeveloperError} Attribute must have a <code>componentsPerAttribute</code>.
  179. * @exception {DeveloperError} Attribute must have a valid <code>componentDatatype</code> or not specify it.
  180. * @exception {DeveloperError} Attribute must have a <code>strideInBytes</code> less than or equal to 255 or not specify it.
  181. * @exception {DeveloperError} Index n is used by more than one attribute.
  182. *
  183. *
  184. * @example
  185. * // Example 1. Create a vertex array with vertices made up of three floating point
  186. * // values, e.g., a position, from a single vertex buffer. No index buffer is used.
  187. * var positionBuffer = Buffer.createVertexBuffer({
  188. * context : context,
  189. * sizeInBytes : 12,
  190. * usage : BufferUsage.STATIC_DRAW
  191. * });
  192. * var attributes = [
  193. * {
  194. * index : 0,
  195. * enabled : true,
  196. * vertexBuffer : positionBuffer,
  197. * componentsPerAttribute : 3,
  198. * componentDatatype : ComponentDatatype.FLOAT,
  199. * normalize : false,
  200. * offsetInBytes : 0,
  201. * strideInBytes : 0 // tightly packed
  202. * instanceDivisor : 0 // not instanced
  203. * }
  204. * ];
  205. * var va = new VertexArray({
  206. * context : context,
  207. * attributes : attributes
  208. * });
  209. *
  210. * @example
  211. * // Example 2. Create a vertex array with vertices from two different vertex buffers.
  212. * // Each vertex has a three-component position and three-component normal.
  213. * var positionBuffer = Buffer.createVertexBuffer({
  214. * context : context,
  215. * sizeInBytes : 12,
  216. * usage : BufferUsage.STATIC_DRAW
  217. * });
  218. * var normalBuffer = Buffer.createVertexBuffer({
  219. * context : context,
  220. * sizeInBytes : 12,
  221. * usage : BufferUsage.STATIC_DRAW
  222. * });
  223. * var attributes = [
  224. * {
  225. * index : 0,
  226. * vertexBuffer : positionBuffer,
  227. * componentsPerAttribute : 3,
  228. * componentDatatype : ComponentDatatype.FLOAT
  229. * },
  230. * {
  231. * index : 1,
  232. * vertexBuffer : normalBuffer,
  233. * componentsPerAttribute : 3,
  234. * componentDatatype : ComponentDatatype.FLOAT
  235. * }
  236. * ];
  237. * var va = new VertexArray({
  238. * context : context,
  239. * attributes : attributes
  240. * });
  241. *
  242. * @example
  243. * // Example 3. Creates the same vertex layout as Example 2 using a single
  244. * // vertex buffer, instead of two.
  245. * var buffer = Buffer.createVertexBuffer({
  246. * context : context,
  247. * sizeInBytes : 24,
  248. * usage : BufferUsage.STATIC_DRAW
  249. * });
  250. * var attributes = [
  251. * {
  252. * vertexBuffer : buffer,
  253. * componentsPerAttribute : 3,
  254. * componentDatatype : ComponentDatatype.FLOAT,
  255. * offsetInBytes : 0,
  256. * strideInBytes : 24
  257. * },
  258. * {
  259. * vertexBuffer : buffer,
  260. * componentsPerAttribute : 3,
  261. * componentDatatype : ComponentDatatype.FLOAT,
  262. * normalize : true,
  263. * offsetInBytes : 12,
  264. * strideInBytes : 24
  265. * }
  266. * ];
  267. * var va = new VertexArray({
  268. * context : context,
  269. * attributes : attributes
  270. * });
  271. *
  272. * @see Buffer#createVertexBuffer
  273. * @see Buffer#createIndexBuffer
  274. * @see Context#draw
  275. *
  276. * @private
  277. */
  278. function VertexArray(options) {
  279. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  280. //>>includeStart('debug', pragmas.debug);
  281. Check.defined("options.context", options.context);
  282. Check.defined("options.attributes", options.attributes);
  283. //>>includeEnd('debug');
  284. var context = options.context;
  285. var gl = context._gl;
  286. var attributes = options.attributes;
  287. var indexBuffer = options.indexBuffer;
  288. var i;
  289. var vaAttributes = [];
  290. var numberOfVertices = 1; // if every attribute is backed by a single value
  291. var hasInstancedAttributes = false;
  292. var hasConstantAttributes = false;
  293. var length = attributes.length;
  294. for (i = 0; i < length; ++i) {
  295. addAttribute(vaAttributes, attributes[i], i, context);
  296. }
  297. length = vaAttributes.length;
  298. for (i = 0; i < length; ++i) {
  299. var attribute = vaAttributes[i];
  300. if (defined(attribute.vertexBuffer) && attribute.instanceDivisor === 0) {
  301. // This assumes that each vertex buffer in the vertex array has the same number of vertices.
  302. var bytes =
  303. attribute.strideInBytes ||
  304. attribute.componentsPerAttribute *
  305. ComponentDatatype.getSizeInBytes(attribute.componentDatatype);
  306. numberOfVertices = attribute.vertexBuffer.sizeInBytes / bytes;
  307. break;
  308. }
  309. }
  310. for (i = 0; i < length; ++i) {
  311. if (vaAttributes[i].instanceDivisor > 0) {
  312. hasInstancedAttributes = true;
  313. }
  314. if (defined(vaAttributes[i].value)) {
  315. hasConstantAttributes = true;
  316. }
  317. }
  318. //>>includeStart('debug', pragmas.debug);
  319. // Verify all attribute names are unique
  320. var uniqueIndices = {};
  321. for (i = 0; i < length; ++i) {
  322. var index = vaAttributes[i].index;
  323. if (uniqueIndices[index]) {
  324. throw new DeveloperError(
  325. "Index " + index + " is used by more than one attribute."
  326. );
  327. }
  328. uniqueIndices[index] = true;
  329. }
  330. //>>includeEnd('debug');
  331. var vao;
  332. // Setup VAO if supported
  333. if (context.vertexArrayObject) {
  334. vao = context.glCreateVertexArray();
  335. context.glBindVertexArray(vao);
  336. bind(gl, vaAttributes, indexBuffer);
  337. context.glBindVertexArray(null);
  338. }
  339. this._numberOfVertices = numberOfVertices;
  340. this._hasInstancedAttributes = hasInstancedAttributes;
  341. this._hasConstantAttributes = hasConstantAttributes;
  342. this._context = context;
  343. this._gl = gl;
  344. this._vao = vao;
  345. this._attributes = vaAttributes;
  346. this._indexBuffer = indexBuffer;
  347. }
  348. function computeNumberOfVertices(attribute) {
  349. return attribute.values.length / attribute.componentsPerAttribute;
  350. }
  351. function computeAttributeSizeInBytes(attribute) {
  352. return (
  353. ComponentDatatype.getSizeInBytes(attribute.componentDatatype) *
  354. attribute.componentsPerAttribute
  355. );
  356. }
  357. function interleaveAttributes(attributes) {
  358. var j;
  359. var name;
  360. var attribute;
  361. // Extract attribute names.
  362. var names = [];
  363. for (name in attributes) {
  364. // Attribute needs to have per-vertex values; not a constant value for all vertices.
  365. if (
  366. attributes.hasOwnProperty(name) &&
  367. defined(attributes[name]) &&
  368. defined(attributes[name].values)
  369. ) {
  370. names.push(name);
  371. if (attributes[name].componentDatatype === ComponentDatatype.DOUBLE) {
  372. attributes[name].componentDatatype = ComponentDatatype.FLOAT;
  373. attributes[name].values = ComponentDatatype.createTypedArray(
  374. ComponentDatatype.FLOAT,
  375. attributes[name].values
  376. );
  377. }
  378. }
  379. }
  380. // Validation. Compute number of vertices.
  381. var numberOfVertices;
  382. var namesLength = names.length;
  383. if (namesLength > 0) {
  384. numberOfVertices = computeNumberOfVertices(attributes[names[0]]);
  385. for (j = 1; j < namesLength; ++j) {
  386. var currentNumberOfVertices = computeNumberOfVertices(
  387. attributes[names[j]]
  388. );
  389. if (currentNumberOfVertices !== numberOfVertices) {
  390. throw new RuntimeError(
  391. "Each attribute list must have the same number of vertices. " +
  392. "Attribute " +
  393. names[j] +
  394. " has a different number of vertices " +
  395. "(" +
  396. currentNumberOfVertices.toString() +
  397. ")" +
  398. " than attribute " +
  399. names[0] +
  400. " (" +
  401. numberOfVertices.toString() +
  402. ")."
  403. );
  404. }
  405. }
  406. }
  407. // Sort attributes by the size of their components. From left to right, a vertex stores floats, shorts, and then bytes.
  408. names.sort(function (left, right) {
  409. return (
  410. ComponentDatatype.getSizeInBytes(attributes[right].componentDatatype) -
  411. ComponentDatatype.getSizeInBytes(attributes[left].componentDatatype)
  412. );
  413. });
  414. // Compute sizes and strides.
  415. var vertexSizeInBytes = 0;
  416. var offsetsInBytes = {};
  417. for (j = 0; j < namesLength; ++j) {
  418. name = names[j];
  419. attribute = attributes[name];
  420. offsetsInBytes[name] = vertexSizeInBytes;
  421. vertexSizeInBytes += computeAttributeSizeInBytes(attribute);
  422. }
  423. if (vertexSizeInBytes > 0) {
  424. // Pad each vertex to be a multiple of the largest component datatype so each
  425. // attribute can be addressed using typed arrays.
  426. var maxComponentSizeInBytes = ComponentDatatype.getSizeInBytes(
  427. attributes[names[0]].componentDatatype
  428. ); // Sorted large to small
  429. var remainder = vertexSizeInBytes % maxComponentSizeInBytes;
  430. if (remainder !== 0) {
  431. vertexSizeInBytes += maxComponentSizeInBytes - remainder;
  432. }
  433. // Total vertex buffer size in bytes, including per-vertex padding.
  434. var vertexBufferSizeInBytes = numberOfVertices * vertexSizeInBytes;
  435. // Create array for interleaved vertices. Each attribute has a different view (pointer) into the array.
  436. var buffer = new ArrayBuffer(vertexBufferSizeInBytes);
  437. var views = {};
  438. for (j = 0; j < namesLength; ++j) {
  439. name = names[j];
  440. var sizeInBytes = ComponentDatatype.getSizeInBytes(
  441. attributes[name].componentDatatype
  442. );
  443. views[name] = {
  444. pointer: ComponentDatatype.createTypedArray(
  445. attributes[name].componentDatatype,
  446. buffer
  447. ),
  448. index: offsetsInBytes[name] / sizeInBytes, // Offset in ComponentType
  449. strideInComponentType: vertexSizeInBytes / sizeInBytes,
  450. };
  451. }
  452. // Copy attributes into one interleaved array.
  453. // PERFORMANCE_IDEA: Can we optimize these loops?
  454. for (j = 0; j < numberOfVertices; ++j) {
  455. for (var n = 0; n < namesLength; ++n) {
  456. name = names[n];
  457. attribute = attributes[name];
  458. var values = attribute.values;
  459. var view = views[name];
  460. var pointer = view.pointer;
  461. var numberOfComponents = attribute.componentsPerAttribute;
  462. for (var k = 0; k < numberOfComponents; ++k) {
  463. pointer[view.index + k] = values[j * numberOfComponents + k];
  464. }
  465. view.index += view.strideInComponentType;
  466. }
  467. }
  468. return {
  469. buffer: buffer,
  470. offsetsInBytes: offsetsInBytes,
  471. vertexSizeInBytes: vertexSizeInBytes,
  472. };
  473. }
  474. // No attributes to interleave.
  475. return undefined;
  476. }
  477. /**
  478. * Creates a vertex array from a geometry. A geometry contains vertex attributes and optional index data
  479. * in system memory, whereas a vertex array contains vertex buffers and an optional index buffer in WebGL
  480. * memory for use with rendering.
  481. * <br /><br />
  482. * The <code>geometry</code> argument should use the standard layout like the geometry returned by {@link BoxGeometry}.
  483. * <br /><br />
  484. * <code>options</code> can have four properties:
  485. * <ul>
  486. * <li><code>geometry</code>: The source geometry containing data used to create the vertex array.</li>
  487. * <li><code>attributeLocations</code>: An object that maps geometry attribute names to vertex shader attribute locations.</li>
  488. * <li><code>bufferUsage</code>: The expected usage pattern of the vertex array's buffers. On some WebGL implementations, this can significantly affect performance. See {@link BufferUsage}. Default: <code>BufferUsage.DYNAMIC_DRAW</code>.</li>
  489. * <li><code>interleave</code>: Determines if all attributes are interleaved in a single vertex buffer or if each attribute is stored in a separate vertex buffer. Default: <code>false</code>.</li>
  490. * </ul>
  491. * <br />
  492. * If <code>options</code> is not specified or the <code>geometry</code> contains no data, the returned vertex array is empty.
  493. *
  494. * @param {Object} options An object defining the geometry, attribute indices, buffer usage, and vertex layout used to create the vertex array.
  495. *
  496. * @exception {RuntimeError} Each attribute list must have the same number of vertices.
  497. * @exception {DeveloperError} The geometry must have zero or one index lists.
  498. * @exception {DeveloperError} Index n is used by more than one attribute.
  499. *
  500. *
  501. * @example
  502. * // Example 1. Creates a vertex array for rendering a box. The default dynamic draw
  503. * // usage is used for the created vertex and index buffer. The attributes are not
  504. * // interleaved by default.
  505. * var geometry = new BoxGeometry();
  506. * var va = VertexArray.fromGeometry({
  507. * context : context,
  508. * geometry : geometry,
  509. * attributeLocations : GeometryPipeline.createAttributeLocations(geometry),
  510. * });
  511. *
  512. * @example
  513. * // Example 2. Creates a vertex array with interleaved attributes in a
  514. * // single vertex buffer. The vertex and index buffer have static draw usage.
  515. * var va = VertexArray.fromGeometry({
  516. * context : context,
  517. * geometry : geometry,
  518. * attributeLocations : GeometryPipeline.createAttributeLocations(geometry),
  519. * bufferUsage : BufferUsage.STATIC_DRAW,
  520. * interleave : true
  521. * });
  522. *
  523. * @example
  524. * // Example 3. When the caller destroys the vertex array, it also destroys the
  525. * // attached vertex buffer(s) and index buffer.
  526. * va = va.destroy();
  527. *
  528. * @see Buffer#createVertexBuffer
  529. * @see Buffer#createIndexBuffer
  530. * @see GeometryPipeline.createAttributeLocations
  531. * @see ShaderProgram
  532. */
  533. VertexArray.fromGeometry = function (options) {
  534. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  535. //>>includeStart('debug', pragmas.debug);
  536. Check.defined("options.context", options.context);
  537. //>>includeEnd('debug');
  538. var context = options.context;
  539. var geometry = defaultValue(options.geometry, defaultValue.EMPTY_OBJECT);
  540. var bufferUsage = defaultValue(options.bufferUsage, BufferUsage.DYNAMIC_DRAW);
  541. var attributeLocations = defaultValue(
  542. options.attributeLocations,
  543. defaultValue.EMPTY_OBJECT
  544. );
  545. var interleave = defaultValue(options.interleave, false);
  546. var createdVAAttributes = options.vertexArrayAttributes;
  547. var name;
  548. var attribute;
  549. var vertexBuffer;
  550. var vaAttributes = defined(createdVAAttributes) ? createdVAAttributes : [];
  551. var attributes = geometry.attributes;
  552. if (interleave) {
  553. // Use a single vertex buffer with interleaved vertices.
  554. var interleavedAttributes = interleaveAttributes(attributes);
  555. if (defined(interleavedAttributes)) {
  556. vertexBuffer = Buffer.createVertexBuffer({
  557. context: context,
  558. typedArray: interleavedAttributes.buffer,
  559. usage: bufferUsage,
  560. });
  561. var offsetsInBytes = interleavedAttributes.offsetsInBytes;
  562. var strideInBytes = interleavedAttributes.vertexSizeInBytes;
  563. for (name in attributes) {
  564. if (attributes.hasOwnProperty(name) && defined(attributes[name])) {
  565. attribute = attributes[name];
  566. if (defined(attribute.values)) {
  567. // Common case: per-vertex attributes
  568. vaAttributes.push({
  569. index: attributeLocations[name],
  570. vertexBuffer: vertexBuffer,
  571. componentDatatype: attribute.componentDatatype,
  572. componentsPerAttribute: attribute.componentsPerAttribute,
  573. normalize: attribute.normalize,
  574. offsetInBytes: offsetsInBytes[name],
  575. strideInBytes: strideInBytes,
  576. });
  577. } else {
  578. // Constant attribute for all vertices
  579. vaAttributes.push({
  580. index: attributeLocations[name],
  581. value: attribute.value,
  582. componentDatatype: attribute.componentDatatype,
  583. normalize: attribute.normalize,
  584. });
  585. }
  586. }
  587. }
  588. }
  589. } else {
  590. // One vertex buffer per attribute.
  591. for (name in attributes) {
  592. if (attributes.hasOwnProperty(name) && defined(attributes[name])) {
  593. attribute = attributes[name];
  594. var componentDatatype = attribute.componentDatatype;
  595. if (componentDatatype === ComponentDatatype.DOUBLE) {
  596. componentDatatype = ComponentDatatype.FLOAT;
  597. }
  598. vertexBuffer = undefined;
  599. if (defined(attribute.values)) {
  600. vertexBuffer = Buffer.createVertexBuffer({
  601. context: context,
  602. typedArray: ComponentDatatype.createTypedArray(
  603. componentDatatype,
  604. attribute.values
  605. ),
  606. usage: bufferUsage,
  607. });
  608. }
  609. vaAttributes.push({
  610. index: attributeLocations[name],
  611. vertexBuffer: vertexBuffer,
  612. value: attribute.value,
  613. componentDatatype: componentDatatype,
  614. componentsPerAttribute: attribute.componentsPerAttribute,
  615. normalize: attribute.normalize,
  616. });
  617. }
  618. }
  619. }
  620. var indexBuffer;
  621. var indices = geometry.indices;
  622. if (defined(indices)) {
  623. if (
  624. Geometry.computeNumberOfVertices(geometry) >=
  625. CesiumMath.SIXTY_FOUR_KILOBYTES &&
  626. context.elementIndexUint
  627. ) {
  628. indexBuffer = Buffer.createIndexBuffer({
  629. context: context,
  630. typedArray: new Uint32Array(indices),
  631. usage: bufferUsage,
  632. indexDatatype: IndexDatatype.UNSIGNED_INT,
  633. });
  634. } else {
  635. indexBuffer = Buffer.createIndexBuffer({
  636. context: context,
  637. typedArray: new Uint16Array(indices),
  638. usage: bufferUsage,
  639. indexDatatype: IndexDatatype.UNSIGNED_SHORT,
  640. });
  641. }
  642. }
  643. return new VertexArray({
  644. context: context,
  645. attributes: vaAttributes,
  646. indexBuffer: indexBuffer,
  647. });
  648. };
  649. Object.defineProperties(VertexArray.prototype, {
  650. numberOfAttributes: {
  651. get: function () {
  652. return this._attributes.length;
  653. },
  654. },
  655. numberOfVertices: {
  656. get: function () {
  657. return this._numberOfVertices;
  658. },
  659. },
  660. indexBuffer: {
  661. get: function () {
  662. return this._indexBuffer;
  663. },
  664. },
  665. });
  666. /**
  667. * index is the location in the array of attributes, not the index property of an attribute.
  668. */
  669. VertexArray.prototype.getAttribute = function (index) {
  670. //>>includeStart('debug', pragmas.debug);
  671. Check.defined("index", index);
  672. //>>includeEnd('debug');
  673. return this._attributes[index];
  674. };
  675. // Workaround for ANGLE, where the attribute divisor seems to be part of the global state instead
  676. // of the VAO state. This function is called when the vao is bound, and should be removed
  677. // once the ANGLE issue is resolved. Setting the divisor should normally happen in vertexAttrib and
  678. // disableVertexAttribArray.
  679. function setVertexAttribDivisor(vertexArray) {
  680. var context = vertexArray._context;
  681. var hasInstancedAttributes = vertexArray._hasInstancedAttributes;
  682. if (!hasInstancedAttributes && !context._previousDrawInstanced) {
  683. return;
  684. }
  685. context._previousDrawInstanced = hasInstancedAttributes;
  686. var divisors = context._vertexAttribDivisors;
  687. var attributes = vertexArray._attributes;
  688. var maxAttributes = ContextLimits.maximumVertexAttributes;
  689. var i;
  690. if (hasInstancedAttributes) {
  691. var length = attributes.length;
  692. for (i = 0; i < length; ++i) {
  693. var attribute = attributes[i];
  694. if (attribute.enabled) {
  695. var divisor = attribute.instanceDivisor;
  696. var index = attribute.index;
  697. if (divisor !== divisors[index]) {
  698. context.glVertexAttribDivisor(index, divisor);
  699. divisors[index] = divisor;
  700. }
  701. }
  702. }
  703. } else {
  704. for (i = 0; i < maxAttributes; ++i) {
  705. if (divisors[i] > 0) {
  706. context.glVertexAttribDivisor(i, 0);
  707. divisors[i] = 0;
  708. }
  709. }
  710. }
  711. }
  712. // Vertex attributes backed by a constant value go through vertexAttrib[1234]f[v]
  713. // which is part of context state rather than VAO state.
  714. function setConstantAttributes(vertexArray, gl) {
  715. var attributes = vertexArray._attributes;
  716. var length = attributes.length;
  717. for (var i = 0; i < length; ++i) {
  718. var attribute = attributes[i];
  719. if (attribute.enabled && defined(attribute.value)) {
  720. attribute.vertexAttrib(gl);
  721. }
  722. }
  723. }
  724. VertexArray.prototype._bind = function () {
  725. if (defined(this._vao)) {
  726. this._context.glBindVertexArray(this._vao);
  727. if (this._context.instancedArrays) {
  728. setVertexAttribDivisor(this);
  729. }
  730. if (this._hasConstantAttributes) {
  731. setConstantAttributes(this, this._gl);
  732. }
  733. } else {
  734. bind(this._gl, this._attributes, this._indexBuffer);
  735. }
  736. };
  737. VertexArray.prototype._unBind = function () {
  738. if (defined(this._vao)) {
  739. this._context.glBindVertexArray(null);
  740. } else {
  741. var attributes = this._attributes;
  742. var gl = this._gl;
  743. for (var i = 0; i < attributes.length; ++i) {
  744. var attribute = attributes[i];
  745. if (attribute.enabled) {
  746. attribute.disableVertexAttribArray(gl);
  747. }
  748. }
  749. if (this._indexBuffer) {
  750. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
  751. }
  752. }
  753. };
  754. VertexArray.prototype.isDestroyed = function () {
  755. return false;
  756. };
  757. VertexArray.prototype.destroy = function () {
  758. var attributes = this._attributes;
  759. for (var i = 0; i < attributes.length; ++i) {
  760. var vertexBuffer = attributes[i].vertexBuffer;
  761. if (
  762. defined(vertexBuffer) &&
  763. !vertexBuffer.isDestroyed() &&
  764. vertexBuffer.vertexArrayDestroyable
  765. ) {
  766. vertexBuffer.destroy();
  767. }
  768. }
  769. var indexBuffer = this._indexBuffer;
  770. if (
  771. defined(indexBuffer) &&
  772. !indexBuffer.isDestroyed() &&
  773. indexBuffer.vertexArrayDestroyable
  774. ) {
  775. indexBuffer.destroy();
  776. }
  777. if (defined(this._vao)) {
  778. this._context.glDeleteVertexArray(this._vao);
  779. }
  780. return destroyObject(this);
  781. };
  782. export default VertexArray;