generated from raulanatol/template-ts-package
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parseSsc.ts
452 lines (395 loc) · 12.1 KB
/
parseSsc.ts
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
import { Fraction } from "./fraction.js";
import { RawSimfile } from "./parseSong.js";
import {
FreezeLocation,
Arrow,
StepchartType,
Stepchart,
Mode,
} from "./types.js";
import {
determineBeat,
mergeSimilarBpmRanges,
normalizedDifficultyMap,
printMaybeError,
renameBackground,
reportError,
} from "./util.js";
// Ref: https://github.com/stepmania/stepmania/wiki/ssc
// eslint-disable-next-line jsdoc/require-jsdoc
function isMetaTag(tag: string): tag is "title" | "titletranslit" | "artist" {
return ["title", "titletranslit", "artist"].includes(tag);
}
// eslint-disable-next-line jsdoc/require-jsdoc
function isImageTag(tag: string): tag is "banner" | "background" | "jacket" {
return ["banner", "background", "jacket"].includes(tag);
}
const chartTagsToConsume = ["stepstype", "difficulty", "meter"];
type ChartInProgress = Partial<StepchartType> & {
chart?: Stepchart;
};
/**
* does a given line count as the end of a notes tag/block?
* @param line contents of the next line to check
* @returns boolean
*/
function concludesANoteTag(line: string | undefined): boolean {
if (line === undefined) {
return true;
}
return line.startsWith(";") || line.startsWith(",;");
}
// eslint-disable-next-line jsdoc/require-jsdoc
function getMeasureLength(lines: string[], i: number): number {
let measureLength = 0;
for (
;
i < lines.length && !concludesANoteTag(lines[i]) && lines[i][0] !== ",";
++i
) {
if (lines[i].trim() !== "") {
measureLength += 1;
}
}
return measureLength;
}
// eslint-disable-next-line jsdoc/require-jsdoc
function trimNoteLine(line: string, mode: "single" | "double"): string {
if (mode === "single") {
return line.substring(0, 4);
} else {
return line.substring(0, 8);
}
}
// eslint-disable-next-line jsdoc/require-jsdoc
function isRest(line: string): boolean {
return line.split("").every((d) => d === "0");
}
/**
* finds first non-empty measure in a chart
* @param mode gameplay mode of this chart
* @param lines all the lines in a current file
* @param i starting line index
* @returns line index for first step, and how many measures were passed in getting there
*/
function findFirstNonEmptyMeasure(
mode: "single" | "double",
lines: string[],
i: number,
): { firstNonEmptyMeasureIndex: number; numMeasuresSkipped: number } {
let numMeasuresSkipped = 0;
let measureIndex = i;
for (; i < lines.length && !concludesANoteTag(lines[i]); ++i) {
const line = lines[i];
if (line.trim() === "") {
continue;
}
if (line.startsWith(",")) {
measureIndex = i + 1;
numMeasuresSkipped += 1;
continue;
}
if (!isRest(trimNoteLine(line, mode))) {
return { firstNonEmptyMeasureIndex: measureIndex, numMeasuresSkipped };
}
}
throw new Error(
"findFirstNonEmptyMeasure, failed to find a non-empty measure in entire song",
);
}
/**
* parse a SSC file
* @param ssc entire contents of the file
* @returns parsed simfile object
*/
export function parseSsc(ssc: string): RawSimfile {
const lines = ssc.split("\n").map((l) => l.trim());
let i = 0;
let bpmString: string | null = null;
let stopsString: string | null = null;
const sc: Partial<RawSimfile> &
Pick<RawSimfile, "images" | "charts" | "availableTypes"> = {
charts: {},
availableTypes: [],
images: {
banner: null,
bg: null,
jacket: null,
},
};
/**
* parse out bpm stops
* @param stopsString input string
* @param emptyOffsetInMeasures number of empty measures at the head of this chart
* @returns list of stop locations and durations
*/
function parseStops(
stopsString: string | null,
emptyOffsetInMeasures: number,
) {
if (!stopsString) {
return [];
}
const entries = stopsString.split(",");
return entries.map((s) => {
const [stopS, durationS] = s.split("=");
return {
offset: Number(stopS) * 0.25 - emptyOffsetInMeasures,
duration: Number(durationS),
};
});
}
/**
* parse a sequence of bpm changes
* @param bpmString input string
* @param emptyOffsetInMeasures number of empty measures at the head of this chart
* @returns a sequence of bpm segments
*/
function parseBpms(bpmString: string, emptyOffsetInMeasures: number) {
const entries = bpmString.split(",");
const bpms = entries.map((e, i, a) => {
const [beatS, bpmS] = e.split("=");
const nextBeatS = a[i + 1]?.split("=")[0] ?? null;
return {
startOffset: Number(beatS) * 0.25 - emptyOffsetInMeasures,
endOffset:
nextBeatS === null
? null
: Number(nextBeatS) * 0.25 - emptyOffsetInMeasures,
bpm: Number(bpmS),
};
});
return mergeSimilarBpmRanges(bpms);
}
/**
* @param lines all lines in this file
* @param i current line
* @param mode chart's gameplay mode, for reporting only
* @param difficulty chart's difficulty category, for reporting only
* @returns array of parsed freeze note locations
*/
function parseFreezes(
lines: string[],
i: number,
mode: string,
difficulty: string,
): FreezeLocation[] {
const freezes: FreezeLocation[] = [];
const open: Record<number, Partial<FreezeLocation> | undefined> = {};
let curOffset = new Fraction(0);
let curMeasureFraction = new Fraction(1, getMeasureLength(lines, i) || 1);
for (; i < lines.length && !concludesANoteTag(lines[i]); ++i) {
const line = lines[i];
if (line.trim() === "") {
continue;
}
if (line[0] === ",") {
curMeasureFraction = new Fraction(
1,
getMeasureLength(lines, i + 1) || 1,
);
continue;
}
if (
line.indexOf("2") === -1 &&
line.indexOf("3") === -1 &&
line.indexOf("4") === -1
) {
curOffset = curOffset.add(curMeasureFraction);
continue;
}
const cleanedLine = line.replace(/[^234]/g, "0");
for (let d = 0; d < cleanedLine.length; ++d) {
if (cleanedLine[d] === "2" || cleanedLine[d] === "4") {
if (open[d]) {
reportError(
`${sc.title}, ${mode}, ${difficulty} -- error parsing freezes, found a new starting freeze before a previous one finished`,
);
} else {
const startBeatFraction = curOffset;
open[d] = {
direction: d as FreezeLocation["direction"],
startOffset: startBeatFraction.n / startBeatFraction.d,
};
}
} else if (cleanedLine[d] === "3") {
const thisFreeze = open[d];
if (!thisFreeze) {
reportError(
`${sc.title}, ${mode}, ${difficulty} -- error parsing freezes, tried to close a freeze that never opened`,
);
} else {
const endBeatFraction = curOffset.add(new Fraction(1, 4));
thisFreeze.endOffset = endBeatFraction.n / endBeatFraction.d;
freezes.push(thisFreeze as FreezeLocation);
open[d] = undefined;
}
}
}
curOffset = curOffset.add(curMeasureFraction);
}
return freezes;
}
/**
* Parse notes info for a chart
* @param lines all lines of current file
* @param i current line
* @param bpmString string of bpm changes for this chart
* @returns number of lines parsed
*/
function parseNotes(lines: string[], i: number, bpmString: string): number {
if (!currentChart || !currentChart.mode || !currentChart.difficulty) {
throw new Error(
"parseSsc: Can't parse notes before mode and difficulty are ready",
);
}
// move past #NOTES into the note metadata
i++;
// now i is pointing at the first measure
const arrows: Arrow[] = [];
const { firstNonEmptyMeasureIndex, numMeasuresSkipped } =
findFirstNonEmptyMeasure(currentChart.mode, lines, i);
i = firstNonEmptyMeasureIndex;
const firstMeasureIndex = i;
let curOffset = new Fraction(0);
// in case the measure is size zero, fall back to dividing by one
// this is just being defensive, this would mean the stepfile has no notes in it
let curMeasureFraction = new Fraction(1, getMeasureLength(lines, i) || 1);
for (; i < lines.length && !concludesANoteTag(lines[i]); ++i) {
// for now, remove freeze ends as they are handled in parseFreezes
// TODO: deal with freezes here, no need to have two functions doing basically the same thing
const line = trimNoteLine(lines[i], currentChart.mode).replace(/3/g, "0");
if (line.trim() === "") {
continue;
}
if (line.startsWith(",")) {
curMeasureFraction = new Fraction(
1,
getMeasureLength(lines, i + 1) || 1,
);
continue;
}
if (!isRest(line)) {
arrows.push({
quantization: determineBeat(curOffset),
offset: curOffset.n / curOffset.d,
direction: line as Arrow["direction"],
});
}
curOffset = curOffset.add(curMeasureFraction);
}
const freezes = parseFreezes(
lines,
firstMeasureIndex,
currentChart.mode,
currentChart.difficulty,
);
currentChart.chart = {
arrows,
freezes,
bpm: parseBpms(bpmString, numMeasuresSkipped),
stops: parseStops(stopsString, numMeasuresSkipped),
};
return i + 1;
}
let currentChart: ChartInProgress | null = null;
/**
* commits currentChart to output & sets a new blank currentChart
*/
function startNextChart() {
if (currentChart) {
const { chart, ...info } = currentChart;
if (!chart) {
reportError("incomplete chart info available");
} else {
info.slug = `${info.mode}-${info.difficulty}`;
sc.charts[info.slug] = chart;
sc.availableTypes.push(info as StepchartType);
}
}
currentChart = {};
}
/**
* Add metadata to currentChart
* @param key tag name
* @param value tag value
*/
function consumeChartTag(key: string, value: string) {
if (!currentChart) {
throw new Error("parseSsc: got chart tag before start of first chart");
}
switch (key) {
case "stepstype":
currentChart.mode = value.replace("dance-", "") as Mode;
break;
case "difficulty":
currentChart.difficulty = normalizedDifficultyMap[value.toLowerCase()];
break;
case "meter":
currentChart.feet = Number(value);
break;
}
}
/**
* @param lines all lines of the file at hand
* @param index current line number
* @returns number of lines consumed
*/
function parseTag(lines: string[], index: number): number {
const line = lines[index];
const r = /#([A-Za-z]+):([^;]*)/;
const result = r.exec(line);
if (result) {
const tag = result[1].toLowerCase();
const value = result[2];
if (isMetaTag(tag)) {
if (value) {
sc[tag] = value;
}
} else if (isImageTag(tag)) {
// @ts-expect-error: background is not an output value, will be cleaned up later
sc.images[tag] = value;
} else if (chartTagsToConsume.includes(tag)) {
consumeChartTag(tag, value);
} else if (tag === "displaybpm") {
sc.displayBpm = value.replace(":", "-");
} else if (tag === "bpms") {
bpmString = value;
} else if (tag === "stops") {
stopsString = value;
} else if (tag === "notedata") {
startNextChart();
} else if (tag === "notes") {
if (!bpmString) {
throw new Error("parseSsc: about to parse notes but never got bpm");
}
return parseNotes(lines, index, bpmString);
}
}
return index + 1;
}
try {
while (i < lines.length) {
const line = lines[i];
if (!line.length || line.startsWith("//")) {
i += 1;
continue;
}
if (line.startsWith("#")) {
i = parseTag(lines, i);
} else {
i += 1;
}
}
// commit last pending chart, if it exists
if (currentChart) {
startNextChart();
}
renameBackground(sc.images);
return sc as RawSimfile;
} catch (e) {
throw new Error(
`error parsing ${ssc.substring(0, 300)}\n${printMaybeError(e)}`,
);
}
}