2
0
Эх сурвалжийг харах

WebGLUniformsGroups: Support for array of Uniform Buffer Object (#27293)

* ubo array support

* dpr to 1

* update ubo

* Update webgl2_ubo_arrays.html

Make example code more consistent to other demos.

* Update WebGLUniformsGroups.js

Clean up.

* feedbacks

* checkout build folder from dev

---------

Co-authored-by: Michael Herzog <[email protected]>
Renaud Rohlinger 1 жил өмнө
parent
commit
fa93997ac7

+ 1 - 0
examples/files.json

@@ -307,6 +307,7 @@
 		"webgl2_rendertarget_texture2darray",
 		"webgl2_texture2darray_compressed",
 		"webgl2_ubo",
+		"webgl2_ubo_arrays",
 		"webgl2_volume_cloud",
 		"webgl2_volume_instancing",
 		"webgl2_volume_perlin"

BIN
examples/screenshots/webgl2_ubo_arrays.jpg


+ 317 - 0
examples/webgl2_ubo_arrays.html

@@ -0,0 +1,317 @@
+<!DOCTYPE html>
+<html lang="en">
+	<head>
+		<title>three.js WebGL 2 - Uniform Buffer Objects Arrays</title>
+		<meta charset="utf-8">
+		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
+		<link type="text/css" rel="stylesheet" href="main.css">
+	</head>
+
+	<body>
+
+		<div id="info">
+			<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - Uniform Buffer Objects Arrays
+		</div>
+		<div id="container"></div>
+
+		<script id="vertexShader" type="x-shader/x-vertex">
+
+			uniform ViewData {
+				mat4 projectionMatrix;
+				mat4 viewMatrix;
+			};
+
+			uniform mat4 modelMatrix;
+			uniform mat3 normalMatrix;
+
+			in vec3 position;
+			in vec3 normal;
+			in vec2 uv;
+			out vec2 vUv;
+
+			out vec3 vPositionEye;
+			out vec3 vNormalEye;
+
+			void main()	{
+
+				vec4 vertexPositionEye = viewMatrix * modelMatrix * vec4( position, 1.0 );
+
+				vPositionEye = (modelMatrix * vec4( position, 1.0 )).xyz;
+				vNormalEye = (vec4(normal , 1.)).xyz;
+
+				vUv = uv;
+
+				gl_Position = projectionMatrix * vertexPositionEye;
+
+			}
+
+		</script>
+
+		<script id="fragmentShader" type="x-shader/x-vertex">
+
+			precision highp float;
+			precision highp int;
+
+			uniform LightingData {
+				vec4 lightPosition[POINTLIGHTS_MAX];
+				vec4 lightColor[POINTLIGHTS_MAX];
+				float pointLightsCount;
+			};
+			
+			#include <common>
+			float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
+		
+				float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
+		
+				if ( cutoffDistance > 0.0 ) {
+		
+					distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
+		
+				}
+		
+				return distanceFalloff;
+			
+			}
+
+			in vec2 vUv;
+			in vec3 vPositionEye;
+			in vec3 vNormalEye;
+			out vec4 fragColor;
+
+			void main()	{
+
+				vec4 color = vec4(vec3(0.), 1.);
+				for (int x = 0; x < int(pointLightsCount); x++) {
+					vec3 offset = lightPosition[x].xyz - vPositionEye;
+					vec3 dirToLight = normalize( offset );
+					float distance = length( offset );
+
+					float diffuse = max(0.0, dot(vNormalEye, dirToLight));
+					float attenuation = 1.0 / (distance * distance);
+
+					vec3 lightWeighting = lightColor[x].xyz * getDistanceAttenuation( distance, 4., .7 );
+					color.rgb += lightWeighting;
+				}
+				fragColor = color;
+
+			}
+
+		</script>
+
+		<!-- Import maps polyfill -->
+		<!-- Remove this when import maps will be widely supported -->
+		<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
+
+		<script type="importmap">
+			{
+				"imports": {
+					"three": "../build/three.module.js",
+					"three/addons/": "./jsm/"
+				}
+			}
+		</script>
+
+		<script type="module">
+
+			import * as THREE from 'three';
+
+			import WebGL from 'three/addons/capabilities/WebGL.js';
+			import Stats from 'three/addons/libs/stats.module.js';
+			import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+			import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
+
+			let camera, scene, renderer, clock, stats;
+
+			let lightingUniformsGroup, lightCenters;
+
+			const container = document.getElementById( 'container' );
+
+			const pointLightsMax = 300;
+
+			const api = {
+				count: 200,
+			};
+
+			init();
+			animate();
+
+			function init() {
+
+				if ( WebGL.isWebGL2Available() === false ) {
+
+					document.body.appendChild( WebGL.getWebGL2ErrorMessage() );
+					return;
+
+				}
+
+				camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 100 );
+				camera.position.set( 0, 50, 50 );
+
+				scene = new THREE.Scene();
+				camera.lookAt( scene.position );
+
+				clock = new THREE.Clock();
+
+				// geometry
+
+				const geometry = new THREE.SphereGeometry();
+
+				// uniforms groups
+
+				lightingUniformsGroup = new THREE.UniformsGroup();
+				lightingUniformsGroup.setName( 'LightingData' );
+
+				const data = [];
+				const dataColors = [];
+				lightCenters = [];
+
+				for ( let i = 0; i < pointLightsMax; i ++ ) {
+
+					const col = new THREE.Color( 0xffffff * Math.random() ).toArray();
+					const x = Math.random() * 50 - 25;
+					const z = Math.random() * 50 - 25;
+
+					data.push( new THREE.Uniform( new THREE.Vector4( x, 1, z, 0 ) ) ); // light position
+					dataColors.push( new THREE.Uniform( new THREE.Vector4( col[ 0 ], col[ 1 ], col[ 2 ], 0 ) ) ); // light color
+
+					// Store the center positions
+					lightCenters.push( { x, z } );
+
+				}
+
+				lightingUniformsGroup.add( data ); // light position
+				lightingUniformsGroup.add( dataColors ); // light position
+				lightingUniformsGroup.add( new THREE.Uniform( pointLightsMax ) ); // light position
+
+				const cameraUniformsGroup = new THREE.UniformsGroup();
+				cameraUniformsGroup.setName( 'ViewData' );
+				cameraUniformsGroup.add( new THREE.Uniform( camera.projectionMatrix ) ); // projection matrix
+				cameraUniformsGroup.add( new THREE.Uniform( camera.matrixWorldInverse ) ); // view matrix
+
+				const material = new THREE.RawShaderMaterial( {
+					uniforms: {
+						modelMatrix: { value: null },
+						normalMatrix: { value: null }
+					},
+					// uniformsGroups: [ cameraUniformsGroup, lightingUniformsGroup ],
+					name: 'Box',
+					defines: {
+						POINTLIGHTS_MAX: pointLightsMax
+					},
+					vertexShader: document.getElementById( 'vertexShader' ).textContent,
+					fragmentShader: document.getElementById( 'fragmentShader' ).textContent,
+					glslVersion: THREE.GLSL3
+				} );
+
+				const plane = new THREE.Mesh( new THREE.PlaneGeometry( 100, 100 ), material.clone() );
+				plane.material.uniformsGroups = [ cameraUniformsGroup, lightingUniformsGroup ];
+				plane.material.uniforms.modelMatrix.value = plane.matrixWorld;
+				plane.material.uniforms.normalMatrix.value = plane.normalMatrix;
+				plane.rotation.x = - Math.PI / 2;
+				plane.position.y = - 1;
+				scene.add( plane );
+
+				// meshes
+				const gridSize = { x: 10, y: 1, z: 10 };
+				const spacing = 6;
+
+				for ( let i = 0; i < gridSize.x; i ++ ) {
+
+					for ( let j = 0; j < gridSize.y; j ++ ) {
+
+						for ( let k = 0; k < gridSize.z; k ++ ) {
+
+							const mesh = new THREE.Mesh( geometry, material.clone() );
+							mesh.name = 'Sphere';
+							mesh.material.uniformsGroups = [ cameraUniformsGroup, lightingUniformsGroup ];
+							mesh.material.uniforms.modelMatrix.value = mesh.matrixWorld;
+							mesh.material.uniforms.normalMatrix.value = mesh.normalMatrix;
+							scene.add( mesh );
+
+							mesh.position.x = i * spacing - ( gridSize.x * spacing ) / 2;
+							mesh.position.y = 0;
+							mesh.position.z = k * spacing - ( gridSize.z * spacing ) / 2;
+
+						}
+
+					}
+
+				}
+
+				//
+
+				renderer = new THREE.WebGLRenderer( { antialias: true } );
+				renderer.setSize( window.innerWidth, window.innerHeight );
+				container.appendChild( renderer.domElement );
+
+				window.addEventListener( 'resize', onWindowResize, false );
+
+				// controls
+
+				const controls = new OrbitControls( camera, renderer.domElement );
+				controls.enabledPan = false;
+
+				// stats
+
+				stats = new Stats();
+				document.body.appendChild( stats.dom );
+
+				// gui
+				const gui = new GUI();
+				gui.add( api, 'count', 1, pointLightsMax ).step( 1 ).onChange( function () {
+
+					lightingUniformsGroup.uniforms[ 2 ].value = api.count;
+
+				} );
+
+			}
+
+			function onWindowResize() {
+
+				camera.aspect = window.innerWidth / window.innerHeight;
+				camera.updateProjectionMatrix();
+
+				renderer.setSize( window.innerWidth, window.innerHeight );
+
+			}
+
+			//
+
+			function animate() {
+
+				requestAnimationFrame( animate );
+
+				stats.update();
+
+				const elapsedTime = clock.getElapsedTime();
+
+				const lights = lightingUniformsGroup.uniforms[ 0 ];
+			
+				// Parameters for circular movement
+				const radius = 5; // Smaller radius for individual circular movements
+				const speed = 0.5; // Speed of rotation
+
+				// Update each light's position
+				for ( let i = 0; i < lights.length; i ++ ) {
+
+					const light = lights[ i ];
+					const center = lightCenters[ i ];
+
+					// Calculate circular movement around the light's center
+					const angle = speed * elapsedTime + i * 0.5; // Phase difference for each light
+					const x = center.x + Math.sin( angle ) * radius;
+					const z = center.z + Math.cos( angle ) * radius;
+
+					// Update the light's position
+					light.value.set( x, 1, z, 0 );
+
+				}
+
+				renderer.render( scene, camera );
+
+			}
+
+		</script>
+
+	</body>
+</html>

