nodeMaterialBlock.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. import { InputBlock } from './Blocks/Input/inputBlock';
  11. import { UniqueIdGenerator } from '../../Misc/uniqueIdGenerator';
  12. import { Scene } from '../../scene';
  13. import { _TypeStore } from '../../Misc/typeStore';
  14. /**
  15. * Defines a block that can be used inside a node based material
  16. */
  17. export class NodeMaterialBlock {
  18. private _buildId: number;
  19. private _buildTarget: NodeMaterialBlockTargets;
  20. private _target: NodeMaterialBlockTargets;
  21. private _isFinalMerger = false;
  22. private _isInput = false;
  23. /** @hidden */
  24. public _inputs = new Array<NodeMaterialConnectionPoint>();
  25. /** @hidden */
  26. public _outputs = new Array<NodeMaterialConnectionPoint>();
  27. /**
  28. * Gets or sets the name of the block
  29. */
  30. public name: string;
  31. /**
  32. * Gets or sets the unique id of the node
  33. */
  34. public uniqueId: number;
  35. /**
  36. * Gets a boolean indicating that this block is an end block (e.g. it is generating a system value)
  37. */
  38. public get isFinalMerger(): boolean {
  39. return this._isFinalMerger;
  40. }
  41. /**
  42. * Gets a boolean indicating that this block is an input (e.g. it sends data to the shader)
  43. */
  44. public get isInput(): boolean {
  45. return this._isInput;
  46. }
  47. /**
  48. * Gets or sets the build Id
  49. */
  50. public get buildId(): number {
  51. return this._buildId;
  52. }
  53. public set buildId(value: number) {
  54. this._buildId = value;
  55. }
  56. /**
  57. * Gets or sets the target of the block
  58. */
  59. public get target() {
  60. return this._target;
  61. }
  62. public set target(value: NodeMaterialBlockTargets) {
  63. if ((this._target & value) !== 0) {
  64. return;
  65. }
  66. this._target = value;
  67. }
  68. /**
  69. * Gets the list of input points
  70. */
  71. public get inputs(): NodeMaterialConnectionPoint[] {
  72. return this._inputs;
  73. }
  74. /** Gets the list of output points */
  75. public get outputs(): NodeMaterialConnectionPoint[] {
  76. return this._outputs;
  77. }
  78. /**
  79. * Find an input by its name
  80. * @param name defines the name of the input to look for
  81. * @returns the input or null if not found
  82. */
  83. public getInputByName(name: string) {
  84. let filter = this._inputs.filter((e) => e.name === name);
  85. if (filter.length) {
  86. return filter[0];
  87. }
  88. return null;
  89. }
  90. /**
  91. * Find an output by its name
  92. * @param name defines the name of the outputto look for
  93. * @returns the output or null if not found
  94. */
  95. public getOutputByName(name: string) {
  96. let filter = this._outputs.filter((e) => e.name === name);
  97. if (filter.length) {
  98. return filter[0];
  99. }
  100. return null;
  101. }
  102. /**
  103. * Creates a new NodeMaterialBlock
  104. * @param name defines the block name
  105. * @param target defines the target of that block (Vertex by default)
  106. * @param isFinalMerger defines a boolean indicating that this block is an end block (e.g. it is generating a system value). Default is false
  107. * @param isInput defines a boolean indicating that this block is an input (e.g. it sends data to the shader). Default is false
  108. */
  109. public constructor(name: string, target = NodeMaterialBlockTargets.Vertex, isFinalMerger = false, isInput = false) {
  110. this.name = name;
  111. this._target = target;
  112. this._isFinalMerger = isFinalMerger;
  113. this._isInput = isInput;
  114. this.uniqueId = UniqueIdGenerator.UniqueId;
  115. }
  116. /**
  117. * Initialize the block and prepare the context for build
  118. * @param state defines the state that will be used for the build
  119. */
  120. public initialize(state: NodeMaterialBuildState) {
  121. // Do nothing
  122. }
  123. /**
  124. * Bind data to effect. Will only be called for blocks with isBindable === true
  125. * @param effect defines the effect to bind data to
  126. * @param nodeMaterial defines the hosting NodeMaterial
  127. * @param mesh defines the mesh that will be rendered
  128. */
  129. public bind(effect: Effect, nodeMaterial: NodeMaterial, mesh?: Mesh) {
  130. // Do nothing
  131. }
  132. protected _declareOutput(output: NodeMaterialConnectionPoint, state: NodeMaterialBuildState): string {
  133. return `${state._getGLType(output.type)} ${output.associatedVariableName}`;
  134. }
  135. protected _writeVariable(currentPoint: NodeMaterialConnectionPoint): string {
  136. let connectionPoint = currentPoint.connectedPoint;
  137. if (connectionPoint) {
  138. return `${currentPoint.associatedVariableName}`;
  139. }
  140. return `0.`;
  141. }
  142. protected _writeFloat(value: number) {
  143. let stringVersion = value.toString();
  144. if (stringVersion.indexOf(".") === -1) {
  145. stringVersion += ".0";
  146. }
  147. return `${stringVersion}`;
  148. }
  149. /**
  150. * Gets the current class name e.g. "NodeMaterialBlock"
  151. * @returns the class name
  152. */
  153. public getClassName() {
  154. return "NodeMaterialBlock";
  155. }
  156. /**
  157. * Register a new input. Must be called inside a block constructor
  158. * @param name defines the connection point name
  159. * @param type defines the connection point type
  160. * @param isOptional defines a boolean indicating that this input can be omitted
  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 registerInput(name: string, type: NodeMaterialBlockConnectionPointTypes, isOptional: boolean = false, target?: NodeMaterialBlockTargets) {
  165. let point = new NodeMaterialConnectionPoint(name, this);
  166. point.type = type;
  167. point.isOptional = isOptional;
  168. if (target) {
  169. point.target = target;
  170. }
  171. this._inputs.push(point);
  172. return this;
  173. }
  174. /**
  175. * Register a new output. Must be called inside a block constructor
  176. * @param name defines the connection point name
  177. * @param type defines the connection point type
  178. * @param target defines the target to use to limit the connection point (will be VetexAndFragment by default)
  179. * @returns the current block
  180. */
  181. public registerOutput(name: string, type: NodeMaterialBlockConnectionPointTypes, target?: NodeMaterialBlockTargets) {
  182. let point = new NodeMaterialConnectionPoint(name, this);
  183. point.type = type;
  184. if (target) {
  185. point.target = target;
  186. }
  187. this._outputs.push(point);
  188. return this;
  189. }
  190. /**
  191. * Will return the first available input e.g. the first one which is not an uniform or an attribute
  192. * @param forOutput defines an optional connection point to check compatibility with
  193. * @returns the first available input or null
  194. */
  195. public getFirstAvailableInput(forOutput: Nullable<NodeMaterialConnectionPoint> = null) {
  196. for (var input of this._inputs) {
  197. if (!input.connectedPoint) {
  198. if (!forOutput || (forOutput.type === input.type) || (input.type === NodeMaterialBlockConnectionPointTypes.AutoDetect)) {
  199. return input;
  200. }
  201. }
  202. }
  203. return null;
  204. }
  205. /**
  206. * Will return the first available output e.g. the first one which is not yet connected and not a varying
  207. * @param forBlock defines an optional block to check compatibility with
  208. * @returns the first available input or null
  209. */
  210. public getFirstAvailableOutput(forBlock: Nullable<NodeMaterialBlock> = null) {
  211. for (var output of this._outputs) {
  212. if (!forBlock || !forBlock.target || forBlock.target === NodeMaterialBlockTargets.Neutral || (forBlock.target & output.target) !== 0) {
  213. return output;
  214. }
  215. }
  216. return null;
  217. }
  218. /**
  219. * Gets the sibling of the given output
  220. * @param current defines the current output
  221. * @returns the next output in the list or null
  222. */
  223. public getSiblingOutput(current: NodeMaterialConnectionPoint) {
  224. let index = this._outputs.indexOf(current);
  225. if (index === -1 || index >= this._outputs.length) {
  226. return null;
  227. }
  228. return this._outputs[index + 1];
  229. }
  230. /**
  231. * Connect current block with another block
  232. * @param other defines the block to connect with
  233. * @param options define the various options to help pick the right connections
  234. * @returns the current block
  235. */
  236. public connectTo(other: NodeMaterialBlock, options?: {
  237. input?: string,
  238. output?: string,
  239. outputSwizzle?: string
  240. }) {
  241. if (this._outputs.length === 0) {
  242. return;
  243. }
  244. let output = options && options.output ? this.getOutputByName(options.output) : this.getFirstAvailableOutput(other);
  245. let notFound = true;
  246. while (notFound) {
  247. let input = options && options.input ? other.getInputByName(options.input) : other.getFirstAvailableInput(output);
  248. if (output && input && output.canConnectTo(input)) {
  249. output.connectTo(input);
  250. notFound = false;
  251. } else if (!output) {
  252. throw "Unable to find a compatible match";
  253. } else {
  254. output = this.getSiblingOutput(output);
  255. }
  256. }
  257. return this;
  258. }
  259. protected _buildBlock(state: NodeMaterialBuildState) {
  260. // Empty. Must be defined by child nodes
  261. }
  262. /**
  263. * Add uniforms, samplers and uniform buffers at compilation time
  264. * @param state defines the state to update
  265. * @param nodeMaterial defines the node material requesting the update
  266. * @param defines defines the material defines to update
  267. */
  268. public updateUniformsAndSamples(state: NodeMaterialBuildState, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines) {
  269. // Do nothing
  270. }
  271. /**
  272. * Add potential fallbacks if shader compilation fails
  273. * @param mesh defines the mesh to be rendered
  274. * @param fallbacks defines the current prioritized list of fallbacks
  275. */
  276. public provideFallbacks(mesh: AbstractMesh, fallbacks: EffectFallbacks) {
  277. // Do nothing
  278. }
  279. /**
  280. * Update defines for shader compilation
  281. * @param mesh defines the mesh to be rendered
  282. * @param nodeMaterial defines the node material requesting the update
  283. * @param defines defines the material defines to update
  284. * @param useInstances specifies that instances should be used
  285. */
  286. public prepareDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  287. // Do nothing
  288. }
  289. /**
  290. * Initialize defines for shader compilation
  291. * @param mesh defines the mesh to be rendered
  292. * @param nodeMaterial defines the node material requesting the update
  293. * @param defines defines the material defines to be prepared
  294. * @param useInstances specifies that instances should be used
  295. */
  296. public initializeDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  297. // Do nothing
  298. }
  299. /**
  300. * Lets the block try to connect some inputs automatically
  301. */
  302. public autoConfigure() {
  303. // Do nothing
  304. }
  305. /**
  306. * Function called when a block is declared as repeatable content generator
  307. * @param vertexShaderState defines the current compilation state for the vertex shader
  308. * @param fragmentShaderState defines the current compilation state for the fragment shader
  309. * @param mesh defines the mesh to be rendered
  310. * @param defines defines the material defines to update
  311. */
  312. public replaceRepeatableContent(vertexShaderState: NodeMaterialBuildState, fragmentShaderState: NodeMaterialBuildState, mesh: AbstractMesh, defines: NodeMaterialDefines) {
  313. // Do nothing
  314. }
  315. /**
  316. * Checks if the block is ready
  317. * @param mesh defines the mesh to be rendered
  318. * @param nodeMaterial defines the node material requesting the update
  319. * @param defines defines the material defines to update
  320. * @param useInstances specifies that instances should be used
  321. * @returns true if the block is ready
  322. */
  323. public isReady(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  324. return true;
  325. }
  326. private _processBuild(block: NodeMaterialBlock, state: NodeMaterialBuildState, input: NodeMaterialConnectionPoint) {
  327. block.build(state);
  328. if (state._vertexState && (block.target & this.target) === 0) { // context switch! We need a varying
  329. if ((!block.isInput && state.target !== block._buildTarget) // block was already emitted by vertex shader
  330. || (block.isInput && (block as InputBlock).isAttribute) // block is an attribute
  331. ) {
  332. let connectedPoint = input.connectedPoint!;
  333. state._vertexState._emitVaryingFromString("v_" + connectedPoint.associatedVariableName, state._getGLType(connectedPoint.type));
  334. state._vertexState.compilationString += `${"v_" + connectedPoint.associatedVariableName} = ${connectedPoint.associatedVariableName};\r\n`;
  335. input.associatedVariableName = "v_" + connectedPoint.associatedVariableName;
  336. input._enforceAssociatedVariableName = true;
  337. }
  338. }
  339. }
  340. /**
  341. * Compile the current node and generate the shader code
  342. * @param state defines the current compilation state (uniforms, samplers, current string)
  343. * @param contextSwitched indicates that the previous block was built for a different context (vertex vs. fragment)
  344. * @returns true if already built
  345. */
  346. public build(state: NodeMaterialBuildState, contextSwitched = false): boolean {
  347. if (this._buildId === state.sharedData.buildId) {
  348. return true;
  349. }
  350. // Check if "parent" blocks are compiled
  351. for (var input of this._inputs) {
  352. if (!input.connectedPoint) {
  353. if (!input.isOptional) { // Emit a warning
  354. state.sharedData.checks.notConnectedNonOptionalInputs.push(input);
  355. }
  356. continue;
  357. }
  358. if (this.target !== NodeMaterialBlockTargets.Neutral) {
  359. if ((input.target & this.target!) === 0) {
  360. continue;
  361. }
  362. if ((input.target & state.target!) === 0) {
  363. continue;
  364. }
  365. }
  366. let block = input.connectedPoint.ownerBlock;
  367. if (block && block !== this) {
  368. this._processBuild(block, state, input);
  369. }
  370. }
  371. if (this._buildId === state.sharedData.buildId) {
  372. return true; // Need to check again as inputs can be connected multiple time to this endpoint
  373. }
  374. // Logs
  375. if (state.sharedData.verbose) {
  376. console.log(`${state.target === NodeMaterialBlockTargets.Vertex ? "Vertex shader" : "Fragment shader"}: Building ${this.name} [${this.getClassName()}]`);
  377. }
  378. if (!this.isInput) {
  379. /** Prepare outputs */
  380. for (var output of this._outputs) {
  381. if (this.target !== NodeMaterialBlockTargets.Neutral) {
  382. if ((output.target & this.target!) === 0) {
  383. continue;
  384. }
  385. if ((output.target & state.target!) === 0) {
  386. continue;
  387. }
  388. }
  389. if (!output.associatedVariableName) {
  390. output.associatedVariableName = state._getFreeVariableName(output.name);
  391. }
  392. }
  393. }
  394. // Checks final outputs
  395. if (this.isFinalMerger) {
  396. switch (state.target) {
  397. case NodeMaterialBlockTargets.Vertex:
  398. state.sharedData.checks.emitVertex = true;
  399. break;
  400. case NodeMaterialBlockTargets.Fragment:
  401. state.sharedData.checks.emitFragment = true;
  402. break;
  403. }
  404. }
  405. if (!this.isInput && state.sharedData.emitComments) {
  406. state.compilationString += `\r\n//${this.name}\r\n`;
  407. }
  408. this._buildBlock(state);
  409. this._buildId = state.sharedData.buildId;
  410. this._buildTarget = state.target;
  411. // Compile connected blocks
  412. for (var output of this._outputs) {
  413. if ((output.target & state.target) === 0) {
  414. continue;
  415. }
  416. for (var endpoint of output.endpoints) {
  417. let block = endpoint.ownerBlock;
  418. if (block && (block.target & state.target) !== 0) {
  419. this._processBuild(block, state, endpoint);
  420. }
  421. }
  422. }
  423. return false;
  424. }
  425. /**
  426. * Clone the current block to a new identical block
  427. * @param scene defines the hosting scene
  428. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  429. * @returns a copy of the current block
  430. */
  431. public clone(scene: Scene, rootUrl: string = "") {
  432. let serializationObject = this.serialize();
  433. let blockType = _TypeStore.GetClass(serializationObject.customType);
  434. if (blockType) {
  435. let block: NodeMaterialBlock = new blockType();
  436. block._deserialize(serializationObject, scene, rootUrl);
  437. return block;
  438. }
  439. return null;
  440. }
  441. /**
  442. * Serializes this block in a JSON representation
  443. * @returns the serialized block object
  444. */
  445. public serialize(): any {
  446. let serializationObject: any = {};
  447. serializationObject.customType = "BABYLON." + this.getClassName();
  448. serializationObject.id = this.uniqueId;
  449. serializationObject.name = this.name;
  450. serializationObject.inputs = [];
  451. for (var input of this.inputs) {
  452. serializationObject.inputs.push(input.serialize());
  453. }
  454. return serializationObject;
  455. }
  456. /** @hidden */
  457. public _deserialize(serializationObject: any, scene: Scene, rootUrl: string) {
  458. this.name = serializationObject.name ;
  459. }
  460. }