-
Notifications
You must be signed in to change notification settings - Fork 16
/
shadermin.js
363 lines (328 loc) · 9.16 KB
/
shadermin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
const SHADERS_DIR = './src/lib/shaders/';
const VERSION_PREFIX = '#version 300 es';
const PRECISION_PREFIX = 'precision highp float;';
const EXTERN_ATTRIBUTES = ['uniform', 'in', 'out'];
const PRECISION_ATTRIBUTES = ['lowp', 'mediump', 'highp'];
const VARIABLE_TYPES = ['bool', 'float', 'vec2', 'vec3', 'vec4', 'mat4'];
const RENAME_ENABLED = true;
const ADD_NEWLINES = false;
const fs = require('fs');
/**
* Returns true if the file is a GLSL shader file.
* @param {string} file
* @return {boolean}
*/
const isShaderFile = (file) =>
file.endsWith('.vert') ||
file.endsWith('.frag');
/**
* Tokenizes a shader file contents.
* @param {string} content
* @return {Array.<string>}
*/
const tokenize = (content) => {
// Capture groups:
// 1) Alphanumeric
// 2) Semicolons
// 2) Other Punctuation (not alphanumeric, not whitespace)
// 3) New lines
const regex = /([\w]+)|(;)|([^\w\s;]+)|(\n)/g;
const results = [];
let next = null;
while ((next = regex.exec(content))) {
results.push(next[0]);
}
return results;
};
/**
* GLSL Parser.
*/
class Parser {
/**
* Creates a new parser.
* @param {!Array.<string>} tokens
*/
constructor(tokens) {
this.tokens = tokens;
this.index = 0;
}
/**
* Resets the current marker to the beginning.
*/
reset() {
this.index = 0;
}
/**
* Returns true if the current marker is at/past the end of file.
* @return {boolean}
*/
eof() {
return this.index >= this.tokens.length;
}
/**
* Returns the a token at an offset from the current token.
* @param {number} delta
* @return {string}
*/
peek(delta) {
const index = this.index + delta;
if (index < 0 || index >= this.tokens.length) {
return 'EOF';
}
return this.tokens[index];
}
/**
* Returns the current token.
* @return {string}
*/
curr() {
return this.peek(0);
}
/**
* Skips ahead until the target value is found.
* @param {string} target
*/
skipTo(target) {
while (this.curr() !== target) {
this.index++;
}
}
/**
* Deletes the current token.
*/
deleteToken() {
this.tokens.splice(this.index, 1);
}
/**
* Deletes tokens from current to target (including the target token).
* @param {string} target
*/
deleteTo(target) {
while (this.curr() !== target) {
this.deleteToken();
}
this.deleteToken();
}
/**
* Removes all comments from the parser tokens.
*/
removeComments() {
this.reset();
while (!this.eof()) {
const curr = this.curr();
if (curr === '//' || curr === '#' || curr === 'precision') {
this.deleteTo('\n');
} else {
this.index++;
}
}
}
/**
* Removes all new lines from the parser tokens.
*/
removeNewLines() {
this.reset();
while (!this.eof()) {
if (this.curr() === '\n') {
this.deleteToken();
} else {
this.index++;
}
}
}
}
/**
* Shader
*/
class Shader {
/**
* Creates a new shader parser
* @param {string} fileName
*/
constructor(fileName) {
this.fileName = fileName;
const content = fs.readFileSync(SHADERS_DIR + fileName, {encoding: 'utf8', flag: 'r'});
const tokens = tokenize(content);
const parser = new Parser(tokens);
parser.removeComments();
parser.removeNewLines();
this.parser = parser;
this.localVariables = {};
}
/**
* Returns the const variable name for the JavaScript output file.
* @return {string}
*/
getConstName() {
return this.fileName.replace('.', '_').toUpperCase();
}
}
/**
* Builds the shaders.js file from the original GLSL shaders.
* @return {!Promise}
*/
exports.buildShaders = () => new Promise((resolve, reject) => {
const fileNames = fs.readdirSync(SHADERS_DIR).filter(isShaderFile);
const files = fileNames.map((fileName) => new Shader(fileName));
// Gather a list of all declarations
const globalVariables = {};
files.forEach((file) => {
const parser = file.parser;
parser.reset();
while (!parser.eof()) {
const curr = parser.curr();
if (EXTERN_ATTRIBUTES.includes(curr)) {
if (PRECISION_ATTRIBUTES.includes(parser.peek(1))) {
const type = parser.peek(1) + ' ' + parser.peek(2);
const name = parser.peek(3);
globalVariables[name] = {type: type, name: name};
parser.index += 4;
} else {
const type = parser.peek(1);
const name = parser.peek(2);
globalVariables[name] = {type: type, name: name};
parser.index += 3;
}
} else if (VARIABLE_TYPES.includes(curr)) {
const type = curr;
const name = parser.peek(1);
if (name.match(/\w+/)) {
file.localVariables[name] = {type: type, name: name, references: 0};
}
parser.index += 2;
} else {
parser.index++;
}
}
});
// Count uses of local variables
files.forEach((file) => {
const tokens = file.parser.tokens;
for (let i = 0; i < tokens.length; i++) {
const input = tokens[i];
if (input.match(/\w+/)) {
const variable = file.localVariables[input];
if (variable) {
variable.references++;
}
}
}
});
// Inline variables
files.forEach((file) => {
Object.values(file.localVariables).forEach((variable) => {
// If the variable is only used once
// Then replace the one use with the body of the variable declaration.
if (variable.references === 2) {
const value = [];
const parser = file.parser;
parser.reset();
while (!parser.eof()) {
if (parser.curr() === variable.type && parser.peek(1) === variable.name) {
// Found the declaration
parser.deleteToken();
parser.deleteToken();
if (parser.curr() !== '=') {
throw new Error('Expected "=" for variable declaration');
}
parser.deleteToken();
while (parser.curr() !== ';') {
value.push(parser.curr());
parser.deleteToken();
}
if (parser.curr() !== ';') {
throw new Error('Expected ";" to end variable declaration');
}
parser.deleteToken();
} else if (parser.curr() === variable.name) {
// Found the use
if (value.length > 1) {
value.unshift('(');
value.push(')');
}
parser.tokens.splice(parser.index, 1, ...value);
} else {
parser.index++;
}
}
}
});
});
const output = [
'// Autogenerated by shadermin.js\n',
'// Do not modify manually\n',
'\n',
];
// Assign replacement names for all variables
const alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
let nextVarIndex = 0;
// Global variables first
Object.values(globalVariables).sort((a, b) => a.name.localeCompare(b.name)).forEach((variable) => {
if (RENAME_ENABLED) {
variable.rename = alphabet.charAt(nextVarIndex++);
} else {
variable.rename = variable.name;
}
if (variable.name.startsWith('u_') || variable.name.startsWith('a_')) {
const constName = variable.name.replace('u_', 'UNIFORM_').replace('a_', 'ATTRIBUTE_').toUpperCase();
output.push(`const ${constName} = '${variable.rename}';\n`);
}
});
const globalCount = nextVarIndex;
// Local variables next
files.forEach((file) => {
nextVarIndex = globalCount;
Object.values(file.localVariables).sort((a, b) => a.name.localeCompare(b.name)).forEach((variable) => {
if (RENAME_ENABLED) {
variable.rename = alphabet.charAt(nextVarIndex++);
} else {
variable.rename = variable.name;
}
});
});
// Now that variables have been renamed,
// actually go through and replace all the names
files.forEach((file) => {
const tokens = file.parser.tokens;
for (let i = 0; i < tokens.length; i++) {
const input = tokens[i];
const globalVariable = globalVariables[input];
const localVariable = file.localVariables[input];
if (globalVariable) {
tokens[i] = globalVariable.rename;
} else if (localVariable) {
tokens[i] = localVariable.rename;
}
}
});
output.push('\n');
output.push(`const GLSL_PREFIX =\n`);
output.push(` '${VERSION_PREFIX}\\n' +\n`);
output.push(` '${PRECISION_PREFIX}';\n`);
// Then re-write the file with variable replacements and other optimizations
files.forEach((file) => {
output.push('\n');
output.push(`const ${file.getConstName()} =\n`);
output.push(` GLSL_PREFIX +\n`);
output.push(` '`);
const tokens = file.parser.tokens;
let prev = '';
for (let i = 0; i < tokens.length; i++) {
const curr = tokens[i];
if (prev.match(/\w+/) && curr.match(/\w+/)) {
output.push(' ');
}
output.push(curr);
if (i !== tokens.length - 1 && (curr === ';' || curr.endsWith('{') || curr.endsWith('}'))) {
if (ADD_NEWLINES) {
output.push('\\n');
}
output.push(`' +\n '`);
}
prev = curr;
}
output.push(`';\n`);
});
fs.writeFileSync('./src/lib/shaders.js', output.join(''));
resolve();
});