NodeBuilder.js 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969
  1. import NodeUniform from './NodeUniform.js';
  2. import NodeAttribute from './NodeAttribute.js';
  3. import NodeVarying from './NodeVarying.js';
  4. import NodeVar from './NodeVar.js';
  5. import NodeCode from './NodeCode.js';
  6. import NodeCache from './NodeCache.js';
  7. import ParameterNode from './ParameterNode.js';
  8. import StructType from './StructType.js';
  9. import FunctionNode from '../code/FunctionNode.js';
  10. import NodeMaterial from '../../materials/nodes/NodeMaterial.js';
  11. import { getTypeFromLength } from './NodeUtils.js';
  12. import { NodeUpdateType, defaultBuildStages, shaderStages } from './constants.js';
  13. import {
  14. NumberNodeUniform, Vector2NodeUniform, Vector3NodeUniform, Vector4NodeUniform,
  15. ColorNodeUniform, Matrix2NodeUniform, Matrix3NodeUniform, Matrix4NodeUniform
  16. } from '../../renderers/common/nodes/NodeUniform.js';
  17. import { stack } from './StackNode.js';
  18. import { getCurrentStack, setCurrentStack } from '../tsl/TSLBase.js';
  19. import CubeRenderTarget from '../../renderers/common/CubeRenderTarget.js';
  20. import ChainMap from '../../renderers/common/ChainMap.js';
  21. import BindGroup from '../../renderers/common/BindGroup.js';
  22. import { REVISION, IntType, UnsignedIntType, LinearFilter, LinearMipmapNearestFilter, NearestMipmapLinearFilter, LinearMipmapLinearFilter } from '../../constants.js';
  23. import { RenderTarget } from '../../core/RenderTarget.js';
  24. import { Color } from '../../math/Color.js';
  25. import { Vector2 } from '../../math/Vector2.js';
  26. import { Vector3 } from '../../math/Vector3.js';
  27. import { Vector4 } from '../../math/Vector4.js';
  28. import { Float16BufferAttribute } from '../../core/BufferAttribute.js';
  29. import { warn, error } from '../../utils.js';
  30. const rendererCache = new WeakMap();
  31. const typeFromArray = new Map( [
  32. [ Int8Array, 'int' ],
  33. [ Int16Array, 'int' ],
  34. [ Int32Array, 'int' ],
  35. [ Uint8Array, 'uint' ],
  36. [ Uint16Array, 'uint' ],
  37. [ Uint32Array, 'uint' ],
  38. [ Float32Array, 'float' ]
  39. ] );
  40. const toFloat = ( value ) => {
  41. if ( /e/g.test( value ) ) {
  42. return String( value ).replace( /\+/g, '' );
  43. } else {
  44. value = Number( value );
  45. return value + ( value % 1 ? '' : '.0' );
  46. }
  47. };
  48. /**
  49. * Base class for builders which generate a shader program based
  50. * on a 3D object and its node material definition.
  51. */
  52. class NodeBuilder {
  53. /**
  54. * Constructs a new node builder.
  55. *
  56. * @param {Object3D} object - The 3D object.
  57. * @param {Renderer} renderer - The current renderer.
  58. * @param {NodeParser} parser - A reference to a node parser.
  59. */
  60. constructor( object, renderer, parser ) {
  61. /**
  62. * The 3D object.
  63. *
  64. * @type {Object3D}
  65. */
  66. this.object = object;
  67. /**
  68. * The material of the 3D object.
  69. *
  70. * @type {?Material}
  71. */
  72. this.material = ( object && object.material ) || null;
  73. /**
  74. * The geometry of the 3D object.
  75. *
  76. * @type {?BufferGeometry}
  77. */
  78. this.geometry = ( object && object.geometry ) || null;
  79. /**
  80. * The current renderer.
  81. *
  82. * @type {Renderer}
  83. */
  84. this.renderer = renderer;
  85. /**
  86. * A reference to a node parser.
  87. *
  88. * @type {NodeParser}
  89. */
  90. this.parser = parser;
  91. /**
  92. * The scene the 3D object belongs to.
  93. *
  94. * @type {?Scene}
  95. * @default null
  96. */
  97. this.scene = null;
  98. /**
  99. * The camera the 3D object is rendered with.
  100. *
  101. * @type {?Camera}
  102. * @default null
  103. */
  104. this.camera = null;
  105. /**
  106. * A list of all nodes the builder is processing
  107. * for this 3D object.
  108. *
  109. * @type {Array<Node>}
  110. */
  111. this.nodes = [];
  112. /**
  113. * A list of all sequential nodes.
  114. *
  115. * @type {Array<Node>}
  116. */
  117. this.sequentialNodes = [];
  118. /**
  119. * A list of all nodes which {@link Node#update} method should be executed.
  120. *
  121. * @type {Array<Node>}
  122. */
  123. this.updateNodes = [];
  124. /**
  125. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  126. *
  127. * @type {Array<Node>}
  128. */
  129. this.updateBeforeNodes = [];
  130. /**
  131. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  132. *
  133. * @type {Array<Node>}
  134. */
  135. this.updateAfterNodes = [];
  136. /**
  137. * A dictionary that assigns each node to a unique hash.
  138. *
  139. * @type {Object<number,Node>}
  140. */
  141. this.hashNodes = {};
  142. /**
  143. * A reference to a node material observer.
  144. *
  145. * @type {?NodeMaterialObserver}
  146. * @default null
  147. */
  148. this.observer = null;
  149. /**
  150. * A reference to the current lights node.
  151. *
  152. * @type {?LightsNode}
  153. * @default null
  154. */
  155. this.lightsNode = null;
  156. /**
  157. * A reference to the current environment node.
  158. *
  159. * @type {?Node}
  160. * @default null
  161. */
  162. this.environmentNode = null;
  163. /**
  164. * A reference to the current fog node.
  165. *
  166. * @type {?Node}
  167. * @default null
  168. */
  169. this.fogNode = null;
  170. /**
  171. * The current clipping context.
  172. *
  173. * @type {?ClippingContext}
  174. */
  175. this.clippingContext = null;
  176. /**
  177. * The generated vertex shader.
  178. *
  179. * @type {?string}
  180. */
  181. this.vertexShader = null;
  182. /**
  183. * The generated fragment shader.
  184. *
  185. * @type {?string}
  186. */
  187. this.fragmentShader = null;
  188. /**
  189. * The generated compute shader.
  190. *
  191. * @type {?string}
  192. */
  193. this.computeShader = null;
  194. /**
  195. * Nodes used in the primary flow of code generation.
  196. *
  197. * @type {Object<string,Array<Node>>}
  198. */
  199. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  200. /**
  201. * Nodes code from `.flowNodes`.
  202. *
  203. * @type {Object<string,string>}
  204. */
  205. this.flowCode = { vertex: '', fragment: '', compute: '' };
  206. /**
  207. * This dictionary holds the node uniforms of the builder.
  208. * The uniforms are maintained in an array for each shader stage.
  209. *
  210. * @type {Object}
  211. */
  212. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  213. /**
  214. * This dictionary holds the output structs of the builder.
  215. * The structs are maintained in an array for each shader stage.
  216. *
  217. * @type {Object}
  218. */
  219. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  220. /**
  221. * This dictionary holds the types of the builder.
  222. *
  223. * @type {Object}
  224. */
  225. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  226. /**
  227. * This dictionary holds the bindings for each shader stage.
  228. *
  229. * @type {Object}
  230. */
  231. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  232. /**
  233. * This dictionary maintains the binding indices per bind group.
  234. *
  235. * @type {Object}
  236. */
  237. this.bindingsIndexes = {};
  238. /**
  239. * Reference to the array of bind groups.
  240. *
  241. * @type {?Array<BindGroup>}
  242. */
  243. this.bindGroups = null;
  244. /**
  245. * This array holds the node attributes of this builder
  246. * created via {@link AttributeNode}.
  247. *
  248. * @type {Array<NodeAttribute>}
  249. */
  250. this.attributes = [];
  251. /**
  252. * This array holds the node attributes of this builder
  253. * created via {@link BufferAttributeNode}.
  254. *
  255. * @type {Array<NodeAttribute>}
  256. */
  257. this.bufferAttributes = [];
  258. /**
  259. * This array holds the node varyings of this builder.
  260. *
  261. * @type {Array<NodeVarying>}
  262. */
  263. this.varyings = [];
  264. /**
  265. * This dictionary holds the (native) node codes of this builder.
  266. * The codes are maintained in an array for each shader stage.
  267. *
  268. * @type {Object<string,Array<NodeCode>>}
  269. */
  270. this.codes = {};
  271. /**
  272. * This dictionary holds the node variables of this builder.
  273. * The variables are maintained in an array for each shader stage.
  274. * This dictionary is also used to count the number of variables
  275. * according to their type (const, vars).
  276. *
  277. * @type {Object<string,Array<NodeVar>|number>}
  278. */
  279. this.vars = {};
  280. /**
  281. * This dictionary holds the declarations for each shader stage.
  282. *
  283. * @type {Object}
  284. */
  285. this.declarations = {};
  286. /**
  287. * Current code flow.
  288. * All code generated in this stack will be stored in `.flow`.
  289. *
  290. * @type {{code: string}}
  291. */
  292. this.flow = { code: '' };
  293. /**
  294. * A chain of nodes.
  295. * Used to check recursive calls in node-graph.
  296. *
  297. * @type {Array<Node>}
  298. */
  299. this.chaining = [];
  300. /**
  301. * The current stack.
  302. * This reflects the current process in the code block hierarchy,
  303. * it is useful to know if the current process is inside a conditional for example.
  304. *
  305. * @type {StackNode}
  306. */
  307. this.stack = stack();
  308. /**
  309. * List of stack nodes.
  310. * The current stack hierarchy is stored in an array.
  311. *
  312. * @type {Array<StackNode>}
  313. */
  314. this.stacks = [];
  315. /**
  316. * A tab value. Used for shader string generation.
  317. *
  318. * @type {string}
  319. * @default '\t'
  320. */
  321. this.tab = '\t';
  322. /**
  323. * Reference to the current function node.
  324. *
  325. * @type {?FunctionNode}
  326. * @default null
  327. */
  328. this.currentFunctionNode = null;
  329. /**
  330. * The builder's context.
  331. *
  332. * @type {Object}
  333. */
  334. this.context = {
  335. material: this.material
  336. };
  337. /**
  338. * The builder's cache.
  339. *
  340. * @type {NodeCache}
  341. */
  342. this.cache = new NodeCache();
  343. /**
  344. * Since the {@link NodeBuilder#cache} might be temporarily
  345. * overwritten by other caches, this member retains the reference
  346. * to the builder's own cache.
  347. *
  348. * @type {NodeCache}
  349. * @default this.cache
  350. */
  351. this.globalCache = this.cache;
  352. this.flowsData = new WeakMap();
  353. /**
  354. * The current shader stage.
  355. *
  356. * @type {?('vertex'|'fragment'|'compute'|'any')}
  357. */
  358. this.shaderStage = null;
  359. /**
  360. * The current build stage.
  361. *
  362. * @type {?('setup'|'analyze'|'generate')}
  363. */
  364. this.buildStage = null;
  365. /**
  366. * The sub-build layers.
  367. *
  368. * @type {Array<SubBuildNode>}
  369. * @default []
  370. */
  371. this.subBuildLayers = [];
  372. /**
  373. * The current stack of nodes.
  374. *
  375. * @type {?StackNode}
  376. * @default null
  377. */
  378. this.currentStack = null;
  379. /**
  380. * The current sub-build TSL function(Fn).
  381. *
  382. * @type {?string}
  383. * @default null
  384. */
  385. this.subBuildFn = null;
  386. }
  387. /**
  388. * Returns the bind groups of the current renderer.
  389. *
  390. * @return {ChainMap} The cache.
  391. */
  392. getBindGroupsCache() {
  393. let bindGroupsCache = rendererCache.get( this.renderer );
  394. if ( bindGroupsCache === undefined ) {
  395. bindGroupsCache = new ChainMap();
  396. rendererCache.set( this.renderer, bindGroupsCache );
  397. }
  398. return bindGroupsCache;
  399. }
  400. /**
  401. * Factory method for creating an instance of {@link RenderTarget} with the given
  402. * dimensions and options.
  403. *
  404. * @param {number} width - The width of the render target.
  405. * @param {number} height - The height of the render target.
  406. * @param {Object} options - The options of the render target.
  407. * @return {RenderTarget} The render target.
  408. */
  409. createRenderTarget( width, height, options ) {
  410. return new RenderTarget( width, height, options );
  411. }
  412. /**
  413. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  414. * dimensions and options.
  415. *
  416. * @param {number} size - The size of the cube render target.
  417. * @param {Object} options - The options of the cube render target.
  418. * @return {CubeRenderTarget} The cube render target.
  419. */
  420. createCubeRenderTarget( size, options ) {
  421. return new CubeRenderTarget( size, options );
  422. }
  423. /**
  424. * Whether the given node is included in the internal array of nodes or not.
  425. *
  426. * @param {Node} node - The node to test.
  427. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  428. */
  429. includes( node ) {
  430. return this.nodes.includes( node );
  431. }
  432. /**
  433. * Returns the output struct name which is required by
  434. * {@link OutputStructNode}.
  435. *
  436. * @abstract
  437. * @return {string} The name of the output struct.
  438. */
  439. getOutputStructName() {}
  440. /**
  441. * Returns a bind group for the given group name and binding.
  442. *
  443. * @private
  444. * @param {string} groupName - The group name.
  445. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  446. * @return {BindGroup} The bind group
  447. */
  448. _getBindGroup( groupName, bindings ) {
  449. const bindGroupsCache = this.getBindGroupsCache();
  450. //
  451. const bindingsArray = [];
  452. let sharedGroup = true;
  453. for ( const binding of bindings ) {
  454. bindingsArray.push( binding );
  455. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  456. }
  457. //
  458. let bindGroup;
  459. if ( sharedGroup ) {
  460. bindGroup = bindGroupsCache.get( bindingsArray );
  461. if ( bindGroup === undefined ) {
  462. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  463. bindGroupsCache.set( bindingsArray, bindGroup );
  464. }
  465. } else {
  466. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  467. }
  468. return bindGroup;
  469. }
  470. /**
  471. * Returns an array of node uniform groups for the given group name and shader stage.
  472. *
  473. * @param {string} groupName - The group name.
  474. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  475. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  476. */
  477. getBindGroupArray( groupName, shaderStage ) {
  478. const bindings = this.bindings[ shaderStage ];
  479. let bindGroup = bindings[ groupName ];
  480. if ( bindGroup === undefined ) {
  481. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  482. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  483. }
  484. bindings[ groupName ] = bindGroup = [];
  485. }
  486. return bindGroup;
  487. }
  488. /**
  489. * Returns a list bindings of all shader stages separated by groups.
  490. *
  491. * @return {Array<BindGroup>} The list of bindings.
  492. */
  493. getBindings() {
  494. let bindingsGroups = this.bindGroups;
  495. if ( bindingsGroups === null ) {
  496. const groups = {};
  497. const bindings = this.bindings;
  498. for ( const shaderStage of shaderStages ) {
  499. for ( const groupName in bindings[ shaderStage ] ) {
  500. const uniforms = bindings[ shaderStage ][ groupName ];
  501. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  502. groupUniforms.push( ...uniforms );
  503. }
  504. }
  505. bindingsGroups = [];
  506. for ( const groupName in groups ) {
  507. const group = groups[ groupName ];
  508. const bindingsGroup = this._getBindGroup( groupName, group );
  509. bindingsGroups.push( bindingsGroup );
  510. }
  511. this.bindGroups = bindingsGroups;
  512. }
  513. return bindingsGroups;
  514. }
  515. /**
  516. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  517. */
  518. sortBindingGroups() {
  519. const bindingsGroups = this.getBindings();
  520. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  521. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  522. const bindingGroup = bindingsGroups[ i ];
  523. this.bindingsIndexes[ bindingGroup.name ].group = i;
  524. bindingGroup.index = i;
  525. }
  526. }
  527. /**
  528. * The builder maintains each node in a hash-based dictionary.
  529. * This method sets the given node (value) with the given hash (key) into this dictionary.
  530. *
  531. * @param {Node} node - The node to add.
  532. * @param {number} hash - The hash of the node.
  533. */
  534. setHashNode( node, hash ) {
  535. this.hashNodes[ hash ] = node;
  536. }
  537. /**
  538. * Adds a node to this builder.
  539. *
  540. * @param {Node} node - The node to add.
  541. */
  542. addNode( node ) {
  543. if ( this.nodes.includes( node ) === false ) {
  544. this.nodes.push( node );
  545. this.setHashNode( node, node.getHash( this ) );
  546. }
  547. }
  548. /**
  549. * It is used to add Nodes that will be used as FRAME and RENDER events,
  550. * and need to follow a certain sequence in the calls to work correctly.
  551. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  552. *
  553. * @param {Node} node - The node to add.
  554. */
  555. addSequentialNode( node ) {
  556. if ( this.sequentialNodes.includes( node ) === false ) {
  557. this.sequentialNodes.push( node );
  558. }
  559. }
  560. /**
  561. * Checks the update types of nodes
  562. */
  563. buildUpdateNodes() {
  564. for ( const node of this.nodes ) {
  565. const updateType = node.getUpdateType();
  566. if ( updateType !== NodeUpdateType.NONE ) {
  567. this.updateNodes.push( node );
  568. }
  569. }
  570. for ( const node of this.sequentialNodes ) {
  571. const updateBeforeType = node.getUpdateBeforeType();
  572. const updateAfterType = node.getUpdateAfterType();
  573. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  574. this.updateBeforeNodes.push( node );
  575. }
  576. if ( updateAfterType !== NodeUpdateType.NONE ) {
  577. this.updateAfterNodes.push( node );
  578. }
  579. }
  580. }
  581. /**
  582. * A reference the current node which is the
  583. * last node in the chain of nodes.
  584. *
  585. * @type {Node}
  586. */
  587. get currentNode() {
  588. return this.chaining[ this.chaining.length - 1 ];
  589. }
  590. /**
  591. * Whether the given texture is filtered or not.
  592. *
  593. * @param {Texture} texture - The texture to check.
  594. * @return {boolean} Whether the given texture is filtered or not.
  595. */
  596. isFilteredTexture( texture ) {
  597. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  598. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  599. }
  600. /**
  601. * Adds the given node to the internal node chain.
  602. * This is used to check recursive calls in node-graph.
  603. *
  604. * @param {Node} node - The node to add.
  605. */
  606. addChain( node ) {
  607. /*
  608. if ( this.chaining.indexOf( node ) !== - 1 ) {
  609. warn( 'Recursive node: ', node );
  610. }
  611. */
  612. this.chaining.push( node );
  613. }
  614. /**
  615. * Removes the given node from the internal node chain.
  616. *
  617. * @param {Node} node - The node to remove.
  618. */
  619. removeChain( node ) {
  620. const lastChain = this.chaining.pop();
  621. if ( lastChain !== node ) {
  622. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  623. }
  624. }
  625. /**
  626. * Returns the native shader method name for a given generic name. E.g.
  627. * the method name `textureDimensions` matches the WGSL name but must be
  628. * resolved to `textureSize` in GLSL.
  629. *
  630. * @abstract
  631. * @param {string} method - The method name to resolve.
  632. * @return {string} The resolved method name.
  633. */
  634. getMethod( method ) {
  635. return method;
  636. }
  637. /**
  638. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  639. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  640. *
  641. * @abstract
  642. * @param {string} condSnippet - The condition determining which expression gets resolved.
  643. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  644. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  645. * @return {string} The resolved method name.
  646. */
  647. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  648. return null;
  649. }
  650. /**
  651. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  652. *
  653. * @param {number} hash - The hash of the node.
  654. * @return {Node} The found node.
  655. */
  656. getNodeFromHash( hash ) {
  657. return this.hashNodes[ hash ];
  658. }
  659. /**
  660. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  661. *
  662. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  663. * @param {Node} node - The node to add.
  664. * @return {Node} The node.
  665. */
  666. addFlow( shaderStage, node ) {
  667. this.flowNodes[ shaderStage ].push( node );
  668. return node;
  669. }
  670. /**
  671. * Sets builder's context.
  672. *
  673. * @param {Object} context - The context to set.
  674. */
  675. setContext( context ) {
  676. this.context = context;
  677. }
  678. /**
  679. * Returns the builder's current context.
  680. *
  681. * @return {Object} The builder's current context.
  682. */
  683. getContext() {
  684. return this.context;
  685. }
  686. /**
  687. * Gets a context used in shader construction that can be shared across different materials.
  688. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  689. *
  690. * @return {Object} The builder's current context without material.
  691. */
  692. getSharedContext() {
  693. const context = { ...this.context };
  694. delete context.material;
  695. return this.context;
  696. }
  697. /**
  698. * Sets builder's cache.
  699. *
  700. * @param {NodeCache} cache - The cache to set.
  701. */
  702. setCache( cache ) {
  703. this.cache = cache;
  704. }
  705. /**
  706. * Returns the builder's current cache.
  707. *
  708. * @return {NodeCache} The builder's current cache.
  709. */
  710. getCache() {
  711. return this.cache;
  712. }
  713. /**
  714. * Returns a cache for the given node.
  715. *
  716. * @param {Node} node - The node.
  717. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  718. * @return {NodeCache} The cache.
  719. */
  720. getCacheFromNode( node, parent = true ) {
  721. const data = this.getDataFromNode( node );
  722. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  723. return data.cache;
  724. }
  725. /**
  726. * Whether the requested feature is available or not.
  727. *
  728. * @abstract
  729. * @param {string} name - The requested feature.
  730. * @return {boolean} Whether the requested feature is supported or not.
  731. */
  732. isAvailable( /*name*/ ) {
  733. return false;
  734. }
  735. /**
  736. * Returns the vertexIndex input variable as a native shader string.
  737. *
  738. * @abstract
  739. * @return {string} The instanceIndex shader string.
  740. */
  741. getVertexIndex() {
  742. warn( 'Abstract function.' );
  743. }
  744. /**
  745. * Contextually returns either the vertex stage instance index builtin
  746. * or the linearized index of an compute invocation within a grid of workgroups.
  747. *
  748. * @abstract
  749. * @return {string} The instanceIndex shader string.
  750. */
  751. getInstanceIndex() {
  752. warn( 'Abstract function.' );
  753. }
  754. /**
  755. * Returns the drawIndex input variable as a native shader string.
  756. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  757. *
  758. * @abstract
  759. * @return {?string} The drawIndex shader string.
  760. */
  761. getDrawIndex() {
  762. warn( 'Abstract function.' );
  763. }
  764. /**
  765. * Returns the frontFacing input variable as a native shader string.
  766. *
  767. * @abstract
  768. * @return {string} The frontFacing shader string.
  769. */
  770. getFrontFacing() {
  771. warn( 'Abstract function.' );
  772. }
  773. /**
  774. * Returns the fragCoord input variable as a native shader string.
  775. *
  776. * @abstract
  777. * @return {string} The fragCoord shader string.
  778. */
  779. getFragCoord() {
  780. warn( 'Abstract function.' );
  781. }
  782. /**
  783. * Whether to flip texture data along its vertical axis or not. WebGL needs
  784. * this method evaluate to `true`, WebGPU to `false`.
  785. *
  786. * @abstract
  787. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  788. */
  789. isFlipY() {
  790. return false;
  791. }
  792. /**
  793. * Calling this method increases the usage count for the given node by one.
  794. *
  795. * @param {Node} node - The node to increase the usage count for.
  796. * @return {number} The updated usage count.
  797. */
  798. increaseUsage( node ) {
  799. const nodeData = this.getDataFromNode( node );
  800. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  801. return nodeData.usageCount;
  802. }
  803. /**
  804. * Generates a texture sample shader string for the given texture data.
  805. *
  806. * @abstract
  807. * @param {Texture} texture - The texture.
  808. * @param {string} textureProperty - The texture property name.
  809. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  810. * @return {string} The generated shader string.
  811. */
  812. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  813. warn( 'Abstract function.' );
  814. }
  815. /**
  816. * Generates a texture LOD shader string for the given texture data.
  817. *
  818. * @abstract
  819. * @param {Texture} texture - The texture.
  820. * @param {string} textureProperty - The texture property name.
  821. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  822. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  823. * @param {string} levelSnippet - Snippet defining the mip level.
  824. * @return {string} The generated shader string.
  825. */
  826. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  827. warn( 'Abstract function.' );
  828. }
  829. /**
  830. * Generates the array declaration string.
  831. *
  832. * @param {string} type - The type.
  833. * @param {?number} [count] - The count.
  834. * @return {string} The generated value as a shader string.
  835. */
  836. generateArrayDeclaration( type, count ) {
  837. return this.getType( type ) + '[ ' + count + ' ]';
  838. }
  839. /**
  840. * Generates the array shader string for the given type and value.
  841. *
  842. * @param {string} type - The type.
  843. * @param {?number} [count] - The count.
  844. * @param {?Array<Node>} [values=null] - The default values.
  845. * @return {string} The generated value as a shader string.
  846. */
  847. generateArray( type, count, values = null ) {
  848. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  849. for ( let i = 0; i < count; i ++ ) {
  850. const value = values ? values[ i ] : null;
  851. if ( value !== null ) {
  852. snippet += value.build( this, type );
  853. } else {
  854. snippet += this.generateConst( type );
  855. }
  856. if ( i < count - 1 ) snippet += ', ';
  857. }
  858. snippet += ' )';
  859. return snippet;
  860. }
  861. /**
  862. * Generates the struct shader string.
  863. *
  864. * @param {string} type - The type.
  865. * @param {Array<Object>} [membersLayout] - The count.
  866. * @param {?Array<Node>} [values=null] - The default values.
  867. * @return {string} The generated value as a shader string.
  868. */
  869. generateStruct( type, membersLayout, values = null ) {
  870. const snippets = [];
  871. for ( const member of membersLayout ) {
  872. const { name, type } = member;
  873. if ( values && values[ name ] && values[ name ].isNode ) {
  874. snippets.push( values[ name ].build( this, type ) );
  875. } else {
  876. snippets.push( this.generateConst( type ) );
  877. }
  878. }
  879. return type + '( ' + snippets.join( ', ' ) + ' )';
  880. }
  881. /**
  882. * Generates the shader string for the given type and value.
  883. *
  884. * @param {string} type - The type.
  885. * @param {?any} [value=null] - The value.
  886. * @return {string} The generated value as a shader string.
  887. */
  888. generateConst( type, value = null ) {
  889. if ( value === null ) {
  890. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  891. else if ( type === 'bool' ) value = false;
  892. else if ( type === 'color' ) value = new Color();
  893. else if ( type === 'vec2' ) value = new Vector2();
  894. else if ( type === 'vec3' ) value = new Vector3();
  895. else if ( type === 'vec4' ) value = new Vector4();
  896. }
  897. if ( type === 'float' ) return toFloat( value );
  898. if ( type === 'int' ) return `${ Math.round( value ) }`;
  899. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  900. if ( type === 'bool' ) return value ? 'true' : 'false';
  901. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  902. const typeLength = this.getTypeLength( type );
  903. const componentType = this.getComponentType( type );
  904. const generateConst = value => this.generateConst( componentType, value );
  905. if ( typeLength === 2 ) {
  906. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  907. } else if ( typeLength === 3 ) {
  908. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  909. } else if ( typeLength === 4 && type !== 'mat2' ) {
  910. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  911. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  912. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  913. } else if ( typeLength > 4 ) {
  914. return `${ this.getType( type ) }()`;
  915. }
  916. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  917. }
  918. /**
  919. * It might be necessary to convert certain data types to different ones
  920. * so this method can be used to hide the conversion.
  921. *
  922. * @param {string} type - The type.
  923. * @return {string} The updated type.
  924. */
  925. getType( type ) {
  926. if ( type === 'color' ) return 'vec3';
  927. return type;
  928. }
  929. /**
  930. * Whether the given attribute name is defined in the geometry or not.
  931. *
  932. * @param {string} name - The attribute name.
  933. * @return {boolean} Whether the given attribute name is defined in the geometry.
  934. */
  935. hasGeometryAttribute( name ) {
  936. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  937. }
  938. /**
  939. * Returns a node attribute for the given name and type.
  940. *
  941. * @param {string} name - The attribute's name.
  942. * @param {string} type - The attribute's type.
  943. * @return {NodeAttribute} The node attribute.
  944. */
  945. getAttribute( name, type ) {
  946. const attributes = this.attributes;
  947. // find attribute
  948. for ( const attribute of attributes ) {
  949. if ( attribute.name === name ) {
  950. return attribute;
  951. }
  952. }
  953. // create a new if no exist
  954. const attribute = new NodeAttribute( name, type );
  955. this.registerDeclaration( attribute );
  956. attributes.push( attribute );
  957. return attribute;
  958. }
  959. /**
  960. * Returns for the given node and shader stage the property name for the shader.
  961. *
  962. * @param {Node} node - The node.
  963. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  964. * @return {string} The property name.
  965. */
  966. getPropertyName( node/*, shaderStage*/ ) {
  967. return node.name;
  968. }
  969. /**
  970. * Whether the given type is a vector type or not.
  971. *
  972. * @param {string} type - The type to check.
  973. * @return {boolean} Whether the given type is a vector type or not.
  974. */
  975. isVector( type ) {
  976. return /vec\d/.test( type );
  977. }
  978. /**
  979. * Whether the given type is a matrix type or not.
  980. *
  981. * @param {string} type - The type to check.
  982. * @return {boolean} Whether the given type is a matrix type or not.
  983. */
  984. isMatrix( type ) {
  985. return /mat\d/.test( type );
  986. }
  987. /**
  988. * Whether the given type is a reference type or not.
  989. *
  990. * @param {string} type - The type to check.
  991. * @return {boolean} Whether the given type is a reference type or not.
  992. */
  993. isReference( type ) {
  994. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  995. }
  996. /**
  997. * Checks if the given texture requires a manual conversion to the working color space.
  998. *
  999. * @abstract
  1000. * @param {Texture} texture - The texture to check.
  1001. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  1002. */
  1003. needsToWorkingColorSpace( /*texture*/ ) {
  1004. return false;
  1005. }
  1006. /**
  1007. * Returns the component type of a given texture.
  1008. *
  1009. * @param {Texture} texture - The texture.
  1010. * @return {string} The component type.
  1011. */
  1012. getComponentTypeFromTexture( texture ) {
  1013. const type = texture.type;
  1014. if ( texture.isDataTexture ) {
  1015. if ( type === IntType ) return 'int';
  1016. if ( type === UnsignedIntType ) return 'uint';
  1017. }
  1018. return 'float';
  1019. }
  1020. /**
  1021. * Returns the element type for a given type.
  1022. *
  1023. * @param {string} type - The type.
  1024. * @return {string} The element type.
  1025. */
  1026. getElementType( type ) {
  1027. if ( type === 'mat2' ) return 'vec2';
  1028. if ( type === 'mat3' ) return 'vec3';
  1029. if ( type === 'mat4' ) return 'vec4';
  1030. return this.getComponentType( type );
  1031. }
  1032. /**
  1033. * Returns the component type for a given type.
  1034. *
  1035. * @param {string} type - The type.
  1036. * @return {string} The component type.
  1037. */
  1038. getComponentType( type ) {
  1039. type = this.getVectorType( type );
  1040. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  1041. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  1042. if ( componentType === null ) return null;
  1043. if ( componentType[ 1 ] === 'b' ) return 'bool';
  1044. if ( componentType[ 1 ] === 'i' ) return 'int';
  1045. if ( componentType[ 1 ] === 'u' ) return 'uint';
  1046. return 'float';
  1047. }
  1048. /**
  1049. * Returns the vector type for a given type.
  1050. *
  1051. * @param {string} type - The type.
  1052. * @return {string} The vector type.
  1053. */
  1054. getVectorType( type ) {
  1055. if ( type === 'color' ) return 'vec3';
  1056. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  1057. return type;
  1058. }
  1059. /**
  1060. * Returns the data type for the given the length and component type.
  1061. *
  1062. * @param {number} length - The length.
  1063. * @param {string} [componentType='float'] - The component type.
  1064. * @return {string} The type.
  1065. */
  1066. getTypeFromLength( length, componentType = 'float' ) {
  1067. if ( length === 1 ) return componentType;
  1068. let baseType = getTypeFromLength( length );
  1069. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  1070. // fix edge case for mat2x2 being same size as vec4
  1071. if ( /mat2/.test( componentType ) === true ) {
  1072. baseType = baseType.replace( 'vec', 'mat' );
  1073. }
  1074. return prefix + baseType;
  1075. }
  1076. /**
  1077. * Returns the type for a given typed array.
  1078. *
  1079. * @param {TypedArray} array - The typed array.
  1080. * @return {string} The type.
  1081. */
  1082. getTypeFromArray( array ) {
  1083. return typeFromArray.get( array.constructor );
  1084. }
  1085. /**
  1086. * Returns the type is an integer type.
  1087. *
  1088. * @param {string} type - The type.
  1089. * @return {boolean} Whether the type is an integer type or not.
  1090. */
  1091. isInteger( type ) {
  1092. return /int|uint|(i|u)vec/.test( type );
  1093. }
  1094. /**
  1095. * Returns the type for a given buffer attribute.
  1096. *
  1097. * @param {BufferAttribute} attribute - The buffer attribute.
  1098. * @return {string} The type.
  1099. */
  1100. getTypeFromAttribute( attribute ) {
  1101. let dataAttribute = attribute;
  1102. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  1103. const array = dataAttribute.array;
  1104. const itemSize = attribute.itemSize;
  1105. const normalized = attribute.normalized;
  1106. let arrayType;
  1107. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  1108. arrayType = this.getTypeFromArray( array );
  1109. }
  1110. return this.getTypeFromLength( itemSize, arrayType );
  1111. }
  1112. /**
  1113. * Returns the length for the given data type.
  1114. *
  1115. * @param {string} type - The data type.
  1116. * @return {number} The length.
  1117. */
  1118. getTypeLength( type ) {
  1119. const vecType = this.getVectorType( type );
  1120. const vecNum = /vec([2-4])/.exec( vecType );
  1121. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  1122. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  1123. if ( /mat2/.test( type ) === true ) return 4;
  1124. if ( /mat3/.test( type ) === true ) return 9;
  1125. if ( /mat4/.test( type ) === true ) return 16;
  1126. return 0;
  1127. }
  1128. /**
  1129. * Returns the vector type for a given matrix type.
  1130. *
  1131. * @param {string} type - The matrix type.
  1132. * @return {string} The vector type.
  1133. */
  1134. getVectorFromMatrix( type ) {
  1135. return type.replace( 'mat', 'vec' );
  1136. }
  1137. /**
  1138. * For a given type this method changes the component type to the
  1139. * given value. E.g. `vec4` should be changed to the new component type
  1140. * `uint` which results in `uvec4`.
  1141. *
  1142. * @param {string} type - The type.
  1143. * @param {string} newComponentType - The new component type.
  1144. * @return {string} The new type.
  1145. */
  1146. changeComponentType( type, newComponentType ) {
  1147. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  1148. }
  1149. /**
  1150. * Returns the integer type pendant for the given type.
  1151. *
  1152. * @param {string} type - The type.
  1153. * @return {string} The integer type.
  1154. */
  1155. getIntegerType( type ) {
  1156. const componentType = this.getComponentType( type );
  1157. if ( componentType === 'int' || componentType === 'uint' ) return type;
  1158. return this.changeComponentType( type, 'int' );
  1159. }
  1160. /**
  1161. * Adds a stack node to the internal stack.
  1162. *
  1163. * @return {StackNode} The added stack node.
  1164. */
  1165. addStack() {
  1166. this.stack = stack( this.stack );
  1167. const previousStack = getCurrentStack();
  1168. this.stacks.push( previousStack );
  1169. setCurrentStack( this.stack );
  1170. return this.stack;
  1171. }
  1172. /**
  1173. * Removes the last stack node from the internal stack.
  1174. *
  1175. * @return {StackNode} The removed stack node.
  1176. */
  1177. removeStack() {
  1178. const lastStack = this.stack;
  1179. this.stack = lastStack.parent;
  1180. setCurrentStack( this.stacks.pop() );
  1181. return lastStack;
  1182. }
  1183. /**
  1184. * The builder maintains (cached) data for each node during the building process. This method
  1185. * can be used to get these data for a specific shader stage and cache.
  1186. *
  1187. * @param {Node} node - The node to get the data for.
  1188. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  1189. * @param {?NodeCache} cache - An optional cache.
  1190. * @return {Object} The node data.
  1191. */
  1192. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  1193. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  1194. let nodeData = cache.getData( node );
  1195. if ( nodeData === undefined ) {
  1196. nodeData = {};
  1197. cache.setData( node, nodeData );
  1198. }
  1199. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  1200. //
  1201. let data = nodeData[ shaderStage ];
  1202. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  1203. const subBuild = this.getClosestSubBuild( subBuilds );
  1204. if ( subBuild ) {
  1205. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  1206. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  1207. data.subBuilds = subBuilds;
  1208. }
  1209. return data;
  1210. }
  1211. /**
  1212. * Returns the properties for the given node and shader stage.
  1213. *
  1214. * @param {Node} node - The node to get the properties for.
  1215. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  1216. * @return {Object} The node properties.
  1217. */
  1218. getNodeProperties( node, shaderStage = 'any' ) {
  1219. const nodeData = this.getDataFromNode( node, shaderStage );
  1220. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  1221. }
  1222. /**
  1223. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  1224. *
  1225. * @param {BufferAttributeNode} node - The buffer attribute node.
  1226. * @param {string} type - The node type.
  1227. * @return {NodeAttribute} The node attribute.
  1228. */
  1229. getBufferAttributeFromNode( node, type ) {
  1230. const nodeData = this.getDataFromNode( node );
  1231. let bufferAttribute = nodeData.bufferAttribute;
  1232. if ( bufferAttribute === undefined ) {
  1233. const index = this.uniforms.index ++;
  1234. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  1235. this.bufferAttributes.push( bufferAttribute );
  1236. nodeData.bufferAttribute = bufferAttribute;
  1237. }
  1238. return bufferAttribute;
  1239. }
  1240. /**
  1241. * Returns an instance of {@link StructType} for the given struct name and shader stage
  1242. * or null if not found.
  1243. *
  1244. * @param {string} name - The name of the struct.
  1245. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  1246. * @return {?StructType} The struct type or null if not found.
  1247. */
  1248. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  1249. return this.types[ shaderStage ][ name ] || null;
  1250. }
  1251. /**
  1252. * Returns an instance of {@link StructType} for the given output struct node.
  1253. *
  1254. * @param {OutputStructNode} node - The output struct node.
  1255. * @param {Array<Object>} membersLayout - The output struct types.
  1256. * @param {?string} [name=null] - The name of the struct.
  1257. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  1258. * @return {StructType} The struct type attribute.
  1259. */
  1260. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  1261. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  1262. let structType = nodeData.structType;
  1263. if ( structType === undefined ) {
  1264. const index = this.structs.index ++;
  1265. if ( name === null ) name = 'StructType' + index;
  1266. structType = new StructType( name, membersLayout );
  1267. this.structs[ shaderStage ].push( structType );
  1268. this.types[ shaderStage ][ name ] = node;
  1269. nodeData.structType = structType;
  1270. }
  1271. return structType;
  1272. }
  1273. /**
  1274. * Returns an instance of {@link StructType} for the given output struct node.
  1275. *
  1276. * @param {OutputStructNode} node - The output struct node.
  1277. * @param {Array<Object>} membersLayout - The output struct types.
  1278. * @return {StructType} The struct type attribute.
  1279. */
  1280. getOutputStructTypeFromNode( node, membersLayout ) {
  1281. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  1282. structType.output = true;
  1283. return structType;
  1284. }
  1285. /**
  1286. * Returns an instance of {@link NodeUniform} for the given uniform node.
  1287. *
  1288. * @param {UniformNode} node - The uniform node.
  1289. * @param {string} type - The uniform type.
  1290. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  1291. * @param {?string} name - The name of the uniform.
  1292. * @return {NodeUniform} The node uniform.
  1293. */
  1294. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  1295. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  1296. let nodeUniform = nodeData.uniform;
  1297. if ( nodeUniform === undefined ) {
  1298. const index = this.uniforms.index ++;
  1299. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  1300. this.uniforms[ shaderStage ].push( nodeUniform );
  1301. this.registerDeclaration( nodeUniform );
  1302. nodeData.uniform = nodeUniform;
  1303. }
  1304. return nodeUniform;
  1305. }
  1306. /**
  1307. * Returns an instance of {@link NodeVar} for the given variable node.
  1308. *
  1309. * @param {VarNode} node - The variable node.
  1310. * @param {?string} name - The variable's name.
  1311. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  1312. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  1313. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  1314. *
  1315. * @return {NodeVar} The node variable.
  1316. */
  1317. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  1318. const nodeData = this.getDataFromNode( node, shaderStage );
  1319. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  1320. let nodeVar = nodeData[ subBuildVariable ];
  1321. if ( nodeVar === undefined ) {
  1322. const idNS = readOnly ? '_const' : '_var';
  1323. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  1324. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  1325. if ( name === null ) {
  1326. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  1327. this.vars[ idNS ] ++;
  1328. }
  1329. //
  1330. if ( subBuildVariable !== 'variable' ) {
  1331. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  1332. }
  1333. //
  1334. const count = node.getArrayCount( this );
  1335. nodeVar = new NodeVar( name, type, readOnly, count );
  1336. if ( ! readOnly ) {
  1337. vars.push( nodeVar );
  1338. }
  1339. this.registerDeclaration( nodeVar );
  1340. nodeData[ subBuildVariable ] = nodeVar;
  1341. }
  1342. return nodeVar;
  1343. }
  1344. /**
  1345. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  1346. *
  1347. * @param {Node} node - The varying node.
  1348. * @return {boolean} Returns true if deterministic.
  1349. */
  1350. isDeterministic( node ) {
  1351. if ( node.isMathNode ) {
  1352. return this.isDeterministic( node.aNode ) &&
  1353. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  1354. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  1355. } else if ( node.isOperatorNode ) {
  1356. return this.isDeterministic( node.aNode ) &&
  1357. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  1358. } else if ( node.isArrayNode ) {
  1359. if ( node.values !== null ) {
  1360. for ( const n of node.values ) {
  1361. if ( ! this.isDeterministic( n ) ) {
  1362. return false;
  1363. }
  1364. }
  1365. }
  1366. return true;
  1367. } else if ( node.isConstNode ) {
  1368. return true;
  1369. }
  1370. return false;
  1371. }
  1372. /**
  1373. * Returns an instance of {@link NodeVarying} for the given varying node.
  1374. *
  1375. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  1376. * @param {?string} name - The varying's name.
  1377. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  1378. * @param {?string} interpolationType - The interpolation type of the varying.
  1379. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  1380. * @return {NodeVar} The node varying.
  1381. */
  1382. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  1383. const nodeData = this.getDataFromNode( node, 'any' );
  1384. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  1385. let nodeVarying = nodeData[ subBuildVarying ];
  1386. if ( nodeVarying === undefined ) {
  1387. const varyings = this.varyings;
  1388. const index = varyings.length;
  1389. if ( name === null ) name = 'nodeVarying' + index;
  1390. //
  1391. if ( subBuildVarying !== 'varying' ) {
  1392. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  1393. }
  1394. //
  1395. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  1396. varyings.push( nodeVarying );
  1397. this.registerDeclaration( nodeVarying );
  1398. nodeData[ subBuildVarying ] = nodeVarying;
  1399. }
  1400. return nodeVarying;
  1401. }
  1402. /**
  1403. * Registers a node declaration in the current shader stage.
  1404. *
  1405. * @param {Object} node - The node to be registered.
  1406. */
  1407. registerDeclaration( node ) {
  1408. const shaderStage = this.shaderStage;
  1409. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  1410. const property = this.getPropertyName( node );
  1411. let index = 1;
  1412. let name = property;
  1413. // Automatically renames the property if the name is already in use.
  1414. while ( declarations[ name ] !== undefined ) {
  1415. name = property + '_' + index ++;
  1416. }
  1417. if ( index > 1 ) {
  1418. node.name = name;
  1419. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  1420. }
  1421. declarations[ name ] = node;
  1422. }
  1423. /**
  1424. * Returns an instance of {@link NodeCode} for the given code node.
  1425. *
  1426. * @param {CodeNode} node - The code node.
  1427. * @param {string} type - The node type.
  1428. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  1429. * @return {NodeCode} The node code.
  1430. */
  1431. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  1432. const nodeData = this.getDataFromNode( node );
  1433. let nodeCode = nodeData.code;
  1434. if ( nodeCode === undefined ) {
  1435. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  1436. const index = codes.length;
  1437. nodeCode = new NodeCode( 'nodeCode' + index, type );
  1438. codes.push( nodeCode );
  1439. nodeData.code = nodeCode;
  1440. }
  1441. return nodeCode;
  1442. }
  1443. /**
  1444. * Adds a code flow based on the code-block hierarchy.
  1445. * This is used so that code-blocks like If,Else create their variables locally if the Node
  1446. * is only used inside one of these conditionals in the current shader stage.
  1447. *
  1448. * @param {Node} node - The node to add.
  1449. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  1450. */
  1451. addFlowCodeHierarchy( node, nodeBlock ) {
  1452. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  1453. let needsFlowCode = true;
  1454. let nodeBlockHierarchy = nodeBlock;
  1455. while ( nodeBlockHierarchy ) {
  1456. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  1457. needsFlowCode = false;
  1458. break;
  1459. }
  1460. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  1461. }
  1462. if ( needsFlowCode ) {
  1463. for ( const flowCode of flowCodes ) {
  1464. this.addLineFlowCode( flowCode );
  1465. }
  1466. }
  1467. }
  1468. /**
  1469. * Add a inline-code to the current flow code-block.
  1470. *
  1471. * @param {Node} node - The node to add.
  1472. * @param {string} code - The code to add.
  1473. * @param {Node} nodeBlock - Current ConditionalNode
  1474. */
  1475. addLineFlowCodeBlock( node, code, nodeBlock ) {
  1476. const nodeData = this.getDataFromNode( node );
  1477. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  1478. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  1479. flowCodes.push( code );
  1480. codeBlock.set( nodeBlock, true );
  1481. }
  1482. /**
  1483. * Add a inline-code to the current flow.
  1484. *
  1485. * @param {string} code - The code to add.
  1486. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  1487. * @return {NodeBuilder} A reference to this node builder.
  1488. */
  1489. addLineFlowCode( code, node = null ) {
  1490. if ( code === '' ) return this;
  1491. if ( node !== null && this.context.nodeBlock ) {
  1492. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  1493. }
  1494. code = this.tab + code;
  1495. if ( ! /;\s*$/.test( code ) ) {
  1496. code = code + ';\n';
  1497. }
  1498. this.flow.code += code;
  1499. return this;
  1500. }
  1501. /**
  1502. * Adds a code to the current code flow.
  1503. *
  1504. * @param {string} code - Shader code.
  1505. * @return {NodeBuilder} A reference to this node builder.
  1506. */
  1507. addFlowCode( code ) {
  1508. this.flow.code += code;
  1509. return this;
  1510. }
  1511. /**
  1512. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  1513. * Typically used in codes with If,Else.
  1514. *
  1515. * @return {NodeBuilder} A reference to this node builder.
  1516. */
  1517. addFlowTab() {
  1518. this.tab += '\t';
  1519. return this;
  1520. }
  1521. /**
  1522. * Removes a tab.
  1523. *
  1524. * @return {NodeBuilder} A reference to this node builder.
  1525. */
  1526. removeFlowTab() {
  1527. this.tab = this.tab.slice( 0, - 1 );
  1528. return this;
  1529. }
  1530. /**
  1531. * Gets the current flow data based on a Node.
  1532. *
  1533. * @param {Node} node - Node that the flow was started.
  1534. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  1535. * @return {Object} The flow data.
  1536. */
  1537. getFlowData( node/*, shaderStage*/ ) {
  1538. return this.flowsData.get( node );
  1539. }
  1540. /**
  1541. * Executes the node flow based on a root node to generate the final shader code.
  1542. *
  1543. * @param {Node} node - The node to execute.
  1544. * @return {Object} The code flow.
  1545. */
  1546. flowNode( node ) {
  1547. const output = node.getNodeType( this );
  1548. const flowData = this.flowChildNode( node, output );
  1549. this.flowsData.set( node, flowData );
  1550. return flowData;
  1551. }
  1552. /**
  1553. * Includes a node in the current function node.
  1554. *
  1555. * @param {Node} node - The node to include.
  1556. * @returns {void}
  1557. */
  1558. addInclude( node ) {
  1559. if ( this.currentFunctionNode !== null ) {
  1560. this.currentFunctionNode.includes.push( node );
  1561. }
  1562. }
  1563. /**
  1564. * Returns the native shader operator name for a given generic name.
  1565. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  1566. *
  1567. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  1568. * @return {FunctionNode} The build function node.
  1569. */
  1570. buildFunctionNode( shaderNode ) {
  1571. const fn = new FunctionNode();
  1572. const previous = this.currentFunctionNode;
  1573. this.currentFunctionNode = fn;
  1574. fn.code = this.buildFunctionCode( shaderNode );
  1575. this.currentFunctionNode = previous;
  1576. return fn;
  1577. }
  1578. /**
  1579. * Generates a code flow based on a TSL function: Fn().
  1580. *
  1581. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  1582. * @return {Object}
  1583. */
  1584. flowShaderNode( shaderNode ) {
  1585. const layout = shaderNode.layout;
  1586. const inputs = {
  1587. [ Symbol.iterator ]() {
  1588. let index = 0;
  1589. const values = Object.values( this );
  1590. return {
  1591. next: () => ( {
  1592. value: values[ index ],
  1593. done: index ++ >= values.length
  1594. } )
  1595. };
  1596. }
  1597. };
  1598. for ( const input of layout.inputs ) {
  1599. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  1600. }
  1601. //
  1602. shaderNode.layout = null;
  1603. const callNode = shaderNode.call( inputs );
  1604. const flowData = this.flowStagesNode( callNode, layout.type );
  1605. shaderNode.layout = layout;
  1606. return flowData;
  1607. }
  1608. /**
  1609. * Executes the node in a specific build stage.
  1610. *
  1611. * @param {Node} node - The node to execute.
  1612. * @param {string} buildStage - The build stage to execute the node in.
  1613. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  1614. * @return {?(Node|string)} The result of the node build.
  1615. */
  1616. flowBuildStage( node, buildStage, output = null ) {
  1617. const previousBuildStage = this.getBuildStage();
  1618. this.setBuildStage( buildStage );
  1619. const result = node.build( this, output );
  1620. this.setBuildStage( previousBuildStage );
  1621. return result;
  1622. }
  1623. /**
  1624. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  1625. *
  1626. * @param {Node} node - The node to execute.
  1627. * @param {?string} output - Expected output type. For example 'vec3'.
  1628. * @return {Object}
  1629. */
  1630. flowStagesNode( node, output = null ) {
  1631. const previousFlow = this.flow;
  1632. const previousVars = this.vars;
  1633. const previousDeclarations = this.declarations;
  1634. const previousCache = this.cache;
  1635. const previousBuildStage = this.buildStage;
  1636. const previousStack = this.stack;
  1637. const flow = {
  1638. code: ''
  1639. };
  1640. this.flow = flow;
  1641. this.vars = {};
  1642. this.declarations = {};
  1643. this.cache = new NodeCache();
  1644. this.stack = stack();
  1645. for ( const buildStage of defaultBuildStages ) {
  1646. this.setBuildStage( buildStage );
  1647. flow.result = node.build( this, output );
  1648. }
  1649. flow.vars = this.getVars( this.shaderStage );
  1650. this.flow = previousFlow;
  1651. this.vars = previousVars;
  1652. this.declarations = previousDeclarations;
  1653. this.cache = previousCache;
  1654. this.stack = previousStack;
  1655. this.setBuildStage( previousBuildStage );
  1656. return flow;
  1657. }
  1658. /**
  1659. * Returns the native shader operator name for a given generic name.
  1660. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  1661. *
  1662. * @abstract
  1663. * @param {string} op - The operator name to resolve.
  1664. * @return {?string} The resolved operator name.
  1665. */
  1666. getFunctionOperator( /* op */ ) {
  1667. return null;
  1668. }
  1669. /**
  1670. * Builds the given shader node.
  1671. *
  1672. * @abstract
  1673. * @param {ShaderNodeInternal} shaderNode - The shader node.
  1674. * @return {string} The function code.
  1675. */
  1676. buildFunctionCode( /* shaderNode */ ) {
  1677. warn( 'Abstract function.' );
  1678. }
  1679. /**
  1680. * Generates a code flow based on a child Node.
  1681. *
  1682. * @param {Node} node - The node to execute.
  1683. * @param {?string} output - Expected output type. For example 'vec3'.
  1684. * @return {Object} The code flow.
  1685. */
  1686. flowChildNode( node, output = null ) {
  1687. const previousFlow = this.flow;
  1688. const flow = {
  1689. code: ''
  1690. };
  1691. this.flow = flow;
  1692. flow.result = node.build( this, output );
  1693. this.flow = previousFlow;
  1694. return flow;
  1695. }
  1696. /**
  1697. * Executes a flow of code in a different stage.
  1698. *
  1699. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  1700. * return the value in fragment-stage even if it is being executed in an input fragment.
  1701. *
  1702. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  1703. * @param {Node} node - The node to execute.
  1704. * @param {?string} output - Expected output type. For example 'vec3'.
  1705. * @param {?string} propertyName - The property name to assign the result.
  1706. * @return {?(Object|Node)} The code flow or node.build() result.
  1707. */
  1708. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  1709. const previousTab = this.tab;
  1710. const previousCache = this.cache;
  1711. const previousShaderStage = this.shaderStage;
  1712. const previousContext = this.context;
  1713. this.setShaderStage( shaderStage );
  1714. const context = { ...this.context };
  1715. delete context.nodeBlock;
  1716. this.cache = this.globalCache;
  1717. this.tab = '\t';
  1718. this.context = context;
  1719. let result = null;
  1720. if ( this.buildStage === 'generate' ) {
  1721. const flowData = this.flowChildNode( node, output );
  1722. if ( propertyName !== null ) {
  1723. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  1724. }
  1725. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  1726. result = flowData;
  1727. } else {
  1728. result = node.build( this );
  1729. }
  1730. this.setShaderStage( previousShaderStage );
  1731. this.cache = previousCache;
  1732. this.tab = previousTab;
  1733. this.context = previousContext;
  1734. return result;
  1735. }
  1736. /**
  1737. * Returns an array holding all node attributes of this node builder.
  1738. *
  1739. * @return {Array<NodeAttribute>} The node attributes of this builder.
  1740. */
  1741. getAttributesArray() {
  1742. return this.attributes.concat( this.bufferAttributes );
  1743. }
  1744. /**
  1745. * Returns the attribute definitions as a shader string for the given shader stage.
  1746. *
  1747. * @abstract
  1748. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  1749. * @return {string} The attribute code section.
  1750. */
  1751. getAttributes( /*shaderStage*/ ) {
  1752. warn( 'Abstract function.' );
  1753. }
  1754. /**
  1755. * Returns the varying definitions as a shader string for the given shader stage.
  1756. *
  1757. * @abstract
  1758. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  1759. * @return {string} The varying code section.
  1760. */
  1761. getVaryings( /*shaderStage*/ ) {
  1762. warn( 'Abstract function.' );
  1763. }
  1764. /**
  1765. * Returns a single variable definition as a shader string for the given variable type and name.
  1766. *
  1767. * @param {string} type - The variable's type.
  1768. * @param {string} name - The variable's name.
  1769. * @param {?number} [count=null] - The array length.
  1770. * @return {string} The shader string.
  1771. */
  1772. getVar( type, name, count = null ) {
  1773. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  1774. }
  1775. /**
  1776. * Returns the variable definitions as a shader string for the given shader stage.
  1777. *
  1778. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  1779. * @return {string} The variable code section.
  1780. */
  1781. getVars( shaderStage ) {
  1782. let snippet = '';
  1783. const vars = this.vars[ shaderStage ];
  1784. if ( vars !== undefined ) {
  1785. for ( const variable of vars ) {
  1786. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  1787. }
  1788. }
  1789. return snippet;
  1790. }
  1791. /**
  1792. * Returns the uniform definitions as a shader string for the given shader stage.
  1793. *
  1794. * @abstract
  1795. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  1796. * @return {string} The uniform code section.
  1797. */
  1798. getUniforms( /*shaderStage*/ ) {
  1799. warn( 'Abstract function.' );
  1800. }
  1801. /**
  1802. * Returns the native code definitions as a shader string for the given shader stage.
  1803. *
  1804. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  1805. * @return {string} The native code section.
  1806. */
  1807. getCodes( shaderStage ) {
  1808. const codes = this.codes[ shaderStage ];
  1809. let code = '';
  1810. if ( codes !== undefined ) {
  1811. for ( const nodeCode of codes ) {
  1812. code += nodeCode.code + '\n';
  1813. }
  1814. }
  1815. return code;
  1816. }
  1817. /**
  1818. * Returns the hash of this node builder.
  1819. *
  1820. * @return {string} The hash.
  1821. */
  1822. getHash() {
  1823. return this.vertexShader + this.fragmentShader + this.computeShader;
  1824. }
  1825. /**
  1826. * Sets the current shader stage.
  1827. *
  1828. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  1829. */
  1830. setShaderStage( shaderStage ) {
  1831. this.shaderStage = shaderStage;
  1832. }
  1833. /**
  1834. * Returns the current shader stage.
  1835. *
  1836. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  1837. */
  1838. getShaderStage() {
  1839. return this.shaderStage;
  1840. }
  1841. /**
  1842. * Sets the current build stage.
  1843. *
  1844. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  1845. */
  1846. setBuildStage( buildStage ) {
  1847. this.buildStage = buildStage;
  1848. }
  1849. /**
  1850. * Returns the current build stage.
  1851. *
  1852. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  1853. */
  1854. getBuildStage() {
  1855. return this.buildStage;
  1856. }
  1857. /**
  1858. * Controls the code build of the shader stages.
  1859. *
  1860. * @abstract
  1861. */
  1862. buildCode() {
  1863. warn( 'Abstract function.' );
  1864. }
  1865. /**
  1866. * Returns the current sub-build layer.
  1867. *
  1868. * @return {SubBuildNode} The current sub-build layers.
  1869. */
  1870. get subBuild() {
  1871. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  1872. }
  1873. /**
  1874. * Adds a sub-build layer to the node builder.
  1875. *
  1876. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  1877. */
  1878. addSubBuild( subBuild ) {
  1879. this.subBuildLayers.push( subBuild );
  1880. }
  1881. /**
  1882. * Removes the last sub-build layer from the node builder.
  1883. *
  1884. * @return {SubBuildNode} The removed sub-build layer.
  1885. */
  1886. removeSubBuild() {
  1887. return this.subBuildLayers.pop();
  1888. }
  1889. /**
  1890. * Returns the closest sub-build layer for the given data.
  1891. *
  1892. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  1893. * @return {?string} The closest sub-build name or null if none found.
  1894. */
  1895. getClosestSubBuild( data ) {
  1896. let subBuilds;
  1897. if ( data && data.isNode ) {
  1898. if ( data.isShaderCallNodeInternal ) {
  1899. subBuilds = data.shaderNode.subBuilds;
  1900. } else if ( data.isStackNode ) {
  1901. subBuilds = [ data.subBuild ];
  1902. } else {
  1903. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  1904. }
  1905. } else if ( data instanceof Set ) {
  1906. subBuilds = [ ...data ];
  1907. } else {
  1908. subBuilds = data;
  1909. }
  1910. if ( ! subBuilds ) return null;
  1911. const subBuildLayers = this.subBuildLayers;
  1912. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  1913. const subBuild = subBuilds[ i ];
  1914. if ( subBuildLayers.includes( subBuild ) ) {
  1915. return subBuild;
  1916. }
  1917. }
  1918. return null;
  1919. }
  1920. /**
  1921. * Returns the output node of a sub-build layer.
  1922. *
  1923. * @param {Node} node - The node to get the output from.
  1924. * @return {string} The output node name.
  1925. */
  1926. getSubBuildOutput( node ) {
  1927. return this.getSubBuildProperty( 'outputNode', node );
  1928. }
  1929. /**
  1930. * Returns the sub-build property name for the given property and node.
  1931. *
  1932. * @param {string} [property=''] - The property name.
  1933. * @param {?Node} [node=null] - The node to get the sub-build from.
  1934. * @return {string} The sub-build property name.
  1935. */
  1936. getSubBuildProperty( property = '', node = null ) {
  1937. let subBuild;
  1938. if ( node !== null ) {
  1939. subBuild = this.getClosestSubBuild( node );
  1940. } else {
  1941. subBuild = this.subBuildFn;
  1942. }
  1943. let result;
  1944. if ( subBuild ) {
  1945. result = property ? ( subBuild + '_' + property ) : subBuild;
  1946. } else {
  1947. result = property;
  1948. }
  1949. return result;
  1950. }
  1951. /**
  1952. * Central build method which controls the build for the given object.
  1953. *
  1954. * @return {NodeBuilder} A reference to this node builder.
  1955. */
  1956. build() {
  1957. const { object, material, renderer } = this;
  1958. if ( material !== null ) {
  1959. let nodeMaterial = renderer.library.fromMaterial( material );
  1960. if ( nodeMaterial === null ) {
  1961. error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  1962. nodeMaterial = new NodeMaterial();
  1963. }
  1964. nodeMaterial.build( this );
  1965. } else {
  1966. this.addFlow( 'compute', object );
  1967. }
  1968. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  1969. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  1970. // generate() -> stage 3: generate shader
  1971. for ( const buildStage of defaultBuildStages ) {
  1972. this.setBuildStage( buildStage );
  1973. if ( this.context.vertex && this.context.vertex.isNode ) {
  1974. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  1975. }
  1976. for ( const shaderStage of shaderStages ) {
  1977. this.setShaderStage( shaderStage );
  1978. const flowNodes = this.flowNodes[ shaderStage ];
  1979. for ( const node of flowNodes ) {
  1980. if ( buildStage === 'generate' ) {
  1981. this.flowNode( node );
  1982. } else {
  1983. node.build( this );
  1984. }
  1985. }
  1986. }
  1987. }
  1988. this.setBuildStage( null );
  1989. this.setShaderStage( null );
  1990. // stage 4: build code for a specific output
  1991. this.buildCode();
  1992. this.buildUpdateNodes();
  1993. return this;
  1994. }
  1995. /**
  1996. * Returns a uniform representation which is later used for UBO generation and rendering.
  1997. *
  1998. * @param {NodeUniform} uniformNode - The uniform node.
  1999. * @param {string} type - The requested type.
  2000. * @return {Uniform} The uniform.
  2001. */
  2002. getNodeUniform( uniformNode, type ) {
  2003. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  2004. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  2005. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  2006. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  2007. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  2008. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  2009. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  2010. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  2011. throw new Error( `Uniform "${type}" not declared.` );
  2012. }
  2013. /**
  2014. * Formats the given shader snippet from a given type into another one. E.g.
  2015. * this method might be used to convert a simple float string `"1.0"` into a
  2016. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  2017. *
  2018. * @param {string} snippet - The shader snippet.
  2019. * @param {string} fromType - The source type.
  2020. * @param {string} toType - The target type.
  2021. * @return {string} The updated shader string.
  2022. */
  2023. format( snippet, fromType, toType ) {
  2024. fromType = this.getVectorType( fromType );
  2025. toType = this.getVectorType( toType );
  2026. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  2027. return snippet;
  2028. }
  2029. const fromTypeLength = this.getTypeLength( fromType );
  2030. const toTypeLength = this.getTypeLength( toType );
  2031. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  2032. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  2033. }
  2034. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  2035. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  2036. }
  2037. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  2038. // @TODO: ignore for now
  2039. return snippet;
  2040. }
  2041. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  2042. // @TODO: ignore for now
  2043. return snippet;
  2044. }
  2045. if ( fromTypeLength === toTypeLength ) {
  2046. return `${ this.getType( toType ) }( ${ snippet } )`;
  2047. }
  2048. if ( fromTypeLength > toTypeLength ) {
  2049. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  2050. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  2051. }
  2052. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  2053. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  2054. }
  2055. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  2056. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  2057. }
  2058. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  2059. // convert a number value to vector type, e.g:
  2060. // vec3( 1u ) -> vec3( float( 1u ) )
  2061. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  2062. }
  2063. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  2064. }
  2065. /**
  2066. * Returns a signature with the engine's current revision.
  2067. *
  2068. * @return {string} The signature.
  2069. */
  2070. getSignature() {
  2071. return `// Three.js r${ REVISION } - Node System\n`;
  2072. }
  2073. }
  2074. export default NodeBuilder;
粤ICP备19079148号