shaderProcessor.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. import { ShaderCodeNode } from './shaderCodeNode';
  2. import { ShaderCodeCursor } from './shaderCodeCursor';
  3. import { ShaderCodeConditionNode } from './shaderCodeConditionNode';
  4. import { ShaderCodeTestNode } from './shaderCodeTestNode';
  5. import { ShaderDefineIsDefinedOperator } from './Expressions/Operators/shaderDefineIsDefinedOperator';
  6. import { ShaderDefineOrOperator } from './Expressions/Operators/shaderDefineOrOperator';
  7. import { ShaderDefineAndOperator } from './Expressions/Operators/shaderDefineAndOperator';
  8. import { ShaderDefineExpression } from './Expressions/shaderDefineExpression';
  9. import { ShaderDefineArithmeticOperator } from './Expressions/Operators/shaderDefineArithmeticOperator';
  10. import { ProcessingOptions } from './shaderProcessingOptions';
  11. import { _DevTools } from '../../Misc/devTools';
  12. declare type WebRequest = import("../../Misc/webRequest").WebRequest;
  13. declare type LoadFileError = import("../../Misc/fileTools").LoadFileError;
  14. declare type IOfflineProvider = import("../../Offline/IOfflineProvider").IOfflineProvider;
  15. declare type IFileRequest = import("../../Misc/fileRequest").IFileRequest;
  16. const regexSE = /defined\s*?\((.+?)\)/g;
  17. const regexSERevert = /defined\s*?\[(.+?)\]/g;
  18. /** @hidden */
  19. export class ShaderProcessor {
  20. public static Initialize(options: ProcessingOptions): void {
  21. if (options.processor && options.processor.initializeShaders) {
  22. options.processor.initializeShaders(options.processingContext);
  23. }
  24. }
  25. public static Process(sourceCode: string, options: ProcessingOptions, callback: (migratedCode: string) => void) {
  26. this._ProcessIncludes(sourceCode, options, (codeWithIncludes) => {
  27. let migratedCode = this._ProcessShaderConversion(codeWithIncludes, options);
  28. callback(migratedCode);
  29. });
  30. }
  31. public static Finalize(vertexCode: string, fragmentCode: string, options: ProcessingOptions): { vertexCode: string, fragmentCode: string } {
  32. if (!options.processor || !options.processor.finalizeShaders) {
  33. return { vertexCode, fragmentCode };
  34. }
  35. return options.processor.finalizeShaders(vertexCode, fragmentCode, options.processingContext);
  36. }
  37. private static _ProcessPrecision(source: string, options: ProcessingOptions): string {
  38. const shouldUseHighPrecisionShader = options.shouldUseHighPrecisionShader;
  39. if (source.indexOf("precision highp float") === -1) {
  40. if (!shouldUseHighPrecisionShader) {
  41. source = "precision mediump float;\n" + source;
  42. } else {
  43. source = "precision highp float;\n" + source;
  44. }
  45. } else {
  46. if (!shouldUseHighPrecisionShader) { // Moving highp to mediump
  47. source = source.replace("precision highp float", "precision mediump float");
  48. }
  49. }
  50. return source;
  51. }
  52. private static _ExtractOperation(expression: string) {
  53. let regex = /defined\((.+)\)/;
  54. let match = regex.exec(expression);
  55. if (match && match.length) {
  56. return new ShaderDefineIsDefinedOperator(match[1].trim(), expression[0] === "!");
  57. }
  58. let operators = ["==", ">=", "<=", "<", ">"];
  59. let operator = "";
  60. let indexOperator = 0;
  61. for (operator of operators) {
  62. indexOperator = expression.indexOf(operator);
  63. if (indexOperator > -1) {
  64. break;
  65. }
  66. }
  67. if (indexOperator === -1) {
  68. return new ShaderDefineIsDefinedOperator(expression);
  69. }
  70. let define = expression.substring(0, indexOperator).trim();
  71. let value = expression.substring(indexOperator + operator.length).trim();
  72. return new ShaderDefineArithmeticOperator(define, operator, value);
  73. }
  74. private static _BuildSubExpression(expression: string): ShaderDefineExpression {
  75. expression = expression.replace(regexSE, "defined[$1]");
  76. const postfix = ShaderDefineExpression.infixToPostfix(expression);
  77. const stack: (string | ShaderDefineExpression)[] = [];
  78. for (let c of postfix) {
  79. if (c !== '||' && c !== '&&') {
  80. stack.push(c);
  81. } else if (stack.length >= 2) {
  82. let v1 = stack[stack.length - 1],
  83. v2 = stack[stack.length - 2];
  84. stack.length -= 2;
  85. let operator = c == '&&' ? new ShaderDefineAndOperator() : new ShaderDefineOrOperator();
  86. if (typeof(v1) === 'string') {
  87. v1 = v1.replace(regexSERevert, "defined($1)");
  88. }
  89. if (typeof(v2) === 'string') {
  90. v2 = v2.replace(regexSERevert, "defined($1)");
  91. }
  92. operator.leftOperand = typeof(v2) === 'string' ? this._ExtractOperation(v2) : v2;
  93. operator.rightOperand = typeof(v1) === 'string' ? this._ExtractOperation(v1) : v1;
  94. stack.push(operator);
  95. }
  96. }
  97. let result = stack[stack.length - 1];
  98. if (typeof(result) === 'string') {
  99. result = result.replace(regexSERevert, "defined($1)");
  100. }
  101. // note: stack.length !== 1 if there was an error in the parsing
  102. return typeof(result) === 'string' ? this._ExtractOperation(result) : result;
  103. }
  104. private static _BuildExpression(line: string, start: number): ShaderCodeTestNode {
  105. let node = new ShaderCodeTestNode();
  106. let command = line.substring(0, start);
  107. let expression = line.substring(start);
  108. expression = expression.substring(0, ((expression.indexOf("//") + 1) || (expression.length + 1)) - 1).trim();
  109. if (command === "#ifdef") {
  110. node.testExpression = new ShaderDefineIsDefinedOperator(expression);
  111. } else if (command === "#ifndef") {
  112. node.testExpression = new ShaderDefineIsDefinedOperator(expression, true);
  113. } else {
  114. node.testExpression = this._BuildSubExpression(expression);
  115. }
  116. return node;
  117. }
  118. private static _MoveCursorWithinIf(cursor: ShaderCodeCursor, rootNode: ShaderCodeConditionNode, ifNode: ShaderCodeNode) {
  119. let line = cursor.currentLine;
  120. while (this._MoveCursor(cursor, ifNode)) {
  121. line = cursor.currentLine;
  122. let first5 = line.substring(0, 5).toLowerCase();
  123. if (first5 === "#else") {
  124. let elseNode = new ShaderCodeNode();
  125. rootNode.children.push(elseNode);
  126. this._MoveCursor(cursor, elseNode);
  127. return;
  128. } else if (first5 === "#elif") {
  129. let elifNode = this._BuildExpression(line, 5);
  130. rootNode.children.push(elifNode);
  131. ifNode = elifNode;
  132. }
  133. }
  134. }
  135. private static _MoveCursor(cursor: ShaderCodeCursor, rootNode: ShaderCodeNode): boolean {
  136. while (cursor.canRead) {
  137. cursor.lineIndex++;
  138. let line = cursor.currentLine;
  139. const keywords = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;
  140. const matches = keywords.exec(line);
  141. if (matches && matches.length) {
  142. let keyword = matches[0];
  143. switch (keyword) {
  144. case "#ifdef": {
  145. let newRootNode = new ShaderCodeConditionNode();
  146. rootNode.children.push(newRootNode);
  147. let ifNode = this._BuildExpression(line, 6);
  148. newRootNode.children.push(ifNode);
  149. this._MoveCursorWithinIf(cursor, newRootNode, ifNode);
  150. break;
  151. }
  152. case "#else":
  153. case "#elif":
  154. return true;
  155. case "#endif":
  156. return false;
  157. case "#ifndef": {
  158. let newRootNode = new ShaderCodeConditionNode();
  159. rootNode.children.push(newRootNode);
  160. let ifNode = this._BuildExpression(line, 7);
  161. newRootNode.children.push(ifNode);
  162. this._MoveCursorWithinIf(cursor, newRootNode, ifNode);
  163. break;
  164. }
  165. case "#if": {
  166. let newRootNode = new ShaderCodeConditionNode();
  167. let ifNode = this._BuildExpression(line, 3);
  168. rootNode.children.push(newRootNode);
  169. newRootNode.children.push(ifNode);
  170. this._MoveCursorWithinIf(cursor, newRootNode, ifNode);
  171. break;
  172. }
  173. }
  174. }
  175. else {
  176. let newNode = new ShaderCodeNode();
  177. newNode.line = line;
  178. rootNode.children.push(newNode);
  179. // Detect additional defines
  180. if (line[0] === "#" && line[1] === "d") {
  181. let split = line.replace(";", "").split(" ");
  182. newNode.additionalDefineKey = split[1];
  183. if (split.length === 3) {
  184. newNode.additionalDefineValue = split[2];
  185. }
  186. }
  187. }
  188. }
  189. return false;
  190. }
  191. private static _EvaluatePreProcessors(sourceCode: string, preprocessors: { [key: string]: string }, options: ProcessingOptions): string {
  192. const rootNode = new ShaderCodeNode();
  193. let cursor = new ShaderCodeCursor();
  194. cursor.lineIndex = -1;
  195. cursor.lines = sourceCode.split("\n");
  196. // Decompose (We keep it in 2 steps so it is easier to maintain and perf hit is insignificant)
  197. this._MoveCursor(cursor, rootNode);
  198. // Recompose
  199. return rootNode.process(preprocessors, options);
  200. }
  201. private static _PreparePreProcessors(options: ProcessingOptions): { [key: string]: string } {
  202. let defines = options.defines;
  203. let preprocessors: { [key: string]: string } = {};
  204. for (var define of defines) {
  205. let keyValue = define.replace("#define", "").replace(";", "").trim();
  206. let split = keyValue.split(" ");
  207. preprocessors[split[0]] = split.length > 1 ? split[1] : "";
  208. }
  209. preprocessors["GL_ES"] = "true";
  210. preprocessors["__VERSION__"] = options.version;
  211. preprocessors[options.platformName] = "true";
  212. return preprocessors;
  213. }
  214. private static _ProcessShaderConversion(sourceCode: string, options: ProcessingOptions): string {
  215. var preparedSourceCode = this._ProcessPrecision(sourceCode, options);
  216. if (!options.processor) {
  217. return preparedSourceCode;
  218. }
  219. // Already converted
  220. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  221. return preparedSourceCode.replace("#version 300 es", "");
  222. }
  223. let defines = options.defines;
  224. let preprocessors = this._PreparePreProcessors(options);
  225. // General pre processing
  226. if (options.processor.preProcessor) {
  227. preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext);
  228. }
  229. preparedSourceCode = this._EvaluatePreProcessors(preparedSourceCode, preprocessors, options);
  230. // Post processing
  231. if (options.processor.postProcessor) {
  232. preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext);
  233. }
  234. return preparedSourceCode;
  235. }
  236. private static _ProcessIncludes(sourceCode: string, options: ProcessingOptions, callback: (data: any) => void): void {
  237. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  238. var match = regex.exec(sourceCode);
  239. var returnValue = new String(sourceCode);
  240. var keepProcessing = false;
  241. while (match != null) {
  242. var includeFile = match[1];
  243. // Uniform declaration
  244. if (includeFile.indexOf("__decl__") !== -1) {
  245. includeFile = includeFile.replace(/__decl__/, "");
  246. if (options.supportsUniformBuffers) {
  247. includeFile = includeFile.replace(/Vertex/, "Ubo");
  248. includeFile = includeFile.replace(/Fragment/, "Ubo");
  249. }
  250. includeFile = includeFile + "Declaration";
  251. }
  252. if (options.includesShadersStore[includeFile]) {
  253. // Substitution
  254. var includeContent = options.includesShadersStore[includeFile];
  255. if (match[2]) {
  256. var splits = match[3].split(",");
  257. for (var index = 0; index < splits.length; index += 2) {
  258. var source = new RegExp(splits[index], "g");
  259. var dest = splits[index + 1];
  260. includeContent = includeContent.replace(source, dest);
  261. }
  262. }
  263. if (match[4]) {
  264. var indexString = match[5];
  265. if (indexString.indexOf("..") !== -1) {
  266. var indexSplits = indexString.split("..");
  267. var minIndex = parseInt(indexSplits[0]);
  268. var maxIndex = parseInt(indexSplits[1]);
  269. var sourceIncludeContent = includeContent.slice(0);
  270. includeContent = "";
  271. if (isNaN(maxIndex)) {
  272. maxIndex = options.indexParameters[indexSplits[1]];
  273. }
  274. for (var i = minIndex; i < maxIndex; i++) {
  275. if (!options.supportsUniformBuffers) {
  276. // Ubo replacement
  277. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, (str: string, p1: string) => {
  278. return p1 + "{X}";
  279. });
  280. }
  281. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  282. }
  283. } else {
  284. if (!options.supportsUniformBuffers) {
  285. // Ubo replacement
  286. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, (str: string, p1: string) => {
  287. return p1 + "{X}";
  288. });
  289. }
  290. includeContent = includeContent.replace(/\{X\}/g, indexString);
  291. }
  292. }
  293. // Replace
  294. returnValue = returnValue.replace(match[0], includeContent);
  295. keepProcessing = keepProcessing || includeContent.indexOf("#include<") >= 0;
  296. } else {
  297. var includeShaderUrl = options.shadersRepository + "ShadersInclude/" + includeFile + ".fx";
  298. ShaderProcessor._FileToolsLoadFile(includeShaderUrl, (fileContent) => {
  299. options.includesShadersStore[includeFile] = fileContent as string;
  300. this._ProcessIncludes(<string>returnValue, options, callback);
  301. });
  302. return;
  303. }
  304. match = regex.exec(sourceCode);
  305. }
  306. if (keepProcessing) {
  307. this._ProcessIncludes(returnValue.toString(), options, callback);
  308. } else {
  309. callback(returnValue);
  310. }
  311. }
  312. /**
  313. * Loads a file from a url
  314. * @param url url to load
  315. * @param onSuccess callback called when the file successfully loads
  316. * @param onProgress callback called while file is loading (if the server supports this mode)
  317. * @param offlineProvider defines the offline provider for caching
  318. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  319. * @param onError callback called when the file fails to load
  320. * @returns a file request object
  321. * @hidden
  322. */
  323. public static _FileToolsLoadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (ev: ProgressEvent) => void, offlineProvider?: IOfflineProvider, useArrayBuffer?: boolean, onError?: (request?: WebRequest, exception?: LoadFileError) => void): IFileRequest {
  324. throw _DevTools.WarnImport("FileTools");
  325. }
  326. }