TSLEncoder.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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. '&&': 'and',
  17. '||': 'or',
  18. '^^': 'xor',
  19. '&': 'bitAnd',
  20. '|': 'bitOr',
  21. '^': 'bitXor',
  22. '<<': 'shiftLeft',
  23. '>>': 'shiftRight',
  24. '+=': 'addAssign',
  25. '-=': 'subAssign',
  26. '*=': 'mulAssign',
  27. '/=': 'divAssign',
  28. '%=': 'remainderAssign',
  29. '^=': 'bitXorAssign',
  30. '&=': 'bitAndAssign',
  31. '|=': 'bitOrAssign',
  32. '<<=': 'shiftLeftAssign',
  33. '>>=': 'shiftRightAssign'
  34. };
  35. const unaryLib = {
  36. '+': '', // positive
  37. '-': 'negate',
  38. '~': 'bitNot',
  39. '!': 'not',
  40. '++': 'increment', // incrementBefore
  41. '--': 'decrement' // decrementBefore
  42. };
  43. const isPrimitive = ( value ) => /^(true|false|-?(\d|\.\d))/.test( value );
  44. class TSLEncoder {
  45. constructor() {
  46. this.tab = '';
  47. this.imports = new Set();
  48. this.global = new Set();
  49. this.overloadings = new Map();
  50. this.iife = false;
  51. this.uniqueNames = false;
  52. this.reference = false;
  53. this._currentProperties = {};
  54. this._lastStatement = null;
  55. }
  56. addImport( name ) {
  57. // import only if it's a node
  58. name = name.split( '.' )[ 0 ];
  59. if ( TSL[ name ] !== undefined && this.global.has( name ) === false && this._currentProperties[ name ] === undefined ) {
  60. this.imports.add( name );
  61. }
  62. }
  63. emitUniform( node ) {
  64. let code = `const ${ node.name } = `;
  65. if ( this.reference === true ) {
  66. this.addImport( 'reference' );
  67. this.global.add( node.name );
  68. //code += `reference( '${ node.name }', '${ node.type }', uniforms )`;
  69. // legacy
  70. code += `reference( 'value', '${ node.type }', uniforms[ '${ node.name }' ] )`;
  71. } else {
  72. this.addImport( 'uniform' );
  73. this.global.add( node.name );
  74. code += `uniform( '${ node.type }' )`;
  75. }
  76. return code;
  77. }
  78. emitExpression( node ) {
  79. let code;
  80. if ( node.isAccessor ) {
  81. this.addImport( node.property );
  82. code = node.property;
  83. } else if ( node.isNumber ) {
  84. if ( node.type === 'int' || node.type === 'uint' ) {
  85. code = node.type + '( ' + node.value + ' )';
  86. this.addImport( node.type );
  87. } else {
  88. code = node.value;
  89. }
  90. } else if ( node.isString ) {
  91. code = '\'' + node.value + '\'';
  92. } else if ( node.isOperator ) {
  93. const opFn = opLib[ node.type ] || node.type;
  94. const left = this.emitExpression( node.left );
  95. const right = this.emitExpression( node.right );
  96. if ( isPrimitive( left ) && isPrimitive( right ) ) {
  97. return left + ' ' + node.type + ' ' + right;
  98. }
  99. if ( isPrimitive( left ) ) {
  100. code = opFn + '( ' + left + ', ' + right + ' )';
  101. this.addImport( opFn );
  102. } else if ( opFn === '.' ) {
  103. code = left + opFn + right;
  104. } else {
  105. code = left + '.' + opFn + '( ' + right + ' )';
  106. }
  107. } else if ( node.isFunctionCall ) {
  108. const params = [];
  109. for ( const parameter of node.params ) {
  110. params.push( this.emitExpression( parameter ) );
  111. }
  112. this.addImport( node.name );
  113. const paramsStr = params.length > 0 ? ' ' + params.join( ', ' ) + ' ' : '';
  114. code = `${ node.name }(${ paramsStr })`;
  115. } else if ( node.isReturn ) {
  116. code = 'return';
  117. if ( node.value ) {
  118. code += ' ' + this.emitExpression( node.value );
  119. }
  120. } else if ( node.isAccessorElements ) {
  121. code = this.emitExpression( node.object );
  122. for ( const element of node.elements ) {
  123. if ( element.isStaticElement ) {
  124. code += '.' + this.emitExpression( element.value );
  125. } else if ( element.isDynamicElement ) {
  126. const value = this.emitExpression( element.value );
  127. if ( isPrimitive( value ) ) {
  128. code += `[ ${ value } ]`;
  129. } else {
  130. code += `.element( ${ value } )`;
  131. }
  132. }
  133. }
  134. } else if ( node.isDynamicElement ) {
  135. code = this.emitExpression( node.value );
  136. } else if ( node.isStaticElement ) {
  137. code = this.emitExpression( node.value );
  138. } else if ( node.isFor ) {
  139. code = this.emitFor( node );
  140. } else if ( node.isVariableDeclaration ) {
  141. code = this.emitVariables( node );
  142. } else if ( node.isUniform ) {
  143. code = this.emitUniform( node );
  144. } else if ( node.isVarying ) {
  145. code = this.emitVarying( node );
  146. } else if ( node.isTernary ) {
  147. code = this.emitTernary( node );
  148. } else if ( node.isConditional ) {
  149. code = this.emitConditional( node );
  150. } else if ( node.isUnary && node.expression.isNumber ) {
  151. code = node.expression.type + '( ' + node.type + ' ' + node.expression.value + ' )';
  152. this.addImport( node.expression.type );
  153. } else if ( node.isUnary ) {
  154. let type = unaryLib[ node.type ];
  155. if ( node.after === false && ( node.type === '++' || node.type === '--' ) ) {
  156. type += 'Before';
  157. }
  158. const exp = this.emitExpression( node.expression );
  159. if ( isPrimitive( exp ) ) {
  160. this.addImport( type );
  161. code = type + '( ' + exp + ' )';
  162. } else {
  163. code = exp + '.' + type + '()';
  164. }
  165. } else {
  166. console.warn( 'Unknown node type', node );
  167. }
  168. if ( ! code ) code = '/* unknown statement */';
  169. return code;
  170. }
  171. emitBody( body ) {
  172. this.setLastStatement( null );
  173. let code = '';
  174. this.tab += '\t';
  175. for ( const statement of body ) {
  176. code += this.emitExtraLine( statement );
  177. code += this.tab + this.emitExpression( statement );
  178. if ( code.slice( - 1 ) !== '}' ) code += ';';
  179. code += '\n';
  180. this.setLastStatement( statement );
  181. }
  182. code = code.slice( 0, - 1 ); // remove the last extra line
  183. this.tab = this.tab.slice( 0, - 1 );
  184. return code;
  185. }
  186. emitTernary( node ) {
  187. const condStr = this.emitExpression( node.cond );
  188. const leftStr = this.emitExpression( node.left );
  189. const rightStr = this.emitExpression( node.right );
  190. this.addImport( 'select' );
  191. return `select( ${ condStr }, ${ leftStr }, ${ rightStr } )`;
  192. }
  193. emitConditional( node ) {
  194. const condStr = this.emitExpression( node.cond );
  195. const bodyStr = this.emitBody( node.body );
  196. let ifStr = `If( ${ condStr }, () => {
  197. ${ bodyStr }
  198. ${ this.tab }} )`;
  199. let current = node;
  200. while ( current.elseConditional ) {
  201. const elseBodyStr = this.emitBody( current.elseConditional.body );
  202. if ( current.elseConditional.cond ) {
  203. const elseCondStr = this.emitExpression( current.elseConditional.cond );
  204. ifStr += `.ElseIf( ${ elseCondStr }, () => {
  205. ${ elseBodyStr }
  206. ${ this.tab }} )`;
  207. } else {
  208. ifStr += `.Else( () => {
  209. ${ elseBodyStr }
  210. ${ this.tab }} )`;
  211. }
  212. current = current.elseConditional;
  213. }
  214. this.imports.add( 'If' );
  215. return ifStr;
  216. }
  217. emitLoop( node ) {
  218. const start = this.emitExpression( node.initialization.value );
  219. const end = this.emitExpression( node.condition.right );
  220. const name = node.initialization.name;
  221. const type = node.initialization.type;
  222. const condition = node.condition.type;
  223. const update = node.afterthought.type;
  224. const nameParam = name !== 'i' ? `, name: '${ name }'` : '';
  225. const typeParam = type !== 'int' ? `, type: '${ type }'` : '';
  226. const conditionParam = condition !== '<' ? `, condition: '${ condition }'` : '';
  227. const updateParam = update !== '++' ? `, update: '${ update }'` : '';
  228. let loopStr = `Loop( { start: ${ start }, end: ${ end + nameParam + typeParam + conditionParam + updateParam } }, ( { ${ name } } ) => {\n\n`;
  229. loopStr += this.emitBody( node.body ) + '\n\n';
  230. loopStr += this.tab + '} )';
  231. this.imports.add( 'Loop' );
  232. return loopStr;
  233. }
  234. emitFor( node ) {
  235. const { initialization, condition, afterthought } = node;
  236. if ( ( initialization && initialization.isVariableDeclaration && initialization.next === null ) &&
  237. ( condition && condition.left.isAccessor && condition.left.property === initialization.name ) &&
  238. ( afterthought && afterthought.isUnary ) &&
  239. ( initialization.name === afterthought.expression.property )
  240. ) {
  241. return this.emitLoop( node );
  242. }
  243. return this.emitForWhile( node );
  244. }
  245. emitForWhile( node ) {
  246. const initialization = this.emitExpression( node.initialization );
  247. const condition = this.emitExpression( node.condition );
  248. const afterthought = this.emitExpression( node.afterthought );
  249. this.tab += '\t';
  250. let forStr = '{\n\n' + this.tab + initialization + ';\n\n';
  251. forStr += `${ this.tab }While( ${ condition }, () => {\n\n`;
  252. forStr += this.emitBody( node.body ) + '\n\n';
  253. forStr += this.tab + '\t' + afterthought + ';\n\n';
  254. forStr += this.tab + '} )\n\n';
  255. this.tab = this.tab.slice( 0, - 1 );
  256. forStr += this.tab + '}';
  257. this.imports.add( 'While' );
  258. return forStr;
  259. }
  260. emitVariables( node, isRoot = true ) {
  261. const { name, type, value, next } = node;
  262. const valueStr = value ? this.emitExpression( value ) : '';
  263. let varStr = isRoot ? 'const ' : '';
  264. varStr += name;
  265. if ( value ) {
  266. if ( value.isFunctionCall && value.name === type ) {
  267. varStr += ' = ' + valueStr;
  268. } else {
  269. varStr += ` = ${ type }( ${ valueStr } )`;
  270. }
  271. } else {
  272. varStr += ` = ${ type }()`;
  273. }
  274. if ( node.immutable === false ) {
  275. varStr += '.toVar()';
  276. }
  277. if ( next ) {
  278. varStr += ', ' + this.emitVariables( next, false );
  279. }
  280. this.addImport( type );
  281. return varStr;
  282. }
  283. emitVarying( node ) {
  284. const { name, type } = node;
  285. this.addImport( 'varying' );
  286. this.addImport( type );
  287. return `const ${ name } = varying( ${ type }(), '${ name }' )`;
  288. }
  289. emitOverloadingFunction( nodes ) {
  290. const { name } = nodes[ 0 ];
  291. this.addImport( 'overloadingFn' );
  292. const prefix = this.iife === false ? 'export ' : '';
  293. return `${ prefix }const ${ name } = /*#__PURE__*/ overloadingFn( [ ${ nodes.map( node => node.name + '_' + nodes.indexOf( node ) ).join( ', ' ) } ] );\n`;
  294. }
  295. emitFunction( node ) {
  296. const { name, type } = node;
  297. this._currentProperties = { name: node };
  298. const params = [];
  299. const inputs = [];
  300. const mutableParams = [];
  301. let hasPointer = false;
  302. for ( const param of node.params ) {
  303. let str = `{ name: '${ param.name }', type: '${ param.type }'`;
  304. let name = param.name;
  305. if ( param.immutable === false && ( param.qualifier !== 'inout' && param.qualifier !== 'out' ) ) {
  306. name = name + '_immutable';
  307. mutableParams.push( param );
  308. }
  309. if ( param.qualifier ) {
  310. if ( param.qualifier === 'inout' || param.qualifier === 'out' ) {
  311. hasPointer = true;
  312. }
  313. str += ', qualifier: \'' + param.qualifier + '\'';
  314. }
  315. inputs.push( str + ' }' );
  316. params.push( name );
  317. this._currentProperties[ name ] = param;
  318. }
  319. for ( const param of mutableParams ) {
  320. node.body.unshift( new VariableDeclaration( param.type, param.name, new Accessor( param.name + '_immutable' ) ) );
  321. }
  322. const paramsStr = params.length > 0 ? ' [ ' + params.join( ', ' ) + ' ] ' : '';
  323. const bodyStr = this.emitBody( node.body );
  324. let fnName = name;
  325. let overloadingNodes = null;
  326. if ( this.overloadings.has( name ) ) {
  327. const overloadings = this.overloadings.get( name );
  328. if ( overloadings.length > 1 ) {
  329. const index = overloadings.indexOf( node );
  330. fnName += '_' + index;
  331. if ( index === overloadings.length - 1 ) {
  332. overloadingNodes = overloadings;
  333. }
  334. }
  335. }
  336. const prefix = this.iife === false ? 'export ' : '';
  337. let funcStr = `${ prefix }const ${ fnName } = /*#__PURE__*/ Fn( (${ paramsStr }) => {
  338. ${ bodyStr }
  339. ${ this.tab }} )`;
  340. const layoutInput = inputs.length > 0 ? '\n\t\t' + this.tab + inputs.join( ',\n\t\t' + this.tab ) + '\n\t' + this.tab : '';
  341. if ( node.layout !== false && hasPointer === false ) {
  342. const uniqueName = this.uniqueNames ? fnName + '_' + Math.random().toString( 36 ).slice( 2 ) : fnName;
  343. funcStr += `.setLayout( {
  344. ${ this.tab }\tname: '${ uniqueName }',
  345. ${ this.tab }\ttype: '${ type }',
  346. ${ this.tab }\tinputs: [${ layoutInput }]
  347. ${ this.tab }} )`;
  348. }
  349. funcStr += ';\n';
  350. this.imports.add( 'Fn' );
  351. this.global.add( node.name );
  352. if ( overloadingNodes !== null ) {
  353. funcStr += '\n' + this.emitOverloadingFunction( overloadingNodes );
  354. }
  355. return funcStr;
  356. }
  357. setLastStatement( statement ) {
  358. this._lastStatement = statement;
  359. }
  360. emitExtraLine( statement ) {
  361. const last = this._lastStatement;
  362. if ( last === null ) return '';
  363. if ( statement.isReturn ) return '\n';
  364. const isExpression = ( st ) => st.isFunctionDeclaration !== true && st.isFor !== true && st.isConditional !== true;
  365. const lastExp = isExpression( last );
  366. const currExp = isExpression( statement );
  367. if ( lastExp !== currExp || ( ! lastExp && ! currExp ) ) return '\n';
  368. return '';
  369. }
  370. emit( ast ) {
  371. let code = '\n';
  372. if ( this.iife ) this.tab += '\t';
  373. const overloadings = this.overloadings;
  374. for ( const statement of ast.body ) {
  375. if ( statement.isFunctionDeclaration ) {
  376. if ( overloadings.has( statement.name ) === false ) {
  377. overloadings.set( statement.name, [] );
  378. }
  379. overloadings.get( statement.name ).push( statement );
  380. }
  381. }
  382. for ( const statement of ast.body ) {
  383. code += this.emitExtraLine( statement );
  384. if ( statement.isFunctionDeclaration ) {
  385. code += this.tab + this.emitFunction( statement );
  386. } else {
  387. code += this.tab + this.emitExpression( statement ) + ';\n';
  388. }
  389. this.setLastStatement( statement );
  390. }
  391. const imports = [ ...this.imports ];
  392. const exports = [ ...this.global ];
  393. let header = '// Three.js Transpiler r' + REVISION + '\n\n';
  394. let footer = '';
  395. if ( this.iife ) {
  396. header += '( function ( TSL, uniforms ) {\n\n';
  397. header += imports.length > 0 ? '\tconst { ' + imports.join( ', ' ) + ' } = TSL;\n' : '';
  398. footer += exports.length > 0 ? '\treturn { ' + exports.join( ', ' ) + ' };\n' : '';
  399. footer += '\n} );';
  400. } else {
  401. header += imports.length > 0 ? 'import { ' + imports.join( ', ' ) + ' } from \'three/tsl\';\n' : '';
  402. }
  403. return header + code + footer;
  404. }
  405. }
  406. export default TSLEncoder;
粤ICP备19079148号