NodeMaterial.js 14 KB

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