nodeMaterialBlock.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. import { NodeMaterialBlockConnectionPointTypes } from './nodeMaterialBlockConnectionPointTypes';
  2. import { NodeMaterialBuildState } from './nodeMaterialBuildState';
  3. import { Nullable } from '../../types';
  4. import { NodeMaterialConnectionPoint } from './nodeMaterialBlockConnectionPoint';
  5. import { NodeMaterialBlockTargets } from './nodeMaterialBlockTargets';
  6. import { Effect, EffectFallbacks } from '../effect';
  7. import { AbstractMesh } from '../../Meshes/abstractMesh';
  8. import { Mesh } from '../../Meshes/mesh';
  9. import { NodeMaterial, NodeMaterialDefines } from './nodeMaterial';
  10. /**
  11. * Defines a block that can be used inside a node based material
  12. */
  13. export class NodeMaterialBlock {
  14. private _buildId: number;
  15. private _target: NodeMaterialBlockTargets;
  16. private _isFinalMerger = false;
  17. /** @hidden */
  18. public _inputs = new Array<NodeMaterialConnectionPoint>();
  19. /** @hidden */
  20. public _outputs = new Array<NodeMaterialConnectionPoint>();
  21. /**
  22. * Gets or sets the name of the block
  23. */
  24. public name: string;
  25. /**
  26. * Gets a boolean indicating that this block is an end block (e.g. it is generating a system value)
  27. */
  28. public get isFinalMerger(): boolean {
  29. return this._isFinalMerger;
  30. }
  31. /**
  32. * Gets or sets the build Id
  33. */
  34. public get buildId(): number {
  35. return this._buildId;
  36. }
  37. public set buildId(value: number) {
  38. this._buildId = value;
  39. }
  40. /**
  41. * Gets or sets the target of the block
  42. */
  43. public get target() {
  44. return this._target;
  45. }
  46. public set target(value: NodeMaterialBlockTargets) {
  47. if ((this._target & value) !== 0) {
  48. return;
  49. }
  50. this._target = value;
  51. }
  52. /**
  53. * Gets the list of input points
  54. */
  55. public get inputs(): NodeMaterialConnectionPoint[] {
  56. return this._inputs;
  57. }
  58. /** Gets the list of output points */
  59. public get outputs(): NodeMaterialConnectionPoint[] {
  60. return this._outputs;
  61. }
  62. /**
  63. * Find an input by its name
  64. * @param name defines the name of the input to look for
  65. * @returns the input or null if not found
  66. */
  67. public getInputByName(name: string) {
  68. let filter = this._inputs.filter((e) => e.name === name);
  69. if (filter.length) {
  70. return filter[0];
  71. }
  72. return null;
  73. }
  74. /**
  75. * Find an output by its name
  76. * @param name defines the name of the outputto look for
  77. * @returns the output or null if not found
  78. */
  79. public getOutputByName(name: string) {
  80. let filter = this._outputs.filter((e) => e.name === name);
  81. if (filter.length) {
  82. return filter[0];
  83. }
  84. return null;
  85. }
  86. /**
  87. * Creates a new NodeMaterialBlock
  88. * @param name defines the block name
  89. * @param target defines the target of that block (Vertex by default)
  90. * @param isFinalMerger defines a boolean indicating that this block is an end block (e.g. it is generating a system value). Default is false
  91. */
  92. public constructor(name: string, target = NodeMaterialBlockTargets.Vertex, isFinalMerger = false) {
  93. this.name = name;
  94. this._target = target;
  95. if (isFinalMerger) {
  96. this._isFinalMerger = true;
  97. }
  98. }
  99. /**
  100. * Initialize the block and prepare the context for build
  101. * @param state defines the state that will be used for the build
  102. */
  103. public initialize(state: NodeMaterialBuildState) {
  104. // Do nothing
  105. }
  106. /**
  107. * Bind data to effect. Will only be called for blocks with isBindable === true
  108. * @param effect defines the effect to bind data to
  109. * @param nodeMaterial defines the hosting NodeMaterial
  110. * @param mesh defines the mesh that will be rendered
  111. */
  112. public bind(effect: Effect, nodeMaterial: NodeMaterial, mesh?: Mesh) {
  113. // Do nothing
  114. }
  115. protected _declareOutput(output: NodeMaterialConnectionPoint, state: NodeMaterialBuildState): string {
  116. if (output.isVarying) {
  117. return `${output.associatedVariableName}`;
  118. }
  119. return `${state._getGLType(output.type)} ${output.associatedVariableName}`;
  120. }
  121. protected _writeVariable(currentPoint: NodeMaterialConnectionPoint): string {
  122. let connectionPoint = currentPoint.connectedPoint!;
  123. return `${currentPoint.associatedVariableName}${connectionPoint.swizzle ? "." + connectionPoint.swizzle : ""}`;
  124. }
  125. protected _writeFloat(value: number) {
  126. let stringVersion = value.toString();
  127. if (stringVersion.indexOf(".") === -1) {
  128. stringVersion += ".0";
  129. }
  130. return `${stringVersion}`;
  131. }
  132. /**
  133. * Gets the current class name e.g. "NodeMaterialBlock"
  134. * @returns the class name
  135. */
  136. public getClassName() {
  137. return "NodeMaterialBlock";
  138. }
  139. /**
  140. * Register a new input. Must be called inside a block constructor
  141. * @param name defines the connection point name
  142. * @param type defines the connection point type
  143. * @param isOptional defines a boolean indicating that this input can be omitted
  144. * @param target defines the target to use to limit the connection point (will be VetexAndFragment by default)
  145. * @returns the current block
  146. */
  147. public registerInput(name: string, type: NodeMaterialBlockConnectionPointTypes, isOptional: boolean = false, target?: NodeMaterialBlockTargets) {
  148. let point = new NodeMaterialConnectionPoint(name, this);
  149. point.type = type;
  150. point.isOptional = isOptional;
  151. if (target) {
  152. point.target = target;
  153. }
  154. this._inputs.push(point);
  155. return this;
  156. }
  157. /**
  158. * Register a new output. Must be called inside a block constructor
  159. * @param name defines the connection point name
  160. * @param type defines the connection point type
  161. * @param target defines the target to use to limit the connection point (will be VetexAndFragment by default)
  162. * @returns the current block
  163. */
  164. public registerOutput(name: string, type: NodeMaterialBlockConnectionPointTypes, target?: NodeMaterialBlockTargets) {
  165. let point = new NodeMaterialConnectionPoint(name, this);
  166. point.type = type;
  167. if (target) {
  168. point.target = target;
  169. }
  170. this._outputs.push(point);
  171. return this;
  172. }
  173. /**
  174. * Will return the first available input e.g. the first one which is not an uniform or an attribute
  175. * @param forOutput defines an optional connection point to check compatibility with
  176. * @returns the first available input or null
  177. */
  178. public getFirstAvailableInput(forOutput: Nullable<NodeMaterialConnectionPoint> = null) {
  179. for (var input of this._inputs) {
  180. if (!input.isUniform && !input.isAttribute && !input.connectedPoint) {
  181. if (!forOutput || (forOutput.type & input.type) !== 0) {
  182. return input;
  183. }
  184. }
  185. }
  186. return null;
  187. }
  188. /**
  189. * Will return the first available output e.g. the first one which is not yet connected and not a varying
  190. * @param forBlock defines an optional block to check compatibility with
  191. * @returns the first available input or null
  192. */
  193. public getFirstAvailableOutput(forBlock: Nullable<NodeMaterialBlock> = null) {
  194. for (var output of this._outputs) {
  195. if (!forBlock || !forBlock.target || (forBlock.target & output.target) !== 0) {
  196. return output;
  197. }
  198. }
  199. return null;
  200. }
  201. /**
  202. * Connect current block with another block
  203. * @param other defines the block to connect with
  204. * @param options define the various options to help pick the right connections
  205. * @returns the current block
  206. */
  207. public connectTo(other: NodeMaterialBlock, options?: {
  208. input?: string,
  209. output?: string,
  210. outputSwizzle?: string
  211. }) {
  212. if (this._outputs.length === 0) {
  213. return;
  214. }
  215. let output = options && options.output ? this.getOutputByName(options.output) : this.getFirstAvailableOutput(other);
  216. let input = options && options.input ? other.getInputByName(options.input) : other.getFirstAvailableInput(output);
  217. if (output && input) {
  218. output.swizzle = options ? options.outputSwizzle || "" : "";
  219. output.connectTo(input);
  220. } else {
  221. throw "Unable to find a compatible match";
  222. }
  223. return this;
  224. }
  225. protected _buildBlock(state: NodeMaterialBuildState) {
  226. // Empty. Must be defined by child nodes
  227. }
  228. /**
  229. * Add potential fallbacks if shader compilation fails
  230. * @param mesh defines the mesh to be rendered
  231. * @param fallbacks defines the current prioritized list of fallbacks
  232. */
  233. public provideFallbacks(mesh: AbstractMesh, fallbacks: EffectFallbacks) {
  234. // Do nothing
  235. }
  236. /**
  237. * Update defines for shader compilation
  238. * @param mesh defines the mesh to be rendered
  239. * @param nodeMaterial defines the node material requesting the update
  240. * @param defines defines the material defines to update
  241. * @param useInstances specifies that instances should be used
  242. */
  243. public prepareDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  244. // Do nothing
  245. }
  246. /**
  247. * Lets the block try to connect some inputs automatically
  248. */
  249. public autoConfigure() {
  250. // Do nothing
  251. }
  252. /**
  253. * Function called when a block is declared as repeatable content generator
  254. * @param vertexShaderState defines the current compilation state for the vertex shader
  255. * @param fragmentShaderState defines the current compilation state for the fragment shader
  256. * @param mesh defines the mesh to be rendered
  257. * @param defines defines the material defines to update
  258. */
  259. public replaceRepeatableContent(vertexShaderState: NodeMaterialBuildState, fragmentShaderState: NodeMaterialBuildState, mesh: AbstractMesh, defines: NodeMaterialDefines) {
  260. // Do nothing
  261. }
  262. /**
  263. * Checks if the block is ready
  264. * @param mesh defines the mesh to be rendered
  265. * @param nodeMaterial defines the node material requesting the update
  266. * @param defines defines the material defines to update
  267. * @param useInstances specifies that instances should be used
  268. * @returns true if the block is ready
  269. */
  270. public isReady(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  271. return true;
  272. }
  273. /**
  274. * Compile the current node and generate the shader code
  275. * @param state defines the current compilation state (uniforms, samplers, current string)
  276. * @returns the current block
  277. */
  278. public build(state: NodeMaterialBuildState) {
  279. if (this._buildId === state.sharedData.buildId) {
  280. return;
  281. }
  282. // Check if "parent" blocks are compiled
  283. for (var input of this._inputs) {
  284. if (!input.connectedPoint) {
  285. if (!input.isOptional && !input.isAttribute && !input.isUniform) { // Emit a warning
  286. state.sharedData.checks.notConnectedNonOptionalInputs.push(input);
  287. }
  288. continue;
  289. }
  290. if ((input.target & this.target!) === 0) {
  291. continue;
  292. }
  293. if ((input.target & state.target!) === 0) {
  294. continue;
  295. }
  296. let block = input.connectedPoint.ownerBlock;
  297. if (block && block !== this && block.buildId !== state.sharedData.buildId) {
  298. block.build(state);
  299. }
  300. }
  301. if (this._buildId === state.sharedData.buildId) {
  302. return; // Need to check again as inputs can be connected multiple time to this endpoint
  303. }
  304. // Logs
  305. if (state.sharedData.verbose) {
  306. console.log(`${state.target === NodeMaterialBlockTargets.Vertex ? "Vertex shader" : "Fragment shader"}: Building ${this.name} [${this.getClassName()}]`);
  307. }
  308. /** Prepare outputs */
  309. for (var output of this._outputs) {
  310. if ((output.target & this.target!) === 0) {
  311. continue;
  312. }
  313. if ((output.target & state.target!) === 0) {
  314. continue;
  315. }
  316. output.associatedVariableName = state._getFreeVariableName(output.name);
  317. state._emitVaryings(output);
  318. }
  319. // Build
  320. for (var input of this._inputs) {
  321. if ((input.target & this.target!) === 0) {
  322. continue;
  323. }
  324. if ((input.target & state.target!) === 0) {
  325. continue;
  326. }
  327. state._emitUniformOrAttributes(input);
  328. }
  329. // Checks final outputs
  330. if (this.isFinalMerger) {
  331. switch (state.target) {
  332. case NodeMaterialBlockTargets.Vertex:
  333. state.sharedData.checks.emitVertex = true;
  334. break;
  335. case NodeMaterialBlockTargets.Fragment:
  336. state.sharedData.checks.emitFragment = true;
  337. break;
  338. }
  339. }
  340. if (state.sharedData.emitComments) {
  341. state.compilationString += `\r\n//${this.name}\r\n`;
  342. }
  343. this._buildBlock(state);
  344. this._buildId = state.sharedData.buildId;
  345. // Compile connected blocks
  346. for (var output of this._outputs) {
  347. if ((output.target & state.target) === 0) {
  348. continue;
  349. }
  350. for (var block of output.connectedBlocks) {
  351. if (block && (block.target & state.target) !== 0) {
  352. block.build(state);
  353. }
  354. }
  355. }
  356. return this;
  357. }
  358. }