Browse Source

GLTExporter: implement 4-byte data alignment for buffer

This change ensures the allocated buffer size is aligned to the next 4-byte boundary. See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment 

There may also be other allocated buffers (glb output?) that require 4-byte alignment, but this fixes validation of the exported file for me. 

This change is cribbed from getBufferPadded.js of obj2gltf but is modified for this use case.
Christopher Cook 7 years ago
parent
commit
20df8d4530
1 changed files with 25 additions and 0 deletions
  1. 25 0
      examples/js/exporters/GLTFExporter.js

+ 25 - 0
examples/js/exporters/GLTFExporter.js

@@ -180,6 +180,27 @@ THREE.GLTFExporter.prototype = {
 
 
 		}
 		}
 
 
+		/**
+		 * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
+		 * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
+		 *
+		 * @param {Integer} bufferSize The size the original buffer.
+		 * @returns {Integer} new buffer size with required padding.
+		 *
+		 */
+		function getPaddedBufferSize( bufferSize ) {
+			
+			// adapted from https://github.com/AnalyticalGraphicsInc/obj2gltf/blob/master/lib/getBufferPadded.js
+
+			var boundary = 4;
+
+			var remainder = bufferSize % boundary;
+			
+			var padding =  (remainder === 0 ) ? 0 : boundary - remainder;
+
+			return bufferSize + padding;
+		}
+		
 		/**
 		/**
 		 * Process a buffer to append to the default one.
 		 * Process a buffer to append to the default one.
 		 * @param  {THREE.BufferAttribute} attribute     Attribute to store
 		 * @param  {THREE.BufferAttribute} attribute     Attribute to store
@@ -208,6 +229,10 @@ THREE.GLTFExporter.prototype = {
 
 
 			// Create a new dataview and dump the attribute's array into it
 			// Create a new dataview and dump the attribute's array into it
 			var byteLength = count * attribute.itemSize * componentSize;
 			var byteLength = count * attribute.itemSize * componentSize;
+			
+			// adjust required size of array buffer with padding 
+			// to satisfy gltf requirement that the length is divisible by 4
+			byteLength = getPaddedBufferSize( byteLength );
 
 
 			var dataView = new DataView( new ArrayBuffer( byteLength ) );
 			var dataView = new DataView( new ArrayBuffer( byteLength ) );