TSLEncoder.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. import { REVISION } from 'three/webgpu';
  2. import * as TSL from 'three/tsl';
  3. import { VariableDeclaration, Accessor } from './AST.js';
  4. const opLib = {
  5. '=': 'assign',
  6. '+': 'add',
  7. '-': 'sub',
  8. '*': 'mul',
  9. '/': 'div',
  10. '%': 'remainder',
  11. '<': 'lessThan',
  12. '>': 'greaterThan',
  13. '<=': 'lessThanEqual',
  14. '>=': 'greaterThanEqual',
  15. '==': 'equal',
  16. '!=': 'notEqual',
  17. '&&': 'and',
  18. '||': 'or',
  19. '^^': 'xor',
  20. '&': 'bitAnd',
  21. '|': 'bitOr',
  22. '^': 'bitXor',
  23. '<<': 'shiftLeft',
  24. '>>': 'shiftRight',
  25. '+=': 'addAssign',
  26. '-=': 'subAssign',
  27. '*=': 'mulAssign',
  28. '/=': 'divAssign',
  29. '%=': 'remainderAssign',
  30. '^=': 'bitXorAssign',
  31. '&=': 'bitAndAssign',
  32. '|=': 'bitOrAssign',
  33. '<<=': 'shiftLeftAssign',
  34. '>>=': 'shiftRightAssign'
  35. };
  36. const unaryLib = {
  37. '+': '', // positive
  38. '-': 'negate',
  39. '~': 'bitNot',
  40. '!': 'not',
  41. '++': 'increment', // incrementBefore
  42. '--': 'decrement' // decrementBefore
  43. };
  44. const textureLookupFunctions = [ 'texture', 'texture2D', 'texture3D', 'textureCube', 'textureLod', 'texelFetch', 'textureGrad' ];
  45. const isPrimitive = ( value ) => /^(true|false|-?(\d|\.\d))/.test( value );
  46. class TSLEncoder {
  47. constructor() {
  48. this.tab = '';
  49. this.imports = new Set();
  50. this.global = new Set();
  51. this.overloadings = new Map();
  52. this.iife = false;
  53. this.reference = false;
  54. this._currentVariable = null;
  55. this._currentProperties = {};
  56. this._lastStatement = null;
  57. this.block = null;
  58. }
  59. addImport( name ) {
  60. // import only if it's a node
  61. name = name.split( '.' )[ 0 ];
  62. if ( TSL[ name ] !== undefined && this.global.has( name ) === false && this._currentProperties[ name ] === undefined ) {
  63. this.imports.add( name );
  64. }
  65. }
  66. emitUniform( node ) {
  67. let code = `const ${ node.name } = `;
  68. this.global.add( node.name );
  69. if ( this.reference === true ) {
  70. this.addImport( 'reference' );
  71. //code += `reference( '${ node.name }', '${ node.type }', uniforms )`;
  72. // legacy
  73. code += `reference( 'value', '${ node.type }', uniforms[ '${ node.name }' ] )`;
  74. } else {
  75. if ( node.type === 'texture' ) {
  76. this.addImport( 'texture' );
  77. code += 'texture( /* <THREE.Texture> */ )';
  78. } else if ( node.type === 'cubeTexture' ) {
  79. this.addImport( 'cubeTexture' );
  80. code += 'cubeTexture( /* <THREE.CubeTexture> */ )';
  81. } else if ( node.type === 'texture3D' ) {
  82. this.addImport( 'texture3D' );
  83. code += 'texture3D( /* <THREE.Data3DTexture> */ )';
  84. } else {
  85. // default uniform
  86. this.addImport( 'uniform' );
  87. code += `uniform( '${ node.type }' )`;
  88. }
  89. }
  90. return code;
  91. }
  92. emitExpression( node ) {
  93. let code;
  94. if ( node.isAccessor ) {
  95. this.addImport( node.property );
  96. code = node.property;
  97. } else if ( node.isNumber ) {
  98. if ( node.type === 'int' || node.type === 'uint' ) {
  99. code = node.type + '( ' + node.value + ' )';
  100. this.addImport( node.type );
  101. } else {
  102. code = node.value;
  103. }
  104. } else if ( node.isString ) {
  105. code = '\'' + node.value + '\'';
  106. } else if ( node.isOperator ) {
  107. const opFn = opLib[ node.type ] || node.type;
  108. const left = this.emitExpression( node.left );
  109. const right = this.emitExpression( node.right );
  110. if ( isPrimitive( left ) && isPrimitive( right ) ) {
  111. return left + ' ' + node.type + ' ' + right;
  112. }
  113. if ( isPrimitive( left ) ) {
  114. code = opFn + '( ' + left + ', ' + right + ' )';
  115. this.addImport( opFn );
  116. } else if ( opFn === '.' ) {
  117. code = left + opFn + right;
  118. } else {
  119. code = left + '.' + opFn + '( ' + right + ' )';
  120. }
  121. } else if ( node.isFunctionCall ) {
  122. const params = [];
  123. for ( const parameter of node.params ) {
  124. params.push( this.emitExpression( parameter ) );
  125. }
  126. // handle texture lookup function calls in separate branch
  127. if ( textureLookupFunctions.includes( node.name ) ) {
  128. code = `${ params[ 0 ] }.sample( ${ params[ 1 ] } )`;
  129. if ( node.name === 'texture' || node.name === 'texture2D' || node.name === 'texture3D' || node.name === 'textureCube' ) {
  130. if ( params.length === 3 ) {
  131. code += `.bias( ${ params[ 2 ] } )`;
  132. }
  133. } else if ( node.name === 'textureLod' ) {
  134. code += `.level( ${ params[ 2 ] } )`;
  135. } else if ( node.name === 'textureGrad' ) {
  136. code += `.grad( ${ params[ 2 ] }, ${ params[ 3 ] } )`;
  137. } else if ( node.name === 'texelFetch' ) {
  138. code += '.setSampler( false )';
  139. }
  140. } else {
  141. this.addImport( node.name );
  142. const paramsStr = params.length > 0 ? ' ' + params.join( ', ' ) + ' ' : '';
  143. code = `${ node.name }(${ paramsStr })`;
  144. }
  145. } else if ( node.isReturn ) {
  146. code = 'return';
  147. if ( node.value ) {
  148. code += ' ' + this.emitExpression( node.value );
  149. }
  150. } else if ( node.isDiscard ) {
  151. this.addImport( 'Discard' );
  152. code = 'Discard()';
  153. } else if ( node.isBreak ) {
  154. this.addImport( 'Break' );
  155. code = 'Break()';
  156. } else if ( node.isContinue ) {
  157. this.addImport( 'Continue' );
  158. code = 'Continue()';
  159. } else if ( node.isAccessorElements ) {
  160. code = this.emitExpression( node.object );
  161. for ( const element of node.elements ) {
  162. if ( element.isStaticElement ) {
  163. code += '.' + this.emitExpression( element.value );
  164. } else if ( element.isDynamicElement ) {
  165. const value = this.emitExpression( element.value );
  166. if ( isPrimitive( value ) ) {
  167. code += `[ ${ value } ]`;
  168. } else {
  169. code += `.element( ${ value } )`;
  170. }
  171. }
  172. }
  173. } else if ( node.isDynamicElement ) {
  174. code = this.emitExpression( node.value );
  175. } else if ( node.isStaticElement ) {
  176. code = this.emitExpression( node.value );
  177. } else if ( node.isFor ) {
  178. code = this.emitFor( node );
  179. } else if ( node.isSwitch ) {
  180. code = this.emitSwitch( node );
  181. } else if ( node.isVariableDeclaration ) {
  182. code = this.emitVariables( node );
  183. } else if ( node.isUniform ) {
  184. code = this.emitUniform( node );
  185. } else if ( node.isVarying ) {
  186. code = this.emitVarying( node );
  187. } else if ( node.isTernary ) {
  188. code = this.emitTernary( node );
  189. } else if ( node.isConditional ) {
  190. code = this.emitConditional( node );
  191. } else if ( node.isUnary && node.expression.isNumber ) {
  192. code = node.expression.type + '( ' + node.type + ' ' + node.expression.value + ' )';
  193. this.addImport( node.expression.type );
  194. } else if ( node.isUnary ) {
  195. let type = unaryLib[ node.type ];
  196. if ( node.type === '++' || node.type === '--' ) {
  197. if ( this._currentVariable === null ) {
  198. // optimize increment/decrement operator
  199. // to avoid creating a new variable
  200. node.after = false;
  201. }
  202. if ( node.after === false ) {
  203. type += 'Before';
  204. }
  205. }
  206. const exp = this.emitExpression( node.expression );
  207. if ( isPrimitive( exp ) ) {
  208. this.addImport( type );
  209. code = type + '( ' + exp + ' )';
  210. } else {
  211. code = exp + '.' + type + '()';
  212. }
  213. } else {
  214. console.warn( 'Unknown node type', node );
  215. }
  216. if ( ! code ) code = '/* unknown statement */';
  217. return code;
  218. }
  219. emitBody( body ) {
  220. this.setLastStatement( null );
  221. let code = '';
  222. this.tab += '\t';
  223. for ( const statement of body ) {
  224. if ( this.block && this.block.isSwitchCase ) {
  225. if ( statement.isBreak ) continue; // skip break statements in switch cases
  226. }
  227. code += this.emitExtraLine( statement );
  228. code += this.tab + this.emitExpression( statement );
  229. if ( code.slice( - 1 ) !== '}' ) code += ';';
  230. code += '\n';
  231. this.setLastStatement( statement );
  232. }
  233. code = code.slice( 0, - 1 ); // remove the last extra line
  234. this.tab = this.tab.slice( 0, - 1 );
  235. return code;
  236. }
  237. emitTernary( node ) {
  238. const condStr = this.emitExpression( node.cond );
  239. const leftStr = this.emitExpression( node.left );
  240. const rightStr = this.emitExpression( node.right );
  241. this.addImport( 'select' );
  242. return `select( ${ condStr }, ${ leftStr }, ${ rightStr } )`;
  243. }
  244. emitConditional( node ) {
  245. const condStr = this.emitExpression( node.cond );
  246. const bodyStr = this.emitBody( node.body );
  247. let ifStr = `If( ${ condStr }, () => {
  248. ${ bodyStr }
  249. ${ this.tab }} )`;
  250. let current = node;
  251. while ( current.elseConditional ) {
  252. const elseBodyStr = this.emitBody( current.elseConditional.body );
  253. if ( current.elseConditional.cond ) {
  254. const elseCondStr = this.emitExpression( current.elseConditional.cond );
  255. ifStr += `.ElseIf( ${ elseCondStr }, () => {
  256. ${ elseBodyStr }
  257. ${ this.tab }} )`;
  258. } else {
  259. ifStr += `.Else( () => {
  260. ${ elseBodyStr }
  261. ${ this.tab }} )`;
  262. }
  263. current = current.elseConditional;
  264. }
  265. this.imports.add( 'If' );
  266. return ifStr;
  267. }
  268. emitLoop( node ) {
  269. const start = this.emitExpression( node.initialization.value );
  270. const end = this.emitExpression( node.condition.right );
  271. const name = node.initialization.name;
  272. const type = node.initialization.type;
  273. const condition = node.condition.type;
  274. const nameParam = name !== 'i' ? `, name: '${ name }'` : '';
  275. const typeParam = type !== 'int' ? `, type: '${ type }'` : '';
  276. const conditionParam = condition !== '<' ? `, condition: '${ condition }'` : '';
  277. let updateParam = '';
  278. if ( node.afterthought.isUnary ) {
  279. if ( node.afterthought.type !== '++' ) {
  280. updateParam = `, update: '${ node.afterthought.type }'`;
  281. }
  282. } else if ( node.afterthought.isOperator ) {
  283. if ( node.afterthought.right.isAccessor || node.afterthought.right.isNumber ) {
  284. updateParam = `, update: ${ this.emitExpression( node.afterthought.right ) }`;
  285. } else {
  286. updateParam = `, update: ( { i } ) => ${ this.emitExpression( node.afterthought ) }`;
  287. }
  288. }
  289. let loopStr = `Loop( { start: ${ start }, end: ${ end + nameParam + typeParam + conditionParam + updateParam } }, ( { ${ name } } ) => {\n\n`;
  290. loopStr += this.emitBody( node.body ) + '\n\n';
  291. loopStr += this.tab + '} )';
  292. this.imports.add( 'Loop' );
  293. return loopStr;
  294. }
  295. emitSwitch( switchNode ) {
  296. const discriminantString = this.emitExpression( switchNode.discriminant );
  297. this.tab += '\t';
  298. let switchString = `Switch( ${ discriminantString } )\n${ this.tab }`;
  299. let caseNode = switchNode.case;
  300. const previousBlock = this.block;
  301. while ( caseNode !== null ) {
  302. this.block = caseNode;
  303. let caseBodyString;
  304. if ( ! caseNode.isDefault ) {
  305. const caseConditions = [ this.emitExpression( caseNode.caseCondition ) ];
  306. while ( caseNode.body.length === 0 && caseNode.nextCase !== null && caseNode.nextCase.isDefault !== true ) {
  307. caseNode = caseNode.nextCase;
  308. caseConditions.push( this.emitExpression( caseNode.caseCondition ) );
  309. }
  310. caseBodyString = this.emitBody( caseNode.body );
  311. switchString += `.Case( ${ caseConditions.join( ', ' ) }, `;
  312. } else {
  313. caseBodyString = this.emitBody( caseNode.body );
  314. switchString += '.Default( ';
  315. }
  316. switchString += `() => {
  317. ${ caseBodyString }
  318. ${ this.tab }} )`;
  319. caseNode = caseNode.nextCase;
  320. }
  321. this.block = previousBlock;
  322. this.tab = this.tab.slice( 0, - 1 );
  323. this.imports.add( 'Switch' );
  324. return switchString;
  325. }
  326. emitFor( node ) {
  327. const { initialization, condition, afterthought } = node;
  328. if ( ( initialization && initialization.isVariableDeclaration && initialization.next === null ) &&
  329. ( condition && condition.left.isAccessor && condition.left.property === initialization.name ) &&
  330. ( afterthought && (
  331. ( afterthought.isUnary && ( initialization.name === afterthought.expression.property ) ) ||
  332. ( afterthought.isOperator && ( initialization.name === afterthought.left.property ) )
  333. ) )
  334. ) {
  335. return this.emitLoop( node );
  336. }
  337. return this.emitForWhile( node );
  338. }
  339. emitForWhile( node ) {
  340. const initialization = this.emitExpression( node.initialization );
  341. const condition = this.emitExpression( node.condition );
  342. const afterthought = this.emitExpression( node.afterthought );
  343. this.tab += '\t';
  344. let forStr = '{\n\n' + this.tab + initialization + ';\n\n';
  345. forStr += `${ this.tab }Loop( ${ condition }, () => {\n\n`;
  346. forStr += this.emitBody( node.body ) + '\n\n';
  347. forStr += this.tab + '\t' + afterthought + ';\n\n';
  348. forStr += this.tab + '} )\n\n';
  349. this.tab = this.tab.slice( 0, - 1 );
  350. forStr += this.tab + '}';
  351. this.imports.add( 'Loop' );
  352. return forStr;
  353. }
  354. emitVariables( node, isRoot = true ) {
  355. const { name, type, value, next } = node;
  356. this._currentVariable = node;
  357. const valueStr = value ? this.emitExpression( value ) : '';
  358. let varStr = isRoot ? 'const ' : '';
  359. varStr += name;
  360. if ( value ) {
  361. if ( value.isFunctionCall && value.name === type ) {
  362. varStr += ' = ' + valueStr;
  363. } else {
  364. varStr += ` = ${ type }( ${ valueStr } )`;
  365. }
  366. } else {
  367. varStr += ` = ${ type }()`;
  368. }
  369. if ( node.immutable === false ) {
  370. varStr += '.toVar()';
  371. }
  372. if ( next ) {
  373. varStr += ', ' + this.emitVariables( next, false );
  374. }
  375. this.addImport( type );
  376. this._currentVariable = null;
  377. return varStr;
  378. }
  379. emitVarying( node ) {
  380. const { name, type } = node;
  381. this.addImport( 'varying' );
  382. this.addImport( type );
  383. return `const ${ name } = varying( ${ type }(), '${ name }' )`;
  384. }
  385. emitOverloadingFunction( nodes ) {
  386. const { name } = nodes[ 0 ];
  387. this.addImport( 'overloadingFn' );
  388. const prefix = this.iife === false ? 'export ' : '';
  389. return `${ prefix }const ${ name } = /*#__PURE__*/ overloadingFn( [ ${ nodes.map( node => node.name + '_' + nodes.indexOf( node ) ).join( ', ' ) } ] );\n`;
  390. }
  391. emitFunction( node ) {
  392. const { name, type } = node;
  393. this._currentProperties = { name: node };
  394. const params = [];
  395. const inputs = [];
  396. const mutableParams = [];
  397. let hasPointer = false;
  398. for ( const param of node.params ) {
  399. let name = param.name;
  400. if ( param.immutable === false && ( param.qualifier !== 'inout' && param.qualifier !== 'out' ) ) {
  401. name = name + '_immutable';
  402. mutableParams.push( param );
  403. }
  404. if ( param.qualifier ) {
  405. if ( param.qualifier === 'inout' || param.qualifier === 'out' ) {
  406. hasPointer = true;
  407. }
  408. }
  409. inputs.push( param.name + ': \'' + param.type + '\'' );
  410. params.push( name );
  411. this._currentProperties[ name ] = param;
  412. }
  413. for ( const param of mutableParams ) {
  414. node.body.unshift( new VariableDeclaration( param.type, param.name, new Accessor( param.name + '_immutable' ) ) );
  415. }
  416. const paramsStr = params.length > 0 ? ' [ ' + params.join( ', ' ) + ' ] ' : '';
  417. const bodyStr = this.emitBody( node.body );
  418. let fnName = name;
  419. let overloadingNodes = null;
  420. if ( this.overloadings.has( name ) ) {
  421. const overloadings = this.overloadings.get( name );
  422. if ( overloadings.length > 1 ) {
  423. const index = overloadings.indexOf( node );
  424. fnName += '_' + index;
  425. if ( index === overloadings.length - 1 ) {
  426. overloadingNodes = overloadings;
  427. }
  428. }
  429. }
  430. const prefix = this.iife === false ? 'export ' : '';
  431. let funcStr = `${ prefix }const ${ fnName } = /*#__PURE__*/ Fn( (${ paramsStr }) => {
  432. ${ bodyStr }
  433. ${ this.tab }}`;
  434. if ( node.layout !== false && hasPointer === false ) {
  435. funcStr += ', { ' + inputs.join( ', ' ) + ', return: \'' + type + '\' }';
  436. }
  437. funcStr += ' );\n';
  438. this.imports.add( 'Fn' );
  439. this.global.add( node.name );
  440. if ( overloadingNodes !== null ) {
  441. funcStr += '\n' + this.emitOverloadingFunction( overloadingNodes );
  442. }
  443. return funcStr;
  444. }
  445. setLastStatement( statement ) {
  446. this._lastStatement = statement;
  447. }
  448. emitExtraLine( statement ) {
  449. const last = this._lastStatement;
  450. if ( last === null ) return '';
  451. if ( statement.isReturn ) return '\n';
  452. const isExpression = ( st ) => st.isFunctionDeclaration !== true && st.isFor !== true && st.isConditional !== true && st.isSwitch !== true;
  453. const lastExp = isExpression( last );
  454. const currExp = isExpression( statement );
  455. if ( lastExp !== currExp || ( ! lastExp && ! currExp ) ) return '\n';
  456. return '';
  457. }
  458. emit( ast ) {
  459. let code = '\n';
  460. if ( this.iife ) this.tab += '\t';
  461. const overloadings = this.overloadings;
  462. for ( const statement of ast.body ) {
  463. if ( statement.isFunctionDeclaration ) {
  464. if ( overloadings.has( statement.name ) === false ) {
  465. overloadings.set( statement.name, [] );
  466. }
  467. overloadings.get( statement.name ).push( statement );
  468. }
  469. }
  470. for ( const statement of ast.body ) {
  471. code += this.emitExtraLine( statement );
  472. if ( statement.isFunctionDeclaration ) {
  473. code += this.tab + this.emitFunction( statement );
  474. } else {
  475. code += this.tab + this.emitExpression( statement ) + ';\n';
  476. }
  477. this.setLastStatement( statement );
  478. }
  479. const imports = [ ...this.imports ];
  480. const exports = [ ...this.global ];
  481. let header = '// Three.js Transpiler r' + REVISION + '\n\n';
  482. let footer = '';
  483. if ( this.iife ) {
  484. header += '( function ( TSL, uniforms ) {\n\n';
  485. header += imports.length > 0 ? '\tconst { ' + imports.join( ', ' ) + ' } = TSL;\n' : '';
  486. footer += exports.length > 0 ? '\treturn { ' + exports.join( ', ' ) + ' };\n' : '';
  487. footer += '\n} );';
  488. } else {
  489. header += imports.length > 0 ? 'import { ' + imports.join( ', ' ) + ' } from \'three/tsl\';\n' : '';
  490. }
  491. return header + code + footer;
  492. }
  493. }
  494. export default TSLEncoder;
粤ICP备19079148号