-
Notifications
You must be signed in to change notification settings - Fork 1
/
gulpfile.js
339 lines (299 loc) · 11.9 KB
/
gulpfile.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
// -----------------------------------------------------------------------------
// Imports
// -----------------------------------------------------------------------------
const AsepriteCli = require('aseprite-cli');
const chalk = require('chalk');
const { execSync } = require('child_process');
const fs = require('fs');
const gulp = require('gulp');
const log = require('fancy-log');
const { Packer } = require('roadroller');
const p8tojs = require('p8-to-js');
const rollup = require('rollup');
const rollupNodeResolve = require('@rollup/plugin-node-resolve');
const FontExporter = require('./tools/font-exporter');
const WorldBuilder = require('./tools/world-builder');
// -----------------------------------------------------------------------------
// Gulp Plugins
// -----------------------------------------------------------------------------
const advzip = require('gulp-advzip');
const concat = require('gulp-concat');
const cleancss = require('gulp-clean-css');
const htmlmin = require('gulp-htmlmin');
const size = require('gulp-size');
const sourcemaps = require('gulp-sourcemaps');
const template = require('gulp-template');
const terser = require('gulp-terser');
const zip = require('gulp-zip');
// -----------------------------------------------------------------------------
// Flags
// -----------------------------------------------------------------------------
let watching = false;
let dist = process.argv.includes('--dist');
// -----------------------------------------------------------------------------
// Assets Build
// -----------------------------------------------------------------------------
async function exportFont() {
// Normally, I would export all frames of all Aseprite files into a big spritesheet,
// with no concern where the frames end up -- we'd use the JSON output to determine
// the new coordinates of all images.
//
// The font is a special case because it is also the source file for our TSX (tileset)
// file in Tiled, so that we can see the in-game characters while editing the map.
// So we will export this one to its own dedicated output file.
const src = 'src/assets/font-bizcat-knife.aseprite';
const png = 'src/assets/font-gen.png';
const output = 'src/js/Font-gen.js';
try {
await AsepriteCli.exec([
'--tag', 'font',
src,
'--sheet', png
]);
} catch (e) {
// Allow developers without Aseprite to build the project (if desired, they'll need
// to update the generated image files manually).
log.error(e);
log.warn(chalk.red(`Failed to update ${png}, but continuing anyway...`));
}
await FontExporter.export(png, output);
}
async function crushFont() {
execSync('pngout src/assets/font-gen.png', { stdio: 'inherit' });
execSync('ect src/assets/font-gen.png', { stdio: 'inherit' });
}
async function generateWorld() {
const mapFile = 'src/assets/world.tmx';
const detailFile = 'src/assets/world.yaml';
const worldFile = 'src/js/WorldData-gen.js';
const jsonFile = 'src/assets/WorldData-gen.json';
await WorldBuilder.build(mapFile, detailFile, worldFile, jsonFile);
}
async function generateAudio() {
const p8File = 'src/assets/audio.p8';
const jsFile = 'src/js/AudioData-gen.js';
await p8tojs.convertFile(p8File, jsFile, {
export: 'AudioData',
sections: ['sfx', 'music'],
encoding: 'hex'
});
}
const buildAssets = gulp.series(
exportFont,
crushFont,
generateWorld,
generateAudio
);
// -----------------------------------------------------------------------------
// JavaScript Build
// -----------------------------------------------------------------------------
async function compileBuild() {
try {
const bundle = await rollup.rollup({
input: 'src/js/index.js',
plugins: [rollupNodeResolve.nodeResolve()],
// Hack... yes, my game has circular dependencies everywhere :). These
// really aren't a problem as long as structures don't initialize themselves
// on load (this is why most structures are inert until you execute `init()`
// on them).
//
// Here we intentionally suppress any warnings related to circular dependency.
onwarn: (warning, rollupWarn) => {
if (warning.code !== 'CIRCULAR_DEPENDENCY') {
rollupWarn(warning);
}
}
});
await bundle.write({
file: 'temp/bundled/app.js',
format: 'iife',
name: 'app',
sourcemap: true,
sourcemapFile: 'temp/bundled/app.js.map'
});
} catch (error) {
// We are calling rollup's API directly instead of using the CLI, and the output is
// not nearly as good. This hack imports and calls the same error handler that
// the CLI uses, so we get the nice context in code showing us the issue.
require('rollup/dist/shared/loadConfigFile').handleError(error, true);
throw error;
}
}
let nameCache;
function minifyBuild() {
let index = 0;
// Before we begin mangling, we can pre-populate the name cache with a
// customized list of names that can't be mangled (because names like RSTUDY
// will be both keys and name strings throughout the code, we need them
// to match).
/*const world = JSON.parse(fs.readFileSync('src/assets/WorldData-gen.json'));
const names = world.floors.reduce((list, floor) =>
list.concat(floor.rooms.map(room => room.name)).concat(floor.objects.map(object => object.name)),
[]
).concat(Object.keys(world.strings));
nameCache = {
props: {
props: Object.fromEntries(names.map(name => [`$${name}`, `${name[1]}${index++}`]))
}
};*/
// We use an extremely aggressive mangle -- all top-level names and all properties
// of all objects -- basically every property we can find unless it's in the
// list of exclusions above.
return gulp.src('temp/bundled/app.js')
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(terser({
toplevel: true,
nameCache,
mangle: {
properties: {
reserved: [
// Additional properties to exclude from mangling
'ArrowUp',
'ArrowLeft',
'ArrowDown',
'ArrowRight',
'KeyC',
'KeyL',
'KeyH',
'KeyI',
'Enter',
'Escape'
]
}
}
}))
.pipe(terser({
nameCache,
mangle: {
properties: {
builtins: true,
// Properties that are normally excluded from mangling due to built-in protection,
// but that we can mangle because we only use it for ourselves.
regex: /^(keyboard|pressed|frame|reset|update|SELECT|BACK|entities|init|finished|visible)$/
}
}
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('temp/minified'));
}
async function packBuild() {
if (!dist) {
log.info('Skipping packBuild (not --dist).');
return;
}
const jsContent = fs.readFileSync('temp/minified/app.js', 'utf8');
log.info(chalk.green('minified ') + jsContent.length + ' bytes');
const packer = new Packer([{
data: jsContent,
type: 'js',
action: 'eval'
}]);
await packer.optimize();
const { firstLine, secondLine } = packer.makeDecoder();
const packedJsContent = [firstLine, secondLine].join('\n');
log.info(chalk.green('packed ') + packedJsContent.length + ' bytes');
fs.mkdirSync('temp/packed', { recursive: true });
fs.writeFileSync('temp/packed/app.js', packedJsContent, 'utf8');
}
const buildJs = gulp.series(
compileBuild,
minifyBuild,
packBuild
);
// -----------------------------------------------------------------------------
// CSS Build
// -----------------------------------------------------------------------------
function buildCss() {
return gulp.src('src/css/*.css')
.pipe(concat('app.css'))
.pipe(cleancss())
.pipe(gulp.dest('temp'));
}
// -----------------------------------------------------------------------------
// HTML Build
// -----------------------------------------------------------------------------
function buildHtml() {
let filename = dist ? 'temp/packed/app.js' : 'temp/minified/app.js';
const cssContent = fs.readFileSync('temp/app.css', 'utf8');
const jsContent = fs.readFileSync(filename, 'utf8');
// Rather than having separate `app.css` and `app.js` files, we embed them both
// inside the HTML file (and any sprites we want have already been embedded
// inside `app.js`).
//
// Reducing the total number of files in the ZIP is a key strategy, since the
// ZIP file format has an overhead of +/-100 bytes for EVERY FILE. Embedding
// the CSS, JS, and PNG inside the HTML can save you almost 250 bytes, even
// with the conversion from binary to base64!
return gulp.src('src/index.html')
.pipe(template({ css: cssContent, js: jsContent }))
.pipe(htmlmin({ collapseWhitespace: true }))
.pipe(gulp.src('temp/minified/app.js.map'))
.pipe(gulp.dest('dist'));
}
// -----------------------------------------------------------------------------
// ZIP Build
// -----------------------------------------------------------------------------
function buildZip() {
let sizeResult;
return gulp.src(['dist/index.html'])
.pipe(size())
.pipe(zip('js13k-2021-shadow-of-the-keening-star.zip'))
.pipe(advzip({ optimizationLevel: 4, iterations: 200 }))
.pipe(sizeResult = size({ title: 'zip' }))
.pipe(gulp.dest('dist/final'))
.on('end', () => {
let remaining = (13 * 1024) - sizeResult.size;
if (remaining < 0) {
log.warn(chalk.red(`${-remaining} bytes over`));
} else {
log.info(chalk.green(`${remaining} bytes remaining`));
}
});
}
// -----------------------------------------------------------------------------
// Build
// -----------------------------------------------------------------------------
const build = gulp.series(
buildAssets,
buildCss,
buildJs,
buildHtml,
...(dist ? [buildZip] : [async () => log.info('Skipping buildZip (not --dist).')]),
ready
);
async function ready() {
if (!watching) return;
// This function doesn't affect the build at all, it's something I use as the
// build gets longer and slower in watch mode -- it flashes and dings the terminal
// when it's safe to refresh my browser.
const BELL = '\u0007';
const REVERSE = '\x1B[?5h';
const NORMAL = '\x1B[?5l';
process.stdout.write(`${BELL}${REVERSE}`);
await new Promise(resolve => setTimeout(resolve, 500));
process.stdout.write(`${NORMAL}\n`);
}
// -----------------------------------------------------------------------------
// Watch
// -----------------------------------------------------------------------------
function watch() {
watching = true;
// All files generated by the build are suffixed with "-gen", so we make
// sure to ignore those when watching for changed files.
gulp.watch(['src/**', '!src/**/*-gen*'], build);
}
// -----------------------------------------------------------------------------
// Task List
// -----------------------------------------------------------------------------
module.exports = {
// Core build steps
buildAssets,
buildCss,
buildJs,
buildHtml,
buildZip,
// Primary entry points
build,
watch,
default: gulp.series(build, watch)
};