webgpu_materials.html 12 KB

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