NodeMaterial.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. import { Material } from '../../materials/Material.js';
  2. import { NormalBlending } from '../../constants.js';
  3. import { getNodeChildren, getCacheKey } from '../core/NodeUtils.js';
  4. import { attribute } from '../core/AttributeNode.js';
  5. import { output, diffuseColor, emissive, varyingProperty } from '../core/PropertyNode.js';
  6. import { materialAlphaTest, materialColor, materialOpacity, materialEmissive, materialNormal, materialLightMap, materialAOMap } from '../accessors/MaterialNode.js';
  7. import { modelViewProjection } from '../accessors/ModelViewProjectionNode.js';
  8. import { transformedNormalView, normalLocal } from '../accessors/NormalNode.js';
  9. import { instance } from '../accessors/InstanceNode.js';
  10. import { batch } from '../accessors/BatchNode.js';
  11. import { materialReference } from '../accessors/MaterialReferenceNode.js';
  12. import { positionLocal, positionView } from '../accessors/PositionNode.js';
  13. import { skinningReference } from '../accessors/SkinningNode.js';
  14. import { morphReference } from '../accessors/MorphNode.js';
  15. import { texture } from '../accessors/TextureNode.js';
  16. import { cubeTexture } from '../accessors/CubeTextureNode.js';
  17. import { lightsNode } from '../lighting/LightsNode.js';
  18. import { mix } from '../math/MathNode.js';
  19. import { float, vec3, vec4 } from '../shadernode/ShaderNode.js';
  20. import AONode from '../lighting/AONode.js';
  21. import { lightingContext } from '../lighting/LightingContextNode.js';
  22. import IrradianceNode from '../lighting/IrradianceNode.js';
  23. import { depth } from '../display/ViewportDepthNode.js';
  24. import { cameraLogDepth } from '../accessors/CameraNode.js';
  25. import { clipping, clippingAlpha } from '../accessors/ClippingNode.js';
  26. import { faceDirection } from '../display/FrontFacingNode.js';
  27. const NodeMaterials = new Map();
  28. class NodeMaterial extends Material {
  29. constructor() {
  30. super();
  31. this.isNodeMaterial = true;
  32. this.type = this.constructor.type;
  33. this.forceSinglePass = false;
  34. this.fog = true;
  35. this.lights = true;
  36. this.normals = true;
  37. this.lightsNode = null;
  38. this.envNode = null;
  39. this.aoNode = null;
  40. this.colorNode = null;
  41. this.normalNode = null;
  42. this.opacityNode = null;
  43. this.backdropNode = null;
  44. this.backdropAlphaNode = null;
  45. this.alphaTestNode = null;
  46. this.positionNode = null;
  47. this.depthNode = null;
  48. this.shadowNode = null;
  49. this.shadowPositionNode = null;
  50. this.outputNode = null;
  51. this.mrtNode = null;
  52. this.fragmentNode = null;
  53. this.vertexNode = null;
  54. }
  55. customProgramCacheKey() {
  56. return this.type + getCacheKey( this );
  57. }
  58. build( builder ) {
  59. this.setup( builder );
  60. }
  61. setup( builder ) {
  62. // < VERTEX STAGE >
  63. builder.addStack();
  64. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  65. builder.addFlow( 'vertex', builder.removeStack() );
  66. // < FRAGMENT STAGE >
  67. builder.addStack();
  68. let resultNode;
  69. const clippingNode = this.setupClipping( builder );
  70. if ( this.depthWrite === true ) this.setupDepth( builder );
  71. if ( this.fragmentNode === null ) {
  72. if ( this.normals === true ) this.setupNormal( builder );
  73. this.setupDiffuseColor( builder );
  74. this.setupVariants( builder );
  75. const outgoingLightNode = this.setupLighting( builder );
  76. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  77. // force unsigned floats - useful for RenderTargets
  78. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  79. resultNode = this.setupOutput( builder, basicOutput );
  80. // OUTPUT NODE
  81. output.assign( resultNode );
  82. //
  83. if ( this.outputNode !== null ) resultNode = this.outputNode;
  84. // MRT
  85. const renderTarget = builder.renderer.getRenderTarget();
  86. if ( renderTarget !== null ) {
  87. const mrt = builder.renderer.getMRT();
  88. const materialMRT = this.mrtNode;
  89. if ( mrt !== null ) {
  90. resultNode = mrt;
  91. if ( materialMRT !== null ) {
  92. resultNode = mrt.merge( materialMRT );
  93. }
  94. } else if ( materialMRT !== null ) {
  95. resultNode = materialMRT;
  96. }
  97. }
  98. } else {
  99. let fragmentNode = this.fragmentNode;
  100. if ( fragmentNode.isOutputStructNode !== true ) {
  101. fragmentNode = vec4( fragmentNode );
  102. }
  103. resultNode = this.setupOutput( builder, fragmentNode );
  104. }
  105. builder.stack.outputNode = resultNode;
  106. builder.addFlow( 'fragment', builder.removeStack() );
  107. }
  108. setupClipping( builder ) {
  109. if ( builder.clippingContext === null ) return null;
  110. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  111. let result = null;
  112. if ( globalClippingCount || localClippingCount ) {
  113. if ( this.alphaToCoverage ) {
  114. // to be added to flow when the color/alpha value has been determined
  115. result = clippingAlpha();
  116. } else {
  117. builder.stack.add( clipping() );
  118. }
  119. }
  120. return result;
  121. }
  122. setupDepth( builder ) {
  123. const { renderer } = builder;
  124. // Depth
  125. let depthNode = this.depthNode;
  126. if ( depthNode === null && renderer.logarithmicDepthBuffer === true ) {
  127. const fragDepth = modelViewProjection().w.add( 1 );
  128. depthNode = fragDepth.log2().mul( cameraLogDepth ).mul( 0.5 );
  129. }
  130. if ( depthNode !== null ) {
  131. depth.assign( depthNode ).append();
  132. }
  133. }
  134. setupPosition( builder ) {
  135. const { object } = builder;
  136. const geometry = object.geometry;
  137. builder.addStack();
  138. // Vertex
  139. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  140. morphReference( object ).append();
  141. }
  142. if ( object.isSkinnedMesh === true ) {
  143. skinningReference( object ).append();
  144. }
  145. if ( this.displacementMap ) {
  146. const displacementMap = materialReference( 'displacementMap', 'texture' );
  147. const displacementScale = materialReference( 'displacementScale', 'float' );
  148. const displacementBias = materialReference( 'displacementBias', 'float' );
  149. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  150. }
  151. if ( object.isBatchedMesh ) {
  152. batch( object ).append();
  153. }
  154. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  155. instance( object ).append();
  156. }
  157. if ( this.positionNode !== null ) {
  158. positionLocal.assign( this.positionNode );
  159. }
  160. const mvp = modelViewProjection();
  161. builder.context.vertex = builder.removeStack();
  162. builder.context.mvp = mvp;
  163. return mvp;
  164. }
  165. setupDiffuseColor( { object, geometry } ) {
  166. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  167. // VERTEX COLORS
  168. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  169. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  170. }
  171. // Instanced colors
  172. if ( object.instanceColor ) {
  173. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  174. colorNode = instanceColor.mul( colorNode );
  175. }
  176. // COLOR
  177. diffuseColor.assign( colorNode );
  178. // OPACITY
  179. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  180. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  181. // ALPHA TEST
  182. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  183. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  184. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  185. }
  186. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  187. diffuseColor.a.assign( 1.0 );
  188. }
  189. }
  190. setupVariants( /*builder*/ ) {
  191. // Interface function.
  192. }
  193. setupNormal() {
  194. // NORMAL VIEW
  195. if ( this.flatShading === true ) {
  196. const normalNode = positionView.dFdx().cross( positionView.dFdy() ).normalize();
  197. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  198. } else {
  199. const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal;
  200. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  201. }
  202. }
  203. setupEnvironment( builder ) {
  204. let node = null;
  205. if ( this.envNode ) {
  206. node = this.envNode;
  207. } else if ( this.envMap ) {
  208. node = this.envMap.isCubeTexture ? cubeTexture( this.envMap ) : texture( this.envMap );
  209. } else if ( builder.environmentNode ) {
  210. node = builder.environmentNode;
  211. }
  212. return node;
  213. }
  214. setupLightMap( builder ) {
  215. let node = null;
  216. if ( builder.material.lightMap ) {
  217. node = new IrradianceNode( materialLightMap );
  218. }
  219. return node;
  220. }
  221. setupLights( builder ) {
  222. const materialLightsNode = [];
  223. //
  224. const envNode = this.setupEnvironment( builder );
  225. if ( envNode && envNode.isLightingNode ) {
  226. materialLightsNode.push( envNode );
  227. }
  228. const lightMapNode = this.setupLightMap( builder );
  229. if ( lightMapNode && lightMapNode.isLightingNode ) {
  230. materialLightsNode.push( lightMapNode );
  231. }
  232. if ( this.aoNode !== null || builder.material.aoMap ) {
  233. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  234. materialLightsNode.push( new AONode( aoNode ) );
  235. }
  236. let lightsN = this.lightsNode || builder.lightsNode;
  237. if ( materialLightsNode.length > 0 ) {
  238. lightsN = lightsNode( [ ...lightsN.lightNodes, ...materialLightsNode ] );
  239. }
  240. return lightsN;
  241. }
  242. setupLightingModel( /*builder*/ ) {
  243. // Interface function.
  244. }
  245. setupLighting( builder ) {
  246. const { material } = builder;
  247. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  248. // OUTGOING LIGHT
  249. const lights = this.lights === true || this.lightsNode !== null;
  250. const lightsNode = lights ? this.setupLights( builder ) : null;
  251. let outgoingLightNode = diffuseColor.rgb;
  252. if ( lightsNode && lightsNode.hasLight !== false ) {
  253. const lightingModel = this.setupLightingModel( builder );
  254. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  255. } else if ( backdropNode !== null ) {
  256. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  257. }
  258. // EMISSIVE
  259. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  260. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  261. outgoingLightNode = outgoingLightNode.add( emissive );
  262. }
  263. return outgoingLightNode;
  264. }
  265. setupOutput( builder, outputNode ) {
  266. // FOG
  267. if ( this.fog === true ) {
  268. const fogNode = builder.fogNode;
  269. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  270. }
  271. return outputNode;
  272. }
  273. setDefaultValues( material ) {
  274. // This approach is to reuse the native refreshUniforms*
  275. // and turn available the use of features like transmission and environment in core
  276. for ( const property in material ) {
  277. const value = material[ property ];
  278. if ( this[ property ] === undefined ) {
  279. this[ property ] = value;
  280. if ( value && value.clone ) this[ property ] = value.clone();
  281. }
  282. }
  283. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  284. for ( const key in descriptors ) {
  285. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  286. descriptors[ key ].get !== undefined ) {
  287. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  288. }
  289. }
  290. }
  291. toJSON( meta ) {
  292. const isRoot = ( meta === undefined || typeof meta === 'string' );
  293. if ( isRoot ) {
  294. meta = {
  295. textures: {},
  296. images: {},
  297. nodes: {}
  298. };
  299. }
  300. const data = Material.prototype.toJSON.call( this, meta );
  301. const nodeChildren = getNodeChildren( this );
  302. data.inputNodes = {};
  303. for ( const { property, childNode } of nodeChildren ) {
  304. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  305. }
  306. // TODO: Copied from Object3D.toJSON
  307. function extractFromCache( cache ) {
  308. const values = [];
  309. for ( const key in cache ) {
  310. const data = cache[ key ];
  311. delete data.metadata;
  312. values.push( data );
  313. }
  314. return values;
  315. }
  316. if ( isRoot ) {
  317. const textures = extractFromCache( meta.textures );
  318. const images = extractFromCache( meta.images );
  319. const nodes = extractFromCache( meta.nodes );
  320. if ( textures.length > 0 ) data.textures = textures;
  321. if ( images.length > 0 ) data.images = images;
  322. if ( nodes.length > 0 ) data.nodes = nodes;
  323. }
  324. return data;
  325. }
  326. copy( source ) {
  327. this.lightsNode = source.lightsNode;
  328. this.envNode = source.envNode;
  329. this.colorNode = source.colorNode;
  330. this.normalNode = source.normalNode;
  331. this.opacityNode = source.opacityNode;
  332. this.backdropNode = source.backdropNode;
  333. this.backdropAlphaNode = source.backdropAlphaNode;
  334. this.alphaTestNode = source.alphaTestNode;
  335. this.positionNode = source.positionNode;
  336. this.depthNode = source.depthNode;
  337. this.shadowNode = source.shadowNode;
  338. this.shadowPositionNode = source.shadowPositionNode;
  339. this.outputNode = source.outputNode;
  340. this.mrtNode = source.mrtNode;
  341. this.fragmentNode = source.fragmentNode;
  342. this.vertexNode = source.vertexNode;
  343. return super.copy( source );
  344. }
  345. static fromMaterial( material ) {
  346. if ( material.isNodeMaterial === true ) { // is already a node material
  347. return material;
  348. }
  349. const type = material.type.replace( 'Material', 'NodeMaterial' );
  350. const nodeMaterial = createNodeMaterialFromType( type );
  351. if ( nodeMaterial === undefined ) {
  352. throw new Error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  353. }
  354. for ( const key in material ) {
  355. nodeMaterial[ key ] = material[ key ];
  356. }
  357. return nodeMaterial;
  358. }
  359. }
  360. export default NodeMaterial;
  361. export function addNodeMaterial( type, nodeMaterial ) {
  362. if ( typeof nodeMaterial !== 'function' || ! type ) throw new Error( `Node material ${ type } is not a class` );
  363. if ( NodeMaterials.has( type ) ) {
  364. console.warn( `Redefinition of node material ${ type }` );
  365. return;
  366. }
  367. NodeMaterials.set( type, nodeMaterial );
  368. nodeMaterial.type = type;
  369. }
  370. export function createNodeMaterialFromType( type ) {
  371. const Material = NodeMaterials.get( type );
  372. if ( Material !== undefined ) {
  373. return new Material();
  374. }
  375. }
  376. addNodeMaterial( 'NodeMaterial', NodeMaterial );