NodeMaterial.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. import { Material, ShaderMaterial, NoColorSpace, LinearSRGBColorSpace } from 'three';
  2. import { getNodeChildren, getCacheKey } from '../core/NodeUtils.js';
  3. import { attribute } from '../core/AttributeNode.js';
  4. import { output, diffuseColor } from '../core/PropertyNode.js';
  5. import { materialNormal } from '../accessors/ExtendedMaterialNode.js';
  6. import { materialAlphaTest, materialColor, materialOpacity, materialEmissive } from '../accessors/MaterialNode.js';
  7. import { modelViewProjection } from '../accessors/ModelViewProjectionNode.js';
  8. import { transformedNormalView } from '../accessors/NormalNode.js';
  9. import { instance } from '../accessors/InstanceNode.js';
  10. import { positionLocal, positionView } from '../accessors/PositionNode.js';
  11. import { skinning } from '../accessors/SkinningNode.js';
  12. import { morph } from '../accessors/MorphNode.js';
  13. import { texture } from '../accessors/TextureNode.js';
  14. import { cubeTexture } from '../accessors/CubeTextureNode.js';
  15. import { lightsWithoutWrap } from '../lighting/LightsNode.js';
  16. import { mix, dFdx, dFdy } from '../math/MathNode.js';
  17. import { float, vec3, vec4 } from '../shadernode/ShaderNode.js';
  18. import AONode from '../lighting/AONode.js';
  19. import EnvironmentNode from '../lighting/EnvironmentNode.js';
  20. const NodeMaterials = new Map();
  21. class NodeMaterial extends ShaderMaterial {
  22. constructor() {
  23. super();
  24. this.isNodeMaterial = true;
  25. this.type = this.constructor.name;
  26. this.forceSinglePass = false;
  27. this.unlit = this.constructor === NodeMaterial.prototype.constructor; // Extended materials are not unlit by default
  28. this.fog = true;
  29. this.lights = true;
  30. this.normals = true;
  31. this.colorSpace = true;
  32. this.lightsNode = null;
  33. this.envNode = null;
  34. this.colorNode = null;
  35. this.normalNode = null;
  36. this.opacityNode = null;
  37. this.backdropNode = null;
  38. this.backdropAlphaNode = null;
  39. this.alphaTestNode = null;
  40. this.positionNode = null;
  41. this.outputNode = null;
  42. }
  43. customProgramCacheKey() {
  44. return this.type + getCacheKey( this );
  45. }
  46. build( builder ) {
  47. this.construct( builder );
  48. }
  49. construct( builder ) {
  50. // < VERTEX STAGE >
  51. builder.addStack();
  52. builder.stack.outputNode = this.constructPosition( builder );
  53. builder.addFlow( 'vertex', builder.removeStack() );
  54. // < FRAGMENT STAGE >
  55. builder.addStack();
  56. let outputNode;
  57. if ( this.unlit === false ) {
  58. if ( this.normals === true ) this.constructNormal( builder );
  59. this.constructDiffuseColor( builder );
  60. this.constructVariants( builder );
  61. const outgoingLightNode = this.constructLighting( builder );
  62. outputNode = this.constructOutput( builder, vec4( outgoingLightNode, diffuseColor.a ) );
  63. // OUTPUT NODE
  64. builder.stack.assign( output, outputNode );
  65. //
  66. if ( this.outputNode !== null ) outputNode = this.outputNode;
  67. } else {
  68. outputNode = this.constructOutput( builder, this.outputNode || vec4( 0, 0, 0, 1 ) );
  69. }
  70. builder.stack.outputNode = outputNode;
  71. builder.addFlow( 'fragment', builder.removeStack() );
  72. }
  73. constructPosition( builder ) {
  74. const object = builder.object;
  75. const geometry = object.geometry;
  76. builder.addStack();
  77. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  78. builder.stack.add( morph( object ) );
  79. }
  80. if ( object.isSkinnedMesh === true ) {
  81. builder.stack.add( skinning( object ) );
  82. }
  83. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) && builder.isAvailable( 'instance' ) === true ) {
  84. builder.stack.add( instance( object ) );
  85. }
  86. if ( this.positionNode !== null ) {
  87. builder.stack.assign( positionLocal, this.positionNode );
  88. }
  89. builder.context.vertex = builder.removeStack();
  90. return modelViewProjection();
  91. }
  92. constructDiffuseColor( { stack, geometry } ) {
  93. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  94. // VERTEX COLORS
  95. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  96. colorNode = vec4( colorNode.xyz.mul( attribute( 'color' ) ), colorNode.a );
  97. }
  98. // COLOR
  99. stack.assign( diffuseColor, colorNode );
  100. // OPACITY
  101. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  102. stack.assign( diffuseColor.a, diffuseColor.a.mul( opacityNode ) );
  103. // ALPHA TEST
  104. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  105. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  106. stack.add( diffuseColor.a.lessThanEqual( alphaTestNode ).discard() );
  107. }
  108. }
  109. constructVariants( /*builder*/ ) {
  110. // Interface function.
  111. }
  112. constructNormal( { stack } ) {
  113. // NORMAL VIEW
  114. if ( this.flatShading === true ) {
  115. const fdx = dFdx( positionView );
  116. const fdy = dFdy( positionView.negate() ); // use -positionView ?
  117. const normalNode = fdx.cross( fdy ).normalize();
  118. stack.assign( transformedNormalView, normalNode );
  119. } else {
  120. const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal;
  121. stack.assign( transformedNormalView, normalNode );
  122. }
  123. }
  124. getEnvNode( builder ) {
  125. let node = null;
  126. if ( this.envNode ) {
  127. node = this.envNode;
  128. } else if ( this.envMap ) {
  129. node = this.envMap.isCubeTexture ? cubeTexture( this.envMap ) : texture( this.envMap );
  130. } else if ( builder.environmentNode ) {
  131. node = builder.environmentNode;
  132. }
  133. return node;
  134. }
  135. constructLights( builder ) {
  136. const envNode = this.getEnvNode( builder );
  137. //
  138. const materialLightsNode = [];
  139. if ( envNode ) {
  140. materialLightsNode.push( new EnvironmentNode( envNode ) );
  141. }
  142. if ( builder.material.aoMap ) {
  143. materialLightsNode.push( new AONode( texture( builder.material.aoMap ) ) );
  144. }
  145. let lightsNode = this.lightsNode || builder.lightsNode;
  146. if ( materialLightsNode.length > 0 ) {
  147. lightsNode = lightsWithoutWrap( [ ...lightsNode.lightNodes, ...materialLightsNode ] );
  148. }
  149. return lightsNode;
  150. }
  151. constructLightingModel( /*builder*/ ) {
  152. // Interface function.
  153. }
  154. constructLighting( builder ) {
  155. const { material } = builder;
  156. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  157. // OUTGOING LIGHT
  158. const lights = this.lights === true || this.lightsNode !== null;
  159. const lightsNode = lights ? this.constructLights( builder ) : null;
  160. let outgoingLightNode = diffuseColor.rgb;
  161. if ( lightsNode && lightsNode.hasLight !== false ) {
  162. const lightingModelNode = this.constructLightingModel( builder );
  163. outgoingLightNode = lightsNode.lightingContext( lightingModelNode, backdropNode, backdropAlphaNode );
  164. } else if ( backdropNode !== null ) {
  165. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  166. }
  167. // EMISSIVE
  168. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  169. outgoingLightNode = outgoingLightNode.add( emissiveNode ? vec3( emissiveNode ) : materialEmissive );
  170. }
  171. return outgoingLightNode;
  172. }
  173. constructOutput( builder, outputNode ) {
  174. const renderer = builder.renderer;
  175. // TONE MAPPING
  176. const toneMappingNode = builder.toneMappingNode;
  177. if ( toneMappingNode ) {
  178. outputNode = vec4( toneMappingNode.context( { color: outputNode.rgb } ), outputNode.a );
  179. }
  180. // FOG
  181. if ( this.fog === true ) {
  182. const fogNode = builder.fogNode;
  183. if ( fogNode ) outputNode = vec4( fogNode.mixAssign( outputNode.rgb ), outputNode.a );
  184. }
  185. // ENCODING
  186. if ( this.colorSpace === true ) {
  187. const renderTarget = renderer.getRenderTarget();
  188. let outputColorSpace;
  189. if ( renderTarget !== null ) {
  190. outputColorSpace = renderTarget.texture.colorSpace;
  191. } else {
  192. outputColorSpace = renderer.outputColorSpace;
  193. }
  194. if ( outputColorSpace !== LinearSRGBColorSpace && outputColorSpace !== NoColorSpace ) {
  195. outputNode = outputNode.linearToColorSpace( outputColorSpace );
  196. }
  197. }
  198. return outputNode;
  199. }
  200. setDefaultValues( material ) {
  201. // This approach is to reuse the native refreshUniforms*
  202. // and turn available the use of features like transmission and environment in core
  203. for ( const property in material ) {
  204. const value = material[ property ];
  205. if ( this[ property ] === undefined ) {
  206. this[ property ] = value;
  207. if ( value && value.clone ) this[ property ] = value.clone();
  208. }
  209. }
  210. Object.assign( this.defines, material.defines );
  211. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  212. for ( const key in descriptors ) {
  213. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  214. descriptors[ key ].get !== undefined ) {
  215. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  216. }
  217. }
  218. }
  219. toJSON( meta ) {
  220. const isRoot = ( meta === undefined || typeof meta === 'string' );
  221. if ( isRoot ) {
  222. meta = {
  223. textures: {},
  224. images: {},
  225. nodes: {}
  226. };
  227. }
  228. const data = Material.prototype.toJSON.call( this, meta );
  229. const nodeChildren = getNodeChildren( this );
  230. data.inputNodes = {};
  231. for ( const { property, childNode } of nodeChildren ) {
  232. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  233. }
  234. // TODO: Copied from Object3D.toJSON
  235. function extractFromCache( cache ) {
  236. const values = [];
  237. for ( const key in cache ) {
  238. const data = cache[ key ];
  239. delete data.metadata;
  240. values.push( data );
  241. }
  242. return values;
  243. }
  244. if ( isRoot ) {
  245. const textures = extractFromCache( meta.textures );
  246. const images = extractFromCache( meta.images );
  247. const nodes = extractFromCache( meta.nodes );
  248. if ( textures.length > 0 ) data.textures = textures;
  249. if ( images.length > 0 ) data.images = images;
  250. if ( nodes.length > 0 ) data.nodes = nodes;
  251. }
  252. return data;
  253. }
  254. copy( source ) {
  255. this.lightsNode = source.lightsNode;
  256. this.envNode = source.envNode;
  257. this.colorNode = source.colorNode;
  258. this.normalNode = source.normalNode;
  259. this.opacityNode = source.opacityNode;
  260. this.backdropNode = source.backdropNode;
  261. this.backdropAlphaNode = source.backdropAlphaNode;
  262. this.alphaTestNode = source.alphaTestNode;
  263. this.positionNode = source.positionNode;
  264. this.outputNode = source.outputNode;
  265. return super.copy( source );
  266. }
  267. static fromMaterial( material ) {
  268. if ( material.isNodeMaterial === true ) { // is already a node material
  269. return material;
  270. }
  271. const type = material.type.replace( 'Material', 'NodeMaterial' );
  272. const nodeMaterial = createNodeMaterialFromType( type );
  273. if ( nodeMaterial === undefined ) {
  274. throw new Error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  275. }
  276. for ( const key in material ) {
  277. nodeMaterial[ key ] = material[ key ];
  278. }
  279. return nodeMaterial;
  280. }
  281. }
  282. export default NodeMaterial;
  283. export function addNodeMaterial( nodeMaterial ) {
  284. if ( typeof nodeMaterial !== 'function' || ! nodeMaterial.name ) throw new Error( `Node material ${ nodeMaterial.name } is not a class` );
  285. if ( NodeMaterials.has( nodeMaterial.name ) ) throw new Error( `Redefinition of node material ${ nodeMaterial.name }` );
  286. NodeMaterials.set( nodeMaterial.name, nodeMaterial );
  287. }
  288. export function createNodeMaterialFromType( type ) {
  289. const Material = NodeMaterials.get( type );
  290. if ( Material !== undefined ) {
  291. return new Material();
  292. }
  293. }
  294. addNodeMaterial( NodeMaterial );