webgpu_loader_materialx.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - materialx loader</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 webgpu - materialx loader">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgpu_loader_materialx.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgpu_loader_materialx.jpg">
  11. <link type="text/css" rel="stylesheet" href="example.css">
  12. <style>
  13. .dg .property-name {
  14. width: 20% !important;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="info">
  20. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  21. <div class="title-wrapper">
  22. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>MaterialX Loader</span>
  23. </div>
  24. <small>
  25. MaterialX Standard Surface loader.
  26. </small>
  27. </div>
  28. <script type="importmap">
  29. {
  30. "imports": {
  31. "three": "../build/three.webgpu.js",
  32. "three/webgpu": "../build/three.webgpu.js",
  33. "three/tsl": "../build/three.tsl.js",
  34. "three/addons/": "./jsm/"
  35. }
  36. }
  37. </script>
  38. <script type="module">
  39. import * as THREE from 'three/webgpu';
  40. import { Fn, abs, fract, fwidth, length, max, saturate, smoothstep, vec4, positionWorld, float } from 'three/tsl';
  41. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  42. import { HDRLoader } from 'three/addons/loaders/HDRLoader.js';
  43. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  44. import * as MikkTSpace from 'three/addons/libs/mikktspace.module.js';
  45. import { computeMikkTSpaceTangents } from 'three/addons/utils/BufferGeometryUtils.js';
  46. import { MaterialXLoader } from 'three/addons/loaders/MaterialXLoader.js';
  47. import { createStrictInterfaceValidator } from 'three/addons/loaders/materialx/MaterialXInterfaceValidation.js';
  48. import { Inspector } from 'three/addons/inspector/Inspector.js';
  49. const SAMPLE_PATH = 'https://raw.githubusercontent.com/materialx/MaterialX/main/resources/Materials/Examples/StandardSurface/';
  50. const LOCAL_SAMPLE_PATH = 'materialx/';
  51. const samples = [
  52. 'standard_surface_brass_tiled.mtlx',
  53. 'standard_surface_brick_procedural.mtlx',
  54. 'standard_surface_carpaint.mtlx',
  55. //'standard_surface_chess_set.mtlx',
  56. 'standard_surface_chrome.mtlx',
  57. 'standard_surface_copper.mtlx',
  58. //'standard_surface_default.mtlx',
  59. //'standard_surface_glass.mtlx',
  60. //'standard_surface_glass_tinted.mtlx',
  61. 'standard_surface_gold.mtlx',
  62. //'standard_surface_greysphere.mtlx',
  63. //'standard_surface_greysphere_calibration.mtlx',
  64. 'standard_surface_jade.mtlx',
  65. //'standard_surface_look_brass_tiled.mtlx',
  66. //'standard_surface_look_wood_tiled.mtlx',
  67. 'standard_surface_marble_solid.mtlx',
  68. 'standard_surface_metal_brushed.mtlx',
  69. 'standard_surface_plastic.mtlx',
  70. //'standard_surface_thin_film.mtlx',
  71. 'standard_surface_velvet.mtlx',
  72. 'standard_surface_wood_tiled.mtlx'
  73. ];
  74. const localSamples = [
  75. 'standard_surface_heightnormal.mtlx',
  76. 'standard_surface_conditional_if_float.mtlx',
  77. 'standard_surface_image_transform.mtlx',
  78. 'standard_surface_color3_vec3_cm_test.mtlx',
  79. 'standard_surface_rotate2d_test.mtlx',
  80. 'standard_surface_rotate3d_test.mtlx',
  81. 'standard_surface_heighttonormal_normal_input.mtlx',
  82. 'standard_surface_roughness_test.mtlx',
  83. 'standard_surface_opacity_test.mtlx',
  84. 'standard_surface_opacity_only_test.mtlx',
  85. 'standard_surface_specular_test.mtlx',
  86. 'standard_surface_ior_test.mtlx',
  87. 'standard_surface_combined_test.mtlx',
  88. 'standard_surface_texture_opacity_test.mtlx',
  89. 'standard_surface_transmission_test.mtlx',
  90. 'standard_surface_transmission_only_test.mtlx',
  91. 'standard_surface_transmission_rough.mtlx',
  92. 'standard_surface_thin_film_rainbow_test.mtlx',
  93. 'standard_surface_thin_film_ior_clamp_test.mtlx',
  94. 'standard_surface_sheen_test.mtlx',
  95. 'gltf_pbr_glass_dispersion.mtlx',
  96. 'open_pbr_surface_velvet.mtlx',
  97. 'open_pbr_surface_pearl.mtlx',
  98. 'open_pbr_surface_honey.mtlx',
  99. ];
  100. let camera, scene, renderer;
  101. let controls, prefab;
  102. const models = [];
  103. const strictInterfaceValidator = createStrictInterfaceValidator();
  104. init();
  105. function init() {
  106. const container = document.createElement( 'div' );
  107. document.body.appendChild( container );
  108. renderer = new THREE.WebGPURenderer( { antialias: true } );
  109. renderer.setPixelRatio( window.devicePixelRatio );
  110. renderer.setSize( window.innerWidth, window.innerHeight );
  111. renderer.toneMapping = THREE.LinearToneMapping;
  112. renderer.toneMappingExposure = .5;
  113. renderer.inspector = new Inspector();
  114. renderer.setAnimationLoop( render );
  115. container.appendChild( renderer.domElement );
  116. camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.25, 200 );
  117. camera.position.set( 10, 10, 20 );
  118. scene = new THREE.Scene();
  119. scene.background = new THREE.Color( 0xffffff );
  120. // Ground plane
  121. const material = new THREE.MeshBasicNodeMaterial();
  122. const grid = Fn( ( [ coord, lineWidth = float( 0.01 ), dotSize = float( 0.03 ) ] ) => {
  123. // https://bgolus.medium.com/the-best-darn-grid-shader-yet-727f9278b9d8
  124. const g = fract( coord );
  125. const fw = fwidth( coord );
  126. const gx = abs( g.x.sub( 0.5 ) );
  127. const gy = abs( g.y.sub( 0.5 ) );
  128. const lineX = saturate( lineWidth.sub( gx ).div( fw.x ).add( 0.5 ) );
  129. const lineY = saturate( lineWidth.sub( gy ).div( fw.y ).add( 0.5 ) );
  130. const lines = max( lineX, lineY );
  131. const squareDist = max( gx, gy );
  132. const aa = max( fw.x, fw.y );
  133. const dots = smoothstep( dotSize.add( aa ), dotSize.sub( aa ), squareDist );
  134. return max( dots, lines );
  135. } );
  136. const fade = Fn( ( [ radius = float( 10.0 ), falloff = float( 1.0 ) ] ) => {
  137. return smoothstep( radius, radius.sub( falloff ), length( positionWorld ) );
  138. } );
  139. const gridColor = vec4( 0.5, 0.5, 0.5, 1.0 );
  140. const baseColor = vec4( 1.0, 1.0, 1.0, 0.0 );
  141. material.colorNode = grid( positionWorld.xz, 0.007, 0.03 ).mix( baseColor, gridColor ).mul( fade( 30.0, 20.0 ) );
  142. material.transparent = true;
  143. const plane = new THREE.Mesh( new THREE.CircleGeometry( 40 ), material );
  144. plane.rotation.x = - Math.PI / 2;
  145. plane.renderOrder = - 1;
  146. scene.add( plane );
  147. //
  148. controls = new OrbitControls( camera );
  149. controls.connect( renderer.domElement );
  150. controls.enableDamping = true;
  151. controls.minDistance = 2;
  152. controls.maxDistance = 40;
  153. //
  154. new HDRLoader()
  155. .setPath( 'textures/equirectangular/' )
  156. .load( 'san_giuseppe_bridge_2k.hdr', async ( texture ) => {
  157. texture.mapping = THREE.EquirectangularReflectionMapping;
  158. scene.environment = texture;
  159. prefab = ( await new GLTFLoader().loadAsync( './models/gltf/ShaderBall.glb' ) ).scene;
  160. await computePrefabTangents();
  161. for ( const sample of samples ) {
  162. await addSample( sample, SAMPLE_PATH );
  163. }
  164. for ( const sample of localSamples ) {
  165. await addSample( sample, LOCAL_SAMPLE_PATH );
  166. }
  167. addGUI();
  168. } );
  169. window.addEventListener( 'resize', onWindowResize );
  170. }
  171. async function computePrefabTangents() {
  172. await MikkTSpace.ready;
  173. prefab.traverse( function ( node ) {
  174. if ( node.isMesh === false ) return;
  175. const geometry = node.geometry;
  176. if ( geometry === undefined ) return;
  177. if ( geometry.hasAttribute( 'tangent' ) ) return;
  178. if ( geometry.hasAttribute( 'position' ) && geometry.hasAttribute( 'normal' ) && geometry.hasAttribute( 'uv' ) ) {
  179. computeMikkTSpaceTangents( geometry, MikkTSpace );
  180. }
  181. } );
  182. }
  183. function updateModelsAlign() {
  184. const COLUMN_COUNT = 6;
  185. const DIST_X = 3;
  186. const DIST_Z = 3;
  187. const lineCount = Math.floor( models.length / COLUMN_COUNT ) - 1.5;
  188. const offsetX = ( DIST_X * ( COLUMN_COUNT - 1 ) ) * - .5;
  189. const offsetZ = ( DIST_Z * lineCount ) * .5;
  190. for ( let i = 0; i < models.length; i ++ ) {
  191. const model = models[ i ];
  192. model.position.x = ( ( i % COLUMN_COUNT ) * DIST_X ) + offsetX;
  193. model.position.z = ( Math.floor( i / COLUMN_COUNT ) * - DIST_Z ) + offsetZ;
  194. }
  195. }
  196. function reportMaterialXLog( sample, materialName, log ) {
  197. if ( log.length === 0 ) return;
  198. const label = materialName ? `"${materialName}"` : `"${sample}"`;
  199. const errorCount = log.filter( ( entry ) => entry.severity === 'error' ).length;
  200. const warningCount = log.filter( ( entry ) => entry.severity === 'warning' ).length;
  201. console.groupCollapsed( `THREE.MaterialXLoader: ${errorCount} error(s), ${warningCount} warning(s) for ${label} (${sample})` );
  202. for ( const entry of log ) {
  203. const nodeName = entry.nodeName ? ` [${entry.nodeName}]` : '';
  204. const style = entry.severity === 'warning' ? 'color: #c90' : 'color: #c00';
  205. console[ entry.severity === 'warning' ? 'warn' : 'error' ]( `%c${entry.severity}: ${entry.code}${nodeName}: ${entry.message}`, style );
  206. }
  207. console.groupEnd();
  208. }
  209. async function addSample( sample, path ) {
  210. const model = prefab.clone();
  211. models.push( model );
  212. scene.add( model );
  213. updateModelsAlign();
  214. //
  215. const { materials, log } = await new MaterialXLoader()
  216. .setPath( path )
  217. .loadAsync( sample, {
  218. uvSpace: 'top-left',
  219. interfaceValidator: strictInterfaceValidator,
  220. throwOnErrors: false,
  221. } );
  222. const material = Object.values( materials ).pop();
  223. reportMaterialXLog( sample, material ? material.name : null, log );
  224. const calibrationMesh = model.getObjectByName( 'Calibration_Mesh' );
  225. calibrationMesh.material = material;
  226. const previewMesh = model.getObjectByName( 'Preview_Mesh' );
  227. previewMesh.material = material;
  228. if ( material.transparent ) {
  229. calibrationMesh.renderOrder = 1;
  230. previewMesh.renderOrder = 2;
  231. }
  232. await renderer.compileAsync( model, camera, scene );
  233. }
  234. function addGUI() {
  235. const gui = renderer.inspector.createParameters( 'MaterialX Loader' );
  236. const API = {
  237. showCalibrationMesh: true,
  238. showPreviewMesh: true
  239. };
  240. gui.add( API, 'showCalibrationMesh' )
  241. .name( 'Calibration Mesh' )
  242. .onChange( function ( value ) {
  243. setVisibility( 'Calibration_Mesh', value );
  244. } );
  245. gui.add( API, 'showPreviewMesh' )
  246. .name( 'Preview Mesh' )
  247. .onChange( function ( value ) {
  248. setVisibility( 'Preview_Mesh', value );
  249. } );
  250. }
  251. function setVisibility( name, visible ) {
  252. scene.traverse( function ( node ) {
  253. if ( node.isMesh ) {
  254. if ( node.name == name ) node.visible = visible;
  255. }
  256. } );
  257. }
  258. //
  259. function onWindowResize() {
  260. camera.aspect = window.innerWidth / window.innerHeight;
  261. camera.updateProjectionMatrix();
  262. renderer.setSize( window.innerWidth, window.innerHeight );
  263. }
  264. function render() {
  265. controls.update();
  266. renderer.render( scene, camera );
  267. }
  268. </script>
  269. </body>
  270. </html>
粤ICP备19079148号