Просмотр исходного кода

TSL: Ensure 4 byte alignment for `instancedArray()` and `attributeArray()` (#31146)

* fix ensure 4 byte alignment

* cleanup
sunag 7 месяцев назад
Родитель
Сommit
efcca9afd2

+ 17 - 0
src/extras/DataUtils.js

@@ -207,6 +207,23 @@ class DataUtils {
 
 	}
 
+	/**
+	 * Aligns a given byte length to the nearest 4-byte boundary.
+	 *
+	 * This function ensures that the returned byte length is a multiple of 4,
+	 * which is often required for memory alignment in certain systems or formats.
+	 *
+	 * @param {number} byteLength - The original byte length to align.
+	 * @returns {number} The aligned byte length, which is a multiple of 4.
+	 */
+	static alignTo4ByteBoundary( byteLength ) {
+
+		// ensure 4 byte alignment, see #20441
+
+		return byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
+
+	}
+
 }
 
 export {

+ 3 - 2
src/nodes/accessors/Arrays.js

@@ -2,6 +2,7 @@ import StorageInstancedBufferAttribute from '../../renderers/common/StorageInsta
 import StorageBufferAttribute from '../../renderers/common/StorageBufferAttribute.js';
 import { storage } from './StorageBufferNode.js';
 import { getLengthFromType, getTypedArrayFromType } from '../core/NodeUtils.js';
+import { DataUtils } from '../../extras/DataUtils.js';
 
 /**
  * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
@@ -18,7 +19,7 @@ export const attributeArray = ( count, type = 'float' ) => {
 
 	if ( type.isStruct === true ) {
 
-		itemSize = type.layout.getLength();
+		itemSize = DataUtils.alignTo4ByteBoundary( type.layout.getLength() );
 		typedArray = getTypedArrayFromType( 'float' );
 
 	} else {
@@ -50,7 +51,7 @@ export const instancedArray = ( count, type = 'float' ) => {
 
 	if ( type.isStruct === true ) {
 
-		itemSize = type.layout.getLength();
+		itemSize = DataUtils.alignTo4ByteBoundary( type.layout.getLength() );
 		typedArray = getTypedArrayFromType( 'float' );
 
 	} else {

+ 2 - 1
src/renderers/webgpu/utils/WebGPUAttributeUtils.js

@@ -1,6 +1,7 @@
 import { GPUInputStepMode } from './WebGPUConstants.js';
 
 import { Float16BufferAttribute } from '../../../core/BufferAttribute.js';
+import { DataUtils } from '../../../extras/DataUtils.js';
 
 const typedArraysToVertexFormatPrefix = new Map( [
 	[ Int8Array, [ 'sint8', 'snorm8' ]],
@@ -113,7 +114,7 @@ class WebGPUAttributeUtils {
 
 			}
 
-			const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
+			const size = DataUtils.alignTo4ByteBoundary( array.byteLength );
 
 			buffer = device.createBuffer( {
 				label: bufferAttribute.name,

粤ICP备19079148号