webgl_gpgpu_protoplanet.html 14 KB

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