NodeMaterial.js 11 KB

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