NodeMaterial.js 11 KB

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