NodeMaterial.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. import { Material, ShaderMaterial, NoToneMapping } from 'three';
  2. import { getNodesKeys, getCacheKey } from '../core/NodeUtils.js';
  3. import { attribute } from '../core/AttributeNode.js';
  4. import { 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 } from '../accessors/PositionNode.js';
  11. import { reference } from '../accessors/ReferenceNode.js';
  12. import { skinning } from '../accessors/SkinningNode.js';
  13. import { texture } from '../accessors/TextureNode.js';
  14. import { toneMapping } from '../display/ToneMappingNode.js';
  15. import { rangeFog } from '../fog/FogRangeNode.js';
  16. import { densityFog } from '../fog/FogExp2Node.js';
  17. import { lightsWithoutWrap } from '../lighting/LightsNode.js';
  18. import AONode from '../lighting/AONode.js';
  19. import EnvironmentNode from '../lighting/EnvironmentNode.js';
  20. import { float, vec3, vec4 } from '../shadernode/ShaderNode.js';
  21. const NodeMaterials = new Map();
  22. class NodeMaterial extends ShaderMaterial {
  23. constructor() {
  24. super();
  25. this.isNodeMaterial = true;
  26. this.type = this.constructor.name;
  27. this.lights = true;
  28. this.normals = true;
  29. this.lightsNode = null;
  30. }
  31. customProgramCacheKey() {
  32. return getCacheKey( this );
  33. }
  34. build( builder ) {
  35. this.construct( builder );
  36. }
  37. construct( builder ) {
  38. // < STACKS >
  39. const vertexStack = builder.createStack();
  40. const fragmentStack = builder.createStack();
  41. // < VERTEX STAGE >
  42. vertexStack.outputNode = this.constructPosition( builder, vertexStack );
  43. // < FRAGMENT STAGE >
  44. if ( this.normals === true ) this.constructNormal( builder, fragmentStack );
  45. this.constructDiffuseColor( builder, fragmentStack );
  46. this.constructVariants( builder, fragmentStack );
  47. const outgoingLightNode = this.constructLighting( builder, fragmentStack );
  48. fragmentStack.outputNode = this.constructOutput( builder, fragmentStack, outgoingLightNode, diffuseColor.a );
  49. // < FLOW >
  50. builder.addFlow( 'vertex', vertexStack );
  51. builder.addFlow( 'fragment', fragmentStack );
  52. }
  53. constructPosition( builder ) {
  54. const object = builder.object;
  55. let vertex = positionLocal;
  56. if ( this.positionNode !== null ) {
  57. vertex = vertex.bypass( positionLocal.assign( this.positionNode ) );
  58. }
  59. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) && builder.isAvailable( 'instance' ) === true ) {
  60. vertex = vertex.bypass( instance( object ) );
  61. }
  62. if ( object.isSkinnedMesh === true ) {
  63. vertex = vertex.bypass( skinning( object ) );
  64. }
  65. builder.context.vertex = vertex;
  66. return modelViewProjection();
  67. }
  68. constructDiffuseColor( builder, stack ) {
  69. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  70. // VERTEX COLORS
  71. if ( this.vertexColors === true && builder.geometry.hasAttribute( 'color' ) ) {
  72. colorNode = vec4( colorNode.xyz.mul( attribute( 'color' ) ), colorNode.a );
  73. }
  74. // COLOR
  75. stack.assign( diffuseColor, colorNode );
  76. // OPACITY
  77. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  78. stack.assign( diffuseColor.a, diffuseColor.a.mul( opacityNode ) );
  79. // ALPHA TEST
  80. if ( this.alphaTestNode || this.alphaTest > 0 ) {
  81. const alphaTestNode = this.alphaTestNode ? float( this.alphaTestNode ) : materialAlphaTest;
  82. stack.add( diffuseColor.a.lessThanEqual( alphaTestNode ).discard() );
  83. }
  84. }
  85. constructVariants( /*builder*/ ) {
  86. // Interface function.
  87. }
  88. constructNormal( builder, stack ) {
  89. // NORMAL VIEW
  90. const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal;
  91. stack.assign( transformedNormalView, normalNode );
  92. return normalNode;
  93. }
  94. constructLights( builder ) {
  95. let lightsNode = this.lightsNode || builder.lightsNode;
  96. const envNode = this.envNode || builder.scene.environmentNode;
  97. const materialLightsNode = [];
  98. if ( envNode ) {
  99. materialLightsNode.push( new EnvironmentNode( envNode ) );
  100. }
  101. if ( builder.material.aoMap ) {
  102. materialLightsNode.push( new AONode( texture( builder.material.aoMap ) ) );
  103. }
  104. if ( materialLightsNode.length > 0 ) {
  105. lightsNode = lightsWithoutWrap( [ ...lightsNode.lightNodes, ...materialLightsNode ] );
  106. }
  107. return lightsNode;
  108. }
  109. constructLightingModel( /*builder*/ ) {
  110. // Interface function.
  111. }
  112. constructLighting( builder ) {
  113. const { material } = builder;
  114. // OUTGOING LIGHT
  115. const lights = this.lights === true || this.lightsNode !== null;
  116. const lightsNode = lights ? this.constructLights( builder ) : null;
  117. const lightingModelNode = lightsNode ? this.constructLightingModel( builder ) : null;
  118. let outgoingLightNode = diffuseColor.rgb;
  119. if ( lightsNode && lightsNode.hasLight !== false ) {
  120. outgoingLightNode = lightsNode.lightingContext( lightingModelNode );
  121. }
  122. // EMISSIVE
  123. if ( ( this.emissiveNode && this.emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  124. outgoingLightNode = outgoingLightNode.add( this.emissiveNode ? vec3( this.emissiveNode ) : materialEmissive );
  125. }
  126. return outgoingLightNode;
  127. }
  128. constructOutput( builder, stack, outgoingLight, opacity ) {
  129. const renderer = builder.renderer;
  130. // TONE MAPPING
  131. let toneMappingNode = renderer.toneMappingNode;
  132. if ( ! toneMappingNode && renderer.toneMapping !== NoToneMapping ) {
  133. toneMappingNode = toneMapping( renderer.toneMapping, reference( 'toneMappingExposure', 'float', renderer ), outgoingLight );
  134. }
  135. if ( toneMappingNode && toneMappingNode.isNode === true ) {
  136. outgoingLight = toneMappingNode.context( { color: outgoingLight } );
  137. }
  138. // @TODO: Optimize outputNode to vec3.
  139. let outputNode = vec4( outgoingLight, opacity );
  140. // ENCODING
  141. outputNode = outputNode.colorSpace( renderer.outputEncoding );
  142. // FOG
  143. let fogNode = builder.fogNode;
  144. if ( ( fogNode && fogNode.isNode !== true ) && builder.scene.fog ) {
  145. const fog = builder.scene.fog;
  146. if ( fog.isFogExp2 ) {
  147. fogNode = densityFog( reference( 'color', 'color', fog ), reference( 'density', 'float', fog ) );
  148. } else if ( fog.isFog ) {
  149. fogNode = rangeFog( reference( 'color', 'color', fog ), reference( 'near', 'float', fog ), reference( 'far', 'float', fog ) );
  150. } else {
  151. console.error( 'NodeMaterial: Unsupported fog configuration.', fog );
  152. }
  153. }
  154. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb ), outputNode.a );
  155. return outputNode;
  156. }
  157. setDefaultValues( values ) {
  158. // This approach is to reuse the native refreshUniforms*
  159. // and turn available the use of features like transmission and environment in core
  160. for ( const property in values ) {
  161. const value = values[ property ];
  162. if ( this[ property ] === undefined ) {
  163. this[ property ] = value;
  164. if ( value && value.clone ) this[ property ] = value.clone();
  165. }
  166. }
  167. Object.assign( this.defines, values.defines );
  168. }
  169. toJSON( meta ) {
  170. const isRoot = ( meta === undefined || typeof meta === 'string' );
  171. if ( isRoot ) {
  172. meta = {
  173. textures: {},
  174. images: {},
  175. nodes: {}
  176. };
  177. }
  178. const data = Material.prototype.toJSON.call( this, meta );
  179. const nodeKeys = getNodesKeys( this );
  180. data.inputNodes = {};
  181. for ( const name of nodeKeys ) {
  182. data.inputNodes[ name ] = this[ name ].toJSON( meta ).uuid;
  183. }
  184. // TODO: Copied from Object3D.toJSON
  185. function extractFromCache( cache ) {
  186. const values = [];
  187. for ( const key in cache ) {
  188. const data = cache[ key ];
  189. delete data.metadata;
  190. values.push( data );
  191. }
  192. return values;
  193. }
  194. if ( isRoot ) {
  195. const textures = extractFromCache( meta.textures );
  196. const images = extractFromCache( meta.images );
  197. const nodes = extractFromCache( meta.nodes );
  198. if ( textures.length > 0 ) data.textures = textures;
  199. if ( images.length > 0 ) data.images = images;
  200. if ( nodes.length > 0 ) data.nodes = nodes;
  201. }
  202. return data;
  203. }
  204. static fromMaterial( material ) {
  205. const type = material.type.replace( 'Material', 'NodeMaterial' );
  206. const nodeMaterial = createNodeMaterialFromType( type );
  207. if ( nodeMaterial === undefined ) {
  208. if ( material.isNodeMaterial !== true ) {
  209. throw new Error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  210. }
  211. return material; // is already a node material
  212. }
  213. for ( const key in material ) {
  214. nodeMaterial[ key ] = material[ key ];
  215. }
  216. return nodeMaterial;
  217. }
  218. }
  219. export default NodeMaterial;
  220. export function addNodeMaterial( nodeMaterial ) {
  221. if ( typeof nodeMaterial !== 'function' || ! nodeMaterial.name ) throw new Error( `Node material ${ nodeMaterial.name } is not a class` );
  222. if ( NodeMaterials.has( nodeMaterial.name ) ) throw new Error( `Redefinition of node material ${ nodeMaterial.name }` );
  223. NodeMaterials.set( nodeMaterial.name, nodeMaterial );
  224. }
  225. export function createNodeMaterialFromType( type ) {
  226. const Material = NodeMaterials.get( type );
  227. if ( Material !== undefined ) {
  228. return new Material();
  229. }
  230. };
  231. addNodeMaterial( NodeMaterial );