TSLEncoder.js 13 KB

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