+ 7 - 1
src/core/UniformsGroup.js

@@ -73,7 +73,13 @@ class UniformsGroup extends EventDispatcher {
 
 		for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
 
-			this.uniforms.push( uniformsSource[ i ].clone() );
+			const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
+
+			for ( let j = 0; j < uniforms.length; j ++ ) {
+
+				this.uniforms.push( uniforms[ j ].clone() );
+
+			}
 
 		}
 

+ 56 - 61
src/renderers/webgl/WebGLUniformsGroups.js

@@ -96,57 +96,62 @@ function WebGLUniformsGroups( gl, info, capabilities, state ) {
 
 		for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
 
-			const uniform = uniforms[ i ];
+			const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
 
-			// partly update the buffer if necessary
+			for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
 
-			if ( hasUniformChanged( uniform, i, cache ) === true ) {
+				const uniform = uniformArray[ j ];
 
-				const offset = uniform.__offset;
+				if ( hasUniformChanged( uniform, i, cache ) === true ) {
 
-				const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
+					const offset = uniform.__offset;
 
-				let arrayOffset = 0;
+					const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
 
-				for ( let i = 0; i < values.length; i ++ ) {
+					let arrayOffset = 0;
 
-					const value = values[ i ];
+					for ( let i = 0; i < values.length; i ++ ) {
 
-					const info = getUniformSize( value );
+						const value = values[ i ];
 
-					if ( typeof value === 'number' || typeof value === 'boolean' ) {
+						const info = getUniformSize( value );
 
-						uniform.__data[ 0 ] = value;
-						gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
+						// TODO add integer and struct support
+						if ( typeof value === 'number' || typeof value === 'boolean' ) {
 
-					} else if ( value.isMatrix3 ) {
+							uniform.__data[ 0 ] = value;
+							gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
 
-						// manually converting 3x3 to 3x4
+						} else if ( value.isMatrix3 ) {
 
-						uniform.__data[ 0 ] = value.elements[ 0 ];
-						uniform.__data[ 1 ] = value.elements[ 1 ];
-						uniform.__data[ 2 ] = value.elements[ 2 ];
-						uniform.__data[ 3 ] = 0;
-						uniform.__data[ 4 ] = value.elements[ 3 ];
-						uniform.__data[ 5 ] = value.elements[ 4 ];
-						uniform.__data[ 6 ] = value.elements[ 5 ];
-						uniform.__data[ 7 ] = 0;
-						uniform.__data[ 8 ] = value.elements[ 6 ];
-						uniform.__data[ 9 ] = value.elements[ 7 ];
-						uniform.__data[ 10 ] = value.elements[ 8 ];
-						uniform.__data[ 11 ] = 0;
+							// manually converting 3x3 to 3x4
 
-					} else {
+							uniform.__data[ 0 ] = value.elements[ 0 ];
+							uniform.__data[ 1 ] = value.elements[ 1 ];
+							uniform.__data[ 2 ] = value.elements[ 2 ];
+							uniform.__data[ 3 ] = 0;
+							uniform.__data[ 4 ] = value.elements[ 3 ];
+							uniform.__data[ 5 ] = value.elements[ 4 ];
+							uniform.__data[ 6 ] = value.elements[ 5 ];
+							uniform.__data[ 7 ] = 0;
+							uniform.__data[ 8 ] = value.elements[ 6 ];
+							uniform.__data[ 9 ] = value.elements[ 7 ];
+							uniform.__data[ 10 ] = value.elements[ 8 ];
+							uniform.__data[ 11 ] = 0;
 
-						value.toArray( uniform.__data, arrayOffset );
+						} else {
 
-						arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
+							value.toArray( uniform.__data, arrayOffset );
+
+							arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
+
+						}
 
 					}
 
-				}
+					gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
 
-				gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
+				}
 
 			}
 
@@ -243,63 +248,53 @@ function WebGLUniformsGroups( gl, info, capabilities, state ) {
 
 		let offset = 0; // global buffer offset in bytes
 		const chunkSize = 16; // size of a chunk in bytes
-		let chunkOffset = 0; // offset within a single chunk in bytes
 
 		for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
 
-			const uniform = uniforms[ i ];
-
-			const infos = {
-				boundary: 0, // bytes
-				storage: 0 // bytes
-			};
+			const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
 
-			const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
+			for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
 
-			for ( let j = 0, jl = values.length; j < jl; j ++ ) {
+				const uniform = uniformArray[ j ];
 
-				const value = values[ j ];
-
-				const info = getUniformSize( value );
+				const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
 
-				infos.boundary += info.boundary;
-				infos.storage += info.storage;
+				for ( let k = 0, kl = values.length; k < kl; k ++ ) {
 
-			}
+					const value = values[ k ];
 
-			// the following two properties will be used for partial buffer updates
+					const info = getUniformSize( value );
 
-			uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT );
-			uniform.__offset = offset;
+					// Calculate the chunk offset
+					const chunkOffsetUniform = offset % chunkSize;
 
-			//
+					// Check for chunk overflow
+					if ( chunkOffsetUniform !== 0 && ( chunkSize - chunkOffsetUniform ) < info.boundary ) {
 
-			if ( i > 0 ) {
+						// Add padding and adjust offset
+						offset += ( chunkSize - chunkOffsetUniform );
 
-				chunkOffset = offset % chunkSize;
+					}
 
-				const remainingSizeInChunk = chunkSize - chunkOffset;
+					// the following two properties will be used for partial buffer updates
 
-				// check for chunk overflow
+					uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
+					uniform.__offset = offset;
 
-				if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) {
 
-					// add padding and adjust offset
+					// Update the global offset
+					offset += info.storage;
 
-					offset += ( chunkSize - chunkOffset );
-					uniform.__offset = offset;
 
 				}
 
 			}
 
-			offset += infos.storage;
-
 		}
 
 		// ensure correct final padding
 
-		chunkOffset = offset % chunkSize;
+		const chunkOffset = offset % chunkSize;
 
 		if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );