nodeMaterialBlock.ts 22 KB

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