webgpu_materials.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js - WebGPU - Materials</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. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> WebGPU - Materials
  12. </div>
  13. <script type="importmap">
  14. {
  15. "imports": {
  16. "three": "../build/three.module.js",
  17. "three/addons/": "./jsm/",
  18. "three/nodes": "./jsm/nodes/Nodes.js"
  19. }
  20. }
  21. </script>
  22. <script type="module">
  23. import * as THREE from 'three';
  24. import * as Nodes from 'three/nodes';
  25. import { tslFn, wgslFn, positionLocal, positionWorld, normalLocal, normalWorld, normalView, color, texture, uv, float, vec2, vec3, vec4, oscSine, triplanarTexture, viewportBottomLeft, js, string, global, loop, MeshBasicNodeMaterial, NodeObjectLoader } from 'three/nodes';
  26. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  27. import WebGPURenderer from 'three/addons/renderers/webgpu/WebGPURenderer.js';
  28. import { TeapotGeometry } from 'three/addons/geometries/TeapotGeometry.js';
  29. import Stats from 'three/addons/libs/stats.module.js';
  30. let stats;
  31. let camera, scene, renderer;
  32. const objects = [], materials = [];
  33. init();
  34. function init() {
  35. if ( WebGPU.isAvailable() === false ) {
  36. document.body.appendChild( WebGPU.getErrorMessage() );
  37. throw new Error( 'No WebGPU support' );
  38. }
  39. const container = document.createElement( 'div' );
  40. document.body.appendChild( container );
  41. camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
  42. camera.position.set( 0, 200, 800 );
  43. scene = new THREE.Scene();
  44. // Grid
  45. const helper = new THREE.GridHelper( 1000, 40, 0x303030, 0x303030 );
  46. helper.position.y = - 75;
  47. scene.add( helper );
  48. // Materials
  49. const textureLoader = new THREE.TextureLoader();
  50. const uvTexture = textureLoader.load( './textures/uv_grid_opengl.jpg' );
  51. uvTexture.wrapS = THREE.RepeatWrapping;
  52. uvTexture.wrapT = THREE.RepeatWrapping;
  53. const opacityTexture = textureLoader.load( './textures/alphaMap.jpg' );
  54. opacityTexture.wrapS = THREE.RepeatWrapping;
  55. opacityTexture.wrapT = THREE.RepeatWrapping;
  56. let material;
  57. //
  58. // BASIC
  59. //
  60. // PositionLocal
  61. material = new MeshBasicNodeMaterial();
  62. material.colorNode = positionLocal;
  63. materials.push( material );
  64. // PositionWorld
  65. material = new MeshBasicNodeMaterial();
  66. material.colorNode = positionWorld;
  67. materials.push( material );
  68. // NormalLocal
  69. material = new MeshBasicNodeMaterial();
  70. material.colorNode = normalLocal;
  71. materials.push( material );
  72. // NormalWorld
  73. material = new MeshBasicNodeMaterial();
  74. material.colorNode = normalWorld;
  75. materials.push( material );
  76. // NormalView
  77. material = new MeshBasicNodeMaterial();
  78. material.colorNode = normalView;
  79. materials.push( material );
  80. // Texture
  81. material = new MeshBasicNodeMaterial();
  82. material.colorNode = texture( uvTexture );
  83. materials.push( material );
  84. // Opacity
  85. material = new MeshBasicNodeMaterial();
  86. material.colorNode = color( 0x0099FF );
  87. material.opacityNode = texture( uvTexture );
  88. material.transparent = true;
  89. materials.push( material );
  90. // AlphaTest
  91. material = new MeshBasicNodeMaterial();
  92. material.colorNode = texture( uvTexture );
  93. material.opacityNode = texture( opacityTexture );
  94. material.alphaTestNode = 0.5;
  95. materials.push( material );
  96. // Normal
  97. material = new THREE.MeshNormalMaterial();
  98. material.opacity = .5;
  99. material.transparent = true;
  100. materials.push( material );
  101. //
  102. // ADVANCED
  103. //
  104. // Custom ShaderNode ( desaturate filter )
  105. const desaturateShaderNode = tslFn( ( input ) => {
  106. return vec3( 0.299, 0.587, 0.114 ).dot( input.color.xyz );
  107. } );
  108. material = new MeshBasicNodeMaterial();
  109. material.colorNode = desaturateShaderNode( { color: texture( uvTexture ) } );
  110. materials.push( material );
  111. // Custom ShaderNode(no inputs) > Approach 2
  112. const desaturateNoInputsShaderNode = tslFn( () => {
  113. return vec3( 0.299, 0.587, 0.114 ).dot( texture( uvTexture ).xyz );
  114. } );
  115. material = new MeshBasicNodeMaterial();
  116. material.colorNode = desaturateNoInputsShaderNode();
  117. materials.push( material );
  118. // Custom WGSL ( desaturate filter )
  119. const desaturateWGSLNode = wgslFn( `
  120. fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  121. let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  122. return vec3<f32>( dot( lum, color ) );
  123. }
  124. ` );
  125. material = new MeshBasicNodeMaterial();
  126. material.colorNode = desaturateWGSLNode( { color: texture( uvTexture ) } );
  127. materials.push( material );
  128. // Custom WGSL ( get texture from keywords )
  129. const getWGSLTextureSample = wgslFn( `
  130. fn getWGSLTextureSample( tex: texture_2d<f32>, tex_sampler: sampler, uv:vec2<f32> ) -> vec4<f32> {
  131. return textureSample( tex, tex_sampler, uv ) * vec4<f32>( 0.0, 1.0, 0.0, 1.0 );
  132. }
  133. ` );
  134. const textureNode = texture( uvTexture );
  135. //getWGSLTextureSample.keywords = { tex: textureNode, tex_sampler: sampler( textureNode ) };
  136. material = new MeshBasicNodeMaterial();
  137. material.colorNode = getWGSLTextureSample( { tex: textureNode, tex_sampler: textureNode, uv: uv() } );
  138. materials.push( material );
  139. // Triplanar Texture Mapping
  140. material = new MeshBasicNodeMaterial();
  141. material.colorNode = triplanarTexture( texture( uvTexture ), null, null, float( .01 ) );
  142. materials.push( material );
  143. // Screen Projection Texture
  144. material = new MeshBasicNodeMaterial();
  145. material.colorNode = texture( uvTexture, viewportBottomLeft );
  146. materials.push( material );
  147. // Loop
  148. material = new MeshBasicNodeMaterial();
  149. materials.push( material );
  150. const loopCount = 10;
  151. material.colorNode = loop( loopCount, ( { i }, stack ) => {
  152. const output = vec4().temp();
  153. const scale = oscSine().mul( .09 ); // just a value to test
  154. const scaleI = scale.mul( i );
  155. const scaleINeg = scaleI.negate();
  156. const leftUV = uv().add( vec2( scaleI, 0 ) );
  157. const rightUV = uv().add( vec2( scaleINeg, 0 ) );
  158. const topUV = uv().add( vec2( 0, scaleI ) );
  159. const bottomUV = uv().add( vec2( 0, scaleINeg ) );
  160. stack.assign( output, output.add( texture( uvTexture, leftUV ) ) );
  161. stack.assign( output, output.add( texture( uvTexture, rightUV ) ) );
  162. stack.assign( output, output.add( texture( uvTexture, topUV ) ) );
  163. stack.assign( output, output.add( texture( uvTexture, bottomUV ) ) );
  164. return output.div( loopCount * 4 );
  165. } );
  166. // Scriptable
  167. global.set( 'THREE', THREE );
  168. global.set( 'TSL', Nodes );
  169. const asyncNode = js( `
  170. layout = {
  171. outputType: 'node'
  172. };
  173. const { float } = TSL;
  174. function init() {
  175. setTimeout( () => {
  176. local.set( 'result', float( 1.0 ) );
  177. refresh(); // refresh the node
  178. }, 1000 );
  179. return float( 0.0 );
  180. }
  181. function main() {
  182. const result = local.get( 'result', init );
  183. //console.log( 'result', result );
  184. return result;
  185. }
  186. ` ).scriptable();
  187. const scriptableNode = js( `
  188. layout = {
  189. outputType: 'node',
  190. elements: [
  191. { name: 'source', inputType: 'node' },
  192. { name: 'contrast', inputType: 'node' },
  193. { name: 'vector3', inputType: 'Vector3' },
  194. { name: 'message', inputType: 'string' },
  195. { name: 'binary', inputType: 'ArrayBuffer' },
  196. { name: 'object3d', inputType: 'Object3D' },
  197. { name: 'execFrom', inputType: 'string' }
  198. ]
  199. };
  200. const { saturation, float, oscSine, mul } = TSL;
  201. function helloWorld() {
  202. console.log( "Hello World!" );
  203. }
  204. function main() {
  205. const source = parameters.get( 'source' ) || float();
  206. const contrast = parameters.get( 'contrast' ) || float();
  207. const material = local.get( 'material' );
  208. //console.log( 'vector3', parameters.get( 'vector3' ) );
  209. if ( parameters.get( 'execFrom' ) === 'serialized' ) {
  210. //console.log( 'message', parameters.get( 'message' ).value );
  211. //console.log( 'binary', parameters.get( 'binary' ) );
  212. //console.log( 'object3d', parameters.get( 'object3d' ) ); // unserializable yet
  213. //console.log( global.get( 'renderer' ) );
  214. }
  215. if ( material ) material.needsUpdate = true;
  216. return mul( saturation( source, oscSine() ), contrast );
  217. }
  218. output = { helloWorld };
  219. ` ).scriptable();
  220. scriptableNode.setParameter( 'source', texture( uvTexture ).xyz );
  221. scriptableNode.setParameter( 'contrast', asyncNode );
  222. scriptableNode.setParameter( 'vector3', vec3( new THREE.Vector3( 1, 1, 1 ) ) );
  223. scriptableNode.setParameter( 'message', string( 'Hello World!' ) );
  224. scriptableNode.setParameter( 'binary', new ArrayBuffer( 4 ) );
  225. scriptableNode.setParameter( 'object3d', new THREE.Group() );
  226. scriptableNode.call( 'helloWorld' );
  227. material = new MeshBasicNodeMaterial();
  228. material.colorNode = scriptableNode;
  229. materials.push( material );
  230. scriptableNode.setLocal( 'material', material );
  231. //
  232. // Geometry
  233. //
  234. const geometry = new TeapotGeometry( 50, 18 );
  235. for ( let i = 0, l = materials.length; i < l; i ++ ) {
  236. addMesh( geometry, materials[ i ] );
  237. }
  238. const serializeMesh = scene.children[ scene.children.length - 1 ];
  239. //
  240. renderer = new WebGPURenderer( { antialias: true } );
  241. renderer.setPixelRatio( window.devicePixelRatio );
  242. renderer.setSize( window.innerWidth, window.innerHeight );
  243. renderer.setAnimationLoop( animate );
  244. container.appendChild( renderer.domElement );
  245. //
  246. stats = new Stats();
  247. container.appendChild( stats.dom );
  248. //
  249. window.addEventListener( 'resize', onWindowResize );
  250. //
  251. setTimeout( () => testSerialization( serializeMesh ), 1000 );
  252. }
  253. function addMesh( geometry, material ) {
  254. const mesh = new THREE.Mesh( geometry, material );
  255. mesh.position.x = ( objects.length % 4 ) * 200 - 400;
  256. mesh.position.z = Math.floor( objects.length / 4 ) * 200 - 200;
  257. mesh.rotation.x = Math.random() * 200 - 100;
  258. mesh.rotation.y = Math.random() * 200 - 100;
  259. mesh.rotation.z = Math.random() * 200 - 100;
  260. objects.push( mesh );
  261. scene.add( mesh );
  262. }
  263. function testSerialization( mesh ) {
  264. const json = mesh.toJSON();
  265. const loader = new NodeObjectLoader();
  266. const serializedMesh = loader.parse( json );
  267. serializedMesh.position.x = ( objects.length % 4 ) * 200 - 400;
  268. serializedMesh.position.z = Math.floor( objects.length / 4 ) * 200 - 200;
  269. const scriptableNode = serializedMesh.material.colorNode;
  270. // it's because local.get( 'material' ) is used in the example ( local/global is unserializable )
  271. scriptableNode.setLocal( 'material', serializedMesh.material );
  272. scriptableNode.setParameter( 'execFrom', 'serialized' );
  273. objects.push( serializedMesh );
  274. scene.add( serializedMesh );
  275. }
  276. function onWindowResize() {
  277. camera.aspect = window.innerWidth / window.innerHeight;
  278. camera.updateProjectionMatrix();
  279. renderer.setSize( window.innerWidth, window.innerHeight );
  280. }
  281. //
  282. function animate() {
  283. const timer = 0.0001 * Date.now();
  284. camera.position.x = Math.cos( timer ) * 1000;
  285. camera.position.z = Math.sin( timer ) * 1000;
  286. camera.lookAt( scene.position );
  287. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  288. const object = objects[ i ];
  289. object.rotation.x += 0.01;
  290. object.rotation.y += 0.005;
  291. }
  292. renderer.render( scene, camera );
  293. stats.update();
  294. }
  295. </script>
  296. </body>
  297. </html>
粤ICP备19079148号