WGSLEncoder.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. import { REVISION } from 'three/webgpu';
  2. import { VariableDeclaration, Accessor } from './AST.js';
  3. import { isExpression } from './TranspilerUtils.js';
  4. // Note: This is a simplified list. A complete implementation would need more mappings.
  5. const typeMap = {
  6. 'float': 'f32',
  7. 'int': 'i32',
  8. 'uint': 'u32',
  9. 'bool': 'bool',
  10. 'vec2': 'vec2f',
  11. 'ivec2': 'vec2i',
  12. 'uvec2': 'vec2u',
  13. 'bvec2': 'vec2b',
  14. 'vec3': 'vec3f',
  15. 'ivec3': 'vec3i',
  16. 'uvec3': 'vec3u',
  17. 'bvec3': 'vec3b',
  18. 'vec4': 'vec4f',
  19. 'ivec4': 'vec4i',
  20. 'uvec4': 'vec4u',
  21. 'bvec4': 'vec4b',
  22. 'mat3': 'mat3x3<f32>',
  23. 'mat4': 'mat4x4<f32>',
  24. 'texture': 'texture_2d<f32>',
  25. 'textureCube': 'texture_cube<f32>',
  26. 'texture3D': 'texture_3d<f32>',
  27. };
  28. // GLSL to WGSL built-in function mapping
  29. const wgslLib = {
  30. 'abs': 'abs',
  31. 'acos': 'acos',
  32. 'asin': 'asin',
  33. 'atan': 'atan',
  34. 'atan2': 'atan2',
  35. 'ceil': 'ceil',
  36. 'clamp': 'clamp',
  37. 'cos': 'cos',
  38. 'cross': 'cross',
  39. 'degrees': 'degrees',
  40. 'distance': 'distance',
  41. 'dot': 'dot',
  42. 'exp': 'exp',
  43. 'exp2': 'exp2',
  44. 'faceforward': 'faceForward',
  45. 'floor': 'floor',
  46. 'fract': 'fract',
  47. 'inverse': 'inverse',
  48. 'inversesqrt': 'inverseSqrt',
  49. 'length': 'length',
  50. 'log': 'log',
  51. 'log2': 'log2',
  52. 'max': 'max',
  53. 'min': 'min',
  54. 'mix': 'mix',
  55. 'normalize': 'normalize',
  56. 'pow': 'pow',
  57. 'radians': 'radians',
  58. 'reflect': 'reflect',
  59. 'refract': 'refract',
  60. 'round': 'round',
  61. 'sign': 'sign',
  62. 'sin': 'sin',
  63. 'smoothstep': 'smoothstep',
  64. 'sqrt': 'sqrt',
  65. 'step': 'step',
  66. 'tan': 'tan',
  67. 'transpose': 'transpose',
  68. 'trunc': 'trunc',
  69. 'dFdx': 'dpdx',
  70. 'dFdy': 'dpdy',
  71. 'fwidth': 'fwidth',
  72. // Texture functions are handled separately
  73. 'texture': 'textureSample',
  74. 'texture2D': 'textureSample',
  75. 'texture3D': 'textureSample',
  76. 'textureCube': 'textureSample',
  77. 'textureLod': 'textureSampleLevel',
  78. 'texelFetch': 'textureLoad',
  79. 'textureGrad': 'textureSampleGrad',
  80. 'floatBitsToInt': 'bitcast<i32>',
  81. 'floatBitsToUint': 'bitcast<u32>',
  82. 'intBitsToFloat': 'bitcast<f32>',
  83. 'uintBitsToFloat': 'bitcast<f32>',
  84. };
  85. class WGSLEncoder {
  86. constructor() {
  87. this.tab = '';
  88. this.functions = new Map();
  89. this.uniforms = [];
  90. this.varyings = [];
  91. this.structs = new Map();
  92. this.polyfills = new Map();
  93. // Assume a single group for simplicity
  94. this.groupIndex = 0;
  95. }
  96. getWgslType( type ) {
  97. return typeMap[ type ] || type;
  98. }
  99. emitExpression( node ) {
  100. if ( ! node ) return '';
  101. let code;
  102. if ( node.isAccessor ) {
  103. // Check if this accessor is part of a uniform struct
  104. const uniform = this.uniforms.find( u => u.name === node.property );
  105. if ( uniform && ! uniform.type.includes( 'texture' ) ) {
  106. return `uniforms.${node.property}`;
  107. }
  108. code = node.property;
  109. } else if ( node.isNumber ) {
  110. code = node.value;
  111. // WGSL requires floating point numbers to have a decimal
  112. if ( node.type === 'float' && ! code.includes( '.' ) ) {
  113. code += '.0';
  114. }
  115. } else if ( node.isOperator ) {
  116. const left = this.emitExpression( node.left );
  117. const right = this.emitExpression( node.right );
  118. code = `${ left } ${ node.type } ${ right }`;
  119. if ( node.parent.isAssignment !== true && node.parent.isOperator ) {
  120. code = `( ${ code } )`;
  121. }
  122. } else if ( node.isFunctionCall ) {
  123. const fnName = wgslLib[ node.name ] || node.name;
  124. if ( fnName === 'mod' ) {
  125. const snippets = node.params.map( p => this.emitExpression( p ) );
  126. const types = node.params.map( p => p.getType() );
  127. const modFnName = 'mod_' + types.join( '_' );
  128. if ( this.polyfills.has( modFnName ) === false ) {
  129. this.polyfills.set( modFnName, `fn ${ modFnName }( x: ${ this.getWgslType( types[ 0 ] ) }, y: ${ this.getWgslType( types[ 1 ] ) } ) -> ${ this.getWgslType( types[ 0 ] ) } {
  130. return x - y * floor( x / y );
  131. }` );
  132. }
  133. code = `${ modFnName }( ${ snippets.join( ', ' ) } )`;
  134. } else if ( fnName.startsWith( 'bitcast' ) ) {
  135. const params = node.params.map( p => this.emitExpression( p ) ).join( ',' );
  136. const types = node.params.map( p => p.getType() );
  137. if ( /.*vec[234]/.test( types[ 0 ] ) ) {
  138. const conversionType = fnName.substring( 8, fnName.length - 1 );
  139. const vectorType = types[ 0 ].substring( - 1 );
  140. code = `bitcast<${ vectorType }<${ conversionType }>>`;
  141. } else {
  142. code = fnName;
  143. }
  144. code += `( ${ params } )`;
  145. } else if ( fnName.startsWith( 'texture' ) ) {
  146. // Handle texture functions separately due to sampler handling
  147. code = this.emitTextureAccess( node );
  148. } else {
  149. const params = node.params.map( p => this.emitExpression( p ) );
  150. if ( typeMap[ fnName ] ) {
  151. // Handle type constructors like vec3(...)
  152. code = this.getWgslType( fnName );
  153. } else {
  154. code = fnName;
  155. }
  156. if ( params.length > 0 ) {
  157. code += '( ' + params.join( ', ' ) + ' )';
  158. } else {
  159. code += '()';
  160. }
  161. }
  162. } else if ( node.isReturn ) {
  163. code = 'return';
  164. if ( node.value ) {
  165. code += ' ' + this.emitExpression( node.value );
  166. }
  167. } else if ( node.isDiscard ) {
  168. code = 'discard';
  169. } else if ( node.isBreak ) {
  170. if ( node.parent.isSwitchCase !== true ) {
  171. code = 'break';
  172. }
  173. } else if ( node.isContinue ) {
  174. code = 'continue';
  175. } else if ( node.isAccessorElements ) {
  176. code = this.emitExpression( node.object );
  177. for ( const element of node.elements ) {
  178. const value = this.emitExpression( element.value );
  179. if ( element.isStaticElement ) {
  180. code += '.' + value;
  181. } else if ( element.isDynamicElement ) {
  182. code += `[${value}]`;
  183. }
  184. }
  185. } else if ( node.isFor ) {
  186. code = this.emitFor( node );
  187. } else if ( node.isWhile ) {
  188. code = this.emitWhile( node );
  189. } else if ( node.isSwitch ) {
  190. code = this.emitSwitch( node );
  191. } else if ( node.isVariableDeclaration ) {
  192. code = this.emitVariables( node );
  193. } else if ( node.isUniform ) {
  194. this.uniforms.push( node );
  195. return ''; // Defer emission to the header
  196. } else if ( node.isVarying ) {
  197. this.varyings.push( node );
  198. return ''; // Defer emission to the header
  199. } else if ( node.isStructDefinition ) {
  200. code = this.emitStructDefinition( node );
  201. } else if ( node.isTernary ) {
  202. const cond = this.emitExpression( node.cond );
  203. const left = this.emitExpression( node.left );
  204. const right = this.emitExpression( node.right );
  205. // WGSL's equivalent to the ternary operator is select(false_val, true_val, condition)
  206. code = `select( ${ right }, ${ left }, ${ cond } )`;
  207. } else if ( node.isConditional ) {
  208. code = this.emitConditional( node );
  209. } else if ( node.isUnary ) {
  210. const expr = this.emitExpression( node.expression );
  211. if ( node.type === '++' || node.type === '--' ) {
  212. const op = node.type === '++' ? '+' : '-';
  213. code = `${ expr } = ${ expr } ${ op } 1`;
  214. } else {
  215. code = `${ node.type }${ expr }`;
  216. }
  217. } else {
  218. console.warn( 'Unknown node type in WGSL Encoder:', node );
  219. code = `/* unknown node: ${ node.constructor.name } */`;
  220. }
  221. return code;
  222. }
  223. emitTextureAccess( node ) {
  224. const wgslFn = wgslLib[ node.name ];
  225. const textureName = this.emitExpression( node.params[ 0 ] );
  226. const uv = this.emitExpression( node.params[ 1 ] );
  227. // WGSL requires explicit samplers. We assume a naming convention.
  228. const samplerName = `${textureName}_sampler`;
  229. let code;
  230. switch ( node.name ) {
  231. case 'texture':
  232. case 'texture2D':
  233. case 'texture3D':
  234. case 'textureCube':
  235. // format: textureSample(texture, sampler, coords, [offset])
  236. code = `${wgslFn}(${textureName}, ${samplerName}, ${uv}`;
  237. // Handle optional bias parameter (note: WGSL uses textureSampleBias)
  238. if ( node.params.length === 3 ) {
  239. const bias = this.emitExpression( node.params[ 2 ] );
  240. code = `textureSampleBias(${textureName}, ${samplerName}, ${uv}, ${bias})`;
  241. } else {
  242. code += ')';
  243. }
  244. break;
  245. case 'textureLod':
  246. // format: textureSampleLevel(texture, sampler, coords, level)
  247. const lod = this.emitExpression( node.params[ 2 ] );
  248. code = `${wgslFn}(${textureName}, ${samplerName}, ${uv}, ${lod})`;
  249. break;
  250. case 'textureGrad':
  251. // format: textureSampleGrad(texture, sampler, coords, ddx, ddy)
  252. const ddx = this.emitExpression( node.params[ 2 ] );
  253. const ddy = this.emitExpression( node.params[ 3 ] );
  254. code = `${wgslFn}(${textureName}, ${samplerName}, ${uv}, ${ddx}, ${ddy})`;
  255. break;
  256. case 'texelFetch':
  257. // format: textureLoad(texture, coords, [level])
  258. const coords = this.emitExpression( node.params[ 1 ] ); // should be ivec
  259. const lodFetch = node.params.length > 2 ? this.emitExpression( node.params[ 2 ] ) : '0';
  260. code = `${wgslFn}(${textureName}, ${coords}, ${lodFetch})`;
  261. break;
  262. default:
  263. code = `/* unsupported texture op: ${node.name} */`;
  264. }
  265. return code;
  266. }
  267. emitBody( body ) {
  268. let code = '';
  269. this.tab += '\t';
  270. for ( const statement of body ) {
  271. code += this.emitExtraLine( statement, body );
  272. if ( statement.isComment ) {
  273. code += this.emitComment( statement, body );
  274. continue;
  275. }
  276. const statementCode = this.emitExpression( statement );
  277. if ( statementCode ) {
  278. code += this.tab + statementCode;
  279. if ( ! statementCode.endsWith( '}' ) && ! statementCode.endsWith( '{' ) ) {
  280. code += ';';
  281. }
  282. code += '\n';
  283. }
  284. }
  285. this.tab = this.tab.slice( 0, - 1 );
  286. return code.slice( 0, - 1 ); // remove the last extra line
  287. }
  288. emitConditional( node ) {
  289. const condStr = this.emitExpression( node.cond );
  290. const bodyStr = this.emitBody( node.body );
  291. let ifStr = `if ( ${ condStr } ) {\n\n${ bodyStr }\n\n${ this.tab }}`;
  292. let current = node;
  293. while ( current.elseConditional ) {
  294. current = current.elseConditional;
  295. const elseBodyStr = this.emitBody( current.body );
  296. if ( current.cond ) { // This is an 'else if'
  297. const elseCondStr = this.emitExpression( current.cond );
  298. ifStr += ` else if ( ${ elseCondStr } ) {\n\n${ elseBodyStr }\n\n${ this.tab }}`;
  299. } else { // This is an 'else'
  300. ifStr += ` else {\n\n${ elseBodyStr }\n\n${ this.tab }}`;
  301. }
  302. }
  303. return ifStr;
  304. }
  305. emitFor( node ) {
  306. const init = this.emitExpression( node.initialization );
  307. const cond = this.emitExpression( node.condition );
  308. const after = this.emitExpression( node.afterthought );
  309. const body = this.emitBody( node.body );
  310. return `for ( ${ init }; ${ cond }; ${ after } ) {\n\n${ body }\n\n${ this.tab }}`;
  311. }
  312. emitWhile( node ) {
  313. const cond = this.emitExpression( node.condition );
  314. const body = this.emitBody( node.body );
  315. return `while ( ${ cond } ) {\n\n${ body }\n\n${ this.tab }}`;
  316. }
  317. emitSwitch( node ) {
  318. const discriminant = this.emitExpression( node.discriminant );
  319. let switchStr = `switch ( ${ discriminant } ) {\n\n`;
  320. this.tab += '\t';
  321. for ( const switchCase of node.cases ) {
  322. const body = this.emitBody( switchCase.body );
  323. if ( switchCase.isDefault ) {
  324. switchStr += `${ this.tab }default: {\n\n${ body }\n\n${ this.tab }}\n\n`;
  325. } else {
  326. const cases = switchCase.conditions.map( c => this.emitExpression( c ) ).join( ', ' );
  327. switchStr += `${ this.tab }case ${ cases }: {\n\n${ body }\n\n${ this.tab }}\n\n`;
  328. }
  329. }
  330. this.tab = this.tab.slice( 0, - 1 );
  331. switchStr += `${this.tab}}`;
  332. return switchStr;
  333. }
  334. emitVariables( node ) {
  335. const declarations = [];
  336. let current = node;
  337. while ( current ) {
  338. const type = this.getWgslType( current.type );
  339. let valueStr = '';
  340. if ( current.value ) {
  341. valueStr = ` = ${this.emitExpression( current.value )}`;
  342. }
  343. // The AST linker tracks if a variable is ever reassigned.
  344. // If so, use 'var'; otherwise, use 'let'.
  345. let keyword;
  346. if ( current.linker ) {
  347. if ( current.linker.assignments.length > 0 ) {
  348. keyword = 'var'; // Reassigned variable
  349. } else {
  350. if ( current.value && current.value.isNumericExpression ) {
  351. keyword = 'const'; // Immutable numeric expression
  352. } else {
  353. keyword = 'let'; // Immutable variable
  354. }
  355. }
  356. }
  357. declarations.push( `${ keyword } ${ current.name }: ${ type }${ valueStr }` );
  358. current = current.next;
  359. }
  360. // In WGSL, multiple declarations in one line are not supported, so join with semicolons.
  361. return declarations.join( ';\n' + this.tab );
  362. }
  363. emitStructDefinition( node ) {
  364. const { name, members } = node;
  365. let structString = `struct ${ name } {\n`;
  366. for ( let i = 0; i < members.length; i += 1 ) {
  367. const member = members[ i ];
  368. structString += `${ this.tab }\t${ member.name }: ${ this.getWgslType( member.type ) }`;
  369. const delimiter = ( i != members.length - 1 ) ? ',\n' : '\n';
  370. structString += delimiter;
  371. }
  372. structString += this.tab + '}';
  373. return structString;
  374. }
  375. emitFunction( node ) {
  376. const name = node.name;
  377. const returnType = this.getWgslType( node.type );
  378. const params = [];
  379. // We will prepend to a copy of the body, not the original AST node.
  380. const body = [ ...node.body ];
  381. for ( const param of node.params ) {
  382. const paramName = param.name;
  383. let paramType = this.getWgslType( param.type );
  384. // Handle 'inout' and 'out' qualifiers using pointers. They are already mutable.
  385. if ( param.qualifier === 'inout' || param.qualifier === 'out' ) {
  386. paramType = `ptr<function, ${paramType}>`;
  387. params.push( `${paramName}: ${paramType}` );
  388. continue;
  389. }
  390. // If the parameter is reassigned within the function, we need to
  391. // create a local, mutable variable that shadows the parameter's name.
  392. if ( param.linker && param.linker.assignments.length > 0 ) {
  393. // 1. Rename the incoming parameter to avoid name collision.
  394. const immutableParamName = `${paramName}_in`;
  395. params.push( `${immutableParamName}: ${paramType}` );
  396. // 2. Create a new Accessor node for the renamed immutable parameter.
  397. const immutableAccessor = new Accessor( immutableParamName );
  398. immutableAccessor.isAccessor = true;
  399. immutableAccessor.property = immutableParamName;
  400. // 3. Create a new VariableDeclaration node for the mutable local variable.
  401. // This new variable will have the original parameter's name.
  402. const mutableVar = new VariableDeclaration( param.type, param.name, immutableAccessor );
  403. // 4. Mark this new variable as mutable so `emitVariables` uses `var`.
  404. mutableVar.linker = { assignments: [ true ] };
  405. // 5. Prepend this new declaration to the function's body.
  406. body.unshift( mutableVar );
  407. } else {
  408. // This parameter is not reassigned, so treat it as a normal immutable parameter.
  409. params.push( `${paramName}: ${paramType}` );
  410. }
  411. }
  412. const paramsStr = params.length > 0 ? ' ' + params.join( ', ' ) + ' ' : '';
  413. const returnStr = ( returnType && returnType !== 'void' ) ? ` -> ${returnType}` : '';
  414. // Emit the function body, which now includes our injected variable declarations.
  415. const bodyStr = this.emitBody( body );
  416. return `fn ${name}(${paramsStr})${returnStr} {\n\n${bodyStr}\n\n${this.tab}}`;
  417. }
  418. emitComment( statement, body ) {
  419. const index = body.indexOf( statement );
  420. const previous = body[ index - 1 ];
  421. const next = body[ index + 1 ];
  422. let output = '';
  423. if ( previous && isExpression( previous ) ) {
  424. output += '\n';
  425. }
  426. output += this.tab + statement.comment.replace( /\n/g, '\n' + this.tab ) + '\n';
  427. if ( next && isExpression( next ) ) {
  428. output += '\n';
  429. }
  430. return output;
  431. }
  432. emitExtraLine( statement, body ) {
  433. const index = body.indexOf( statement );
  434. const previous = body[ index - 1 ];
  435. if ( previous === undefined ) return '';
  436. if ( statement.isReturn ) return '\n';
  437. const lastExp = isExpression( previous );
  438. const currExp = isExpression( statement );
  439. if ( lastExp !== currExp || ( ! lastExp && ! currExp ) ) return '\n';
  440. return '';
  441. }
  442. emit( ast ) {
  443. const header = '// Three.js Transpiler r' + REVISION + '\n\n';
  444. let globals = '';
  445. let functions = '';
  446. let dependencies = '';
  447. // 1. Pre-process to find all global declarations
  448. for ( const statement of ast.body ) {
  449. if ( statement.isFunctionDeclaration ) {
  450. this.functions.set( statement.name, statement );
  451. } else if ( statement.isUniform ) {
  452. this.uniforms.push( statement );
  453. } else if ( statement.isVarying ) {
  454. this.varyings.push( statement );
  455. }
  456. }
  457. // 2. Build resource bindings (uniforms, textures, samplers)
  458. if ( this.uniforms.length > 0 ) {
  459. let bindingIndex = 0;
  460. const uniformStructMembers = [];
  461. const textureGlobals = [];
  462. for ( const uniform of this.uniforms ) {
  463. // Textures are declared as separate global variables, not in the UBO
  464. if ( uniform.type.includes( 'texture' ) ) {
  465. textureGlobals.push( `@group(${this.groupIndex}) @binding(${bindingIndex ++}) var ${uniform.name}: ${this.getWgslType( uniform.type )};` );
  466. textureGlobals.push( `@group(${this.groupIndex}) @binding(${bindingIndex ++}) var ${uniform.name}_sampler: sampler;` );
  467. } else {
  468. uniformStructMembers.push( `\t${uniform.name}: ${this.getWgslType( uniform.type )},` );
  469. }
  470. }
  471. // Create a UBO struct if there are any non-texture uniforms
  472. if ( uniformStructMembers.length > 0 ) {
  473. globals += 'struct Uniforms {\n';
  474. globals += uniformStructMembers.join( '\n' );
  475. globals += '\n};\n';
  476. globals += `@group(${this.groupIndex}) @binding(${bindingIndex ++}) var<uniform> uniforms: Uniforms;\n\n`;
  477. }
  478. // Add the texture and sampler globals
  479. globals += textureGlobals.join( '\n' ) + '\n\n';
  480. }
  481. // 3. Build varying structs for stage I/O
  482. // This is a simplification; a full implementation would need to know the shader stage.
  483. if ( this.varyings.length > 0 ) {
  484. globals += 'struct Varyings {\n';
  485. let location = 0;
  486. for ( const varying of this.varyings ) {
  487. globals += `\t@location(${location ++}) ${varying.name}: ${this.getWgslType( varying.type )},\n`;
  488. }
  489. globals += '};\n\n';
  490. }
  491. // 4. Emit all functions and other global statements
  492. for ( const statement of ast.body ) {
  493. functions += this.emitExtraLine( statement, ast.body );
  494. if ( statement.isFunctionDeclaration ) {
  495. functions += this.emitFunction( statement ) + '\n';
  496. } else if ( statement.isComment ) {
  497. functions += this.emitComment( statement, ast.body );
  498. } else if ( ! statement.isUniform && ! statement.isVarying ) {
  499. // Handle other top-level statements like 'const'
  500. functions += this.emitExpression( statement ) + ';\n';
  501. }
  502. }
  503. // 4. Build dependencies
  504. for ( const value of this.polyfills.values() ) {
  505. dependencies = `${ value }\n\n`;
  506. }
  507. return header + dependencies + globals + functions.trimEnd() + '\n';
  508. }
  509. }
  510. export default WGSLEncoder;
粤ICP备19079148号