NodeMaterial.js 11 KB

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