webgl_ubo_arrays.html 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js WebGL 2 - Uniform Buffer Objects Arrays</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <meta property="og:title" content="three.js WebGL 2 - Uniform Buffer Objects Arrays">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgl_ubo_arrays.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgl_ubo_arrays.jpg">
  11. <link type="text/css" rel="stylesheet" href="main.css">
  12. </head>
  13. <body>
  14. <div id="info">
  15. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - Uniform Buffer Objects Arrays
  16. </div>
  17. <div id="container"></div>
  18. <script id="vertexShader" type="x-shader/x-vertex">
  19. uniform ViewData {
  20. mat4 projectionMatrix;
  21. mat4 viewMatrix;
  22. };
  23. uniform mat4 modelMatrix;
  24. uniform mat3 normalMatrix;
  25. in vec3 position;
  26. in vec3 normal;
  27. in vec2 uv;
  28. out vec2 vUv;
  29. out vec3 vPositionEye;
  30. out vec3 vNormalEye;
  31. void main() {
  32. vec4 vertexPositionEye = viewMatrix * modelMatrix * vec4( position, 1.0 );
  33. vPositionEye = (modelMatrix * vec4( position, 1.0 )).xyz;
  34. vNormalEye = (vec4(normal , 1.)).xyz;
  35. vUv = uv;
  36. gl_Position = projectionMatrix * vertexPositionEye;
  37. }
  38. </script>
  39. <script id="fragmentShader" type="x-shader/x-vertex">
  40. precision highp float;
  41. precision highp int;
  42. uniform LightingData {
  43. vec4 lightPosition[POINTLIGHTS_MAX];
  44. vec4 lightColor[POINTLIGHTS_MAX];
  45. float pointLightsCount;
  46. };
  47. #include <common>
  48. float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
  49. float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
  50. if ( cutoffDistance > 0.0 ) {
  51. distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
  52. }
  53. return distanceFalloff;
  54. }
  55. in vec2 vUv;
  56. in vec3 vPositionEye;
  57. in vec3 vNormalEye;
  58. out vec4 fragColor;
  59. void main() {
  60. vec4 color = vec4(vec3(0.), 1.);
  61. for (int x = 0; x < int(pointLightsCount); x++) {
  62. vec3 offset = lightPosition[x].xyz - vPositionEye;
  63. vec3 dirToLight = normalize( offset );
  64. float distance = length( offset );
  65. float diffuse = max(0.0, dot(vNormalEye, dirToLight));
  66. float attenuation = 1.0 / (distance * distance);
  67. vec3 lightWeighting = lightColor[x].xyz * getDistanceAttenuation( distance, 4., .7 );
  68. color.rgb += lightWeighting;
  69. }
  70. fragColor = color;
  71. }
  72. </script>
  73. <script type="importmap">
  74. {
  75. "imports": {
  76. "three": "../build/three.module.js",
  77. "three/addons/": "./jsm/"
  78. }
  79. }
  80. </script>
  81. <script type="module">
  82. import * as THREE from 'three';
  83. import Stats from 'three/addons/libs/stats.module.js';
  84. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  85. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  86. let camera, scene, renderer, timer, stats;
  87. let lightingUniformsGroup, lightCenters;
  88. const container = document.getElementById( 'container' );
  89. const pointLightsMax = 300;
  90. const api = {
  91. count: 200,
  92. };
  93. init();
  94. function init() {
  95. camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 100 );
  96. camera.position.set( 0, 50, 50 );
  97. scene = new THREE.Scene();
  98. camera.lookAt( scene.position );
  99. timer = new THREE.Timer();
  100. timer.connect( document );
  101. // geometry
  102. const geometry = new THREE.SphereGeometry();
  103. // uniforms groups
  104. lightingUniformsGroup = new THREE.UniformsGroup();
  105. lightingUniformsGroup.setName( 'LightingData' );
  106. const data = [];
  107. const dataColors = [];
  108. lightCenters = [];
  109. for ( let i = 0; i < pointLightsMax; i ++ ) {
  110. const col = new THREE.Color( 0xffffff * Math.random() ).toArray();
  111. const x = Math.random() * 50 - 25;
  112. const z = Math.random() * 50 - 25;
  113. data.push( new THREE.Uniform( new THREE.Vector4( x, 1, z, 0 ) ) ); // light position
  114. dataColors.push( new THREE.Uniform( new THREE.Vector4( col[ 0 ], col[ 1 ], col[ 2 ], 0 ) ) ); // light color
  115. // Store the center positions
  116. lightCenters.push( { x, z } );
  117. }
  118. lightingUniformsGroup.add( data ); // light position
  119. lightingUniformsGroup.add( dataColors ); // light position
  120. lightingUniformsGroup.add( new THREE.Uniform( pointLightsMax ) ); // light position
  121. const cameraUniformsGroup = new THREE.UniformsGroup();
  122. cameraUniformsGroup.setName( 'ViewData' );
  123. cameraUniformsGroup.add( new THREE.Uniform( camera.projectionMatrix ) ); // projection matrix
  124. cameraUniformsGroup.add( new THREE.Uniform( camera.matrixWorldInverse ) ); // view matrix
  125. const material = new THREE.RawShaderMaterial( {
  126. uniforms: {
  127. modelMatrix: { value: null },
  128. normalMatrix: { value: null }
  129. },
  130. // uniformsGroups: [ cameraUniformsGroup, lightingUniformsGroup ],
  131. name: 'Box',
  132. defines: {
  133. POINTLIGHTS_MAX: pointLightsMax
  134. },
  135. vertexShader: document.getElementById( 'vertexShader' ).textContent,
  136. fragmentShader: document.getElementById( 'fragmentShader' ).textContent,
  137. glslVersion: THREE.GLSL3
  138. } );
  139. const plane = new THREE.Mesh( new THREE.PlaneGeometry( 100, 100 ), material.clone() );
  140. plane.material.uniformsGroups = [ cameraUniformsGroup, lightingUniformsGroup ];
  141. plane.material.uniforms.modelMatrix.value = plane.matrixWorld;
  142. plane.material.uniforms.normalMatrix.value = plane.normalMatrix;
  143. plane.rotation.x = - Math.PI / 2;
  144. plane.position.y = - 1;
  145. scene.add( plane );
  146. // meshes
  147. const gridSize = { x: 10, y: 1, z: 10 };
  148. const spacing = 6;
  149. for ( let i = 0; i < gridSize.x; i ++ ) {
  150. for ( let j = 0; j < gridSize.y; j ++ ) {
  151. for ( let k = 0; k < gridSize.z; k ++ ) {
  152. const mesh = new THREE.Mesh( geometry, material.clone() );
  153. mesh.name = 'Sphere';
  154. mesh.material.uniformsGroups = [ cameraUniformsGroup, lightingUniformsGroup ];
  155. mesh.material.uniforms.modelMatrix.value = mesh.matrixWorld;
  156. mesh.material.uniforms.normalMatrix.value = mesh.normalMatrix;
  157. scene.add( mesh );
  158. mesh.position.x = i * spacing - ( gridSize.x * spacing ) / 2;
  159. mesh.position.y = 0;
  160. mesh.position.z = k * spacing - ( gridSize.z * spacing ) / 2;
  161. }
  162. }
  163. }
  164. //
  165. renderer = new THREE.WebGLRenderer( { antialias: true } );
  166. renderer.setSize( window.innerWidth, window.innerHeight );
  167. renderer.setAnimationLoop( animate );
  168. container.appendChild( renderer.domElement );
  169. window.addEventListener( 'resize', onWindowResize, false );
  170. // controls
  171. const controls = new OrbitControls( camera, renderer.domElement );
  172. controls.enablePan = false;
  173. // stats
  174. stats = new Stats();
  175. document.body.appendChild( stats.dom );
  176. // gui
  177. const gui = new GUI();
  178. gui.add( api, 'count', 1, pointLightsMax ).step( 1 ).onChange( function () {
  179. lightingUniformsGroup.uniforms[ 2 ].value = api.count;
  180. } );
  181. }
  182. function onWindowResize() {
  183. camera.aspect = window.innerWidth / window.innerHeight;
  184. camera.updateProjectionMatrix();
  185. renderer.setSize( window.innerWidth, window.innerHeight );
  186. }
  187. //
  188. function animate() {
  189. timer.update();
  190. const elapsedTime = timer.getElapsed();
  191. const lights = lightingUniformsGroup.uniforms[ 0 ];
  192. // Parameters for circular movement
  193. const radius = 5; // Smaller radius for individual circular movements
  194. const speed = 0.5; // Speed of rotation
  195. // Update each light's position
  196. for ( let i = 0; i < lights.length; i ++ ) {
  197. const light = lights[ i ];
  198. const center = lightCenters[ i ];
  199. // Calculate circular movement around the light's center
  200. const angle = speed * elapsedTime + i * 0.5; // Phase difference for each light
  201. const x = center.x + Math.sin( angle ) * radius;
  202. const z = center.z + Math.cos( angle ) * radius;
  203. // Update the light's position
  204. light.value.set( x, 1, z, 0 );
  205. }
  206. renderer.render( scene, camera );
  207. stats.update();
  208. }
  209. </script>
  210. </body>
  211. </html>
粤ICP备19079148号