NodeMaterial.js 13 KB

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