NodeMaterial.js 12 KB

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