webgl_gpgpu_protoplanet.html 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - gpgpu - protoplanet</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 - gpgpu - protoplanet">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgl_gpgpu_protoplanet.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgl_gpgpu_protoplanet.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> - <span id="protoplanets"></span> webgl gpgpu debris
  16. </div>
  17. <!-- Fragment shader for protoplanet's position -->
  18. <script id="computeShaderPosition" type="x-shader/x-fragment">
  19. #define delta ( 1.0 / 60.0 )
  20. void main() {
  21. vec2 uv = gl_FragCoord.xy / resolution.xy;
  22. vec4 tmpPos = texture2D( texturePosition, uv );
  23. vec3 pos = tmpPos.xyz;
  24. vec4 tmpVel = texture2D( textureVelocity, uv );
  25. vec3 vel = tmpVel.xyz;
  26. float mass = tmpVel.w;
  27. if ( mass == 0.0 ) {
  28. vel = vec3( 0.0 );
  29. }
  30. // Dynamics
  31. pos += vel * delta;
  32. gl_FragColor = vec4( pos, 1.0 );
  33. }
  34. </script>
  35. <!-- Fragment shader for protoplanet's velocity -->
  36. <script id="computeShaderVelocity" type="x-shader/x-fragment">
  37. // For PI declaration:
  38. #include <common>
  39. #define delta ( 1.0 / 60.0 )
  40. uniform float gravityConstant;
  41. uniform float density;
  42. const float width = resolution.x;
  43. const float height = resolution.y;
  44. float radiusFromMass( float mass ) {
  45. // Calculate radius of a sphere from mass and density
  46. return pow( ( 3.0 / ( 4.0 * PI ) ) * mass / density, 1.0 / 3.0 );
  47. }
  48. void main() {
  49. vec2 uv = gl_FragCoord.xy / resolution.xy;
  50. float idParticle = uv.y * resolution.x + uv.x;
  51. vec4 tmpPos = texture2D( texturePosition, uv );
  52. vec3 pos = tmpPos.xyz;
  53. vec4 tmpVel = texture2D( textureVelocity, uv );
  54. vec3 vel = tmpVel.xyz;
  55. float mass = tmpVel.w;
  56. if ( mass > 0.0 ) {
  57. float radius = radiusFromMass( mass );
  58. vec3 acceleration = vec3( 0.0 );
  59. // Gravity interaction
  60. for ( float y = 0.0; y < height; y++ ) {
  61. for ( float x = 0.0; x < width; x++ ) {
  62. vec2 secondParticleCoords = vec2( x + 0.5, y + 0.5 ) / resolution.xy;
  63. vec3 pos2 = texture2D( texturePosition, secondParticleCoords ).xyz;
  64. vec4 velTemp2 = texture2D( textureVelocity, secondParticleCoords );
  65. vec3 vel2 = velTemp2.xyz;
  66. float mass2 = velTemp2.w;
  67. float idParticle2 = secondParticleCoords.y * resolution.x + secondParticleCoords.x;
  68. if ( idParticle == idParticle2 ) {
  69. continue;
  70. }
  71. if ( mass2 == 0.0 ) {
  72. continue;
  73. }
  74. vec3 dPos = pos2 - pos;
  75. float distance = length( dPos );
  76. float radius2 = radiusFromMass( mass2 );
  77. if ( distance == 0.0 ) {
  78. continue;
  79. }
  80. // Checks collision
  81. if ( distance < radius + radius2 ) {
  82. if ( idParticle < idParticle2 ) {
  83. // This particle is aggregated by the other
  84. vel = ( vel * mass + vel2 * mass2 ) / ( mass + mass2 );
  85. mass += mass2;
  86. radius = radiusFromMass( mass );
  87. }
  88. else {
  89. // This particle dies
  90. mass = 0.0;
  91. radius = 0.0;
  92. vel = vec3( 0.0 );
  93. break;
  94. }
  95. }
  96. float distanceSq = distance * distance;
  97. float gravityField = gravityConstant * mass2 / distanceSq;
  98. gravityField = min( gravityField, 1000.0 );
  99. acceleration += gravityField * normalize( dPos );
  100. }
  101. if ( mass == 0.0 ) {
  102. break;
  103. }
  104. }
  105. // Dynamics
  106. vel += delta * acceleration;
  107. }
  108. gl_FragColor = vec4( vel, mass );
  109. }
  110. </script>
  111. <!-- Particles vertex shader -->
  112. <script type="x-shader/x-vertex" id="particleVertexShader">
  113. // For PI declaration:
  114. #include <common>
  115. uniform sampler2D texturePosition;
  116. uniform sampler2D textureVelocity;
  117. uniform float cameraConstant;
  118. uniform float density;
  119. varying vec4 vColor;
  120. float radiusFromMass( float mass ) {
  121. // Calculate radius of a sphere from mass and density
  122. return pow( ( 3.0 / ( 4.0 * PI ) ) * mass / density, 1.0 / 3.0 );
  123. }
  124. void main() {
  125. vec4 posTemp = texture2D( texturePosition, uv );
  126. vec3 pos = posTemp.xyz;
  127. vec4 velTemp = texture2D( textureVelocity, uv );
  128. vec3 vel = velTemp.xyz;
  129. float mass = velTemp.w;
  130. vColor = vec4( 1.0, mass / 250.0, 0.0, 1.0 );
  131. vec4 mvPosition = modelViewMatrix * vec4( pos, 1.0 );
  132. // Calculate radius of a sphere from mass and density
  133. //float radius = pow( ( 3.0 / ( 4.0 * PI ) ) * mass / density, 1.0 / 3.0 );
  134. float radius = radiusFromMass( mass );
  135. // Apparent size in pixels
  136. if ( mass == 0.0 ) {
  137. gl_PointSize = 0.0;
  138. }
  139. else {
  140. gl_PointSize = radius * cameraConstant / ( - mvPosition.z );
  141. }
  142. gl_Position = projectionMatrix * mvPosition;
  143. }
  144. </script>
  145. <!-- Particles fragment shader -->
  146. <script type="x-shader/x-fragment" id="particleFragmentShader">
  147. varying vec4 vColor;
  148. void main() {
  149. if ( vColor.y == 0.0 ) discard;
  150. float f = length( gl_PointCoord - vec2( 0.5, 0.5 ) );
  151. if ( f > 0.5 ) {
  152. discard;
  153. }
  154. gl_FragColor = vColor;
  155. }
  156. </script>
  157. <script type="importmap">
  158. {
  159. "imports": {
  160. "three": "../build/three.module.js",
  161. "three/addons/": "./jsm/"
  162. }
  163. }
  164. </script>
  165. <script type="module">
  166. import * as THREE from 'three';
  167. import Stats from 'three/addons/libs/stats.module.js';
  168. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  169. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  170. import { GPUComputationRenderer } from 'three/addons/misc/GPUComputationRenderer.js';
  171. // Texture width for simulation (each texel is a debris particle)
  172. const WIDTH = 64;
  173. let container, stats;
  174. let camera, scene, renderer, geometry;
  175. const PARTICLES = WIDTH * WIDTH;
  176. let gpuCompute;
  177. let velocityVariable;
  178. let positionVariable;
  179. let velocityUniforms;
  180. let particleUniforms;
  181. let effectController;
  182. init();
  183. function init() {
  184. container = document.createElement( 'div' );
  185. document.body.appendChild( container );
  186. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 5, 15000 );
  187. camera.position.y = 120;
  188. camera.position.z = 400;
  189. scene = new THREE.Scene();
  190. renderer = new THREE.WebGLRenderer();
  191. renderer.setPixelRatio( window.devicePixelRatio );
  192. renderer.setSize( window.innerWidth, window.innerHeight );
  193. renderer.setAnimationLoop( animate );
  194. container.appendChild( renderer.domElement );
  195. const controls = new OrbitControls( camera, renderer.domElement );
  196. controls.minDistance = 100;
  197. controls.maxDistance = 1000;
  198. effectController = {
  199. // Can be changed dynamically
  200. gravityConstant: 100.0,
  201. density: 0.45,
  202. // Must restart simulation
  203. radius: 300,
  204. height: 8,
  205. exponent: 0.4,
  206. maxMass: 15.0,
  207. velocity: 70,
  208. velocityExponent: 0.2,
  209. randVelocity: 0.001
  210. };
  211. initComputeRenderer();
  212. stats = new Stats();
  213. container.appendChild( stats.dom );
  214. window.addEventListener( 'resize', onWindowResize );
  215. initGUI();
  216. initProtoplanets();
  217. dynamicValuesChanger();
  218. }
  219. function initComputeRenderer() {
  220. gpuCompute = new GPUComputationRenderer( WIDTH, WIDTH, renderer );
  221. const dtPosition = gpuCompute.createTexture();
  222. const dtVelocity = gpuCompute.createTexture();
  223. fillTextures( dtPosition, dtVelocity );
  224. velocityVariable = gpuCompute.addVariable( 'textureVelocity', document.getElementById( 'computeShaderVelocity' ).textContent, dtVelocity );
  225. positionVariable = gpuCompute.addVariable( 'texturePosition', document.getElementById( 'computeShaderPosition' ).textContent, dtPosition );
  226. gpuCompute.setVariableDependencies( velocityVariable, [ positionVariable, velocityVariable ] );
  227. gpuCompute.setVariableDependencies( positionVariable, [ positionVariable, velocityVariable ] );
  228. velocityUniforms = velocityVariable.material.uniforms;
  229. velocityUniforms[ 'gravityConstant' ] = { value: 0.0 };
  230. velocityUniforms[ 'density' ] = { value: 0.0 };
  231. const error = gpuCompute.init();
  232. if ( error !== null ) {
  233. console.error( error );
  234. }
  235. }
  236. function restartSimulation() {
  237. const dtPosition = gpuCompute.createTexture();
  238. const dtVelocity = gpuCompute.createTexture();
  239. fillTextures( dtPosition, dtVelocity );
  240. gpuCompute.renderTexture( dtPosition, positionVariable.renderTargets[ 0 ] );
  241. gpuCompute.renderTexture( dtPosition, positionVariable.renderTargets[ 1 ] );
  242. gpuCompute.renderTexture( dtVelocity, velocityVariable.renderTargets[ 0 ] );
  243. gpuCompute.renderTexture( dtVelocity, velocityVariable.renderTargets[ 1 ] );
  244. }
  245. function initProtoplanets() {
  246. geometry = new THREE.BufferGeometry();
  247. const positions = new Float32Array( PARTICLES * 3 );
  248. let p = 0;
  249. for ( let i = 0; i < PARTICLES; i ++ ) {
  250. positions[ p ++ ] = ( Math.random() * 2 - 1 ) * effectController.radius;
  251. positions[ p ++ ] = 0; //( Math.random() * 2 - 1 ) * effectController.radius;
  252. positions[ p ++ ] = ( Math.random() * 2 - 1 ) * effectController.radius;
  253. }
  254. const uvs = new Float32Array( PARTICLES * 2 );
  255. p = 0;
  256. for ( let j = 0; j < WIDTH; j ++ ) {
  257. for ( let i = 0; i < WIDTH; i ++ ) {
  258. uvs[ p ++ ] = i / ( WIDTH - 1 );
  259. uvs[ p ++ ] = j / ( WIDTH - 1 );
  260. }
  261. }
  262. geometry.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  263. geometry.setAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  264. particleUniforms = {
  265. 'texturePosition': { value: null },
  266. 'textureVelocity': { value: null },
  267. 'cameraConstant': { value: getCameraConstant( camera ) },
  268. 'density': { value: 0.0 }
  269. };
  270. // THREE.ShaderMaterial
  271. const material = new THREE.ShaderMaterial( {
  272. uniforms: particleUniforms,
  273. vertexShader: document.getElementById( 'particleVertexShader' ).textContent,
  274. fragmentShader: document.getElementById( 'particleFragmentShader' ).textContent
  275. } );
  276. const particles = new THREE.Points( geometry, material );
  277. particles.matrixAutoUpdate = false;
  278. particles.updateMatrix();
  279. scene.add( particles );
  280. }
  281. function fillTextures( texturePosition, textureVelocity ) {
  282. const posArray = texturePosition.image.data;
  283. const velArray = textureVelocity.image.data;
  284. const radius = effectController.radius;
  285. const height = effectController.height;
  286. const exponent = effectController.exponent;
  287. const maxMass = effectController.maxMass * 1024 / PARTICLES;
  288. const maxVel = effectController.velocity;
  289. const velExponent = effectController.velocityExponent;
  290. const randVel = effectController.randVelocity;
  291. for ( let k = 0, kl = posArray.length; k < kl; k += 4 ) {
  292. // Position
  293. let x, z, rr;
  294. do {
  295. x = ( Math.random() * 2 - 1 );
  296. z = ( Math.random() * 2 - 1 );
  297. rr = x * x + z * z;
  298. } while ( rr > 1 );
  299. rr = Math.sqrt( rr );
  300. const rExp = radius * Math.pow( rr, exponent );
  301. // Velocity
  302. const vel = maxVel * Math.pow( rr, velExponent );
  303. const vx = vel * z + ( Math.random() * 2 - 1 ) * randVel;
  304. const vy = ( Math.random() * 2 - 1 ) * randVel * 0.05;
  305. const vz = - vel * x + ( Math.random() * 2 - 1 ) * randVel;
  306. x *= rExp;
  307. z *= rExp;
  308. const y = ( Math.random() * 2 - 1 ) * height;
  309. const mass = Math.random() * maxMass + 1;
  310. // Fill in texture values
  311. posArray[ k + 0 ] = x;
  312. posArray[ k + 1 ] = y;
  313. posArray[ k + 2 ] = z;
  314. posArray[ k + 3 ] = 1;
  315. velArray[ k + 0 ] = vx;
  316. velArray[ k + 1 ] = vy;
  317. velArray[ k + 2 ] = vz;
  318. velArray[ k + 3 ] = mass;
  319. }
  320. }
  321. function onWindowResize() {
  322. camera.aspect = window.innerWidth / window.innerHeight;
  323. camera.updateProjectionMatrix();
  324. renderer.setSize( window.innerWidth, window.innerHeight );
  325. particleUniforms[ 'cameraConstant' ].value = getCameraConstant( camera );
  326. }
  327. function dynamicValuesChanger() {
  328. velocityUniforms[ 'gravityConstant' ].value = effectController.gravityConstant;
  329. velocityUniforms[ 'density' ].value = effectController.density;
  330. particleUniforms[ 'density' ].value = effectController.density;
  331. }
  332. function initGUI() {
  333. const gui = new GUI( { width: 280 } );
  334. const folder1 = gui.addFolder( 'Dynamic parameters' );
  335. folder1.add( effectController, 'gravityConstant', 0.0, 1000.0, 0.05 ).onChange( dynamicValuesChanger );
  336. folder1.add( effectController, 'density', 0.0, 10.0, 0.001 ).onChange( dynamicValuesChanger );
  337. const folder2 = gui.addFolder( 'Static parameters' );
  338. folder2.add( effectController, 'radius', 10.0, 1000.0, 1.0 );
  339. folder2.add( effectController, 'height', 0.0, 50.0, 0.01 );
  340. folder2.add( effectController, 'exponent', 0.0, 2.0, 0.001 );
  341. folder2.add( effectController, 'maxMass', 1.0, 50.0, 0.1 );
  342. folder2.add( effectController, 'velocity', 0.0, 150.0, 0.1 );
  343. folder2.add( effectController, 'velocityExponent', 0.0, 1.0, 0.01 );
  344. folder2.add( effectController, 'randVelocity', 0.0, 50.0, 0.1 );
  345. const buttonRestart = {
  346. restartSimulation: function () {
  347. restartSimulation();
  348. }
  349. };
  350. folder2.add( buttonRestart, 'restartSimulation' );
  351. folder1.open();
  352. folder2.open();
  353. }
  354. function getCameraConstant( camera ) {
  355. return window.innerHeight / ( Math.tan( THREE.MathUtils.DEG2RAD * 0.5 * camera.fov ) / camera.zoom );
  356. }
  357. function animate() {
  358. render();
  359. stats.update();
  360. }
  361. function render() {
  362. gpuCompute.compute();
  363. particleUniforms[ 'texturePosition' ].value = gpuCompute.getCurrentRenderTarget( positionVariable ).texture;
  364. particleUniforms[ 'textureVelocity' ].value = gpuCompute.getCurrentRenderTarget( velocityVariable ).texture;
  365. renderer.render( scene, camera );
  366. }
  367. </script>
  368. </body>
  369. </html>
粤ICP备19079148号