NodeMaterial.js 12 KB

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