NodeMaterial.js 13 KB

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